ima2-gen 1.1.1 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/config.js +1 -1
- package/package.json +1 -1
- package/ui/dist/assets/{index-C60__40a.js → index-BjX_nzuK.js} +3 -3
- package/ui/dist/assets/{index-C60__40a.js.map → index-BjX_nzuK.js.map} +1 -1
- package/ui/dist/assets/{index-DzSsElhv.css → index-DHyUax4_.css} +1 -1
- package/ui/dist/index.html +2 -2
|
@@ -12,12 +12,12 @@ Error generating stack: `+s.message+`
|
|
|
12
12
|
|
|
13
13
|
`);for(;m!==-1;){const v=d.slice(0,m);d=d.slice(m+2);const x=e1(v);if(x){if(x.event==="partial")i.onPartial?.(x.data);else if(x.event==="phase")i.onPhase?.(x.data);else if(x.event==="done")g=x.data;else if(x.event==="error"){const S=x.data,w=S?.error?.message??"Node generation failed",j=new Error(w);throw j.code=S?.error?.code,j}}m=d.indexOf(`
|
|
14
14
|
|
|
15
|
-
`)}}if(!g)throw new Error("Node stream ended without a final image");return g}function n1(){return ot("/api/sessions")}function a1(t){return ot("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t})})}function m0(t){return ot(`/api/sessions/${encodeURIComponent(t)}`)}function i1(t,i){return ot(`/api/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:i})})}function l1(t){return ot(`/api/sessions/${encodeURIComponent(t)}`,{method:"DELETE"})}function o1(t,i,l,o,r={}){const u={"Content-Type":"application/json","If-Match":String(i)};return r.saveId&&(u["X-Ima2-Graph-Save-Id"]=r.saveId),r.saveReason&&(u["X-Ima2-Graph-Save-Reason"]=r.saveReason),r.tabId&&(u["X-Ima2-Tab-Id"]=r.tabId),ot(`/api/sessions/${encodeURIComponent(t)}/graph`,{method:"PUT",headers:u,body:JSON.stringify({nodes:l,edges:o})})}function s1(t){return ot(`/api/sessions/${encodeURIComponent(t)}/style-sheet`)}function r1(t,i,l){return ot(`/api/sessions/${encodeURIComponent(t)}/style-sheet`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({styleSheet:i,enabled:l})})}function c1(t,i){return ot(`/api/sessions/${encodeURIComponent(t)}/style-sheet/enabled`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:i})})}function u1(t,i,l){return ot(`/api/sessions/${encodeURIComponent(t)}/style-sheet/extract`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:i,referenceDataUrl:l})})}function d1(t,i=256){return new Promise(l=>{const o=new Image;o.onload=()=>{const r=Math.min(1,i/Math.max(o.width,o.height)),u=document.createElement("canvas");u.width=o.width*r,u.height=o.height*r;const d=u.getContext("2d");if(!d)return l(t);d.drawImage(o,0,0,u.width,u.height),l(u.toDataURL("image/jpeg",.6))},o.onerror=()=>l(t),o.src=t})}const f1={maxB64Bytes:6e6,preserveTransparency:!1,maxEdge:4096,qualityLadder:[.85,.7,.55]},zp=16777216;function h1(t,i,l){let o=t,r=i;if(o<=0||r<=0)return{w:1,h:1};const u=Math.max(o,r);if(u>l){const d=l/u;o=Math.round(o*d),r=Math.round(r*d)}if(o*r>zp){const d=Math.sqrt(zp/(o*r));o=Math.max(1,Math.floor(o*d)),r=Math.max(1,Math.floor(r*d))}return{w:o,h:r}}function Md(t){return new Promise((i,l)=>{const o=new FileReader;o.onload=()=>{typeof o.result=="string"?i(o.result):l(new Error("FileReader returned non-string"))},o.onerror=()=>l(o.error??new Error("FileReader failed")),o.readAsDataURL(t)})}function Rp(t,i,l){return new Promise((o,r)=>{t.toBlob(u=>u?o(u):r(new Error("canvas.toBlob returned null")),i,l)})}function jd(t){const i=t.indexOf(",");return i<0?t.length:t.length-i-1}async function Dp(t,i={}){const l={...f1,...i},o=await Md(t);if(jd(o)<=l.maxB64Bytes)return o;let r;try{r=await createImageBitmap(t)}catch(u){throw new Error("이미지 디코드 실패. JPEG/PNG로 변환 후 다시 시도해 주세요.",{cause:u})}try{const{w:u,h:d}=h1(r.width,r.height,l.maxEdge),g=document.createElement("canvas");g.width=u,g.height=d;const p=g.getContext("2d");if(!p)throw new Error("canvas 2d context unavailable");if(p.drawImage(r,0,0,u,d),l.preserveTransparency){const y=await Rp(g,"image/png"),m=await Md(y);if(jd(m)>l.maxB64Bytes)throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.");return m}for(const y of l.qualityLadder){const m=await Rp(g,"image/jpeg",y),v=await Md(m);if(jd(v)<=l.maxB64Bytes)return v}throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.")}finally{r.close?.()}}function fr(t){const i=(t.type||"").toLowerCase();if(i.includes("heic")||i.includes("heif"))return!0;const l=(t.name||"").toLowerCase();return l.endsWith(".heic")||l.endsWith(".heif")}function Op(t){return(t.type||"").toLowerCase()==="image/png"}const g1={ok:"확인",cancel:"취소",delete:"삭제",close:"닫기"},m1={localStorageFull:"로컬 저장소가 가득 차서 최근 상태가 저장되지 않을 수 있습니다.",refLimitExceeded:"참조 이미지는 최대 5장까지 추가할 수 있습니다. 초과한 이미지는 제외되었습니다.",refTooLarge:"이미지가 너무 큽니다. JPEG/PNG로 미리 변환하거나 해상도를 낮춰 다시 시도해 주세요.",refNotBase64:"이미지 파일이 손상되었거나 지원하지 않는 형식입니다.",refEmpty:"빈 이미지 파일입니다. 다른 파일을 선택해 주세요.",refHeicUnsupported:"HEIC/HEIF는 지원하지 않습니다. JPEG 또는 PNG로 변환 후 다시 시도해 주세요.",noCurrentImageForRef:"참조로 사용할 현재 이미지가 없습니다.",refSlotFull:"참조 이미지 슬롯이 가득 찼습니다. 최대 5장까지 가능합니다.",currentImageLoadFailed:"현재 이미지를 불러오지 못했습니다.",addedCurrentAsRef:"현재 이미지를 참조에 추가했습니다.",sessionLoadFailed:"세션을 불러오지 못했습니다.",sessionCreateFailed:"세션을 만들지 못했습니다.",sessionRenameFailed:"세션 이름을 바꾸지 못했습니다.",sessionDeleteFailed:"세션을 삭제하지 못했습니다.",promptRequired:"프롬프트를 입력하세요.",nodeCreated:"노드 {id} 생성 완료 ({elapsed}초)",nodeCreateFailed:"노드 생성에 실패했습니다.",generatedBatch:"{count}장을 {elapsed}초 만에 생성했습니다.",generatedSingle:"{elapsed}초 만에 생성했습니다.",generateFailed:"생성에 실패했습니다.",sessionReloadedElsewhere:"그래프 버전이 달라져 최신 그래프를 다시 불러왔습니다.",promptCopied:"프롬프트를 복사했습니다",imageCopied:"클립보드에 복사했습니다",copyFailed:"복사에 실패했습니다",openGeneratedDirFailed:"이미지 폴더를 열지 못했습니다. ima2 doctor로 저장 경로를 확인해 주세요.",noPromptToFork:"가져올 프롬프트가 없습니다",forkStarted:"이 이미지의 프롬프트를 가져왔습니다. 수정 후 다시 생성하세요"},p1={queued:"대기 중",streaming:"생성 중",decoding:"마무리 중"},y1={title:"크기",width:"가로",height:"세로",hint:"한 변 최소 1024, 최대 3824, 16의 배수, 비율은 최대 3:1",autoLabel:"자동",autoSub:"모델 추천",customLabel:"직접 입력",customSub:"자유 설정"},v1={title:"크기 조정이 필요합니다",body:"입력한 크기가 이미지 생성 제한을 벗어나 자동 조정이 필요합니다.",requested:"요청한 크기",adjusted:"조정될 크기",approve:"승인 후 생성",cancel:"취소",reasonRatio:"비율 제한 3:1을 초과했습니다.",reasonPixels:"최대 픽셀 수 제한을 초과했습니다.",reasonMin:"최소 크기보다 작습니다.",reasonMax:"최대 크기보다 큽니다.",reasonSnap:"16px 단위에 맞춰야 합니다."},x1={title:"품질",lowLabel:"낮음",lowSub:"빠름",mediumLabel:"중간",mediumSub:"균형",highLabel:"높음",highSub:"최상"},b1={title:"모더레이션",autoLabel:"자동",autoSub:"표준 필터",lowLabel:"낮음",lowSub:"완화 필터",explain:"자동은 표준 안전 필터를 사용합니다. 낮음은 제한을 조금 완화해 경계선 프롬프트가 더 통과할 수 있습니다."},S1={title:"포맷"},w1={title:"개수"},N1={button:"생성",buttonLoading:"생성 중 ({n})"},_1={label:"API 상태",checking:"확인 중...",offline:"오프라인",remaining:"${remaining} 남음",thisMonth:"이번 달 ${amount}",oauthFree:"OAuth 무료 사용 가능",apiDisabled:"API 키 비활성화됨 (OAuth 전용)",oauthMode:"OAuth 모드"},E1={openGalleryAria:"갤러리 열기",openGalleryTitle:"전체 갤러리 열기"},C1={closeSettings:"설정 닫기",detailSettings:"세부 설정",toggleShow:"세부 설정 보기",toggleHide:"세부 설정 숨기기",open:"열기",close:"닫기"},T1={label:"프롬프트",refCount:"참조 {count}/{max}",refChipTitle:"참조 이미지 {n}",refChipAlt:"참조 이미지 {n}",refRemoveAria:"참조 이미지 {n} 제거",placeholder:"원하는 이미지를 설명하고, 드래그 앤 드롭이나 붙여넣기로 참조 이미지를 추가할 수 있어요...",placeholderWithRefs:"첨부한 이미지로 무엇을 만들지 설명해 주세요...",attach:"첨부",attachTitle:"참조 이미지 첨부",useCurrent:"현재 결과 사용",useCurrentTitle:"현재 결과를 참조로 사용",style:"스타일",styleTitle:"스타일 일관성 설정 열기",directMode:"Direct",directModeTitle:"프롬프트를 원문 그대로 전달 (Direct 모드)",hint:"Ctrl + Enter로 생성",dropHere:"놓아서 참조 이미지로 추가 ({max}장까지)"},A1={resultAlt:"생성 결과",imageViewerAria:"생성 이미지 뷰어. 좌우 방향키로 이전 또는 다음 이미지를 볼 수 있습니다.",tokens:"{n} 토큰"},M1={today:"오늘",yesterday:"어제",thisWeek:"이번 주",earlier:"이전",imageAltFallback:"생성 이미지",deleteTitle:"삭제 (10초 내 복구 가능)",deleteAria:"이미지 삭제",ariaLabel:"이미지 갤러리",title:"갤러리",total:"총 {n}장",totalFiltered:" / 전체 {n}장",sortByAria:"정렬 기준",sortByDate:"날짜",sortBySession:"세션",searchPlaceholder:"프롬프트나 파일명을 검색",searchDisabledPlaceholder:"세션 보기에서는 검색이 비활성화됩니다",closeAria:"갤러리 닫기",closeTitle:"닫기 (Esc)",sessionLabel:"세션 {name}",standalone:"독립 이미지",emptySessions:"아직 저장된 세션이 없습니다.",emptyAll:"아직 생성된 이미지가 없습니다. 먼저 하나 만들어보세요.",noResults:"검색 결과가 없습니다.",storageNoticeTitle:"저장 위치 안내",storageNoticeRecoverable:"놀라게 해드려 죄송합니다. 최근 버전에서 갤러리 저장 위치가 설치 폴더에서 사용자 데이터 폴더로 바뀌었습니다. 예전 이미지가 이전 generated 폴더에 남아 있을 수 있어요. ima2 doctor를 실행하거나 복구 안내를 확인해 주세요.",storageNoticeNotFound:"놀라게 해드려 죄송합니다. 현재 이 컴퓨터에서 이전 generated 폴더를 찾지 못했습니다. 업데이트 중 예전 전역 설치 폴더가 교체된 경우 자동 복구가 어려울 수 있습니다. ima2 doctor와 복구 안내의 수동 검색 방법을 확인해 주세요.",storageNoticeUnknown:"저장 위치 상태를 확인하지 못했습니다. 업데이트 후 갤러리가 비어 보인다면 ima2 doctor로 이미지 폴더를 확인해 주세요.",openGeneratedDir:"폴더 열기",openGeneratedDirTitle:"생성 이미지 폴더 열기",cardNewsSet:"카드뉴스 세트",cardNewsCard:"카드뉴스 카드",openCardNewsSet:"세트 열기",openCardNewsSetFailed:"카드뉴스 세트를 열지 못했습니다.",copyCardNewsSetPath:"경로 복사",cardNewsPathCopied:"카드뉴스 세트 경로를 복사했습니다.",downloadCardNewsManifest:"매니페스트",cardNewsCount:"{n}장",deleted:"삭제됨: {filename}",undo:"되돌리기",secondsSuffix:"{n}초"},j1={empty:"비어 있음",pending:"생성 중",reconciling:"동기화 중",reconcilingPhase:"동기화 중 · {phase}",ready:"완료 · {elapsed}s",readyWithSearch:"완료 · {elapsed}s · 검색 {searches}",stale:"오래된 상태",staleWithError:"오래된 상태: {error}",assetMissing:"에셋 누락",assetMissingWithError:"에셋 누락: {error}",error:"오류: {error}",errorUnknown:"알 수 없음",nodeImageAlt:"노드 이미지",partialImageAlt:"노드 중간 이미지 미리보기",noAsset:"에셋 없음",stateStale:"상태 오래됨",noImage:"이미지 없음",editPromptPlaceholder:"수정 프롬프트...",promptPlaceholder:"프롬프트...",regenerate:"재생성",newVariation:"새 변형",generate:"생성",addChild:"자식",addChildTitle:"자식 노드 추가",duplicateBranch:"복제",duplicateBranchTitle:"새 브랜치 루트로 복제",deleteTitle:"삭제",regenerateTitle:"현재 노드 이미지를 제자리에서 다시 생성",newVariationTitle:"같은 부모 아래 새 변형 노드를 생성",parentImageRequired:"부모 이미지를 먼저 생성해야 합니다.",attachRef:"첨부",attachRefTitle:"노드 참조 이미지 첨부",refAlt:"노드 참조 이미지 {n}",removeRef:"참조 이미지 {n} 제거",dropRefs:"이미지를 여기에 놓기",nodeRefsUnsupportedForEdit:"추가 참조 이미지는 현재 루트 노드에서만 지원합니다.",nodeRefsUsedWithParent:"부모 이미지와 함께 참조로 사용됩니다.",classicRefsParkedTitle:"클래식 참조 이미지가 보관 중입니다",classicRefsParkedBody:"이 이미지는 클래식 작성창용이라 노드 모드 생성에는 사용되지 않습니다.",clearParkedRefs:"보관된 참조 비우기",styleSheetActive:"세션 스타일 시트 적용 중"},z1={selectionOn:"선택 중",selectionOff:"선택",selectAll:"전체 선택",summary:"선택 {selected} · 미생성 {missing} · 영향 {stale}",generateMissing:"없는 것만 생성",regenerateSelected:"선택 재생성",stopRemaining:"남은 작업 중단",stopping:"중단 중",clear:"해제",noneSelected:"선택된 노드가 없습니다.",parentRequired:"부모 이미지가 준비되지 않은 선택 노드가 {count}개 있습니다.",nothingToRun:"생성할 선택 노드가 없습니다.",stopQueued:"현재 노드가 끝나면 남은 작업을 중단합니다.",failed:"{done}/{total} 완료 후 중단되었습니다.",finished:"{done}/{total} 노드 작업 완료",staleBecauseParentChanged:"상위 노드가 재생성되어 다시 확인이 필요합니다."},R1={disconnected:"연결선을 끊었습니다.",parentConflict:"한 노드에는 부모 연결을 하나만 둘 수 있습니다."},D1={authTitle:"인증 방식",apiLabel:"API 키",oauthNotReady:"OAuth 프록시가 아직 준비되지 않았습니다.",codexLoginRequired:"Codex 로그인이 필요합니다.",codexLoginHint:"터미널에서 `codex login`을 실행한 뒤 이 페이지를 새로고침하세요.",oauthStarting:"OAuth 프록시가 시작 중입니다. 몇 초 후 다시 시도하세요.",serverUnreachable:"서버에 연결할 수 없습니다. 백엔드가 실행 중인지 확인하세요.",apiInvalid:"API 키가 없거나 유효하지 않습니다. 서버의 .env 파일에서 OPENAI_API_KEY를 확인하세요.",availableTitle:"{name} 사용 가능",availableAria:"{name}: 사용 가능",unavailableAria:"{name}: 사용 불가",availableSr:"(사용 가능)",unavailableSr:"(사용 불가)"},O1={free:"무료",approx:"약 ${amount}",label:"예상 비용"},H1={download:"다운로드",copyImage:"이미지 복사",copyPrompt:"프롬프트 복사",continueHere:"여기서 이어서",continueHereTitle:"이 이미지의 프롬프트를 가져와 이어서 작업"},I1={switchTitle:"세션 전환",loading:"불러오는 중...",newSession:"새 세션",newSessionTitle:"새 세션",renameTitle:"이름 변경",renamePrompt:"세션 이름",deleteTitle:"삭제",deleteConfirm:'"{title}" 세션을 삭제할까요? 이 작업은 되돌릴 수 없습니다.',empty:"아직 세션이 없습니다",firstGraph:"첫 번째 그래프",untitled:"제목 없는 세션",assetAbortedError:"생성이 정상적으로 끝나지 않았습니다. 이 노드에서 다시 시도하세요."},B1={ariaLabel:"UI 모드",classic:"기본",node:"노드",cardNews:"카드뉴스"},L1={workspace:"카드뉴스 작업공간",composer:"카드뉴스",composerHint:"템플릿은 스냅샷 기준이고, 출력 크기는 별도로 지정합니다.",topic:"주제",topicPlaceholder:"예: 중간고사 역전 플랜",audience:"대상",audiencePlaceholder:"예: 학부모",goal:"목표",goalPlaceholder:"예: 상담 신청",brief:"내용",briefPlaceholder:"카드뉴스에 들어갈 핵심 내용과 금지사항을 적어주세요.",outputSize:"출력 크기",customSize:"직접",draft:"초안 만들기",drafting:"초안 작성 중...",generateSet:"세트 생성",batchGenerate:"일괄 생성",generating:"생성 중...",generated:"{count}장 생성 완료.",missingGeneratedCard:"생성 응답에 이 카드가 포함되지 않았습니다.",error:"카드 생성에 실패했습니다.",imageTemplate:"이미지 템플릿",roleTemplate:"카드 구조",newTemplateLater:"커스텀 템플릿은 dev MVP 이후에 지원합니다",emptyTitle:"초안 대기 중",emptyBody:"왼쪽 설정으로 카드 덱을 준비합니다.",inspector:"카드 편집",cardTitle:"카드 제목",headline:"제목",body:"본문",visualPrompt:"이미지 프롬프트",summaryCopy:"요약 문구",designPrompt:"장면 / 디자인 프롬프트",textFields:"텍스트 박스",addTextField:"텍스트 박스 추가",removeTextField:"삭제",noTextFields:"아직 텍스트 박스가 없습니다.",textFieldText:"텍스트",textKind:"종류",placement:"위치",renderMode:"표시 방식",hierarchyLabel:"위계",textTooLong:"권장 길이를 초과했습니다.",selectTextField:"텍스트 박스 선택: {text}",textKinds:{headline:"제목",body:"설명 텍스트",caption:"캡션",cta:"행동 유도",badge:"배지",number:"숫자"},renderModes:{"in-image":"이미지에 표시","ui-only":"메모만"},hierarchy:{primary:"주요",secondary:"보조",supporting:"부가"},placements:{"top-left":"좌측 상단","top-center":"상단 중앙","top-right":"우측 상단","center-left":"좌측 중앙",center:"중앙","center-right":"우측 중앙","bottom-left":"좌측 하단","bottom-center":"하단 중앙","bottom-right":"우측 하단",free:"직접 지정"},roles:{cover:"표지",hook:"후킹",problem:"문제",insight:"인사이트",example:"예시",data:"데이터",summary:"요약",cta:"행동 유도"},locked:"잠김",unlocked:"열림",noCard:"선택된 카드 없음",generatedMeta:"생성 메타데이터",lockedHelp:"잠긴 카드는 일괄 생성과 재시도에서 제외됩니다.",retryCard:"이 카드 재시도",actions:{copyPrompt:"프롬프트 복사",copyCopy:"문구 복사",openImage:"이미지 열기",downloadCard:"다운로드"},status:{draft:"초안",queued:"대기",generating:"생성 중",generated:"완료",error:"오류",skipped:"제외",locked:"잠김"},progress:{generating:"생성 중 {done}/{total}",summary:"완료 {done}/{total}",detail:"대기 {queued} · 오류 {errors} · 제외 {skipped}",cardGenerating:"이 카드를 생성 중입니다."},planner:{structured:"구조화 JSON",jsonMode:"JSON 모드",repaired:"보정됨",fallback:"기본 초안",jsonOnlyHelp:"초안은 JSON만 만들고 이미지는 나중에 생성합니다.",error:"초안 생성 실패"}},k1={appName:"이미지 생성기",imageModelLabel:"모델",imageModelAria:"이미지 모델 선택",nodeModeHint:"노드 모드에서는 노드를 눌러 프롬프트를 수정한 뒤 생성하세요. 오른쪽 패널의 설정 (품질/크기)은 새로 만드는 모든 결과에 적용됩니다."},U1={openAria:"설정 열기",openTitle:"설정",closeAria:"설정 닫기",closeTitle:"캔버스로 돌아가기",navAria:"설정 섹션",contentAria:"설정 내용",jumpTo:"{section} 섹션으로 이동",eyebrow:"작업공간 설정",title:"설정",subtitle:"계정, 화면, 앞으로 늘어날 작업공간 옵션을 이곳에 모아 생성 흐름은 가볍게 유지합니다.",sections:{account:{title:"계정",hint:"OAuth 상태"},generation:{title:"생성",hint:"모델 기본값"},appearance:{title:"화면",hint:"라이트/다크"},language:{title:"언어",hint:"UI 문구"},future:{title:"예정",hint:"확장 공간"}},account:{primaryEyebrow:"현재 공급자",oauthTitle:"OAuth 사용 중",oauthBody:"현재 생성은 Codex OAuth 세션으로 실행됩니다. 이 빌드에서는 API-Key 생성 모드가 비활성화되어 있습니다.",apiSourceEnv:"OPENAI_API_KEY 감지됨",apiSourceConfig:"config.json API 키 감지됨",apiTitle:"Configured but disabled",apiBody:"env/config에서 API 키를 찾았지만, 지금 ima2-gen은 OAuth 전용으로 동작합니다. 이 상태 표시를 숨기고 싶을 때만 키를 제거하세요.",apiDisabled:"비활성화",apiUnknown:"상태 불명"},imageModel:{title:"이미지 모델",body:"앞으로 생성 요청에 사용할 OAuth 이미지 모델을 선택합니다.",gpt54Mini:"GPT-5.4 Mini",gpt54:"GPT-5.4",gpt55:"GPT-5.5",gpt53CodexSpark:"GPT-5.3 Codex Spark — 이미지 생성 미지원",unsupportedHelp:"기본값은 GPT-5.4 Mini입니다. GPT-5.3 Codex Spark는 OAuth 모델 상태에 보일 수 있지만 image_generation 도구를 지원하지 않습니다."},appearance:{themeTitle:"테마",themeBody:"이 기기에서 작업공간을 어떤 톤으로 볼지 선택합니다."},language:{title:"언어",body:"생성 프롬프트와 무관하게 인터페이스 언어만 바꿉니다."},future:{title:"나중을 위한 자리",body:"OAuth 복구 도구나 작업공간 옵션이 실제로 필요해지면 이곳에 추가합니다."}},q1={loading:"세션 불러오는 중...",addFirst:"+ 첫 노드 추가",addRootTitle:"루트 노드 추가",hint:"핸들을 빈 공간으로 드래그하면 새 브랜치가 생깁니다. Delete 또는 Backspace로 삭제할 수 있습니다."},G1={title:"{provider} 사용 불가",ariaLabel:"{provider} 사용 불가"},Y1={label:"언어",ko:"한국어",en:"English"},V1={label:"테마",system:"시스템",dark:"다크",light:"라이트"},X1={toggle:"스타일 일관성 적용",extract:"프롬프트에서 추출",extracting:"추출 중…",edit:"편집",save:"저장",cancel:"취소",emptyHint:"아직 스타일 시트가 없어요. 현재 프롬프트에서 추출해서 룩을 고정하세요.",noPrompt:"먼저 프롬프트를 입력하세요",extracted:"스타일 시트가 추출됐어요",editorTitle:"스타일 시트 편집",saved:"스타일 시트를 저장했어요",errNoKey:"스타일 시트 추출에는 OpenAI API 키가 필요해요. setup에서 연결해주세요.",errBadOutput:"모델이 사용 가능한 시트를 못 만들었어요 — 프롬프트를 더 구체적으로 적어주세요.",placeholderMedium:"예: 유화, 시네마틱 사진",placeholderComposition:"예: 중앙 인물, 와이드 풍경",placeholderMood:"예: 시네마틱, 몽환적",placeholderSubject:"예: 빨간 재킷 입은 젊은 여성",placeholderPalette:"#0a0a0a, #f97316, 따뜻한 앰버",placeholderNegative:"blur, 워터마크, 텍스트",fields:{medium:"매체",composition:"구도",mood:"분위기",subject:"피사체 디테일",palette:"팔레트 (쉼표로 구분된 hex 또는 이름)",negative:"네거티브 (쉼표로 구분)"}},$1={close:"닫기",details:"자세한 원본 오류 보기",unknown:{title:"알 수 없는 오류가 발생했어요",body:"잠시 후 다시 시도해 주세요. 문제가 계속되면 원본 오류 메시지를 복사해 제보해 주세요."},moderationRefused:{title:"프롬프트가 모더레이션에 걸렸어요",body:"표현 수위를 낮추거나 다른 문구로 바꿔 보세요. 레퍼런스 이미지의 선정적/폭력적 요소도 영향을 줄 수 있어요.",cta:"프롬프트 수정"},upstream5xx:{title:"OpenAI 서버가 혼잡합니다",body:"잠시 후 다시 시도하면 대부분 해결돼요. 상태 페이지(status.openai.com)도 확인해 보세요.",cta:"다시 시도"},authChatgptExpired:{title:"Codex ChatGPT 로그인이 만료됐어요",body:"터미널에서 `npx @openai/codex login`을 다시 실행한 뒤 앱을 새로고침해 주세요.",cta:"새로고침"},authApiKeyInvalid:{title:"API 키 인증 실패",body:"키가 잘못됐거나 한도/조직 권한 문제예요. 본 앱은 API-Key 모드가 비활성화되어 있어 OAuth(ChatGPT 로그인)로 전환하는 편이 좋아요.",cta:"확인"},networkFailed:{title:"네트워크 연결 실패",body:"OpenAI 또는 로컬 런타임 서비스에 연결하지 못했어요. 먼저 새로고침하고, 계속되면 VPN/방화벽과 `ima2 doctor`에 표시되는 포트를 확인해 주세요.",cta:"새로고침"},oauthUnavailable:{title:"OAuth 프록시를 사용할 수 없어요",body:"OAuth 프록시가 아직 시작 중이거나, 사용할 수 없거나, fallback 포트로 이동했을 수 있어요. 먼저 새로고침하고, 계속되면 `ima2 doctor`의 OAuth URL을 확인해 주세요.",cta:"새로고침"},apikeyDisabled:{title:"API-Key 모드가 비활성화되어 있어요",body:"본 앱은 OAuth(ChatGPT 로그인) 전용으로 동작합니다. 공급자를 OAuth로 전환해 주세요.",cta:"확인"}},Z1={common:g1,toast:m1,inflight:p1,size:y1,sizeConfirm:v1,quality:x1,moderation:b1,format:S1,count:w1,generate:N1,billing:_1,history:E1,panel:C1,prompt:T1,canvas:A1,gallery:M1,node:j1,nodeBatch:z1,edge:R1,provider:D1,cost:O1,result:H1,session:I1,uiMode:B1,cardNews:L1,sidebar:k1,settings:U1,nodeCanvas:q1,apiDisabled:G1,language:Y1,theme:V1,styleSheet:X1,errorCard:$1},K1={ok:"OK",cancel:"Cancel",delete:"Delete",close:"Close"},Q1={localStorageFull:"Local storage is full — recent state may not persist.",refLimitExceeded:"References are capped at 5. Extra images were dropped.",refTooLarge:"Image is too large. Convert to JPEG/PNG or lower the resolution and try again.",refNotBase64:"Image file is corrupted or uses an unsupported encoding.",refEmpty:"Empty image file. Please pick a different file.",refHeicUnsupported:"HEIC/HEIF is not supported. Convert to JPEG or PNG and try again.",noCurrentImageForRef:"No current image to use as reference.",refSlotFull:"Reference slots are full (max 5).",currentImageLoadFailed:"Failed to load current image.",addedCurrentAsRef:"Added current image as a reference.",sessionLoadFailed:"Failed to load session.",sessionCreateFailed:"Failed to create session.",sessionRenameFailed:"Failed to rename session.",sessionDeleteFailed:"Failed to delete session.",promptRequired:"Enter a prompt.",nodeCreated:"Node {id} created ({elapsed}s)",nodeCreateFailed:"Node generation failed.",generatedBatch:"Generated {count} images in {elapsed}s.",generatedSingle:"Generated in {elapsed}s.",generateFailed:"Generation failed.",sessionReloadedElsewhere:"Graph version changed, so the latest graph was reloaded.",promptCopied:"Prompt copied",imageCopied:"Copied to clipboard",copyFailed:"Copy failed",openGeneratedDirFailed:"Could not open the image folder. Run ima2 doctor to check the storage path.",noPromptToFork:"No prompt to fork",forkStarted:"Prompt imported. Edit and generate again."},F1={queued:"Queued",streaming:"Generating",decoding:"Finalizing"},P1={title:"Size",width:"Width",height:"Height",hint:"Each side 1024–3824, multiple of 16, ratio up to 3:1",autoLabel:"Auto",autoSub:"Model pick",customLabel:"Custom",customSub:"Free form"},J1={title:"Size adjustment required",body:"The requested size is outside the image generation limits.",requested:"Requested size",adjusted:"Adjusted size",approve:"Approve and generate",cancel:"Cancel",reasonRatio:"The ratio exceeds the 3:1 limit.",reasonPixels:"The maximum pixel limit is exceeded.",reasonMin:"The size is below the minimum.",reasonMax:"The size is above the maximum.",reasonSnap:"The size must align to 16px increments."},W1={title:"Quality",lowLabel:"Low",lowSub:"Fast",mediumLabel:"Medium",mediumSub:"Balanced",highLabel:"High",highSub:"Best"},ew={title:"Moderation",autoLabel:"Auto",autoSub:"Standard filter",lowLabel:"Low",lowSub:"Relaxed filter",explain:"Auto uses the standard safety filter. Low relaxes limits so borderline prompts may pass through."},tw={title:"Format"},nw={title:"Count"},aw={button:"Generate",buttonLoading:"Generating ({n})"},iw={label:"API Status",checking:"Checking...",offline:"Offline",remaining:"${remaining} remaining",thisMonth:"${amount} this month",oauthFree:"OAuth · free via codex",apiDisabled:"API key disabled (OAuth only)",oauthMode:"OAuth mode"},lw={openGalleryAria:"Open gallery",openGalleryTitle:"Open full gallery"},ow={closeSettings:"Close settings",detailSettings:"Settings",toggleShow:"Show settings",toggleHide:"Hide settings",open:"Open",close:"Close"},sw={label:"Prompt",refCount:"Refs {count}/{max}",refChipTitle:"Reference {n}",refChipAlt:"Reference {n}",refRemoveAria:"Remove reference {n}",placeholder:"Describe the image you want. Drag & drop or paste to attach reference images...",placeholderWithRefs:"Describe what to do with the attached images...",attach:"Attach",attachTitle:"Attach reference images",useCurrent:"Use current",useCurrentTitle:"Use current result as a reference",style:"Style",styleTitle:"Open style consistency settings",directMode:"Direct",directModeTitle:"Pass prompt through verbatim (Direct mode)",hint:"Ctrl + Enter to generate",dropHere:"Drop to attach as reference (up to {max})"},rw={resultAlt:"result",imageViewerAria:"Generated image viewer. Use left and right arrow keys to move between images.",tokens:"{n} tokens"},cw={today:"Today",yesterday:"Yesterday",thisWeek:"This week",earlier:"Earlier",imageAltFallback:"Generated image",deleteTitle:"Delete (10s undo)",deleteAria:"Delete image",ariaLabel:"Image gallery",title:"Gallery",total:"{n} total",totalFiltered:" / {n} total",sortByAria:"Sort by",sortByDate:"Date",sortBySession:"Session",searchPlaceholder:"Search prompts or filenames",searchDisabledPlaceholder:"Search is disabled in session view",closeAria:"Close gallery",closeTitle:"Close (Esc)",sessionLabel:"Session {name}",standalone:"Standalone images",emptySessions:"No sessions saved yet.",emptyAll:"No images yet. Create one first.",noResults:"No results.",storageNoticeTitle:"Storage notice",storageNoticeRecoverable:"Sorry for the scare. Recent versions moved the gallery folder from the installed package to your user data folder. Your old images may still be in the previous generated folder. Run ima2 doctor or open the recovery guide.",storageNoticeNotFound:"Sorry for the scare. We could not find a previous generated folder on this machine. If the old global install folder was replaced during update, automatic recovery may not be possible. Run ima2 doctor and check the recovery guide for manual search steps.",storageNoticeUnknown:"Storage status could not be checked. If the gallery looks empty after an update, run ima2 doctor to inspect the image folder.",openGeneratedDir:"Open folder",openGeneratedDirTitle:"Open generated image folder",cardNewsSet:"Card News set",cardNewsCard:"Card News card",openCardNewsSet:"Open set",openCardNewsSetFailed:"Could not open the Card News set.",copyCardNewsSetPath:"Copy path",cardNewsPathCopied:"Card News set path copied.",downloadCardNewsManifest:"Manifest",cardNewsCount:"{n} cards",deleted:"Deleted: {filename}",undo:"Undo",secondsSuffix:"{n}s"},uw={empty:"Empty",pending:"Generating",reconciling:"Syncing",reconcilingPhase:"Syncing · {phase}",ready:"Done · {elapsed}s",readyWithSearch:"Done · {elapsed}s · searched {searches}",stale:"Stale",staleWithError:"Stale: {error}",assetMissing:"Asset missing",assetMissingWithError:"Asset missing: {error}",error:"Error: {error}",errorUnknown:"unknown",nodeImageAlt:"Node image",partialImageAlt:"Partial node image preview",noAsset:"No asset",stateStale:"State stale",noImage:"No image",editPromptPlaceholder:"Edit prompt...",promptPlaceholder:"Prompt...",regenerate:"Regen",newVariation:"New variant",generate:"Generate",addChild:"Child",addChildTitle:"Add child node",duplicateBranch:"Branch",duplicateBranchTitle:"Duplicate as a new branch root",deleteTitle:"Delete",regenerateTitle:"Regenerate this node in place",newVariationTitle:"Create a new sibling variant under the same parent",parentImageRequired:"Generate the parent image first.",attachRef:"Attach",attachRefTitle:"Attach node reference images",refAlt:"Node reference {n}",removeRef:"Remove reference {n}",dropRefs:"Drop images here",nodeRefsUnsupportedForEdit:"Extra references are only supported on root nodes for now.",nodeRefsUsedWithParent:"Used together with the parent image.",classicRefsParkedTitle:"Classic references are parked",classicRefsParkedBody:"These images belong to the classic composer and are inactive in node mode.",clearParkedRefs:"Clear parked references",styleSheetActive:"Session style sheet active"},dw={selectionOn:"Selecting",selectionOff:"Select",selectAll:"Select all",summary:"{selected} selected · {missing} missing · {stale} affected",generateMissing:"Generate missing",regenerateSelected:"Regenerate selected",stopRemaining:"Stop remaining",stopping:"Stopping",clear:"Clear",noneSelected:"No nodes selected.",parentRequired:"{count} selected node(s) need a ready parent image first.",nothingToRun:"No selected nodes need generation.",stopQueued:"The current node will finish, then the remaining queue will stop.",failed:"Stopped after {done}/{total} node(s).",finished:"Finished {done}/{total} node(s).",staleBecauseParentChanged:"An upstream node was regenerated; refresh this node when needed."},fw={disconnected:"Connection removed.",parentConflict:"A node can only have one parent connection."},hw={authTitle:"Authentication",apiLabel:"API Key",oauthNotReady:"OAuth proxy is not ready yet.",codexLoginRequired:"Codex login required.",codexLoginHint:"Run `codex login` in your terminal, then refresh this page.",oauthStarting:"OAuth proxy is starting. Try again in a few seconds.",serverUnreachable:"Cannot reach the server. Make sure the backend is running.",apiInvalid:"API key is missing or invalid. Check OPENAI_API_KEY in the server's .env.",availableTitle:"{name} available",availableAria:"{name}: available",unavailableAria:"{name}: unavailable",availableSr:"(available)",unavailableSr:"(unavailable)"},gw={free:"free",approx:"~${amount}",label:"Est. cost"},mw={download:"Download",copyImage:"Copy image",copyPrompt:"Copy prompt",continueHere:"Continue here",continueHereTitle:"Import this image's prompt and keep working"},pw={switchTitle:"Switch session",loading:"Loading...",newSession:"New session",newSessionTitle:"New session",renameTitle:"Rename",renamePrompt:"Session name",deleteTitle:"Delete",deleteConfirm:'Delete session "{title}"? This cannot be undone.',empty:"No sessions yet",firstGraph:"My first graph",untitled:"Untitled session",assetAbortedError:"Generation did not finish cleanly. Retry from this node."},yw={ariaLabel:"UI mode",classic:"Classic",node:"Node",cardNews:"Card News"},vw={workspace:"Card News workspace",composer:"Card News",composerHint:"Templates are visual snapshots; output size is set separately.",topic:"Topic",topicPlaceholder:"e.g. Exam comeback plan",audience:"Audience",audiencePlaceholder:"e.g. Parents",goal:"Goal",goalPlaceholder:"e.g. Book a consultation",brief:"Brief",briefPlaceholder:"Describe the card news content, required points, and exclusions.",outputSize:"Output size",customSize:"Custom",draft:"Draft outline",drafting:"Drafting...",generateSet:"Generate set",batchGenerate:"Batch generate",generating:"Generating...",generated:"Generated {count} cards.",missingGeneratedCard:"The generation response did not include this card.",error:"Card generation failed.",imageTemplate:"Image template",roleTemplate:"Card structure",newTemplateLater:"Custom templates are planned after the dev MVP",emptyTitle:"Waiting for a draft",emptyBody:"Use the left setup panel to prepare the card deck.",inspector:"Card inspector",cardTitle:"Card title",headline:"Headline",body:"Body",visualPrompt:"Image prompt",summaryCopy:"Summary copy",designPrompt:"Scene / design prompt",textFields:"Text boxes",addTextField:"Add text box",removeTextField:"Remove",noTextFields:"No text boxes yet.",textFieldText:"Text",textKind:"Kind",placement:"Placement",renderMode:"Render mode",hierarchyLabel:"Hierarchy",textTooLong:"Text exceeds the suggested length.",selectTextField:"Select text box: {text}",textKinds:{headline:"Headline",body:"Supporting text",caption:"Caption",cta:"CTA",badge:"Badge",number:"Number"},renderModes:{"in-image":"In image","ui-only":"UI only"},hierarchy:{primary:"Primary",secondary:"Secondary",supporting:"Supporting"},placements:{"top-left":"Top-left","top-center":"Top-center","top-right":"Top-right","center-left":"Center-left",center:"Center","center-right":"Center-right","bottom-left":"Bottom-left","bottom-center":"Bottom-center","bottom-right":"Bottom-right",free:"Free"},roles:{cover:"Cover",hook:"Hook",problem:"Problem",insight:"Insight",example:"Example",data:"Data",summary:"Summary",cta:"CTA"},locked:"Locked",unlocked:"Unlocked",noCard:"No card selected",generatedMeta:"Generated metadata",lockedHelp:"Locked cards are excluded from batch generation and retry.",retryCard:"Retry this card",actions:{copyPrompt:"Copy prompt",copyCopy:"Copy copy",openImage:"Open image",downloadCard:"Download"},status:{draft:"Draft",queued:"Queued",generating:"Generating",generated:"Done",error:"Error",skipped:"Skipped",locked:"Locked"},progress:{generating:"Generating {done}/{total}",summary:"Done {done}/{total}",detail:"{queued} queued · {errors} errors · {skipped} skipped",cardGenerating:"Generating this card."},planner:{structured:"Structured JSON",jsonMode:"JSON mode",repaired:"Repaired",fallback:"Fallback draft",jsonOnlyHelp:"Draft creates JSON only. Images are generated later.",error:"Draft failed"}},xw={appName:"Image Generator",imageModelLabel:"Model",imageModelAria:"Choose image model",nodeModeHint:"In node mode, click a node to edit its prompt and generate. Settings on the right panel (quality/size) apply to every new result."},bw={openAria:"Open settings",openTitle:"Settings",closeAria:"Close settings",closeTitle:"Return to canvas",navAria:"Settings sections",contentAria:"Settings content",jumpTo:"Jump to {section}",eyebrow:"Workspace settings",title:"Settings",subtitle:"Account, display, and future workspace controls live here so the generator stays focused.",sections:{account:{title:"Account",hint:"OAuth status"},generation:{title:"Generation",hint:"Model defaults"},appearance:{title:"Appearance",hint:"Light and dark"},language:{title:"Language",hint:"Interface copy"},future:{title:"Future",hint:"Reserved"}},account:{primaryEyebrow:"Active provider",oauthTitle:"OAuth is active",oauthBody:"Generation currently runs through your Codex OAuth session. API-key generation remains disabled in this build.",apiSourceEnv:"OPENAI_API_KEY detected",apiSourceConfig:"config.json API key detected",apiTitle:"Configured but disabled",apiBody:"ima2-gen found an API key in env/config, but the app is OAuth-only right now. Remove the key only if you do not want this status shown.",apiDisabled:"Disabled",apiUnknown:"Status unknown"},imageModel:{title:"Image model",body:"Choose the OAuth model used for future image generations.",gpt54Mini:"GPT-5.4 Mini",gpt54:"GPT-5.4",gpt55:"GPT-5.5",gpt53CodexSpark:"GPT-5.3 Codex Spark — unsupported for images",unsupportedHelp:"Default is GPT-5.4 Mini. GPT-5.3 Codex Spark may appear in OAuth model status, but it does not support the image_generation tool."},appearance:{themeTitle:"Theme",themeBody:"Choose how the workspace should look on this device."},language:{title:"Language",body:"Switch the UI language without changing generated content."},future:{title:"Reserved for later",body:"Future provider repair and workspace controls will appear here when they become useful."}},Sw={loading:"Loading session...",addFirst:"+ Add first node",addRootTitle:"Add root node",hint:"Drag a handle into empty space to branch. Press Delete or Backspace to remove."},ww={title:"{provider} unavailable",ariaLabel:"{provider} unavailable"},Nw={label:"Language",ko:"한국어",en:"English"},_w={label:"Theme",system:"System",dark:"Dark",light:"Light"},Ew={toggle:"Apply style consistency",extract:"Extract from prompt",extracting:"Extracting…",edit:"Edit",save:"Save",cancel:"Cancel",emptyHint:"No style sheet yet. Extract from the current prompt to lock in a look.",noPrompt:"Enter a prompt first",extracted:"Style sheet extracted",editorTitle:"Edit style sheet",saved:"Style sheet saved",errNoKey:"Style-sheet extraction needs an OpenAI API key. Connect one via setup.",errBadOutput:"Model returned an unusable sheet — try a more specific prompt.",placeholderMedium:"e.g. oil painting, cinematic photo",placeholderComposition:"e.g. centered portrait, wide landscape",placeholderMood:"e.g. cinematic, dreamlike",placeholderSubject:"e.g. young woman in red jacket",placeholderPalette:"#0a0a0a, #f97316, warm amber",placeholderNegative:"blur, watermark, text",fields:{medium:"Medium",composition:"Composition",mood:"Mood",subject:"Subject details",palette:"Palette (comma-separated hex or names)",negative:"Negative (comma-separated)"}},Cw={close:"Close",details:"Show raw error details",unknown:{title:"An unexpected error occurred",body:"Please try again shortly. If it persists, copy the raw error message below and report it."},moderationRefused:{title:"Prompt blocked by moderation",body:"Soften the wording or rephrase. Sensitive/violent content in reference images can also trigger this.",cta:"Edit prompt"},upstream5xx:{title:"OpenAI is currently busy",body:"Retrying usually resolves this. Check status.openai.com if it persists.",cta:"Retry"},authChatgptExpired:{title:"Codex ChatGPT session expired",body:"Run `npx @openai/codex login` in your terminal, then reload this app.",cta:"Reload"},authApiKeyInvalid:{title:"API key authentication failed",body:"The key is invalid, revoked, out of quota, or tied to the wrong org. This app runs in OAuth mode, so switch to ChatGPT login.",cta:"OK"},networkFailed:{title:"Network connection failed",body:"Could not reach OpenAI or the local runtime service. Reload first; if it persists, check VPN/firewall and the port shown by `ima2 doctor`.",cta:"Reload"},oauthUnavailable:{title:"OAuth proxy unavailable",body:"The OAuth proxy is starting, unavailable, or moved to a fallback port. Reload first; if it persists, run `ima2 doctor` and check the reported OAuth URL.",cta:"Reload"},apikeyDisabled:{title:"API-key mode is disabled",body:"This app is OAuth-only (ChatGPT login). Switch the provider to OAuth.",cta:"OK"}},Tw={common:K1,toast:Q1,inflight:F1,size:P1,sizeConfirm:J1,quality:W1,moderation:ew,format:tw,count:nw,generate:aw,billing:iw,history:lw,panel:ow,prompt:sw,canvas:rw,gallery:cw,node:uw,nodeBatch:dw,edge:fw,provider:hw,cost:gw,result:mw,session:pw,uiMode:yw,cardNews:vw,sidebar:xw,settings:bw,nodeCanvas:Sw,apiDisabled:ww,language:Nw,theme:_w,styleSheet:Ew,errorCard:Cw},Hp={ko:Z1,en:Tw};function Ip(t,i){return i.split(".").reduce((l,o)=>{if(l!=null)return l[o]},t)}function Aw(t,i){return t.replace(/\{(\w+)\}/g,(l,o)=>o in i?String(i[o]):`{${o}}`)}function ve(t,i){const l=W.getState().locale;return p0(l,t,i)}function p0(t,i,l){const o=Ip(Hp[t],i),r=typeof o=="string"?o:Ip(Hp.en,i),u=typeof r=="string"?r:i;return l?Aw(u,l):u}function Te(){const t=W(i=>i.locale);return{locale:t,t:(i,l)=>p0(t,i,l)}}const Mw=["ko","en"];function jw(){try{const t=localStorage.getItem("ima2.locale");if(t==="ko"||t==="en")return t}catch{}return typeof navigator<"u"&&(navigator.language||"").toLowerCase().startsWith("ko")?"ko":"en"}function zw(t){try{localStorage.setItem("ima2.locale",t)}catch{}}function Rw(t){return Math.round(t/16)*16}const y0=1024,v0=3824,hr=3,zd=8294400;function Bp(t){return Math.floor(t/16)*16}function Lp(t){return Math.ceil(t/16)*16}function ti(t){return Math.min(v0,Math.max(y0,t))}function sl(t,i){const l=typeof t=="number"?t:Number.parseInt(t,10);return Number.isFinite(l)?l:i}function rl(t,i){t.includes(i)||t.push(i)}function kp(t,i){const l=Rw(t);return l!==t&&rl(i,"snap"),l}function Up(t,i){return t<y0&&rl(i,"min"),t>v0&&rl(i,"max"),ti(t)}function qp(t,i,l){return t>i*hr?(rl(l,"ratio"),{w:t,h:ti(Lp(t/hr))}):i>t*hr?(rl(l,"ratio"),{w:ti(Lp(i/hr)),h:i}):{w:t,h:i}}function Dw(t,i,l){if(t*i<=zd)return{w:t,h:i};rl(l,"pixels");const o=Math.sqrt(zd/(t*i));let r=ti(Bp(t*o)),u=ti(Bp(i*o));for(;r*u>zd;)r>=u?r=ti(r-16):u=ti(u-16);return{w:r,h:u}}function Ow(t,i,l,o){const r=[],u=sl(t,l),d=sl(i,o);let g=Up(kp(u,r),r),p=Up(kp(d,r),r);return{w:g,h:p}=qp(g,p,r),{w:g,h:p}=Dw(g,p,r),{w:g,h:p}=qp(g,p,r),{requestedW:u,requestedH:d,w:g,h:p,adjusted:g!==u||p!==d,reasons:r}}const Hw=[{value:"1024x1024",label:"1024×1024",sub:"1:1"},{value:"1536x1024",label:"1536×1024",sub:"3:2"},{value:"1024x1536",label:"1024×1536",sub:"2:3"}],Iw=[{value:"1360x1024",label:"1360×1024",sub:"4:3"},{value:"1024x1360",label:"1024×1360",sub:"3:4"},{value:"1824x1024",label:"1824×1024",sub:"16:9"}],Bw=[{value:"1024x1824",label:"1024×1824",sub:"9:16"},{value:"2048x2048",label:"2048×2048",sub:"2K 1:1"},{value:"2048x1152",label:"2048×1152",sub:"2K 16:9"}],Lw=[{value:"1152x2048",label:"1152×2048",sub:"2K 9:16"},{value:"3824x2160",label:"3824×2160",sub:"4K 16:9"},{value:"2160x3824",label:"2160×3824",sub:"4K 9:16"}];function kw(){return[{value:"auto",label:ve("size.autoLabel"),sub:ve("size.autoSub")},{value:"custom",label:ve("size.customLabel"),sub:ve("size.customSub")}]}const Uw="gpt-5.4-mini",x0="ima2.imageModel",tl=[{value:"gpt-5.4-mini",shortLabel:"5.4m",fullLabelKey:"settings.imageModel.gpt54Mini"},{value:"gpt-5.4",shortLabel:"5.4",fullLabelKey:"settings.imageModel.gpt54"},{value:"gpt-5.5",shortLabel:"5.5",fullLabelKey:"settings.imageModel.gpt55"}],qw=[{value:"gpt-5.3-codex-spark",fullLabelKey:"settings.imageModel.gpt53CodexSpark"}];function Gw(t){return tl.some(i=>i.value===t)}function b0(t){return t?tl.find(i=>i.value===t)?.shortLabel??t:null}const Ji=()=>"nc_"+Math.random().toString(36).slice(2,10);function Gp(t,i){return{x:t*360,y:i*320}}function Yw(t,i){return t.find(l=>l.target===i)??null}function Vw(t,i,l){return t.some(o=>o.target===l&&o.source!==i)}function _a(t,i){const l=new Map(t.map(o=>[o.id,o]));return t.map(o=>{const r=Yw(i,o.id),d=(r?l.get(r.source):null)?.data.serverNodeId??null;return o.data.parentServerNodeId===d?o:{...o,data:{...o.data,parentServerNodeId:d}}})}const Xw=360,S0=320;function $w(t,i,l){const o=new Set(l.filter(r=>r.source===t).map(r=>r.target));return i.filter(r=>o.has(r.id))}function Yp(t){const i=t.filter(o=>!o.data.parentServerNodeId);if(i.length===0)return Gp(0,0);const l=Math.max(...i.map(o=>o.position.y));return{x:Gp(0,0).x,y:l+S0}}function Vp(t,i,l){const o=$w(t.id,i,l),r=t.position.x+Xw;if(o.length===0)return{x:r,y:t.position.y};const u=Math.max(...o.map(d=>d.position.y));return{x:r,y:u+S0}}const w0="ima2.nodeRefs.v1";function pf(){try{const t=localStorage.getItem(w0);if(!t)return{};const i=JSON.parse(t);return i&&typeof i=="object"?i:{}}catch{return{}}}function N0(t){try{localStorage.setItem(w0,JSON.stringify(t))}catch{}}function Zw(t,i){if(!t)return[];const l=pf()[t]?.[i];return Array.isArray(l)?l.filter(o=>typeof o=="string"):[]}function Cr(t,i,l){if(!t)return;const o=pf(),r={...o[t]??{}};l.length===0?delete r[i]:r[i]=l,o[t]=r,N0(o)}function Rd(t,i){Cr(t,i,[])}function Kw(t,i){if(!t)return;const l=pf(),o=l[t];if(!o)return;const r=new Set(i);for(const u of Object.keys(o))r.has(u)||delete o[u];l[t]=o,N0(l)}function Qw(t,i,l){const o=new Set(t.map(g=>g.id));if(!o.has(l))return[];const r=new Map;for(const g of o)r.set(g,new Set);for(const g of i)!o.has(g.source)||!o.has(g.target)||(r.get(g.source)?.add(g.target),r.get(g.target)?.add(g.source));const u=new Set,d=[l];for(let g=0;g<d.length;g++){const p=d[g];if(!u.has(p)){u.add(p);for(const y of r.get(p)??[])u.has(y)||d.push(y)}}return t.filter(g=>u.has(g.id)).map(g=>g.id)}function _0(t){return t.filter(i=>i.selected).map(i=>i.id)}function So(t,i){const l=new Set(i);return t.map(o=>({...o,selected:l.has(o.id)}))}function Fw(t,i,l,o){const r=new Set(Qw(t,i,l));if(!r.size)return t;if(!o)return So(t,r);const u=t.find(p=>p.id===l),d=t.some(p=>r.has(p.id)&&p.selected),g=new Set(_0(t));if(d)u?.selected?g.delete(l):g.add(l);else for(const p of r)g.add(p);return So(t,g)}function E0(t){return t.data.status==="ready"&&!!t.data.imageUrl}function Pw(t,i,l){const o=new Set(l),r=new Set(t.map(v=>v.id)),u=new Map,d=new Map;for(const v of o)r.has(v)&&(u.set(v,0),d.set(v,[]));for(const v of i)!o.has(v.source)||!o.has(v.target)||(d.get(v.source)?.push(v.target),u.set(v.target,(u.get(v.target)??0)+1));const g=t.map(v=>v.id),p=g.filter(v=>o.has(v)&&(u.get(v)??0)===0),y=[];for(let v=0;v<p.length;v++){const x=p[v];y.push(x);for(const S of d.get(x)??[])u.set(S,(u.get(S)??0)-1),(u.get(S)??0)===0&&p.push(S)}const m=new Set(y);return y.concat(g.filter(v=>o.has(v)&&!m.has(v)))}function C0(t,i){const l=new Set(i),o=new Set,r=new Map;for(const d of t){const g=r.get(d.source)??[];g.push(d.target),r.set(d.source,g)}const u=[...l];for(let d=0;d<u.length;d++)for(const g of r.get(u[d])??[])l.has(g)||o.has(g)||(o.add(g),u.push(g));return[...o]}function Jw(t,i,l){const o=new Set(l);return t.filter(r=>r.source===i&&!o.has(r.target)).map(r=>r.target)}function Ww(t,i,l){const o=new Set(l),r=new Map(t.map(d=>[d.id,d])),u=[];for(const d of i){if(!o.has(d.target)||o.has(d.source))continue;r.get(d.source)?.data.serverNodeId||u.push(d.target)}return u}const wo={REF_TOO_LARGE:{surface:"toast",toastKey:"toast.refTooLarge"},REF_NOT_BASE64:{surface:"toast",toastKey:"toast.refNotBase64"},REF_EMPTY:{surface:"toast",toastKey:"toast.refEmpty"},REF_TOO_MANY:{surface:"toast",toastKey:"toast.refLimitExceeded"},MODERATION_REFUSED:{surface:"card",cardKey:"errorCard.moderationRefused",cta:"dismiss"},SAFETY_REFUSAL:{surface:"card",cardKey:"errorCard.moderationRefused",cta:"dismiss"},UPSTREAM_5XX:{surface:"card",cardKey:"errorCard.upstream5xx",cta:"retry"},AUTH_CHATGPT_EXPIRED:{surface:"card",cardKey:"errorCard.authChatgptExpired",cta:"reauth"},AUTH_API_KEY_INVALID:{surface:"card",cardKey:"errorCard.authApiKeyInvalid",cta:"dismiss"},NETWORK_FAILED:{surface:"card",cardKey:"errorCard.networkFailed",cta:"reload"},OAUTH_UNAVAILABLE:{surface:"card",cardKey:"errorCard.oauthUnavailable",cta:"reload"},INVALID_MODERATION:{surface:"toast",toastKey:"toast.generateFailed"},APIKEY_DISABLED:{surface:"card",cardKey:"errorCard.apikeyDisabled",cta:"dismiss"},DB_ERROR:{surface:"toast",toastKey:"toast.generateFailed"},UNKNOWN:{surface:"toast",toastKey:"toast.generateFailed"}};function eN(t){const i=(t||"").toLowerCase();return i?i.includes("moderation_blocked")||i.includes("moderation refused")?"MODERATION_REFUSED":i.includes("token is expired")||i.includes("sign in again")||i.includes("access token")&&i.includes("expired")||i.includes("token")&&i.includes("expired")&&!i.includes("api key")?"AUTH_CHATGPT_EXPIRED":i.includes("incorrect api key")||i.includes("invalid authentication")||i.includes("exceeded your current quota")||i.includes("incorrect organization")?"AUTH_API_KEY_INVALID":i.includes("failed to fetch")||i.includes("econnrefused")||i.includes("econnreset")||i.includes("enotfound")||i.includes("etimedout")||i.includes("network error")?"NETWORK_FAILED":i.includes("oauth")&&(i.includes("not running")||i.includes("unavailable")||i.includes("not ready"))?"OAUTH_UNAVAILABLE":i.includes("an error occurred while processing")||/\b5\d\d\b/.test(i)?"UPSTREAM_5XX":"UNKNOWN":"UNKNOWN"}function tN(t){const i=t,l=typeof i?.message=="string"?i.message:String(t??""),o=typeof i?.code=="string"?i.code:"",r=o&&o in wo?o:eN(l),u=wo[r]??wo.UNKNOWN;return{code:r,spec:u,message:l}}function Xp(t,i){const{code:l,spec:o,message:r}=tN(t);if(o.surface==="card")i.showErrorCard(l,{fallbackMessage:r});else{const u=o.toastKey?ve(o.toastKey):r||ve("toast.generateFailed");i.showToast(u,!0)}return{code:l,message:r}}const yf=!0,T0=!1;function nN(){try{const t=localStorage.getItem("ima2.rightPanelOpen");return t===null?!0:JSON.parse(t)===!0}catch{return!0}}function aN(){try{const t=localStorage.getItem("ima2.uiMode");if(t==="card-news")return T0?t:"classic";if(t==="node")return yf?t:"classic";if(t==="classic")return t}catch{}return"classic"}function Dd(){try{const t=localStorage.getItem("ima2:theme");if(t==="system"||t==="dark"||t==="light")return t}catch{}return"system"}function $p(){try{const t=localStorage.getItem(x0);if(Gw(t))return t}catch{}return Uw}function iN(t){try{localStorage.setItem(x0,t)}catch{}}function gr(t){return t==="dark"||t==="light"?t:typeof window>"u"||typeof window.matchMedia!="function"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}const A0=18e4;function Od(t){const i=t.meta??{},l=t.kind==="classic"||t.kind==="node"?t.kind:i.kind==="classic"||i.kind==="node"?i.kind:void 0;return{id:t.requestId,prompt:typeof t.prompt=="string"?t.prompt:"",startedAt:t.startedAt,phase:typeof t.phase=="string"?t.phase:void 0,sessionId:typeof i.sessionId=="string"?i.sessionId:null,parentNodeId:typeof i.parentNodeId=="string"?i.parentNodeId:null,clientNodeId:typeof i.clientNodeId=="string"?i.clientNodeId:null,kind:l}}function Hd(){try{const t=localStorage.getItem("ima2.inFlight");if(!t)return[];const i=JSON.parse(t);if(!Array.isArray(i))return[];const l=Date.now();return i.filter(o=>o&&typeof o.id=="string"&&typeof o.prompt=="string"&&typeof o.startedAt=="number"&&l-o.startedAt<A0).map(o=>({id:o.id,prompt:o.prompt,startedAt:o.startedAt,phase:typeof o.phase=="string"?o.phase:void 0,sessionId:typeof o.sessionId=="string"?o.sessionId:null,parentNodeId:typeof o.parentNodeId=="string"?o.parentNodeId:null,clientNodeId:typeof o.clientNodeId=="string"?o.clientNodeId:null,kind:o.kind==="classic"||o.kind==="node"?o.kind:void 0}))}catch{return[]}}function Ja(t){try{localStorage.setItem("ima2.inFlight",JSON.stringify(t))}catch(i){const l=window;if(!l.__ima2QuotaWarned){l.__ima2QuotaWarned=!0,console.warn("[ima2] localStorage write failed:",i);try{W.getState().showToast(ve("toast.localStorageFull"),!0)}catch{}}}}function Zp(){try{const t=localStorage.getItem("ima2.selectedFilename");return typeof t=="string"&&t.length>0?t:null}catch{return null}}function vo(t){try{t?localStorage.setItem("ima2.selectedFilename",t):localStorage.removeItem("ima2.selectedFilename")}catch{}}function lN(){try{const t=localStorage.getItem("ima2.activeSessionId");return typeof t=="string"&&t.length>0?t:null}catch{return null}}function Id(t){try{t?localStorage.setItem("ima2.activeSessionId",t):localStorage.removeItem("ima2.activeSessionId")}catch{}}const nl=500,Sa=5;function oN(t){return t==="classic"||t==="edit"||t==="generate"||t==="card-news-card"||t==="card-news-set"?t:null}function Kp(t){return{image:t.url,url:t.url,filename:t.filename,thumb:t.url,prompt:t.prompt??void 0,size:t.size??void 0,quality:t.quality??void 0,format:t.format,model:t.model??void 0,provider:t.provider,usage:t.usage??void 0,createdAt:t.createdAt,sessionId:t.sessionId??null,nodeId:t.nodeId??null,clientNodeId:t.clientNodeId??null,requestId:t.requestId??null,kind:oN(t.kind),setId:t.setId??null,cardId:t.cardId??null,cardOrder:t.cardOrder??null,headline:t.headline??null,body:t.body??null,cards:t.cards,refsCount:t.refsCount??0}}function Qp(t){return t.replace(/^data:[^;]+;base64,/,"")}function M0(t){const i=t.nodes.map(o=>{const r=o.data??{},u=typeof r.imageUrl=="string"&&r.imageUrl.length>0?r.imageUrl:null,d=typeof r.serverNodeId=="string"&&r.serverNodeId.length>0?`/generated/${r.serverNodeId}.png`:null,g=u??d,p={clientId:o.id,serverNodeId:r.serverNodeId??null,parentServerNodeId:r.parentServerNodeId??null,prompt:typeof r.prompt=="string"?r.prompt:"",imageUrl:g,status:r.status??(g?"ready":"empty"),pendingRequestId:r.pendingRequestId??null,recoveryRequestId:r.recoveryRequestId??null,pendingPhase:r.pendingPhase??null,pendingStartedAt:typeof r.pendingStartedAt=="number"?r.pendingStartedAt:null,partialImageUrl:null,error:r.error,elapsed:r.elapsed,webSearchCalls:r.webSearchCalls,model:r.model??null,size:r.size??null,referenceImages:Zw(t.id,o.id)};return{id:o.id,type:"imageNode",position:{x:o.x,y:o.y},data:p}}),l=t.edges.map(o=>({id:o.id,source:o.source,target:o.target}));return{graphNodes:_a(i,l),graphEdges:l,graphVersion:t.graphVersion}}function sN(t,i){return`${t}x${i}`}function mr(t,i){if(t.sizePreset!=="custom")return null;const l=Ow(t.customW,t.customH,t.customW,t.customH);return l.adjusted?{requestedW:l.requestedW,requestedH:l.requestedH,adjustedW:l.w,adjustedH:l.h,reasons:l.reasons,continuation:i}:null}const W=g0((t,i)=>({provider:"oauth",quality:"medium",sizePreset:"1024x1024",customW:1920,customH:1088,format:"png",moderation:"low",count:1,promptMode:"auto",prompt:"",referenceImages:[],addReferences:async l=>{const o=Sa-i().referenceImages.length,r=l.slice(0,Math.max(0,o)),u=r.filter(fr),d=r.filter(m=>!fr(m)),p=(await Promise.all(d.map(async m=>{try{return await Dp(m,{preserveTransparency:Op(m)})}catch(v){return console.warn("[addReferences] compress failed",v),null}}))).filter(m=>!!m);t(m=>({referenceImages:[...m.referenceImages,...p].slice(0,Sa)})),u.length>0&&i().showToast(ve("toast.refHeicUnsupported"),!0),d.length-p.length>0&&i().showToast(ve("toast.refTooLarge"),!0),l.length>o&&i().showToast(ve("toast.refLimitExceeded"),!0)},addReferenceDataUrl:l=>{t(o=>o.referenceImages.length>=Sa?o:{referenceImages:[...o.referenceImages,l]})},removeReference:l=>{t(o=>({referenceImages:o.referenceImages.filter((r,u)=>u!==l)}))},clearReferences:()=>t({referenceImages:[]}),useCurrentAsReference:async()=>{const l=i().currentImage;if(!l){i().showToast(ve("toast.noCurrentImageForRef"),!0);return}if(i().referenceImages.length>=Sa){i().showToast(ve("toast.refSlotFull"),!0);return}let o=l.image;if(!o.startsWith("data:"))try{const u=await(await fetch(o)).blob();o=await new Promise((d,g)=>{const p=new FileReader;p.onload=()=>typeof p.result=="string"?d(p.result):g(new Error("read failed")),p.onerror=()=>g(p.error??new Error("read failed")),p.readAsDataURL(u)})}catch{i().showToast(ve("toast.currentImageLoadFailed"),!0);return}t(r=>({referenceImages:[...r.referenceImages,o].slice(0,Sa)})),i().showToast(ve("toast.addedCurrentAsRef"))},activeGenerations:Hd().length,inFlight:Hd(),startInFlightPolling:()=>{if(typeof window>"u")return;const l=window;if(l.__ima2InflightTimer)return;const o=async()=>{if(i().inFlight.length===0){l.__ima2InflightTimer&&(clearInterval(l.__ima2InflightTimer),l.__ima2InflightTimer=void 0);return}try{const u=i().uiMode==="node"?"node":"classic",d=u==="node"?i().activeSessionId??void 0:void 0,{jobs:g}=await Ad({kind:u,sessionId:d}),p=new Map(g.map(S=>[S.requestId,S]));let y=!1;const m=Date.now(),v=5e3,x=[];for(const S of i().inFlight){if(!((S.kind??"classic")===u&&(u!=="node"||(S.sessionId??null)===(d??null)))){x.push(S);continue}if(!p.has(S.id)&&m-S.startedAt>v){y=!0;continue}const E=p.get(S.id);if(E){const A=Od(E),B={...S,phase:A.phase,sessionId:A.sessionId,parentNodeId:A.parentNodeId,clientNodeId:A.clientNodeId,kind:A.kind};(B.phase!==S.phase||B.sessionId!==S.sessionId||B.parentNodeId!==S.parentNodeId||B.clientNodeId!==S.clientNodeId||B.kind!==S.kind)&&(y=!0),x.push(B)}else x.push(S)}y&&(Ja(x),t({inFlight:x,activeGenerations:x.length}))}catch{}try{const u=i().history.reduce((x,S)=>S.createdAt&&S.createdAt>x?S.createdAt:x,0),{items:d}=await Wd({limit:nl,since:u}),g=d.map(Kp),p=i().history,y=g.filter(x=>!p.some(S=>S.filename===x.filename));y.length>0&&t(x=>{const S=x.currentImage??y[0];return!x.currentImage&&y[0]?.filename&&vo(y[0].filename),{history:[...y,...x.history].slice(0,nl),currentImage:S}});const m=Date.now(),v=i().inFlight.filter(x=>m-x.startedAt<A0);v.length!==i().inFlight.length&&(Ja(v),t({inFlight:v,activeGenerations:v.length}))}catch{}};l.__ima2InflightTimer=window.setInterval(o,1500)},reconcileInflight:async()=>{try{const l=i().uiMode==="node"?"node":"classic",o=l==="node"?i().activeSessionId??void 0:void 0,{jobs:r}=await Ad({kind:l,sessionId:o}),u=new Map(r.map(m=>[m.requestId,m])),d=Date.now(),p=i().inFlight.flatMap(m=>{const v=u.get(m.id);if(v){const w=Od(v);return[{...m,...w,prompt:m.prompt||w.prompt}]}return(m.kind??"classic")===l&&(l!=="node"||(m.sessionId??null)===(o??null))?d-m.startedAt<1e4?[m]:[]:[m]}),y=new Set(p.map(m=>m.id));for(const m of r)y.has(m.requestId)||p.push(Od(m));Ja(p),t({inFlight:p,activeGenerations:p.length}),p.length>0&&i().startInFlightPolling()}catch{}},syncFromStorage:()=>{const l=Hd(),o=Zp(),r=$p();t(u=>({inFlight:l,activeGenerations:l.length,imageModel:r,currentImage:o&&u.currentImage?.filename!==o?u.history.find(d=>d.filename===o)??u.currentImage:u.currentImage})),l.length>0&&i().startInFlightPolling()},currentImage:null,history:[],toast:null,customSizeConfirm:null,errorCard:null,rightPanelOpen:nN(),toggleRightPanel:()=>t(l=>{const o=!l.rightPanelOpen;try{localStorage.setItem("ima2.rightPanelOpen",JSON.stringify(o))}catch{}return{rightPanelOpen:o}}),galleryOpen:!1,openGallery:()=>t({galleryOpen:!0}),closeGallery:()=>t({galleryOpen:!1}),imageModel:$p(),settingsOpen:!1,activeSettingsSection:"account",openSettings:(l="account")=>t({settingsOpen:!0,activeSettingsSection:l}),closeSettings:()=>t({settingsOpen:!1}),toggleSettings:()=>t(l=>({settingsOpen:!l.settingsOpen,activeSettingsSection:l.settingsOpen?l.activeSettingsSection:"account"})),setActiveSettingsSection:l=>t({activeSettingsSection:l}),uiMode:aN(),setUIMode:l=>{const o=l==="card-news"&&!T0?"classic":l;try{localStorage.setItem("ima2.uiMode",o)}catch{}t({uiMode:o})},theme:Dd(),resolvedTheme:gr(Dd()),setTheme:l=>{try{localStorage.setItem("ima2:theme",l)}catch{}t({theme:l,resolvedTheme:gr(l)})},syncThemeFromStorage:()=>{const l=Dd();t({theme:l,resolvedTheme:gr(l)})},refreshResolvedTheme:()=>{t(l=>({resolvedTheme:gr(l.theme)}))},locale:jw(),setLocale:l=>{zw(l),t({locale:l})},graphNodes:[],graphEdges:[],setGraphNodes:l=>{t({graphNodes:_a(l,i().graphEdges)}),i().scheduleGraphSave()},setGraphEdges:l=>{t({graphEdges:l,graphNodes:_a(i().graphNodes,l)}),i().scheduleGraphSave()},disconnectEdge:l=>{i().disconnectEdges([l])},disconnectEdges:l=>{const o=new Set(l);if(o.size===0)return;const r=i().graphEdges.filter(p=>o.has(p.id));if(r.length===0)return;const u=i().graphEdges.filter(p=>!o.has(p.id)),d=new Set(r.map(p=>p.target)),g=i().graphNodes.map(p=>{if(!d.has(p.id))return p;const y=u.find(v=>v.target===p.id),m=y?i().graphNodes.find(v=>v.id===y.source):null;return{...p,data:{...p.data,parentServerNodeId:m?.data.serverNodeId??null}}});t({graphNodes:_a(g,u),graphEdges:u}),i().scheduleGraphSave(),i().showToast(ve("edge.disconnected"))},nodeSelectionMode:!1,nodeBatchRunning:!1,nodeBatchStopping:!1,toggleNodeSelectionMode:()=>{const l=!i().nodeSelectionMode;t({nodeSelectionMode:l,...l?{}:{graphNodes:So(i().graphNodes,[])}})},selectAllGraphNodes:()=>{t({graphNodes:So(i().graphNodes,i().graphNodes.map(l=>l.id))})},selectNodeGraph:(l,o)=>{t({graphNodes:Fw(i().graphNodes,i().graphEdges,l,o)})},clearNodeSelection:()=>{t({graphNodes:So(i().graphNodes,[])})},cancelNodeBatch:()=>{i().nodeBatchRunning&&(t({nodeBatchStopping:!0}),i().showToast(ve("nodeBatch.stopQueued")))},sessions:[],activeSessionId:null,activeSessionGraphVersion:null,sessionLoading:!1,styleSheet:null,styleSheetEnabled:!1,styleSheetExtracting:!1,async loadStyleSheet(){const l=i().activeSessionId;if(!l){t({styleSheet:null,styleSheetEnabled:!1});return}try{const o=await s1(l);if(i().activeSessionId!==l)return;t({styleSheet:o.styleSheet,styleSheetEnabled:!!o.enabled})}catch(o){console.warn("[styleSheet] load failed:",o)}},async saveStyleSheet(l,o){const r=i().activeSessionId;if(r)try{if(await r1(r,l,o),i().activeSessionId!==r)return;t({styleSheet:l,...typeof o=="boolean"?{styleSheetEnabled:o}:{}}),i().showToast(ve("styleSheet.saved"))}catch(u){console.warn("[styleSheet] save failed:",u),i().showToast(u.message,!0)}},async toggleStyleSheetEnabled(){const l=i().activeSessionId;if(!l)return;const o=!i().styleSheetEnabled;try{if(await c1(l,o),i().activeSessionId!==l)return;t({styleSheetEnabled:o})}catch(r){console.warn("[styleSheet] toggle failed:",r),i().showToast(r.message,!0)}},async extractStyleSheet(){const l=i().activeSessionId;if(!l)return;const o=i().prompt.trim();if(!o){i().showToast(ve("styleSheet.noPrompt"),!0);return}const r=i().referenceImages[0];t({styleSheetExtracting:!0});try{const{styleSheet:u}=await u1(l,o,r);if(i().activeSessionId!==l){t({styleSheetExtracting:!1});return}t({styleSheet:u,styleSheetEnabled:!0,styleSheetExtracting:!1}),i().showToast(ve("styleSheet.extracted"))}catch(u){t({styleSheetExtracting:!1}),console.warn("[styleSheet] extract failed:",u);const d=u.code,g=d==="STYLE_SHEET_NO_KEY"?ve("styleSheet.errNoKey"):d==="STYLE_SHEET_EMPTY"||d==="STYLE_SHEET_PARSE"||d==="STYLE_SHEET_SHAPE"?ve("styleSheet.errBadOutput"):u.message;i().showToast(g,!0)}},async loadSessions(){try{const{sessions:l}=await n1();if(t({sessions:l}),!i().activeSessionId){const r=lN(),u=r?l.some(d=>d.id===r):!1;r&&u?await i().switchSession(r):await i().createAndSwitchSession(ve("session.firstGraph"))}}catch(l){console.warn("[sessions] load failed:",l)}},async switchSession(l){t({sessionLoading:!0}),await i().flushGraphSave("switch-session");try{const{session:o}=await m0(l),{graphNodes:r,graphEdges:u,graphVersion:d}=M0(o);t({activeSessionId:l,activeSessionGraphVersion:d,graphNodes:r,graphEdges:u,sessionLoading:!1}),Id(l),await i().reconcileGraphPending().catch(()=>{}),i().loadStyleSheet().catch(()=>{})}catch(o){console.warn("[sessions] switch failed:",o),t({sessionLoading:!1}),i().showToast(ve("toast.sessionLoadFailed"),!0)}},async reconcileGraphPending(){const l=i().activeSessionId;if(!l)return;if(i().graphNodes.filter(r=>r.data?.pendingRequestId&&(r.data.status==="pending"||r.data.status==="reconciling")).length>0){let r=[];try{r=(await Ad({kind:"node",sessionId:l})).jobs}catch{r=[]}const u=new Map(r.map(y=>[y.requestId,y.phase])),d=Date.now(),g=1e4,p=i().graphNodes.map(y=>{const m=y.data?.pendingRequestId;if(!m||y.data.status!=="pending"&&y.data.status!=="reconciling")return y;if(u.has(m)){const S=u.get(m)??null;return{...y,data:{...y.data,status:"reconciling",pendingPhase:S}}}const v=y.data.pendingStartedAt??0;if(v&&d-v<g)return{...y,data:{...y.data,status:"reconciling"}};const x=!!y.data.imageUrl||!!y.data.serverNodeId;return{...y,data:{...y.data,pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,status:x?"ready":"stale",error:x?void 0:ve("session.assetAbortedError")}}});t({graphNodes:p})}await D0(i,t).catch(()=>{})},async createAndSwitchSession(l){l==null&&(l=ve("session.untitled"));try{const{session:o}=await a1(l);t({sessions:[o,...i().sessions],activeSessionId:o.id,activeSessionGraphVersion:o.graphVersion,graphNodes:[],graphEdges:[]}),Id(o.id)}catch(o){console.warn("[sessions] create failed:",o),i().showToast(ve("toast.sessionCreateFailed"),!0)}},async renameCurrentSession(l){const o=i().activeSessionId;if(o)try{await i1(o,l),t({sessions:i().sessions.map(r=>r.id===o?{...r,title:l,updatedAt:Date.now()}:r)})}catch{i().showToast(ve("toast.sessionRenameFailed"),!0)}},async deleteSessionById(l){try{await l1(l);const o=i().sessions.filter(r=>r.id!==l);t({sessions:o}),i().activeSessionId===l&&(t({activeSessionId:null,activeSessionGraphVersion:null,graphNodes:[],graphEdges:[]}),Id(null),o.length>0?await i().switchSession(o[0].id):await i().createAndSwitchSession(ve("session.firstGraph")))}catch{i().showToast(ve("toast.sessionDeleteFailed"),!0)}},scheduleGraphSave(){H0(i,t)},async flushGraphSave(l="manual"){await dN(i,t,l)},addRootNode:()=>{const l=Ji(),o={id:l,type:"imageNode",position:Yp(i().graphNodes),data:{clientId:l,serverNodeId:null,parentServerNodeId:null,prompt:"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};return t({graphNodes:[...i().graphNodes,o]}),i().scheduleGraphSave(),l},addChildNode:l=>{const o=i().graphNodes.find(g=>g.id===l);if(!o)return l;const r=Ji(),u={id:r,type:"imageNode",position:Vp(o,i().graphNodes,i().graphEdges),data:{clientId:r,serverNodeId:null,parentServerNodeId:o.data.serverNodeId,prompt:"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},d={id:`${l}->${r}`,source:l,target:r};return t({graphNodes:[...i().graphNodes,u],graphEdges:[...i().graphEdges,d]}),i().scheduleGraphSave(),r},addSiblingNode:l=>{const o=i().graphNodes.find(m=>m.id===l);if(!o)return l;const r=i().graphEdges.find(m=>m.target===l);if(!r){const m=Ji(),v={id:m,type:"imageNode",position:Yp(i().graphNodes),data:{clientId:m,serverNodeId:null,parentServerNodeId:null,prompt:o.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};return t({graphNodes:[...i().graphNodes,v]}),i().scheduleGraphSave(),m}const u=r.source,d=i().graphNodes.find(m=>m.id===u);if(!d)return l;const g=Ji(),p={id:g,type:"imageNode",position:Vp(d,i().graphNodes,i().graphEdges),data:{clientId:g,serverNodeId:null,parentServerNodeId:o.data.parentServerNodeId,prompt:o.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},y={id:`${u}->${g}`,source:u,target:g};return t({graphNodes:[...i().graphNodes,p],graphEdges:[...i().graphEdges,y]}),i().scheduleGraphSave(),g},updateNodePrompt:(l,o)=>{t({graphNodes:i().graphNodes.map(r=>r.id===l?{...r,data:{...r.data,prompt:o}}:r)}),i().scheduleGraphSave()},addNodeReferences:async(l,o)=>{const r=i().graphNodes.find(S=>S.id===l);if(!r)return;const u=r.data.referenceImages??[],d=Sa-u.length;if(d<=0){i().showToast(ve("toast.refLimitExceeded"),!0);return}const g=o.slice(0,Math.max(0,d)),p=g.filter(fr),y=g.filter(S=>!fr(S)),v=(await Promise.all(y.map(async S=>{try{return await Dp(S,{preserveTransparency:Op(S)})}catch(w){return console.warn("[addNodeReferences] compress failed",w),null}}))).filter(S=>!!S);if(v.length>0){const S=i().activeSessionId;t({graphNodes:i().graphNodes.map(w=>{if(w.id!==l)return w;const j=[...w.data.referenceImages??[],...v].slice(0,Sa);return Cr(S,l,j),{...w,data:{...w.data,referenceImages:j}}})}),i().scheduleGraphSave()}p.length>0&&i().showToast(ve("toast.refHeicUnsupported"),!0),y.length-v.length>0&&i().showToast(ve("toast.refTooLarge"),!0),o.length>d&&i().showToast(ve("toast.refLimitExceeded"),!0)},addNodeReferenceDataUrl:(l,o)=>{i().graphNodes.find(u=>u.id===l)&&(t({graphNodes:i().graphNodes.map(u=>{if(u.id!==l)return u;const d=u.data.referenceImages??[];if(d.length>=Sa)return u;const g=[...d,o];return Cr(i().activeSessionId,l,g),{...u,data:{...u.data,referenceImages:g}}})}),i().scheduleGraphSave())},removeNodeReference:(l,o)=>{t({graphNodes:i().graphNodes.map(r=>{if(r.id!==l)return r;const u=(r.data.referenceImages??[]).filter((d,g)=>g!==o);return Cr(i().activeSessionId,l,u),{...r,data:{...r.data,referenceImages:u}}})}),i().scheduleGraphSave()},clearNodeReferences:l=>{Rd(i().activeSessionId,l),t({graphNodes:i().graphNodes.map(o=>o.id===l?{...o,data:{...o.data,referenceImages:void 0}}:o)}),i().scheduleGraphSave()},duplicateBranchRoot:l=>{const o=i().graphNodes.find(d=>d.id===l);if(!o)return l;const r=Ji();i().graphNodes.filter(d=>!d.data.parentServerNodeId).length;const u={id:r,type:"imageNode",position:{x:o.position.x+420,y:o.position.y+40},data:{clientId:r,serverNodeId:null,parentServerNodeId:null,prompt:o.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};if(t({graphNodes:[...i().graphNodes,u]}),i().scheduleGraphSave(),o.data.imageUrl){const d=o.data.imageUrl;(async()=>{try{const p=await(await fetch(d)).blob(),y=await new Promise((m,v)=>{const x=new FileReader;x.onload=()=>typeof x.result=="string"?m(x.result):v(new Error("read failed")),x.onerror=()=>v(x.error??new Error("read failed")),x.readAsDataURL(p)});t({graphNodes:i().graphNodes.map(m=>m.id===r?{...m,data:{...m.data,referenceImages:[y]}}:m)})}catch{}})()}return r},async generateNode(l){const o=i().graphNodes.find(d=>d.id===l);if(!o)return;const{prompt:r}=o.data;if(!r.trim()){i().showToast(ve("toast.promptRequired"),!0);return}const u=mr(i(),{kind:"node",clientId:l});if(u){t({customSizeConfirm:u});return}await i().runGenerateNode(l)},async generateNodeInPlace(l){const o=i().graphNodes.find(u=>u.id===l);if(!o)return;if(!o.data.prompt.trim()){i().showToast(ve("toast.promptRequired"),!0);return}const r=mr(i(),{kind:"node-in-place",clientId:l});if(r){t({customSizeConfirm:r});return}await i().runGenerateNodeInPlace(l)},async generateNodeVariation(l,o){const r=i().graphNodes.find(d=>d.id===l);if(!r)return;if(!r.data.prompt.trim()){i().showToast(ve("toast.promptRequired"),!0);return}if(!o){const d=mr(i(),{kind:"node-variation",clientId:l});if(d){t({customSizeConfirm:d});return}}const u=i().addSiblingNode(l);await i().runGenerateNodeInPlace(u,{sizeOverride:o})},async runGenerateNode(l,o){const u=i().graphNodes.find(d=>d.id===l)?.data.status==="ready"?i().addSiblingNode(l):l;await i().runGenerateNodeInPlace(u,{sizeOverride:o})},async runGenerateNodeInPlace(l,o={}){const r=i().graphNodes,u=_a(r,i().graphEdges);u.some((_,U)=>_.data.parentServerNodeId!==r[U]?.data.parentServerNodeId)&&t({graphNodes:u});const d=u.find(_=>_.id===l);if(!d)return null;const{prompt:g,parentServerNodeId:p}=d.data;if(!g.trim())return i().showToast(ve("toast.promptRequired"),!0),null;const y=d.data.referenceImages??[],m=i(),v=o.sizeOverride??m.getResolvedSize(),x=o.parentServerNodeIdOverride!==void 0?o.parentServerNodeIdOverride:p;if(i().graphEdges.find(_=>_.target===l)&&!x)return i().showToast(ve("node.parentImageRequired"),!0),null;const w=m.activeSessionId,j=Date.now(),E=Math.random().toString(36).slice(2,6),A=`fn_${l}_${j}_${E}`,B=[...m.inFlight,{id:A,prompt:g,startedAt:j,kind:"node",sessionId:w,clientNodeId:l}];Ja(B),t({graphNodes:i().graphNodes.map(_=>_.id===l?{..._,data:{..._.data,status:"pending",pendingRequestId:A,recoveryRequestId:A,pendingPhase:"queued",pendingStartedAt:j,partialImageUrl:null,error:void 0,size:v}}:_),activeGenerations:m.activeGenerations+1,inFlight:B}),i().startInFlightPolling();let C=!0;try{const _=await t1({parentNodeId:x,prompt:g,quality:m.quality,size:v,format:m.format,moderation:m.moderation,model:m.imageModel,requestId:A,sessionId:w,clientNodeId:l,contextMode:"parent-plus-refs",searchMode:"off",...y.length?{references:y.map(Qp)}:{}},{onPartial:U=>{i().activeSessionId===w&&t({graphNodes:i().graphNodes.map(R=>R.id===l?{...R,data:{...R.data,status:"pending",partialImageUrl:U.image,pendingPhase:"partial"}}:R)})},onPhase:U=>{i().activeSessionId===w&&U.phase&&t({graphNodes:i().graphNodes.map(R=>R.id===l?{...R,data:{...R.data,pendingPhase:U.phase??R.data.pendingPhase}}:R)})}});return i().activeSessionId===w&&(t({graphNodes:i().graphNodes.map(U=>{if(U.id!==l)return U;const R={...U.data};return delete R.partialImageUrl,{...U,data:{...R,serverNodeId:_.nodeId,imageUrl:_.url,status:"ready",pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,elapsed:_.elapsed,webSearchCalls:_.webSearchCalls,model:_.model??null,size:_.size??v}}})}),C=!0,o.suppressToast||i().showToast(ve("toast.nodeCreated",{id:_.nodeId.slice(0,8),elapsed:_.elapsed}))),_.nodeId}catch(_){const U=_ instanceof Error?_.message:ve("toast.nodeCreateFailed");return i().activeSessionId===w&&(t({graphNodes:i().graphNodes.map(R=>R.id===l?{...R,data:{...R.data,status:"error",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:U}}:R)}),C=!0,Xp(_,i())),null}finally{const _=i().inFlight.filter(U=>U.id!==A);Ja(_),t({activeGenerations:Math.max(0,i().activeGenerations-1),inFlight:_}),i().activeSessionId===w&&C&&i().scheduleGraphSave()}},async runNodeBatch(l){if(i().nodeBatchRunning)return;const o=_0(i().graphNodes);if(o.length===0){i().showToast(ve("nodeBatch.noneSelected"),!0);return}const r=Ww(i().graphNodes,i().graphEdges,o);if(r.length>0){i().showToast(ve("nodeBatch.parentRequired",{count:r.length}),!0);return}const u=Pw(i().graphNodes,i().graphEdges,o),d=new Set(o),g=u.filter(m=>{if(l==="regenerate-all")return!0;const v=i().graphNodes.find(x=>x.id===m);return v?!E0(v):!1});if(g.length===0){i().showToast(ve("nodeBatch.nothingToRun"));return}t({nodeBatchRunning:!0,nodeBatchStopping:!1});const p=new Map;let y=0;try{for(const m of g){if(i().nodeBatchStopping)break;const v=i().graphEdges.find(E=>E.target===m),x=v?p.get(v.source)??i().graphNodes.find(E=>E.id===m)?.data.parentServerNodeId??null:null,S=await i().runGenerateNodeInPlace(m,{parentServerNodeIdOverride:x,suppressToast:!0});if(!S){i().showToast(ve("nodeBatch.failed",{done:y,total:g.length}),!0);break}y+=1,p.set(m,S);const w=Jw(i().graphEdges,m,d),j=new Set(C0(i().graphEdges,d));t({graphNodes:i().graphNodes.map(E=>j.has(E.id)?{...E,data:{...E.data,status:"stale",parentServerNodeId:w.includes(E.id)?S:E.data.parentServerNodeId,error:ve("nodeBatch.staleBecauseParentChanged")}}:E)})}i().showToast(ve("nodeBatch.finished",{done:y,total:g.length})),i().scheduleGraphSave()}finally{t({nodeBatchRunning:!1,nodeBatchStopping:!1})}},deleteNode:l=>{const r=i().graphNodes.find(g=>g.id===l)?.data?.pendingRequestId;r&&jp(r),Rd(i().activeSessionId,l);const u=i().graphNodes.filter(g=>g.id!==l),d=i().graphEdges.filter(g=>g.source!==l&&g.target!==l);t({graphNodes:_a(u,d),graphEdges:d}),i().scheduleGraphSave()},deleteNodes:l=>{const o=new Set(l);for(const d of o)Rd(i().activeSessionId,d);for(const d of i().graphNodes)o.has(d.id)&&d.data?.pendingRequestId&&jp(d.data.pendingRequestId);const r=i().graphNodes.filter(d=>!o.has(d.id)),u=i().graphEdges.filter(d=>!o.has(d.source)&&!o.has(d.target));t({graphNodes:_a(r,u),graphEdges:u}),i().scheduleGraphSave()},addChildNodeAt:(l,o)=>{const r=i().graphNodes.find(p=>p.id===l);if(!r)return l;const u=Ji(),d={id:u,type:"imageNode",position:o,data:{clientId:u,serverNodeId:null,parentServerNodeId:r.data.serverNodeId,prompt:"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},g={id:`${l}->${u}`,source:l,target:u};return t({graphNodes:[...i().graphNodes,d],graphEdges:[...i().graphEdges,g]}),i().scheduleGraphSave(),u},connectNodes:(l,o)=>{if(l===o||i().graphEdges.find(g=>g.source===l&&g.target===o))return;if(Vw(i().graphEdges,l,o)){i().showToast(ve("edge.parentConflict"),!0);return}if(!i().graphNodes.find(g=>g.id===l))return;const d=[...i().graphEdges,{id:`${l}->${o}`,source:l,target:o}];t({graphNodes:_a(i().graphNodes,d),graphEdges:d}),i().scheduleGraphSave()},setProvider:l=>t({provider:l}),setQuality:l=>t({quality:l}),setSizePreset:l=>t({sizePreset:l}),setCustomSize:(l,o)=>t(r=>({customW:sl(l,r.customW),customH:sl(o,r.customH)})),setFormat:l=>t({format:l}),setModeration:l=>t({moderation:l}),setImageModel:l=>{iN(l),t({imageModel:l})},setCount:l=>t({count:l}),setPromptMode:l=>t({promptMode:l}),setPrompt:l=>t({prompt:l}),selectHistory:l=>{vo(l.filename??null),t({currentImage:l})},removeFromHistory:l=>{const o=i(),r=o.history.filter(d=>d.filename!==l),u=o.currentImage&&o.currentImage.filename===l?null:o.currentImage;t({history:r,currentImage:u}),u===null&&vo(null)},addHistoryItem:l=>{const o=i();if(o.history.some(d=>l.filename&&d.filename===l.filename))return;const u={...l,createdAt:l.createdAt||Date.now()};t({history:[u,...o.history].slice(0,nl)})},getResolvedSize:()=>{const{sizePreset:l,customW:o,customH:r}=i();return l==="custom"?`${o}x${r}`:l},async generate(){const l=i();if(!l.prompt.trim())return;const r=mr(l,{kind:"classic"});if(r){t({customSizeConfirm:r});return}await i().runGenerate()},async runGenerate(l){const o=i(),r=o.prompt.trim();if(!r)return;const u=l??o.getResolvedSize(),d=`f_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,g=Date.now(),p=[...o.inFlight,{id:d,prompt:r,startedAt:g}];Ja(p),t({activeGenerations:o.activeGenerations+1,inFlight:p}),i().startInFlightPolling();try{const y={prompt:r,quality:o.quality,size:u,format:o.format,moderation:o.moderation,provider:o.provider,n:o.count,model:o.imageModel,requestId:d,mode:o.promptMode,...o.referenceImages.length?{references:o.referenceImages.map(Qp)}:{}},m=await KS(y);if(Mp(m)&&m.images.length>1){for(const v of m.images){const x={image:v.image,filename:v.filename,prompt:r,elapsed:m.elapsed,provider:m.provider,usage:m.usage,quality:m.quality??o.quality,size:m.size??u,model:m.model??o.imageModel};await Pp(x,t,i)}i().showToast(ve("toast.generatedBatch",{count:m.images.length,elapsed:m.elapsed}))}else{let v;if(Mp(m)){const x=m.images[0];v={image:x.image,filename:x.filename,prompt:r,elapsed:m.elapsed,provider:m.provider,usage:m.usage,quality:m.quality??o.quality,size:m.size??u,model:m.model??o.imageModel}}else v={image:m.image,filename:m.filename,prompt:r,elapsed:m.elapsed,provider:m.provider,usage:m.usage,quality:m.quality??o.quality,size:m.size??u,model:m.model??o.imageModel};await Pp(v,t,i),i().showToast(ve("toast.generatedSingle",{elapsed:m.elapsed}))}}catch(y){Xp(y,i())}finally{const y=i().inFlight.filter(m=>m.id!==d);Ja(y),t({activeGenerations:Math.max(0,i().activeGenerations-1),inFlight:y})}},async confirmCustomSizeAdjustment(){const l=i().customSizeConfirm;if(!l)return;const o=sN(l.adjustedW,l.adjustedH);if(t({customW:l.adjustedW,customH:l.adjustedH,customSizeConfirm:null}),l.continuation.kind==="classic"){await i().runGenerate(o);return}if(l.continuation.kind==="node-in-place"){await i().runGenerateNodeInPlace(l.continuation.clientId,{sizeOverride:o});return}if(l.continuation.kind==="node-variation"){await i().generateNodeVariation(l.continuation.clientId,o);return}await i().runGenerateNode(l.continuation.clientId,o)},cancelCustomSizeAdjustment:()=>t({customSizeConfirm:null}),hydrateHistory(){(async()=>{try{const o=(await Wd({limit:nl})).items.map(Kp);if(o.length>0){const r=Zp(),u=r?o.find(d=>d.filename===r):null;t({history:o,currentImage:u??o[0]}),u||vo(o[0]?.filename??null)}}catch(l){console.warn("[history] load failed:",l)}})()},showToast(l,o=!1){t({toast:{message:l,error:o,id:Date.now()+Math.random()}})},showErrorCard(l,o){t({errorCard:{code:l,fallbackMessage:o?.fallbackMessage,id:Date.now()+Math.random()}})},dismissErrorCard(){t({errorCard:null})}})),rN=800,Fp="ima2.graphTabId";let gn=null,Tr=!1,Ar=!1,ei=null,j0=0;function z0(){try{const t=sessionStorage.getItem(Fp);if(t)return t;const i=`tab_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;return sessionStorage.setItem(Fp,i),i}catch{return"tab_unavailable"}}function R0(t){const i={...t};return delete i.referenceImages,delete i.partialImageUrl,t.status==="pending"||t.status==="reconciling"?{...i,status:"empty",pendingRequestId:null,recoveryRequestId:t.pendingRequestId??t.recoveryRequestId??null,pendingPhase:null,pendingStartedAt:null,error:void 0}:i}async function D0(t,i){const l=t().activeSessionId;if(!l||t().graphNodes.filter(g=>!g.data.imageUrl&&!g.data.serverNodeId).length===0)return;let r=[];try{r=(await Wd({sessionId:l,limit:nl})).items}catch{return}let u=!1;const d=t().graphNodes.map(g=>{if(g.data.imageUrl||g.data.serverNodeId)return g;const p=g.data.pendingStartedAt??0,y=g.data.pendingRequestId??g.data.recoveryRequestId??null,v=(y?r.find(x=>(x.sessionId??null)===l&&(x.requestId??null)===y):null)??r.find(x=>(x.sessionId??null)===l&&(x.clientNodeId??null)===g.id&&(!p||(x.createdAt??0)>=p));return v?(u=!0,{...g,data:{...g.data,status:"ready",imageUrl:v.url,serverNodeId:v.nodeId??g.data.serverNodeId,size:v.size??g.data.size??null,pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:void 0}}):g});u&&(i({graphNodes:d}),H0(t,i,"recovery"))}async function cN(t,i){const l=t().activeSessionId;if(!l)return;const{session:o}=await m0(l),{graphNodes:r,graphEdges:u,graphVersion:d}=M0(o);i({graphNodes:r,graphEdges:u,activeSessionGraphVersion:d}),t().showToast(ve("toast.sessionReloadedElsewhere"),!0),await D0(t,i).catch(()=>{})}async function uN(t,i,l){const o=t().activeSessionId,r=t().activeSessionGraphVersion;if(!o||r==null)return"skipped";const{graphNodes:u,graphEdges:d}=t(),g=u.map(m=>({id:m.id,x:m.position.x,y:m.position.y,data:R0(m.data)})),p=d.map(m=>({id:m.id,source:m.source,target:m.target,data:{}})),y=`gs_${Date.now().toString(36)}_${++j0}`;try{const m=await o1(o,r,g,p,{saveId:y,saveReason:l,tabId:z0()});return t().activeSessionId!==o?"skipped":(Kw(o,t().graphNodes.map(v=>v.id)),i({activeSessionGraphVersion:m.graphVersion}),"saved")}catch(m){return m.status===409?(await cN(t,i),"conflict"):(console.warn("[sessions] save failed:",m),"failed")}}async function O0(t,i,l){if(Tr){Ar=!0,ei&&await ei;return}Tr=!0,ei=(async()=>{let o=l;do{Ar=!1;const r=await uN(t,i,o);if(r==="conflict"||r==="failed")break;o="queued"}while(Ar)})().finally(()=>{Tr=!1,ei=null}),await ei}function H0(t,i,l="debounced"){const o=t();o.activeSessionId&&(o.sessionLoading||(gn&&clearTimeout(gn),gn=setTimeout(()=>{gn=null,O0(t,i,l)},rN)))}async function dN(t,i,l="manual"){let o=!1;if(gn&&(clearTimeout(gn),gn=null,o=!0),Tr){Ar=!0,ei&&await ei;return}o&&await O0(t,i,l)}function fN(t){const i=t();if(!i.activeSessionId||i.activeSessionGraphVersion==null)return;gn&&(clearTimeout(gn),gn=null);const l=i.graphNodes.map(d=>({id:d.id,x:d.position.x,y:d.position.y,data:R0(d.data)})),o=i.graphEdges.map(d=>({id:d.id,source:d.source,target:d.target,data:{}})),r=`/api/sessions/${encodeURIComponent(i.activeSessionId)}/graph`,u=JSON.stringify({nodes:l,edges:o});try{fetch(r,{method:"PUT",headers:{"Content-Type":"application/json","If-Match":String(i.activeSessionGraphVersion),"X-Ima2-Graph-Save-Id":`gs_${Date.now().toString(36)}_${++j0}`,"X-Ima2-Graph-Save-Reason":"beforeunload","X-Ima2-Tab-Id":z0()},body:u,keepalive:!0})}catch{}}async function Pp(t,i,l){const o=await d1(t.image).catch(()=>t.image),r=t.filename?`/generated/${t.filename}`:t.image,u={...t,thumb:o,url:r,createdAt:t.createdAt||Date.now()},d=[u,...l().history].slice(0,nl);vo(u.filename??null),i({history:d,currentImage:u})}function hN(){const{t}=Te(),i=W(o=>o.uiMode),l=W(o=>o.setUIMode);return h.jsxs("div",{className:"ui-mode-switch",role:"tablist","aria-label":t("uiMode.ariaLabel"),children:[h.jsx("button",{type:"button",role:"tab","aria-selected":i==="classic",className:`ui-mode-switch__tab${i==="classic"?" active":""}`,onClick:()=>l("classic"),children:t("uiMode.classic")}),h.jsx("button",{type:"button",role:"tab","aria-selected":i==="node",className:`ui-mode-switch__tab${i==="node"?" active":""}`,onClick:()=>l("node"),children:t("uiMode.node")}),null]})}const Jp={palette:[],composition:"",mood:"",medium:"",subject_details:"",negative:[]};function I0({open:t,onClose:i}){const{t:l}=Te(),o=W(R=>R.styleSheet),r=W(R=>R.styleSheetEnabled),u=W(R=>R.styleSheetExtracting),d=W(R=>R.activeSessionId),g=W(R=>R.toggleStyleSheetEnabled),p=W(R=>R.extractStyleSheet),y=W(R=>R.saveStyleSheet),[m,v]=Y.useState(!1),[x,S]=Y.useState(o??Jp),[w,j]=Y.useState(!1),[E,A]=Y.useState(!1);if(Y.useEffect(()=>{t?S(o??Jp):(v(!1),j(!1))},[t,o]),Y.useEffect(()=>{if(!t)return;const R=z=>{z.key==="Escape"&&!w&&i()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[t,w,i]),!t||!d)return null;const B=!!o&&(o.composition||o.mood||o.medium||o.subject_details||o.palette.length>0),C=async()=>{if(!w){j(!0);try{await y(x,r),v(!1)}finally{j(!1)}}},_=async()=>{if(!E){A(!0);try{await g()}finally{A(!1)}}},U=R=>S(z=>({...z,...R}));return h.jsx("div",{className:"style-sheet-editor__backdrop",onClick:w?void 0:i,role:"presentation",children:h.jsxs("div",{className:"style-sheet-editor",role:"dialog","aria-modal":"true","aria-label":l("styleSheet.editorTitle"),onClick:R=>R.stopPropagation(),children:[h.jsxs("div",{className:"style-sheet-panel__header",children:[h.jsx("h3",{style:{margin:0,fontSize:16},children:l("styleSheet.editorTitle")}),h.jsxs("label",{className:"style-sheet-panel__toggle",style:{marginLeft:"auto"},children:[h.jsx("input",{type:"checkbox",checked:r,disabled:!B||E,onChange:()=>{_()}}),h.jsx("span",{children:l("styleSheet.toggle")})]})]}),!m&&h.jsxs(h.Fragment,{children:[B?h.jsxs("div",{className:"style-sheet-panel__summary",children:[o.medium&&h.jsxs("div",{children:[h.jsxs("b",{children:[l("styleSheet.fields.medium"),":"]})," ",o.medium]}),o.palette.length>0&&h.jsx("div",{className:"style-sheet-panel__chips",children:o.palette.slice(0,6).map((R,z)=>h.jsx("span",{className:"style-sheet-panel__chip",title:R,children:R},z))}),o.mood&&h.jsxs("div",{className:"style-sheet-panel__muted",children:[l("styleSheet.fields.mood"),": ",o.mood]})]}):h.jsx("div",{className:"style-sheet-panel__muted",children:l("styleSheet.emptyHint")}),h.jsxs("div",{className:"style-sheet-panel__actions",children:[h.jsx("button",{type:"button",className:"btn btn--secondary btn--sm",onClick:()=>{p()},disabled:u,children:l(u?"styleSheet.extracting":"styleSheet.extract")}),h.jsx("button",{type:"button",className:"btn btn--ghost btn--sm",onClick:()=>v(!0),disabled:u,children:l("styleSheet.edit")}),h.jsx("button",{type:"button",className:"btn btn--ghost btn--sm",style:{marginLeft:"auto"},onClick:i,children:l("styleSheet.cancel")})]})]}),m&&h.jsxs(h.Fragment,{children:[h.jsxs("label",{children:[l("styleSheet.fields.medium"),h.jsx("input",{value:x.medium,onChange:R=>U({medium:R.target.value}),placeholder:l("styleSheet.placeholderMedium")})]}),h.jsxs("label",{children:[l("styleSheet.fields.composition"),h.jsx("textarea",{rows:2,value:x.composition,onChange:R=>U({composition:R.target.value}),placeholder:l("styleSheet.placeholderComposition")})]}),h.jsxs("label",{children:[l("styleSheet.fields.mood"),h.jsx("input",{value:x.mood,onChange:R=>U({mood:R.target.value}),placeholder:l("styleSheet.placeholderMood")})]}),h.jsxs("label",{children:[l("styleSheet.fields.subject"),h.jsx("textarea",{rows:2,value:x.subject_details,onChange:R=>U({subject_details:R.target.value}),placeholder:l("styleSheet.placeholderSubject")})]}),h.jsxs("label",{children:[l("styleSheet.fields.palette"),h.jsx("input",{value:x.palette.join(", "),onChange:R=>U({palette:R.target.value.split(",").map(z=>z.trim()).filter(Boolean).slice(0,6)}),placeholder:l("styleSheet.placeholderPalette")})]}),h.jsxs("label",{children:[l("styleSheet.fields.negative"),h.jsx("input",{value:x.negative.join(", "),onChange:R=>U({negative:R.target.value.split(",").map(z=>z.trim()).filter(Boolean).slice(0,4)}),placeholder:l("styleSheet.placeholderNegative")})]}),h.jsxs("div",{className:"style-sheet-editor__actions",children:[h.jsx("button",{type:"button",className:"btn btn--ghost",onClick:()=>v(!1),disabled:w,children:l("styleSheet.cancel")}),h.jsx("button",{type:"button",className:"btn btn--primary",onClick:()=>{C()},disabled:w,children:l(w?"styleSheet.extracting":"styleSheet.save")})]})]})]})})}const Wi=5;function gN(){const t=W(I=>I.prompt),i=W(I=>I.setPrompt),l=W(I=>I.generate),{t:o}=Te(),r=W(I=>I.referenceImages),u=W(I=>I.addReferences),d=W(I=>I.removeReference),g=W(I=>I.useCurrentAsReference),p=W(I=>I.currentImage),y=Y.useRef(null),[m,v]=Y.useState(!1),[x,S]=Y.useState(!1),w=W(I=>I.activeSessionId),j=W(I=>I.styleSheetEnabled),E=W(I=>I.promptMode),A=W(I=>I.setPromptMode),B=r.length<Wi,C=I=>{I.preventDefault(),v(!1);const X=Array.from(I.dataTransfer.files).filter(ce=>ce.type.startsWith("image/"));X.length>0&&u(X)},_=I=>{I.preventDefault(),m||v(!0)},U=I=>{I.currentTarget.contains(I.relatedTarget)||v(!1)},R=I=>{if(!I)return[];const X=[];for(const ce of Array.from(I)){if(ce.kind!=="file"||!ce.type.startsWith("image/"))continue;const K=ce.getAsFile();K&&X.push(K)}return X},z=I=>{if(!B)return;const X=R(I.clipboardData?.items??null);if(X.length===0)return;I.preventDefault();const ce=Wi-r.length;u(X.slice(0,ce))};return Y.useEffect(()=>{const I=X=>{const ce=X.target,K=ce?.tagName;if(K==="INPUT"||K==="TEXTAREA"||ce?.isContentEditable)return;const te=R(X.clipboardData?.items??null);if(te.length===0||r.length>=Wi)return;X.preventDefault();const ue=Wi-r.length;u(te.slice(0,ue))};return window.addEventListener("paste",I),()=>window.removeEventListener("paste",I)},[r.length,u]),h.jsxs("div",{className:`composer${m?" composer--drag":""}`,onDrop:C,onDragOver:_,onDragLeave:U,onPaste:z,children:[h.jsxs("div",{className:"composer__header",children:[h.jsx("span",{className:"section-title composer__label",children:o("prompt.label")}),r.length>0&&h.jsx("span",{className:"composer__count",children:o("prompt.refCount",{count:r.length,max:Wi})})]}),r.length>0&&h.jsx("div",{className:"composer__chips",children:r.map((I,X)=>h.jsxs("div",{className:"composer__chip",title:o("prompt.refChipTitle",{n:X+1}),children:[h.jsx("img",{src:I,alt:o("prompt.refChipAlt",{n:X+1})}),h.jsx("button",{type:"button",className:"composer__chip-remove",onClick:()=>d(X),"aria-label":o("prompt.refRemoveAria",{n:X+1}),children:"×"})]},X))}),h.jsx("textarea",{className:"prompt-area composer__textarea",value:t,placeholder:r.length>0?o("prompt.placeholderWithRefs"):o("prompt.placeholder"),onChange:I=>i(I.target.value),onKeyDown:I=>{I.key==="Enter"&&(I.metaKey||I.ctrlKey)&&(I.preventDefault(),l())}}),h.jsxs("div",{className:"composer__toolbar",children:[h.jsxs("button",{type:"button",className:"composer__tool",onClick:()=>B&&y.current?.click(),disabled:!B,title:o("prompt.attachTitle"),"aria-label":o("prompt.attachTitle"),children:[h.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:h.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),h.jsx("span",{children:o("prompt.attach")})]}),h.jsxs("button",{type:"button",className:"composer__tool",onClick:()=>{g()},disabled:!p||!B,title:o("prompt.useCurrentTitle"),children:[h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[h.jsx("polyline",{points:"23 4 23 10 17 10"}),h.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]}),h.jsx("span",{children:o("prompt.useCurrent")})]}),w&&h.jsxs("button",{type:"button",className:`composer__tool${j?" composer__tool--on":""}`,onClick:()=>S(!0),title:o("prompt.styleTitle"),"aria-label":o("prompt.styleTitle"),"aria-pressed":j,children:[h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[h.jsx("circle",{cx:"12",cy:"12",r:"9"}),h.jsx("circle",{cx:"8",cy:"10",r:"1",fill:"currentColor"}),h.jsx("circle",{cx:"12",cy:"8",r:"1",fill:"currentColor"}),h.jsx("circle",{cx:"16",cy:"10",r:"1",fill:"currentColor"}),h.jsx("path",{d:"M14 14c2 0 3 1 3 3 0 1-1 2-2 2-2 0-3-2-5-2"})]}),h.jsx("span",{children:o("prompt.style")})]}),h.jsxs("button",{type:"button",className:`composer__tool${E==="direct"?" composer__tool--on":""}`,onClick:()=>A(E==="direct"?"auto":"direct"),title:o("prompt.directModeTitle"),"aria-label":o("prompt.directModeTitle"),"aria-pressed":E==="direct",children:[h.jsx("span",{"aria-hidden":"true",style:{fontWeight:700,fontSize:11},children:"1:1"}),h.jsx("span",{children:o("prompt.directMode")})]}),h.jsx("span",{className:"composer__hint",children:o("prompt.hint")})]}),m&&h.jsx("div",{className:"composer__dropzone","aria-hidden":"true",children:o("prompt.dropHere",{max:Wi})}),h.jsx("input",{ref:y,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:I=>{const X=Array.from(I.target.files??[]);X.length>0&&u(X),I.target.value=""}}),h.jsx(I0,{open:x,onClose:()=>S(!1)})]})}function mN(){const t=W(u=>u.activeGenerations),i=W(u=>u.generate),{t:l}=Te(),o=t>0,r=o?l("generate.buttonLoading",{n:t}):l("generate.button");return h.jsx("button",{type:"button",className:`generate-btn${o?" loading":""}`,onClick:()=>{i()},children:r})}function pN(t,i=28){const l=t.trim().replace(/\s+/g," ");return l.length>i?`${l.slice(0,i)}...`:l}function Wp(){const t=W(o=>o.inFlight),{t:i}=Te(),l={queued:i("inflight.queued"),streaming:i("inflight.streaming"),decoding:i("inflight.decoding")};return t.length===0?null:h.jsx("ul",{className:"in-flight-list",children:t.map(o=>{const r=o.phase?l[o.phase]??o.phase:i("inflight.queued");return h.jsxs("li",{className:"in-flight-item","data-phase":o.phase??"queued",children:[h.jsx("span",{className:"in-flight-prompt",children:pN(o.prompt)}),h.jsx("span",{className:"in-flight-phase",children:r}),h.jsx("span",{className:"in-flight-spinner","aria-hidden":"true"})]},o.id)})})}function B0(t){const i=t.currentTarget;if(i.scrollWidth<=i.clientWidth||!(Math.abs(t.deltaY)>Math.abs(t.deltaX)))return;const o=i.scrollLeft<=0,r=i.scrollLeft+i.clientWidth>=i.scrollWidth-1,u=t.deltaY<0,d=t.deltaY>0;u&&o||d&&r||(t.preventDefault(),i.scrollLeft+=t.deltaY)}function yN(){const t=W(u=>u.history),i=W(u=>u.currentImage),l=W(u=>u.selectHistory),o=W(u=>u.openGallery),{t:r}=Te();return h.jsxs("div",{className:"history-strip",onWheel:B0,children:[h.jsx("button",{type:"button",className:"history-thumb history-thumb--add",onClick:o,"aria-label":r("history.openGalleryAria"),title:r("history.openGalleryTitle"),children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),h.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),h.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),h.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}),t.map((u,d)=>{const g=u.filename?i?.filename===u.filename:i?.image===u.image;return h.jsx("img",{src:u.thumb||u.url||u.image,alt:"",className:`history-thumb${g?" active":""}`,onClick:()=>l(u)},u.filename??`${d}-${u.image}`)})]})}function vN(){const{t}=Te(),i=W(x=>x.sessions),l=W(x=>x.activeSessionId),o=W(x=>x.switchSession),r=W(x=>x.createAndSwitchSession),u=W(x=>x.renameCurrentSession),d=W(x=>x.deleteSessionById),[g,p]=Y.useState(!1),y=i.find(x=>x.id===l),m=()=>{const x=window.prompt(t("session.renamePrompt"),y?.title??t("session.newSession"));x&&x.trim()&&u(x.trim())},v=(x,S)=>{window.confirm(t("session.deleteConfirm",{title:S}))&&d(x)};return h.jsxs("div",{className:"session-picker",children:[h.jsxs("div",{className:"session-picker-row",children:[h.jsxs("button",{type:"button",className:"session-current",onClick:()=>p(x=>!x),title:t("session.switchTitle"),children:[h.jsx("span",{className:"session-title",children:y?.title??t("session.loading")}),h.jsx("span",{className:"session-caret",children:g?"▴":"▾"})]}),h.jsx("button",{type:"button",className:"session-btn",onClick:()=>{r(t("session.newSession"))},title:t("session.newSessionTitle"),children:"+"}),h.jsx("button",{type:"button",className:"session-btn",onClick:m,title:t("session.renameTitle"),disabled:!y,children:"✎"})]}),g&&h.jsxs("ul",{className:"session-list",children:[i.map(x=>h.jsxs("li",{className:x.id===l?"is-active":"",children:[h.jsxs("button",{type:"button",className:"session-item",onClick:()=>{p(!1),o(x.id)},children:[h.jsx("span",{className:"session-item-title",children:x.title}),h.jsx("span",{className:"session-item-count",children:x.nodeCount})]}),h.jsx("button",{type:"button",className:"session-del",onClick:()=>v(x.id,x.title),title:t("session.deleteTitle"),children:"×"})]},x.id)),i.length===0&&h.jsx("li",{className:"session-empty",children:t("session.empty")})]})]})}function xN(){const{t}=Te(),i=W(u=>u.activeSessionId),l=W(u=>u.styleSheetEnabled),[o,r]=Y.useState(!1);return i?h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",className:`btn btn--secondary btn--sm${l?" is-on":""}`,onClick:()=>r(!0),"aria-pressed":l,title:t("prompt.styleTitle"),children:t("prompt.style")}),h.jsx(I0,{open:o,onClose:()=>r(!1)})]}):null}function bN(){const{t}=Te(),i=W(o=>o.settingsOpen),l=W(o=>o.toggleSettings);return h.jsx("button",{type:"button",className:`settings-button${i?" is-active":""}`,onClick:l,"aria-label":t("settings.openAria"),"aria-pressed":i,title:t("settings.openTitle"),children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[h.jsx("path",{d:"M12 8.2a3.8 3.8 0 1 0 0 7.6 3.8 3.8 0 0 0 0-7.6Zm0 5.7a1.9 1.9 0 1 1 0-3.8 1.9 1.9 0 0 1 0 3.8Z"}),h.jsx("path",{d:"m20.3 13.4.1-1.4-.1-1.4-2.2-.5a6.9 6.9 0 0 0-.6-1.3l1.2-1.9a9.6 9.6 0 0 0-2-2l-1.9 1.2c-.4-.2-.9-.4-1.3-.6L13 3.3a9.5 9.5 0 0 0-2.8 0l-.5 2.2c-.5.2-.9.3-1.3.6L6.5 4.9a9.6 9.6 0 0 0-2 2l1.2 1.9c-.2.4-.4.9-.6 1.3l-2.2.5a9.5 9.5 0 0 0 0 2.8l2.2.5c.2.5.3.9.6 1.3l-1.2 1.9a9.6 9.6 0 0 0 2 2l1.9-1.2c.4.2.9.4 1.3.6l.5 2.2a9.5 9.5 0 0 0 2.8 0l.5-2.2c.5-.2.9-.3 1.3-.6l1.9 1.2a9.6 9.6 0 0 0 2-2l-1.2-1.9c.2-.4.4-.9.6-1.3l2.2-.5Z"})]})})}function L0({variant:t}){const{t:i}=Te(),[l,o]=Y.useState(!1),r=Y.useRef(null),u=W(m=>m.imageModel),d=W(m=>m.setImageModel),g=t==="settings"?"settings-image-model":"sidebar-image-model",p=tl.find(m=>m.value===u)??tl[0],y=m=>{d(m.target.value)};return Y.useEffect(()=>{if(t!=="sidebar"||!l)return;const m=x=>{const S=x.target;S instanceof Node&&(r.current?.contains(S)||o(!1))},v=x=>{x.key==="Escape"&&o(!1)};return document.addEventListener("pointerdown",m),document.addEventListener("keydown",v),()=>{document.removeEventListener("pointerdown",m),document.removeEventListener("keydown",v)}},[l,t]),t==="sidebar"?h.jsxs("div",{ref:r,className:"image-model-select image-model-select--sidebar",children:[h.jsx("button",{id:g,type:"button",className:"image-model-select__trigger","aria-haspopup":"listbox","aria-expanded":l,"aria-label":i("sidebar.imageModelAria"),onClick:()=>o(m=>!m),children:p.shortLabel}),l?h.jsx("div",{className:"image-model-select__menu",role:"listbox","aria-label":i("sidebar.imageModelAria"),children:tl.map(m=>h.jsxs("button",{type:"button",className:`image-model-select__item${m.value===u?" is-active":""}`,role:"option","aria-selected":m.value===u,onClick:()=>{d(m.value),o(!1)},children:[h.jsx("span",{children:m.shortLabel}),h.jsx("small",{children:i(m.fullLabelKey)})]},m.value))}):null]}):h.jsx("div",{className:"image-model-select image-model-select--settings",children:h.jsxs("select",{id:g,value:u,onChange:y,children:[tl.map(m=>h.jsx("option",{value:m.value,children:i(m.fullLabelKey)},m.value)),qw.map(m=>h.jsx("option",{value:m.value,disabled:!0,children:i(m.fullLabelKey)},m.value))]})})}function k0(t){return{...t,textFields:Array.isArray(t.textFields)?t.textFields:[]}}function No(t){return{...t,cards:Array.isArray(t.cards)?t.cards.map(k0):[]}}async function ci(t,i){const l=await fetch(t,i),o=await l.json().catch(()=>({}));if(!l.ok){const r=o,u=typeof r.error=="string"?r.error:r.error?.message||`Request failed: ${l.status}`,d=new Error(u);throw typeof r.error!="string"&&(d.code=r.error?.code),d}return o}function SN(){return ci("/api/cardnews/image-templates")}function wN(){return ci("/api/cardnews/role-templates")}async function NN(t){const i=await ci("/api/cardnews/draft",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return{...i,plan:No(i.plan)}}function _N(t){return ci("/api/cardnews/jobs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}function EN(t){return ci(`/api/cardnews/jobs/${encodeURIComponent(t)}`)}async function CN(t){const l=(await ci(`/api/cardnews/cards/${encodeURIComponent(t.card.id)}/regenerate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,cards:[t.card]})})).cards.find(o=>o.id===t.card.id);if(!l)throw new Error("Regenerated card not found");return{card:l}}function ey(t){return ci(`/api/cardnews/sets/${encodeURIComponent(t)}`).then(i=>({...i,plan:No(i.plan)}))}function TN(t){return`/api/cardnews/sets/${encodeURIComponent(t)}/manifest?download=1`}function AN(t){return t[0]?.id||"academy-lesson-square"}function MN(t){return t.find(i=>i.id==="mid-5")?.id||t[0]?.id||"mid-5"}function jN(t){return Math.round(t/16)*16}function Hr(t){return Math.min(3824,Math.max(1024,jN(t)))}function ty(t){return t.outputSizePreset!=="custom"?t.outputSizePreset:`${Hr(t.customW)}x${Hr(t.customH)}`}function U0(t){if(t){if(typeof t=="string")return t;if(typeof t=="object"&&"message"in t){const i=t.message;return typeof i=="string"?i:void 0}return String(t)}}function zN(t,i){const l=i.status||"generated";return{...t,...i,textFields:Array.isArray(i.textFields)?i.textFields:t.textFields,status:l,error:l==="error"?U0(i.error)||ve("cardNews.error"):void 0}}function RN(t){return new Promise(i=>setTimeout(i,t))}function Bd(t,i){const l=new Map(i.cards.map(o=>[o.id,o]));return{...t,cards:t.cards.map(o=>{const r=l.get(o.id);return r?{...o,...r,textFields:Array.isArray(r.textFields)?r.textFields:o.textFields,status:r.status||o.status,error:U0(r.error)}:o})}}const Se=g0((t,i)=>({templates:[],roleTemplates:[],activePlan:null,selectedCardId:null,selectedTextFieldId:null,topic:"",audience:"",goal:"",contentBrief:"",imageTemplateId:"academy-lesson-square",roleTemplateId:"mid-5",outputSizePreset:"2048x2048",customW:2048,customH:2048,loading:!1,generating:!1,error:null,draftError:null,plannerMeta:null,async hydrate(){if(!(i().loading||i().templates.length>0)){t({loading:!0,error:null});try{const[l,o]=await Promise.all([SN(),wN()]);t({templates:l.templates,roleTemplates:o.templates,imageTemplateId:AN(l.templates),roleTemplateId:MN(o.templates),loading:!1})}catch(l){t({loading:!1,error:l instanceof Error?l.message:String(l)})}}},setBriefField(l,o){t({[l]:o})},setImageTemplate(l){t({imageTemplateId:l})},setRoleTemplate(l){t({roleTemplateId:l})},setOutputSizePreset(l){t({outputSizePreset:l})},setCustomSize(l,o){t({customW:Hr(l),customH:Hr(o)})},async draft(){const l=i();t({loading:!0,error:null,draftError:null});try{const{plan:o,planner:r}=await NN({topic:l.topic,audience:l.audience,goal:l.goal,contentBrief:l.contentBrief,imageTemplateId:l.imageTemplateId,roleTemplateId:l.roleTemplateId,size:ty(l)});t({activePlan:No(o),selectedCardId:o.cards[0]?.id||null,selectedTextFieldId:null,plannerMeta:r||null,loading:!1})}catch(o){const r=o instanceof Error?o.message:String(o);t({loading:!1,draftError:r,error:r})}},updateCard(l,o){t(r=>({activePlan:r.activePlan?{...r.activePlan,cards:r.activePlan.cards.map(u=>u.id===l?{...u,...o}:u)}:null}))},updateTextField(l,o,r){t(u=>({activePlan:u.activePlan?{...u.activePlan,cards:u.activePlan.cards.map(d=>d.id!==l||d.locked?d:{...d,textFields:d.textFields.map(g=>g.id===o?{...g,...r,source:r.source||"user"}:g)})}:null}))},addTextField(l,o){t(r=>({activePlan:r.activePlan?{...r.activePlan,cards:r.activePlan.cards.map(u=>u.id===l&&!u.locked?{...u,textFields:[...u.textFields,{...o,source:"user"}]}:u)}:null,selectedTextFieldId:o.id}))},removeTextField(l,o){t(r=>({activePlan:r.activePlan?{...r.activePlan,cards:r.activePlan.cards.map(u=>u.id===l&&!u.locked?{...u,textFields:u.textFields.filter(d=>d.id!==o)}:u)}:null,selectedTextFieldId:r.selectedTextFieldId===o?null:r.selectedTextFieldId}))},selectCard(l){t({selectedCardId:l,selectedTextFieldId:null})},selectTextField(l){t({selectedTextFieldId:l})},getGenerationSummary(){const l=i().activePlan?.cards||[];return{total:l.length,done:l.filter(o=>o.status==="generated").length,queued:l.filter(o=>o.status==="queued").length,generating:l.filter(o=>o.status==="generating").length,errors:l.filter(o=>o.status==="error").length,skipped:l.filter(o=>o.locked||o.status==="skipped").length}},async generateSet(){const l=i();if(!l.activePlan)return;const o=W.getState();t({generating:!0,error:null,activePlan:{...l.activePlan,cards:l.activePlan.cards.map(r=>r.locked?{...r,status:"skipped"}:{...r,status:"queued",error:void 0})}});try{const r=i().activePlan||l.activePlan;let d=await _N({...r,size:ty(l),quality:o.quality,moderation:o.moderation,model:o.imageModel,sessionId:o.activeSessionId});for(t(p=>({activePlan:p.activePlan?Bd(p.activePlan,d):p.activePlan}));["queued","running"].includes(d.status);)await RN(900),d=await EN(d.jobId),t(p=>({activePlan:p.activePlan?Bd(p.activePlan,d):p.activePlan}));const g=await ey(d.setId).catch(()=>null);t(p=>({generating:!1,activePlan:g?.plan?No(g.plan):p.activePlan?Bd(p.activePlan,d):p.activePlan,selectedTextFieldId:null})),o.showToast(ve("cardNews.generated",{count:d.generated}))}catch(r){const u=r instanceof Error?r.message:String(r);t(d=>({generating:!1,error:u,activePlan:d.activePlan?{...d.activePlan,cards:d.activePlan.cards.map(g=>g.status==="queued"||g.status==="generating"?{...g,status:"error",error:u}:g)}:d.activePlan}))}},async retryCard(l){const r=i().activePlan,u=r?.cards.find(g=>g.id===l);if(!r||!u||u.locked||!["draft","error"].includes(u.status))return;const d=W.getState();t({error:null,activePlan:{...r,cards:r.cards.map(g=>g.id===l?{...g,status:"generating",error:void 0}:g)}});try{const{card:g}=await CN({setId:r.setId,card:u,quality:d.quality,moderation:d.moderation,model:d.imageModel});t(p=>({activePlan:p.activePlan?{...p.activePlan,cards:p.activePlan.cards.map(y=>y.id===l?zN(y,k0(g)):y)}:p.activePlan}))}catch(g){const p=g instanceof Error?g.message:String(g);t(y=>({error:p,activePlan:y.activePlan?{...y.activePlan,cards:y.activePlan.cards.map(m=>m.id===l?{...m,status:"error",error:p}:m)}:y.activePlan}))}},async loadSet(l){t({loading:!0,error:null,selectedTextFieldId:null});try{const{plan:o}=await ey(l);t({activePlan:No(o),selectedCardId:o.cards[0]?.id||null,selectedTextFieldId:null,loading:!1})}catch(o){t({loading:!1,error:o instanceof Error?o.message:String(o)})}}}));function DN(){const{t}=Te(),i=Se(_=>_.hydrate),l=Se(_=>_.topic),o=Se(_=>_.audience),r=Se(_=>_.goal),u=Se(_=>_.contentBrief),d=Se(_=>_.outputSizePreset),g=Se(_=>_.customW),p=Se(_=>_.customH),y=Se(_=>_.setBriefField),m=Se(_=>_.setOutputSizePreset),v=Se(_=>_.setCustomSize),x=Se(_=>_.draft),S=Se(_=>_.loading),w=Se(_=>_.generating),j=Se(_=>_.draftError),E=Se(_=>_.generateSet),A=Se(_=>_.activePlan),B=A?.cards||[],C={total:B.length,done:B.filter(_=>_.status==="generated").length};return Y.useEffect(()=>{i()},[i]),h.jsxs("section",{className:"card-news-composer","aria-label":t("cardNews.composer"),children:[h.jsx("div",{className:"card-news-composer__head",children:h.jsxs("div",{children:[h.jsx("div",{className:"section-title",children:t("cardNews.composer")}),h.jsx("p",{children:t("cardNews.composerHint")})]})}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.topic")}),h.jsx("input",{value:l,placeholder:t("cardNews.topicPlaceholder"),onChange:_=>y("topic",_.target.value)})]}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.audience")}),h.jsx("input",{value:o,placeholder:t("cardNews.audiencePlaceholder"),onChange:_=>y("audience",_.target.value)})]}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.goal")}),h.jsx("input",{value:r,placeholder:t("cardNews.goalPlaceholder"),onChange:_=>y("goal",_.target.value)})]}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.brief")}),h.jsx("textarea",{value:u,placeholder:t("cardNews.briefPlaceholder"),onChange:_=>y("contentBrief",_.target.value)})]}),h.jsxs("div",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.outputSize")}),h.jsx("div",{className:"card-news-size-row",role:"group","aria-label":t("cardNews.outputSize"),children:["1024x1024","2048x2048","custom"].map(_=>h.jsx("button",{type:"button",className:`option-btn${d===_?" active":""}`,onClick:()=>m(_),children:_==="custom"?t("cardNews.customSize"):_==="1024x1024"?"1024²":"2048²"},_))}),d==="custom"?h.jsxs("div",{className:"card-news-custom-size",children:[h.jsx("input",{className:"custom-size-input",type:"text",inputMode:"numeric",value:g,onChange:_=>v(Number.parseInt(_.target.value,10)||g,p),"aria-label":t("size.width")}),h.jsx("span",{children:"×"}),h.jsx("input",{className:"custom-size-input",type:"text",inputMode:"numeric",value:p,onChange:_=>v(g,Number.parseInt(_.target.value,10)||p),"aria-label":t("size.height")})]}):null]}),h.jsxs("button",{type:"button",className:"generate-btn card-news-draft-btn",onClick:()=>{x()},disabled:S||!l.trim(),children:[S?h.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,t(S?"cardNews.drafting":"cardNews.draft")]}),j?h.jsx("div",{className:"card-news-error",role:"alert",children:j}):null,S?h.jsxs("div",{className:"card-news-inline-status",role:"status",children:[h.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}),h.jsx("span",{children:t("cardNews.drafting")})]}):null,h.jsxs("button",{type:"button",className:"composer__tool card-news-generate-btn",onClick:()=>{E()},disabled:!A||w||A.cards.every(_=>_.locked),children:[w?h.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,w?t("cardNews.progress.generating",{done:C.done,total:C.total}):t("cardNews.batchGenerate")]})]})}function ON(){const{t}=Te(),i=W(d=>d.uiMode),l=W(d=>d.referenceImages),o=W(d=>d.clearReferences),r=W(d=>d.styleSheetEnabled),u=i==="node"&&yf?"node":"classic";return h.jsxs("aside",{className:"sidebar",children:[h.jsxs("div",{className:"sidebar__scroll",children:[h.jsxs("div",{className:"logo",children:[h.jsx("div",{className:"logo-mark","aria-hidden":"true"}),h.jsxs("div",{className:"logo-copy",children:[h.jsx("div",{className:"logo-title",children:"ima2-gen"}),h.jsx("div",{className:"logo-subtitle",children:"gpt-image-2 studio"})]}),h.jsxs("div",{className:"logo-actions",children:[h.jsx(L0,{variant:"sidebar"}),h.jsx(bN,{})]})]}),h.jsx(hN,{}),u==="classic"?h.jsxs(h.Fragment,{children:[h.jsx(gN,{}),h.jsx(mN,{}),h.jsx(Wp,{})]}):u==="card-news"?h.jsx(h.Fragment,{children:h.jsx(DN,{})}):h.jsxs(h.Fragment,{children:[h.jsx(vN,{}),h.jsx(xN,{}),l.length>0?h.jsxs("div",{className:"node-mode-ref-warning",role:"status",children:[h.jsx("strong",{children:t("node.classicRefsParkedTitle")}),h.jsx("span",{children:t("node.classicRefsParkedBody")}),h.jsx("button",{type:"button",onClick:o,children:t("node.clearParkedRefs")})]}):null,r?h.jsx("div",{className:"node-mode-style-badge",role:"status",children:t("node.styleSheetActive")}):null,h.jsx("div",{className:"sidebar__node-hint",children:t("sidebar.nodeModeHint")}),h.jsx(Wp,{})]})]}),h.jsx(yN,{})]})}function HN(){const{t}=Te(),i=W(p=>p.currentImage),l=W(p=>p.showToast),o=W(p=>p.setPrompt);if(!i)return null;const r=()=>{const p=document.createElement("a");p.href=i.image,p.download=i.filename||"generated.png",p.click()},u=async()=>{try{const y=await(await fetch(i.image)).blob();await navigator.clipboard.write([new ClipboardItem({[y.type]:y})]),l(t("toast.imageCopied"))}catch{l(t("toast.copyFailed"),!0)}},d=()=>{i.prompt&&(navigator.clipboard.writeText(i.prompt),l(t("toast.promptCopied")))},g=async()=>{if(!i.prompt){l(t("toast.noPromptToFork"),!0);return}o(i.prompt);try{await W.getState().useCurrentAsReference()}catch{}const p=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');p&&(p.focus(),p.setSelectionRange(p.value.length,p.value.length)),l(t("toast.forkStarted"))};return h.jsxs("div",{className:"result-actions",children:[h.jsx("button",{type:"button",className:"action-btn",onClick:r,children:t("result.download")}),h.jsx("button",{type:"button",className:"action-btn",onClick:u,children:t("result.copyImage")}),h.jsx("button",{type:"button",className:"action-btn",onClick:d,children:t("result.copyPrompt")}),h.jsx("button",{type:"button",className:"action-btn action-btn--primary",onClick:g,title:t("result.continueHereTitle"),children:t("result.continueHere")})]})}function IN(t){return t instanceof HTMLElement?t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t.isContentEditable:!1}function BN(t){return t==="low"?"l":t==="medium"?"m":t==="high"?"h":t??null}function LN(t){if(!t)return null;const i=t.match(/^(\d+)x\1$/);return i?`${i[1]}²`:t.replace("x","×")}function ny(){const t=W(S=>S.currentImage),i=W(S=>S.history),l=W(S=>S.selectHistory),o=W(S=>S.activeGenerations),r=W(S=>S.quality),u=W(S=>S.getResolvedSize),d=W(S=>S.showToast),{t:g}=Te(),p=()=>{t?.prompt&&(navigator.clipboard.writeText(t.prompt),d(g("toast.promptCopied")))},y=BN(t?.quality??r),m=LN(t?.size??u()),v=b0(t?.model),x=S=>{if(S.key!=="ArrowLeft"&&S.key!=="ArrowRight"||S.target!==S.currentTarget||IN(S.target))return;const w=i.findIndex(A=>t?.filename?A.filename===t.filename:A.image===t?.image);if(w<0)return;const j=S.key==="ArrowLeft"?w-1:w+1,E=i[j];E&&(S.preventDefault(),l(E))};return h.jsxs("main",{className:"canvas",children:[h.jsx("div",{className:`progress-bar${o>0?" active":""}`}),t?h.jsxs("div",{className:"result-container visible",tabIndex:0,onKeyDown:x,"aria-label":g("canvas.imageViewerAria"),children:[h.jsx("img",{className:"result-img",src:t.url??t.image,alt:g("canvas.resultAlt")},t.filename??t.url??t.image),t.prompt?h.jsx("div",{className:"result-prompt",onClick:p,children:t.prompt}):null,h.jsx("div",{className:"result-meta",children:[t.elapsed!=null?`${t.elapsed}s`:null,t.usage?g("canvas.tokens",{n:t.usage.total_tokens??"?"}):null,y,m,v,t.provider??null].filter(S=>!!S).join(" · ")}),h.jsx(HN,{})]}):null]})}function st(t){if(typeof t=="string"||typeof t=="number")return""+t;let i="";if(Array.isArray(t))for(let l=0,o;l<t.length;l++)(o=st(t[l]))!==""&&(i+=(i&&" ")+o);else for(let l in t)t[l]&&(i+=(i&&" ")+l);return i}var kN={value:()=>{}};function Zr(){for(var t=0,i=arguments.length,l={},o;t<i;++t){if(!(o=arguments[t]+"")||o in l||/[\s.]/.test(o))throw new Error("illegal type: "+o);l[o]=[]}return new Mr(l)}function Mr(t){this._=t}function UN(t,i){return t.trim().split(/^|\s+/).map(function(l){var o="",r=l.indexOf(".");if(r>=0&&(o=l.slice(r+1),l=l.slice(0,r)),l&&!i.hasOwnProperty(l))throw new Error("unknown type: "+l);return{type:l,name:o}})}Mr.prototype=Zr.prototype={constructor:Mr,on:function(t,i){var l=this._,o=UN(t+"",l),r,u=-1,d=o.length;if(arguments.length<2){for(;++u<d;)if((r=(t=o[u]).type)&&(r=qN(l[r],t.name)))return r;return}if(i!=null&&typeof i!="function")throw new Error("invalid callback: "+i);for(;++u<d;)if(r=(t=o[u]).type)l[r]=ay(l[r],t.name,i);else if(i==null)for(r in l)l[r]=ay(l[r],t.name,null);return this},copy:function(){var t={},i=this._;for(var l in i)t[l]=i[l].slice();return new Mr(t)},call:function(t,i){if((r=arguments.length-2)>0)for(var l=new Array(r),o=0,r,u;o<r;++o)l[o]=arguments[o+2];if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(u=this._[t],o=0,r=u.length;o<r;++o)u[o].value.apply(i,l)},apply:function(t,i,l){if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(var o=this._[t],r=0,u=o.length;r<u;++r)o[r].value.apply(i,l)}};function qN(t,i){for(var l=0,o=t.length,r;l<o;++l)if((r=t[l]).name===i)return r.value}function ay(t,i,l){for(var o=0,r=t.length;o<r;++o)if(t[o].name===i){t[o]=kN,t=t.slice(0,o).concat(t.slice(o+1));break}return l!=null&&t.push({name:i,value:l}),t}var ef="http://www.w3.org/1999/xhtml";const iy={svg:"http://www.w3.org/2000/svg",xhtml:ef,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Kr(t){var i=t+="",l=i.indexOf(":");return l>=0&&(i=t.slice(0,l))!=="xmlns"&&(t=t.slice(l+1)),iy.hasOwnProperty(i)?{space:iy[i],local:t}:t}function GN(t){return function(){var i=this.ownerDocument,l=this.namespaceURI;return l===ef&&i.documentElement.namespaceURI===ef?i.createElement(t):i.createElementNS(l,t)}}function YN(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function q0(t){var i=Kr(t);return(i.local?YN:GN)(i)}function VN(){}function vf(t){return t==null?VN:function(){return this.querySelector(t)}}function XN(t){typeof t!="function"&&(t=vf(t));for(var i=this._groups,l=i.length,o=new Array(l),r=0;r<l;++r)for(var u=i[r],d=u.length,g=o[r]=new Array(d),p,y,m=0;m<d;++m)(p=u[m])&&(y=t.call(p,p.__data__,m,u))&&("__data__"in p&&(y.__data__=p.__data__),g[m]=y);return new Ut(o,this._parents)}function $N(t){return t==null?[]:Array.isArray(t)?t:Array.from(t)}function ZN(){return[]}function G0(t){return t==null?ZN:function(){return this.querySelectorAll(t)}}function KN(t){return function(){return $N(t.apply(this,arguments))}}function QN(t){typeof t=="function"?t=KN(t):t=G0(t);for(var i=this._groups,l=i.length,o=[],r=[],u=0;u<l;++u)for(var d=i[u],g=d.length,p,y=0;y<g;++y)(p=d[y])&&(o.push(t.call(p,p.__data__,y,d)),r.push(p));return new Ut(o,r)}function Y0(t){return function(){return this.matches(t)}}function V0(t){return function(i){return i.matches(t)}}var FN=Array.prototype.find;function PN(t){return function(){return FN.call(this.children,t)}}function JN(){return this.firstElementChild}function WN(t){return this.select(t==null?JN:PN(typeof t=="function"?t:V0(t)))}var e_=Array.prototype.filter;function t_(){return Array.from(this.children)}function n_(t){return function(){return e_.call(this.children,t)}}function a_(t){return this.selectAll(t==null?t_:n_(typeof t=="function"?t:V0(t)))}function i_(t){typeof t!="function"&&(t=Y0(t));for(var i=this._groups,l=i.length,o=new Array(l),r=0;r<l;++r)for(var u=i[r],d=u.length,g=o[r]=[],p,y=0;y<d;++y)(p=u[y])&&t.call(p,p.__data__,y,u)&&g.push(p);return new Ut(o,this._parents)}function X0(t){return new Array(t.length)}function l_(){return new Ut(this._enter||this._groups.map(X0),this._parents)}function Ir(t,i){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=i}Ir.prototype={constructor:Ir,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,i){return this._parent.insertBefore(t,i)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};function o_(t){return function(){return t}}function s_(t,i,l,o,r,u){for(var d=0,g,p=i.length,y=u.length;d<y;++d)(g=i[d])?(g.__data__=u[d],o[d]=g):l[d]=new Ir(t,u[d]);for(;d<p;++d)(g=i[d])&&(r[d]=g)}function r_(t,i,l,o,r,u,d){var g,p,y=new Map,m=i.length,v=u.length,x=new Array(m),S;for(g=0;g<m;++g)(p=i[g])&&(x[g]=S=d.call(p,p.__data__,g,i)+"",y.has(S)?r[g]=p:y.set(S,p));for(g=0;g<v;++g)S=d.call(t,u[g],g,u)+"",(p=y.get(S))?(o[g]=p,p.__data__=u[g],y.delete(S)):l[g]=new Ir(t,u[g]);for(g=0;g<m;++g)(p=i[g])&&y.get(x[g])===p&&(r[g]=p)}function c_(t){return t.__data__}function u_(t,i){if(!arguments.length)return Array.from(this,c_);var l=i?r_:s_,o=this._parents,r=this._groups;typeof t!="function"&&(t=o_(t));for(var u=r.length,d=new Array(u),g=new Array(u),p=new Array(u),y=0;y<u;++y){var m=o[y],v=r[y],x=v.length,S=d_(t.call(m,m&&m.__data__,y,o)),w=S.length,j=g[y]=new Array(w),E=d[y]=new Array(w),A=p[y]=new Array(x);l(m,v,j,E,A,S,i);for(var B=0,C=0,_,U;B<w;++B)if(_=j[B]){for(B>=C&&(C=B+1);!(U=E[C])&&++C<w;);_._next=U||null}}return d=new Ut(d,o),d._enter=g,d._exit=p,d}function d_(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function f_(){return new Ut(this._exit||this._groups.map(X0),this._parents)}function h_(t,i,l){var o=this.enter(),r=this,u=this.exit();return typeof t=="function"?(o=t(o),o&&(o=o.selection())):o=o.append(t+""),i!=null&&(r=i(r),r&&(r=r.selection())),l==null?u.remove():l(u),o&&r?o.merge(r).order():r}function g_(t){for(var i=t.selection?t.selection():t,l=this._groups,o=i._groups,r=l.length,u=o.length,d=Math.min(r,u),g=new Array(r),p=0;p<d;++p)for(var y=l[p],m=o[p],v=y.length,x=g[p]=new Array(v),S,w=0;w<v;++w)(S=y[w]||m[w])&&(x[w]=S);for(;p<r;++p)g[p]=l[p];return new Ut(g,this._parents)}function m_(){for(var t=this._groups,i=-1,l=t.length;++i<l;)for(var o=t[i],r=o.length-1,u=o[r],d;--r>=0;)(d=o[r])&&(u&&d.compareDocumentPosition(u)^4&&u.parentNode.insertBefore(d,u),u=d);return this}function p_(t){t||(t=y_);function i(v,x){return v&&x?t(v.__data__,x.__data__):!v-!x}for(var l=this._groups,o=l.length,r=new Array(o),u=0;u<o;++u){for(var d=l[u],g=d.length,p=r[u]=new Array(g),y,m=0;m<g;++m)(y=d[m])&&(p[m]=y);p.sort(i)}return new Ut(r,this._parents).order()}function y_(t,i){return t<i?-1:t>i?1:t>=i?0:NaN}function v_(){var t=arguments[0];return arguments[0]=this,t.apply(null,arguments),this}function x_(){return Array.from(this)}function b_(){for(var t=this._groups,i=0,l=t.length;i<l;++i)for(var o=t[i],r=0,u=o.length;r<u;++r){var d=o[r];if(d)return d}return null}function S_(){let t=0;for(const i of this)++t;return t}function w_(){return!this.node()}function N_(t){for(var i=this._groups,l=0,o=i.length;l<o;++l)for(var r=i[l],u=0,d=r.length,g;u<d;++u)(g=r[u])&&t.call(g,g.__data__,u,r);return this}function __(t){return function(){this.removeAttribute(t)}}function E_(t){return function(){this.removeAttributeNS(t.space,t.local)}}function C_(t,i){return function(){this.setAttribute(t,i)}}function T_(t,i){return function(){this.setAttributeNS(t.space,t.local,i)}}function A_(t,i){return function(){var l=i.apply(this,arguments);l==null?this.removeAttribute(t):this.setAttribute(t,l)}}function M_(t,i){return function(){var l=i.apply(this,arguments);l==null?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,l)}}function j_(t,i){var l=Kr(t);if(arguments.length<2){var o=this.node();return l.local?o.getAttributeNS(l.space,l.local):o.getAttribute(l)}return this.each((i==null?l.local?E_:__:typeof i=="function"?l.local?M_:A_:l.local?T_:C_)(l,i))}function $0(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function z_(t){return function(){this.style.removeProperty(t)}}function R_(t,i,l){return function(){this.style.setProperty(t,i,l)}}function D_(t,i,l){return function(){var o=i.apply(this,arguments);o==null?this.style.removeProperty(t):this.style.setProperty(t,o,l)}}function O_(t,i,l){return arguments.length>1?this.each((i==null?z_:typeof i=="function"?D_:R_)(t,i,l??"")):cl(this.node(),t)}function cl(t,i){return t.style.getPropertyValue(i)||$0(t).getComputedStyle(t,null).getPropertyValue(i)}function H_(t){return function(){delete this[t]}}function I_(t,i){return function(){this[t]=i}}function B_(t,i){return function(){var l=i.apply(this,arguments);l==null?delete this[t]:this[t]=l}}function L_(t,i){return arguments.length>1?this.each((i==null?H_:typeof i=="function"?B_:I_)(t,i)):this.node()[t]}function Z0(t){return t.trim().split(/^|\s+/)}function xf(t){return t.classList||new K0(t)}function K0(t){this._node=t,this._names=Z0(t.getAttribute("class")||"")}K0.prototype={add:function(t){var i=this._names.indexOf(t);i<0&&(this._names.push(t),this._node.setAttribute("class",this._names.join(" ")))},remove:function(t){var i=this._names.indexOf(t);i>=0&&(this._names.splice(i,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};function Q0(t,i){for(var l=xf(t),o=-1,r=i.length;++o<r;)l.add(i[o])}function F0(t,i){for(var l=xf(t),o=-1,r=i.length;++o<r;)l.remove(i[o])}function k_(t){return function(){Q0(this,t)}}function U_(t){return function(){F0(this,t)}}function q_(t,i){return function(){(i.apply(this,arguments)?Q0:F0)(this,t)}}function G_(t,i){var l=Z0(t+"");if(arguments.length<2){for(var o=xf(this.node()),r=-1,u=l.length;++r<u;)if(!o.contains(l[r]))return!1;return!0}return this.each((typeof i=="function"?q_:i?k_:U_)(l,i))}function Y_(){this.textContent=""}function V_(t){return function(){this.textContent=t}}function X_(t){return function(){var i=t.apply(this,arguments);this.textContent=i??""}}function $_(t){return arguments.length?this.each(t==null?Y_:(typeof t=="function"?X_:V_)(t)):this.node().textContent}function Z_(){this.innerHTML=""}function K_(t){return function(){this.innerHTML=t}}function Q_(t){return function(){var i=t.apply(this,arguments);this.innerHTML=i??""}}function F_(t){return arguments.length?this.each(t==null?Z_:(typeof t=="function"?Q_:K_)(t)):this.node().innerHTML}function P_(){this.nextSibling&&this.parentNode.appendChild(this)}function J_(){return this.each(P_)}function W_(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function eE(){return this.each(W_)}function tE(t){var i=typeof t=="function"?t:q0(t);return this.select(function(){return this.appendChild(i.apply(this,arguments))})}function nE(){return null}function aE(t,i){var l=typeof t=="function"?t:q0(t),o=i==null?nE:typeof i=="function"?i:vf(i);return this.select(function(){return this.insertBefore(l.apply(this,arguments),o.apply(this,arguments)||null)})}function iE(){var t=this.parentNode;t&&t.removeChild(this)}function lE(){return this.each(iE)}function oE(){var t=this.cloneNode(!1),i=this.parentNode;return i?i.insertBefore(t,this.nextSibling):t}function sE(){var t=this.cloneNode(!0),i=this.parentNode;return i?i.insertBefore(t,this.nextSibling):t}function rE(t){return this.select(t?sE:oE)}function cE(t){return arguments.length?this.property("__data__",t):this.node().__data__}function uE(t){return function(i){t.call(this,i,this.__data__)}}function dE(t){return t.trim().split(/^|\s+/).map(function(i){var l="",o=i.indexOf(".");return o>=0&&(l=i.slice(o+1),i=i.slice(0,o)),{type:i,name:l}})}function fE(t){return function(){var i=this.__on;if(i){for(var l=0,o=-1,r=i.length,u;l<r;++l)u=i[l],(!t.type||u.type===t.type)&&u.name===t.name?this.removeEventListener(u.type,u.listener,u.options):i[++o]=u;++o?i.length=o:delete this.__on}}}function hE(t,i,l){return function(){var o=this.__on,r,u=uE(i);if(o){for(var d=0,g=o.length;d<g;++d)if((r=o[d]).type===t.type&&r.name===t.name){this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=u,r.options=l),r.value=i;return}}this.addEventListener(t.type,u,l),r={type:t.type,name:t.name,value:i,listener:u,options:l},o?o.push(r):this.__on=[r]}}function gE(t,i,l){var o=dE(t+""),r,u=o.length,d;if(arguments.length<2){var g=this.node().__on;if(g){for(var p=0,y=g.length,m;p<y;++p)for(r=0,m=g[p];r<u;++r)if((d=o[r]).type===m.type&&d.name===m.name)return m.value}return}for(g=i?hE:fE,r=0;r<u;++r)this.each(g(o[r],i,l));return this}function P0(t,i,l){var o=$0(t),r=o.CustomEvent;typeof r=="function"?r=new r(i,l):(r=o.document.createEvent("Event"),l?(r.initEvent(i,l.bubbles,l.cancelable),r.detail=l.detail):r.initEvent(i,!1,!1)),t.dispatchEvent(r)}function mE(t,i){return function(){return P0(this,t,i)}}function pE(t,i){return function(){return P0(this,t,i.apply(this,arguments))}}function yE(t,i){return this.each((typeof i=="function"?pE:mE)(t,i))}function*vE(){for(var t=this._groups,i=0,l=t.length;i<l;++i)for(var o=t[i],r=0,u=o.length,d;r<u;++r)(d=o[r])&&(yield d)}var J0=[null];function Ut(t,i){this._groups=t,this._parents=i}function Io(){return new Ut([[document.documentElement]],J0)}function xE(){return this}Ut.prototype=Io.prototype={constructor:Ut,select:XN,selectAll:QN,selectChild:WN,selectChildren:a_,filter:i_,data:u_,enter:l_,exit:f_,join:h_,merge:g_,selection:xE,order:m_,sort:p_,call:v_,nodes:x_,node:b_,size:S_,empty:w_,each:N_,attr:j_,style:O_,property:L_,classed:G_,text:$_,html:F_,raise:J_,lower:eE,append:tE,insert:aE,remove:lE,clone:rE,datum:cE,on:gE,dispatch:yE,[Symbol.iterator]:vE};function kt(t){return typeof t=="string"?new Ut([[document.querySelector(t)]],[document.documentElement]):new Ut([[t]],J0)}function bE(t){let i;for(;i=t.sourceEvent;)t=i;return t}function tn(t,i){if(t=bE(t),i===void 0&&(i=t.currentTarget),i){var l=i.ownerSVGElement||i;if(l.createSVGPoint){var o=l.createSVGPoint();return o.x=t.clientX,o.y=t.clientY,o=o.matrixTransform(i.getScreenCTM().inverse()),[o.x,o.y]}if(i.getBoundingClientRect){var r=i.getBoundingClientRect();return[t.clientX-r.left-i.clientLeft,t.clientY-r.top-i.clientTop]}}return[t.pageX,t.pageY]}const SE={passive:!1},Co={capture:!0,passive:!1};function Ld(t){t.stopImmediatePropagation()}function ll(t){t.preventDefault(),t.stopImmediatePropagation()}function W0(t){var i=t.document.documentElement,l=kt(t).on("dragstart.drag",ll,Co);"onselectstart"in i?l.on("selectstart.drag",ll,Co):(i.__noselect=i.style.MozUserSelect,i.style.MozUserSelect="none")}function ev(t,i){var l=t.document.documentElement,o=kt(t).on("dragstart.drag",null);i&&(o.on("click.drag",ll,Co),setTimeout(function(){o.on("click.drag",null)},0)),"onselectstart"in l?o.on("selectstart.drag",null):(l.style.MozUserSelect=l.__noselect,delete l.__noselect)}const pr=t=>()=>t;function tf(t,{sourceEvent:i,subject:l,target:o,identifier:r,active:u,x:d,y:g,dx:p,dy:y,dispatch:m}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:i,enumerable:!0,configurable:!0},subject:{value:l,enumerable:!0,configurable:!0},target:{value:o,enumerable:!0,configurable:!0},identifier:{value:r,enumerable:!0,configurable:!0},active:{value:u,enumerable:!0,configurable:!0},x:{value:d,enumerable:!0,configurable:!0},y:{value:g,enumerable:!0,configurable:!0},dx:{value:p,enumerable:!0,configurable:!0},dy:{value:y,enumerable:!0,configurable:!0},_:{value:m}})}tf.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t};function wE(t){return!t.ctrlKey&&!t.button}function NE(){return this.parentNode}function _E(t,i){return i??{x:t.x,y:t.y}}function EE(){return navigator.maxTouchPoints||"ontouchstart"in this}function tv(){var t=wE,i=NE,l=_E,o=EE,r={},u=Zr("start","drag","end"),d=0,g,p,y,m,v=0;function x(_){_.on("mousedown.drag",S).filter(o).on("touchstart.drag",E).on("touchmove.drag",A,SE).on("touchend.drag touchcancel.drag",B).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function S(_,U){if(!(m||!t.call(this,_,U))){var R=C(this,i.call(this,_,U),_,U,"mouse");R&&(kt(_.view).on("mousemove.drag",w,Co).on("mouseup.drag",j,Co),W0(_.view),Ld(_),y=!1,g=_.clientX,p=_.clientY,R("start",_))}}function w(_){if(ll(_),!y){var U=_.clientX-g,R=_.clientY-p;y=U*U+R*R>v}r.mouse("drag",_)}function j(_){kt(_.view).on("mousemove.drag mouseup.drag",null),ev(_.view,y),ll(_),r.mouse("end",_)}function E(_,U){if(t.call(this,_,U)){var R=_.changedTouches,z=i.call(this,_,U),I=R.length,X,ce;for(X=0;X<I;++X)(ce=C(this,z,_,U,R[X].identifier,R[X]))&&(Ld(_),ce("start",_,R[X]))}}function A(_){var U=_.changedTouches,R=U.length,z,I;for(z=0;z<R;++z)(I=r[U[z].identifier])&&(ll(_),I("drag",_,U[z]))}function B(_){var U=_.changedTouches,R=U.length,z,I;for(m&&clearTimeout(m),m=setTimeout(function(){m=null},500),z=0;z<R;++z)(I=r[U[z].identifier])&&(Ld(_),I("end",_,U[z]))}function C(_,U,R,z,I,X){var ce=u.copy(),K=tn(X||R,U),te,ue,D;if((D=l.call(_,new tf("beforestart",{sourceEvent:R,target:x,identifier:I,active:d,x:K[0],y:K[1],dx:0,dy:0,dispatch:ce}),z))!=null)return te=D.x-K[0]||0,ue=D.y-K[1]||0,function Z(M,H,q){var k=K,J;switch(M){case"start":r[I]=Z,J=d++;break;case"end":delete r[I],--d;case"drag":K=tn(q||H,U),J=d;break}ce.call(M,_,new tf(M,{sourceEvent:H,subject:D,target:x,identifier:I,active:J,x:K[0]+te,y:K[1]+ue,dx:K[0]-k[0],dy:K[1]-k[1],dispatch:ce}),z)}}return x.filter=function(_){return arguments.length?(t=typeof _=="function"?_:pr(!!_),x):t},x.container=function(_){return arguments.length?(i=typeof _=="function"?_:pr(_),x):i},x.subject=function(_){return arguments.length?(l=typeof _=="function"?_:pr(_),x):l},x.touchable=function(_){return arguments.length?(o=typeof _=="function"?_:pr(!!_),x):o},x.on=function(){var _=u.on.apply(u,arguments);return _===u?x:_},x.clickDistance=function(_){return arguments.length?(v=(_=+_)*_,x):Math.sqrt(v)},x}function bf(t,i,l){t.prototype=i.prototype=l,l.constructor=t}function nv(t,i){var l=Object.create(t.prototype);for(var o in i)l[o]=i[o];return l}function Bo(){}var To=.7,Br=1/To,ol="\\s*([+-]?\\d+)\\s*",Ao="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",mn="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",CE=/^#([0-9a-f]{3,8})$/,TE=new RegExp(`^rgb\\(${ol},${ol},${ol}\\)$`),AE=new RegExp(`^rgb\\(${mn},${mn},${mn}\\)$`),ME=new RegExp(`^rgba\\(${ol},${ol},${ol},${Ao}\\)$`),jE=new RegExp(`^rgba\\(${mn},${mn},${mn},${Ao}\\)$`),zE=new RegExp(`^hsl\\(${Ao},${mn},${mn}\\)$`),RE=new RegExp(`^hsla\\(${Ao},${mn},${mn},${Ao}\\)$`),ly={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};bf(Bo,li,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:oy,formatHex:oy,formatHex8:DE,formatHsl:OE,formatRgb:sy,toString:sy});function oy(){return this.rgb().formatHex()}function DE(){return this.rgb().formatHex8()}function OE(){return av(this).formatHsl()}function sy(){return this.rgb().formatRgb()}function li(t){var i,l;return t=(t+"").trim().toLowerCase(),(i=CE.exec(t))?(l=i[1].length,i=parseInt(i[1],16),l===6?ry(i):l===3?new jt(i>>8&15|i>>4&240,i>>4&15|i&240,(i&15)<<4|i&15,1):l===8?yr(i>>24&255,i>>16&255,i>>8&255,(i&255)/255):l===4?yr(i>>12&15|i>>8&240,i>>8&15|i>>4&240,i>>4&15|i&240,((i&15)<<4|i&15)/255):null):(i=TE.exec(t))?new jt(i[1],i[2],i[3],1):(i=AE.exec(t))?new jt(i[1]*255/100,i[2]*255/100,i[3]*255/100,1):(i=ME.exec(t))?yr(i[1],i[2],i[3],i[4]):(i=jE.exec(t))?yr(i[1]*255/100,i[2]*255/100,i[3]*255/100,i[4]):(i=zE.exec(t))?dy(i[1],i[2]/100,i[3]/100,1):(i=RE.exec(t))?dy(i[1],i[2]/100,i[3]/100,i[4]):ly.hasOwnProperty(t)?ry(ly[t]):t==="transparent"?new jt(NaN,NaN,NaN,0):null}function ry(t){return new jt(t>>16&255,t>>8&255,t&255,1)}function yr(t,i,l,o){return o<=0&&(t=i=l=NaN),new jt(t,i,l,o)}function HE(t){return t instanceof Bo||(t=li(t)),t?(t=t.rgb(),new jt(t.r,t.g,t.b,t.opacity)):new jt}function nf(t,i,l,o){return arguments.length===1?HE(t):new jt(t,i,l,o??1)}function jt(t,i,l,o){this.r=+t,this.g=+i,this.b=+l,this.opacity=+o}bf(jt,nf,nv(Bo,{brighter(t){return t=t==null?Br:Math.pow(Br,t),new jt(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?To:Math.pow(To,t),new jt(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new jt(ai(this.r),ai(this.g),ai(this.b),Lr(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:cy,formatHex:cy,formatHex8:IE,formatRgb:uy,toString:uy}));function cy(){return`#${ni(this.r)}${ni(this.g)}${ni(this.b)}`}function IE(){return`#${ni(this.r)}${ni(this.g)}${ni(this.b)}${ni((isNaN(this.opacity)?1:this.opacity)*255)}`}function uy(){const t=Lr(this.opacity);return`${t===1?"rgb(":"rgba("}${ai(this.r)}, ${ai(this.g)}, ${ai(this.b)}${t===1?")":`, ${t})`}`}function Lr(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function ai(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function ni(t){return t=ai(t),(t<16?"0":"")+t.toString(16)}function dy(t,i,l,o){return o<=0?t=i=l=NaN:l<=0||l>=1?t=i=NaN:i<=0&&(t=NaN),new nn(t,i,l,o)}function av(t){if(t instanceof nn)return new nn(t.h,t.s,t.l,t.opacity);if(t instanceof Bo||(t=li(t)),!t)return new nn;if(t instanceof nn)return t;t=t.rgb();var i=t.r/255,l=t.g/255,o=t.b/255,r=Math.min(i,l,o),u=Math.max(i,l,o),d=NaN,g=u-r,p=(u+r)/2;return g?(i===u?d=(l-o)/g+(l<o)*6:l===u?d=(o-i)/g+2:d=(i-l)/g+4,g/=p<.5?u+r:2-u-r,d*=60):g=p>0&&p<1?0:d,new nn(d,g,p,t.opacity)}function BE(t,i,l,o){return arguments.length===1?av(t):new nn(t,i,l,o??1)}function nn(t,i,l,o){this.h=+t,this.s=+i,this.l=+l,this.opacity=+o}bf(nn,BE,nv(Bo,{brighter(t){return t=t==null?Br:Math.pow(Br,t),new nn(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?To:Math.pow(To,t),new nn(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,i=isNaN(t)||isNaN(this.s)?0:this.s,l=this.l,o=l+(l<.5?l:1-l)*i,r=2*l-o;return new jt(kd(t>=240?t-240:t+120,r,o),kd(t,r,o),kd(t<120?t+240:t-120,r,o),this.opacity)},clamp(){return new nn(fy(this.h),vr(this.s),vr(this.l),Lr(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=Lr(this.opacity);return`${t===1?"hsl(":"hsla("}${fy(this.h)}, ${vr(this.s)*100}%, ${vr(this.l)*100}%${t===1?")":`, ${t})`}`}}));function fy(t){return t=(t||0)%360,t<0?t+360:t}function vr(t){return Math.max(0,Math.min(1,t||0))}function kd(t,i,l){return(t<60?i+(l-i)*t/60:t<180?l:t<240?i+(l-i)*(240-t)/60:i)*255}const Sf=t=>()=>t;function LE(t,i){return function(l){return t+l*i}}function kE(t,i,l){return t=Math.pow(t,l),i=Math.pow(i,l)-t,l=1/l,function(o){return Math.pow(t+o*i,l)}}function UE(t){return(t=+t)==1?iv:function(i,l){return l-i?kE(i,l,t):Sf(isNaN(i)?l:i)}}function iv(t,i){var l=i-t;return l?LE(t,l):Sf(isNaN(t)?i:t)}const kr=(function t(i){var l=UE(i);function o(r,u){var d=l((r=nf(r)).r,(u=nf(u)).r),g=l(r.g,u.g),p=l(r.b,u.b),y=iv(r.opacity,u.opacity);return function(m){return r.r=d(m),r.g=g(m),r.b=p(m),r.opacity=y(m),r+""}}return o.gamma=t,o})(1);function qE(t,i){i||(i=[]);var l=t?Math.min(i.length,t.length):0,o=i.slice(),r;return function(u){for(r=0;r<l;++r)o[r]=t[r]*(1-u)+i[r]*u;return o}}function GE(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function YE(t,i){var l=i?i.length:0,o=t?Math.min(l,t.length):0,r=new Array(o),u=new Array(l),d;for(d=0;d<o;++d)r[d]=_o(t[d],i[d]);for(;d<l;++d)u[d]=i[d];return function(g){for(d=0;d<o;++d)u[d]=r[d](g);return u}}function VE(t,i){var l=new Date;return t=+t,i=+i,function(o){return l.setTime(t*(1-o)+i*o),l}}function hn(t,i){return t=+t,i=+i,function(l){return t*(1-l)+i*l}}function XE(t,i){var l={},o={},r;(t===null||typeof t!="object")&&(t={}),(i===null||typeof i!="object")&&(i={});for(r in i)r in t?l[r]=_o(t[r],i[r]):o[r]=i[r];return function(u){for(r in l)o[r]=l[r](u);return o}}var af=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ud=new RegExp(af.source,"g");function $E(t){return function(){return t}}function ZE(t){return function(i){return t(i)+""}}function lv(t,i){var l=af.lastIndex=Ud.lastIndex=0,o,r,u,d=-1,g=[],p=[];for(t=t+"",i=i+"";(o=af.exec(t))&&(r=Ud.exec(i));)(u=r.index)>l&&(u=i.slice(l,u),g[d]?g[d]+=u:g[++d]=u),(o=o[0])===(r=r[0])?g[d]?g[d]+=r:g[++d]=r:(g[++d]=null,p.push({i:d,x:hn(o,r)})),l=Ud.lastIndex;return l<i.length&&(u=i.slice(l),g[d]?g[d]+=u:g[++d]=u),g.length<2?p[0]?ZE(p[0].x):$E(i):(i=p.length,function(y){for(var m=0,v;m<i;++m)g[(v=p[m]).i]=v.x(y);return g.join("")})}function _o(t,i){var l=typeof i,o;return i==null||l==="boolean"?Sf(i):(l==="number"?hn:l==="string"?(o=li(i))?(i=o,kr):lv:i instanceof li?kr:i instanceof Date?VE:GE(i)?qE:Array.isArray(i)?YE:typeof i.valueOf!="function"&&typeof i.toString!="function"||isNaN(i)?XE:hn)(t,i)}var hy=180/Math.PI,lf={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function ov(t,i,l,o,r,u){var d,g,p;return(d=Math.sqrt(t*t+i*i))&&(t/=d,i/=d),(p=t*l+i*o)&&(l-=t*p,o-=i*p),(g=Math.sqrt(l*l+o*o))&&(l/=g,o/=g,p/=g),t*o<i*l&&(t=-t,i=-i,p=-p,d=-d),{translateX:r,translateY:u,rotate:Math.atan2(i,t)*hy,skewX:Math.atan(p)*hy,scaleX:d,scaleY:g}}var xr;function KE(t){const i=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(t+"");return i.isIdentity?lf:ov(i.a,i.b,i.c,i.d,i.e,i.f)}function QE(t){return t==null||(xr||(xr=document.createElementNS("http://www.w3.org/2000/svg","g")),xr.setAttribute("transform",t),!(t=xr.transform.baseVal.consolidate()))?lf:(t=t.matrix,ov(t.a,t.b,t.c,t.d,t.e,t.f))}function sv(t,i,l,o){function r(y){return y.length?y.pop()+" ":""}function u(y,m,v,x,S,w){if(y!==v||m!==x){var j=S.push("translate(",null,i,null,l);w.push({i:j-4,x:hn(y,v)},{i:j-2,x:hn(m,x)})}else(v||x)&&S.push("translate("+v+i+x+l)}function d(y,m,v,x){y!==m?(y-m>180?m+=360:m-y>180&&(y+=360),x.push({i:v.push(r(v)+"rotate(",null,o)-2,x:hn(y,m)})):m&&v.push(r(v)+"rotate("+m+o)}function g(y,m,v,x){y!==m?x.push({i:v.push(r(v)+"skewX(",null,o)-2,x:hn(y,m)}):m&&v.push(r(v)+"skewX("+m+o)}function p(y,m,v,x,S,w){if(y!==v||m!==x){var j=S.push(r(S)+"scale(",null,",",null,")");w.push({i:j-4,x:hn(y,v)},{i:j-2,x:hn(m,x)})}else(v!==1||x!==1)&&S.push(r(S)+"scale("+v+","+x+")")}return function(y,m){var v=[],x=[];return y=t(y),m=t(m),u(y.translateX,y.translateY,m.translateX,m.translateY,v,x),d(y.rotate,m.rotate,v,x),g(y.skewX,m.skewX,v,x),p(y.scaleX,y.scaleY,m.scaleX,m.scaleY,v,x),y=m=null,function(S){for(var w=-1,j=x.length,E;++w<j;)v[(E=x[w]).i]=E.x(S);return v.join("")}}}var FE=sv(KE,"px, ","px)","deg)"),PE=sv(QE,", ",")",")"),JE=1e-12;function gy(t){return((t=Math.exp(t))+1/t)/2}function WE(t){return((t=Math.exp(t))-1/t)/2}function e2(t){return((t=Math.exp(2*t))-1)/(t+1)}const jr=(function t(i,l,o){function r(u,d){var g=u[0],p=u[1],y=u[2],m=d[0],v=d[1],x=d[2],S=m-g,w=v-p,j=S*S+w*w,E,A;if(j<JE)A=Math.log(x/y)/i,E=function(z){return[g+z*S,p+z*w,y*Math.exp(i*z*A)]};else{var B=Math.sqrt(j),C=(x*x-y*y+o*j)/(2*y*l*B),_=(x*x-y*y-o*j)/(2*x*l*B),U=Math.log(Math.sqrt(C*C+1)-C),R=Math.log(Math.sqrt(_*_+1)-_);A=(R-U)/i,E=function(z){var I=z*A,X=gy(U),ce=y/(l*B)*(X*e2(i*I+U)-WE(U));return[g+ce*S,p+ce*w,y*X/gy(i*I+U)]}}return E.duration=A*1e3*i/Math.SQRT2,E}return r.rho=function(u){var d=Math.max(.001,+u),g=d*d,p=g*g;return t(d,g,p)},r})(Math.SQRT2,2,4);var ul=0,xo=0,ho=0,rv=1e3,Ur,bo,qr=0,oi=0,Qr=0,Mo=typeof performance=="object"&&performance.now?performance:Date,cv=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17)};function wf(){return oi||(cv(t2),oi=Mo.now()+Qr)}function t2(){oi=0}function Gr(){this._call=this._time=this._next=null}Gr.prototype=uv.prototype={constructor:Gr,restart:function(t,i,l){if(typeof t!="function")throw new TypeError("callback is not a function");l=(l==null?wf():+l)+(i==null?0:+i),!this._next&&bo!==this&&(bo?bo._next=this:Ur=this,bo=this),this._call=t,this._time=l,of()},stop:function(){this._call&&(this._call=null,this._time=1/0,of())}};function uv(t,i,l){var o=new Gr;return o.restart(t,i,l),o}function n2(){wf(),++ul;for(var t=Ur,i;t;)(i=oi-t._time)>=0&&t._call.call(void 0,i),t=t._next;--ul}function my(){oi=(qr=Mo.now())+Qr,ul=xo=0;try{n2()}finally{ul=0,i2(),oi=0}}function a2(){var t=Mo.now(),i=t-qr;i>rv&&(Qr-=i,qr=t)}function i2(){for(var t,i=Ur,l,o=1/0;i;)i._call?(o>i._time&&(o=i._time),t=i,i=i._next):(l=i._next,i._next=null,i=t?t._next=l:Ur=l);bo=t,of(o)}function of(t){if(!ul){xo&&(xo=clearTimeout(xo));var i=t-oi;i>24?(t<1/0&&(xo=setTimeout(my,t-Mo.now()-Qr)),ho&&(ho=clearInterval(ho))):(ho||(qr=Mo.now(),ho=setInterval(a2,rv)),ul=1,cv(my))}}function py(t,i,l){var o=new Gr;return i=i==null?0:+i,o.restart(r=>{o.stop(),t(r+i)},i,l),o}var l2=Zr("start","end","cancel","interrupt"),o2=[],dv=0,yy=1,sf=2,zr=3,vy=4,rf=5,Rr=6;function Fr(t,i,l,o,r,u){var d=t.__transition;if(!d)t.__transition={};else if(l in d)return;s2(t,l,{name:i,index:o,group:r,on:l2,tween:o2,time:u.time,delay:u.delay,duration:u.duration,ease:u.ease,timer:null,state:dv})}function Nf(t,i){var l=on(t,i);if(l.state>dv)throw new Error("too late; already scheduled");return l}function yn(t,i){var l=on(t,i);if(l.state>zr)throw new Error("too late; already running");return l}function on(t,i){var l=t.__transition;if(!l||!(l=l[i]))throw new Error("transition not found");return l}function s2(t,i,l){var o=t.__transition,r;o[i]=l,l.timer=uv(u,0,l.time);function u(y){l.state=yy,l.timer.restart(d,l.delay,l.time),l.delay<=y&&d(y-l.delay)}function d(y){var m,v,x,S;if(l.state!==yy)return p();for(m in o)if(S=o[m],S.name===l.name){if(S.state===zr)return py(d);S.state===vy?(S.state=Rr,S.timer.stop(),S.on.call("interrupt",t,t.__data__,S.index,S.group),delete o[m]):+m<i&&(S.state=Rr,S.timer.stop(),S.on.call("cancel",t,t.__data__,S.index,S.group),delete o[m])}if(py(function(){l.state===zr&&(l.state=vy,l.timer.restart(g,l.delay,l.time),g(y))}),l.state=sf,l.on.call("start",t,t.__data__,l.index,l.group),l.state===sf){for(l.state=zr,r=new Array(x=l.tween.length),m=0,v=-1;m<x;++m)(S=l.tween[m].value.call(t,t.__data__,l.index,l.group))&&(r[++v]=S);r.length=v+1}}function g(y){for(var m=y<l.duration?l.ease.call(null,y/l.duration):(l.timer.restart(p),l.state=rf,1),v=-1,x=r.length;++v<x;)r[v].call(t,m);l.state===rf&&(l.on.call("end",t,t.__data__,l.index,l.group),p())}function p(){l.state=Rr,l.timer.stop(),delete o[i];for(var y in o)return;delete t.__transition}}function Dr(t,i){var l=t.__transition,o,r,u=!0,d;if(l){i=i==null?null:i+"";for(d in l){if((o=l[d]).name!==i){u=!1;continue}r=o.state>sf&&o.state<rf,o.state=Rr,o.timer.stop(),o.on.call(r?"interrupt":"cancel",t,t.__data__,o.index,o.group),delete l[d]}u&&delete t.__transition}}function r2(t){return this.each(function(){Dr(this,t)})}function c2(t,i){var l,o;return function(){var r=yn(this,t),u=r.tween;if(u!==l){o=l=u;for(var d=0,g=o.length;d<g;++d)if(o[d].name===i){o=o.slice(),o.splice(d,1);break}}r.tween=o}}function u2(t,i,l){var o,r;if(typeof l!="function")throw new Error;return function(){var u=yn(this,t),d=u.tween;if(d!==o){r=(o=d).slice();for(var g={name:i,value:l},p=0,y=r.length;p<y;++p)if(r[p].name===i){r[p]=g;break}p===y&&r.push(g)}u.tween=r}}function d2(t,i){var l=this._id;if(t+="",arguments.length<2){for(var o=on(this.node(),l).tween,r=0,u=o.length,d;r<u;++r)if((d=o[r]).name===t)return d.value;return null}return this.each((i==null?c2:u2)(l,t,i))}function _f(t,i,l){var o=t._id;return t.each(function(){var r=yn(this,o);(r.value||(r.value={}))[i]=l.apply(this,arguments)}),function(r){return on(r,o).value[i]}}function fv(t,i){var l;return(typeof i=="number"?hn:i instanceof li?kr:(l=li(i))?(i=l,kr):lv)(t,i)}function f2(t){return function(){this.removeAttribute(t)}}function h2(t){return function(){this.removeAttributeNS(t.space,t.local)}}function g2(t,i,l){var o,r=l+"",u;return function(){var d=this.getAttribute(t);return d===r?null:d===o?u:u=i(o=d,l)}}function m2(t,i,l){var o,r=l+"",u;return function(){var d=this.getAttributeNS(t.space,t.local);return d===r?null:d===o?u:u=i(o=d,l)}}function p2(t,i,l){var o,r,u;return function(){var d,g=l(this),p;return g==null?void this.removeAttribute(t):(d=this.getAttribute(t),p=g+"",d===p?null:d===o&&p===r?u:(r=p,u=i(o=d,g)))}}function y2(t,i,l){var o,r,u;return function(){var d,g=l(this),p;return g==null?void this.removeAttributeNS(t.space,t.local):(d=this.getAttributeNS(t.space,t.local),p=g+"",d===p?null:d===o&&p===r?u:(r=p,u=i(o=d,g)))}}function v2(t,i){var l=Kr(t),o=l==="transform"?PE:fv;return this.attrTween(t,typeof i=="function"?(l.local?y2:p2)(l,o,_f(this,"attr."+t,i)):i==null?(l.local?h2:f2)(l):(l.local?m2:g2)(l,o,i))}function x2(t,i){return function(l){this.setAttribute(t,i.call(this,l))}}function b2(t,i){return function(l){this.setAttributeNS(t.space,t.local,i.call(this,l))}}function S2(t,i){var l,o;function r(){var u=i.apply(this,arguments);return u!==o&&(l=(o=u)&&b2(t,u)),l}return r._value=i,r}function w2(t,i){var l,o;function r(){var u=i.apply(this,arguments);return u!==o&&(l=(o=u)&&x2(t,u)),l}return r._value=i,r}function N2(t,i){var l="attr."+t;if(arguments.length<2)return(l=this.tween(l))&&l._value;if(i==null)return this.tween(l,null);if(typeof i!="function")throw new Error;var o=Kr(t);return this.tween(l,(o.local?S2:w2)(o,i))}function _2(t,i){return function(){Nf(this,t).delay=+i.apply(this,arguments)}}function E2(t,i){return i=+i,function(){Nf(this,t).delay=i}}function C2(t){var i=this._id;return arguments.length?this.each((typeof t=="function"?_2:E2)(i,t)):on(this.node(),i).delay}function T2(t,i){return function(){yn(this,t).duration=+i.apply(this,arguments)}}function A2(t,i){return i=+i,function(){yn(this,t).duration=i}}function M2(t){var i=this._id;return arguments.length?this.each((typeof t=="function"?T2:A2)(i,t)):on(this.node(),i).duration}function j2(t,i){if(typeof i!="function")throw new Error;return function(){yn(this,t).ease=i}}function z2(t){var i=this._id;return arguments.length?this.each(j2(i,t)):on(this.node(),i).ease}function R2(t,i){return function(){var l=i.apply(this,arguments);if(typeof l!="function")throw new Error;yn(this,t).ease=l}}function D2(t){if(typeof t!="function")throw new Error;return this.each(R2(this._id,t))}function O2(t){typeof t!="function"&&(t=Y0(t));for(var i=this._groups,l=i.length,o=new Array(l),r=0;r<l;++r)for(var u=i[r],d=u.length,g=o[r]=[],p,y=0;y<d;++y)(p=u[y])&&t.call(p,p.__data__,y,u)&&g.push(p);return new Vn(o,this._parents,this._name,this._id)}function H2(t){if(t._id!==this._id)throw new Error;for(var i=this._groups,l=t._groups,o=i.length,r=l.length,u=Math.min(o,r),d=new Array(o),g=0;g<u;++g)for(var p=i[g],y=l[g],m=p.length,v=d[g]=new Array(m),x,S=0;S<m;++S)(x=p[S]||y[S])&&(v[S]=x);for(;g<o;++g)d[g]=i[g];return new Vn(d,this._parents,this._name,this._id)}function I2(t){return(t+"").trim().split(/^|\s+/).every(function(i){var l=i.indexOf(".");return l>=0&&(i=i.slice(0,l)),!i||i==="start"})}function B2(t,i,l){var o,r,u=I2(i)?Nf:yn;return function(){var d=u(this,t),g=d.on;g!==o&&(r=(o=g).copy()).on(i,l),d.on=r}}function L2(t,i){var l=this._id;return arguments.length<2?on(this.node(),l).on.on(t):this.each(B2(l,t,i))}function k2(t){return function(){var i=this.parentNode;for(var l in this.__transition)if(+l!==t)return;i&&i.removeChild(this)}}function U2(){return this.on("end.remove",k2(this._id))}function q2(t){var i=this._name,l=this._id;typeof t!="function"&&(t=vf(t));for(var o=this._groups,r=o.length,u=new Array(r),d=0;d<r;++d)for(var g=o[d],p=g.length,y=u[d]=new Array(p),m,v,x=0;x<p;++x)(m=g[x])&&(v=t.call(m,m.__data__,x,g))&&("__data__"in m&&(v.__data__=m.__data__),y[x]=v,Fr(y[x],i,l,x,y,on(m,l)));return new Vn(u,this._parents,i,l)}function G2(t){var i=this._name,l=this._id;typeof t!="function"&&(t=G0(t));for(var o=this._groups,r=o.length,u=[],d=[],g=0;g<r;++g)for(var p=o[g],y=p.length,m,v=0;v<y;++v)if(m=p[v]){for(var x=t.call(m,m.__data__,v,p),S,w=on(m,l),j=0,E=x.length;j<E;++j)(S=x[j])&&Fr(S,i,l,j,x,w);u.push(x),d.push(m)}return new Vn(u,d,i,l)}var Y2=Io.prototype.constructor;function V2(){return new Y2(this._groups,this._parents)}function X2(t,i){var l,o,r;return function(){var u=cl(this,t),d=(this.style.removeProperty(t),cl(this,t));return u===d?null:u===l&&d===o?r:r=i(l=u,o=d)}}function hv(t){return function(){this.style.removeProperty(t)}}function $2(t,i,l){var o,r=l+"",u;return function(){var d=cl(this,t);return d===r?null:d===o?u:u=i(o=d,l)}}function Z2(t,i,l){var o,r,u;return function(){var d=cl(this,t),g=l(this),p=g+"";return g==null&&(p=g=(this.style.removeProperty(t),cl(this,t))),d===p?null:d===o&&p===r?u:(r=p,u=i(o=d,g))}}function K2(t,i){var l,o,r,u="style."+i,d="end."+u,g;return function(){var p=yn(this,t),y=p.on,m=p.value[u]==null?g||(g=hv(i)):void 0;(y!==l||r!==m)&&(o=(l=y).copy()).on(d,r=m),p.on=o}}function Q2(t,i,l){var o=(t+="")=="transform"?FE:fv;return i==null?this.styleTween(t,X2(t,o)).on("end.style."+t,hv(t)):typeof i=="function"?this.styleTween(t,Z2(t,o,_f(this,"style."+t,i))).each(K2(this._id,t)):this.styleTween(t,$2(t,o,i),l).on("end.style."+t,null)}function F2(t,i,l){return function(o){this.style.setProperty(t,i.call(this,o),l)}}function P2(t,i,l){var o,r;function u(){var d=i.apply(this,arguments);return d!==r&&(o=(r=d)&&F2(t,d,l)),o}return u._value=i,u}function J2(t,i,l){var o="style."+(t+="");if(arguments.length<2)return(o=this.tween(o))&&o._value;if(i==null)return this.tween(o,null);if(typeof i!="function")throw new Error;return this.tween(o,P2(t,i,l??""))}function W2(t){return function(){this.textContent=t}}function eC(t){return function(){var i=t(this);this.textContent=i??""}}function tC(t){return this.tween("text",typeof t=="function"?eC(_f(this,"text",t)):W2(t==null?"":t+""))}function nC(t){return function(i){this.textContent=t.call(this,i)}}function aC(t){var i,l;function o(){var r=t.apply(this,arguments);return r!==l&&(i=(l=r)&&nC(r)),i}return o._value=t,o}function iC(t){var i="text";if(arguments.length<1)return(i=this.tween(i))&&i._value;if(t==null)return this.tween(i,null);if(typeof t!="function")throw new Error;return this.tween(i,aC(t))}function lC(){for(var t=this._name,i=this._id,l=gv(),o=this._groups,r=o.length,u=0;u<r;++u)for(var d=o[u],g=d.length,p,y=0;y<g;++y)if(p=d[y]){var m=on(p,i);Fr(p,t,l,y,d,{time:m.time+m.delay+m.duration,delay:0,duration:m.duration,ease:m.ease})}return new Vn(o,this._parents,t,l)}function oC(){var t,i,l=this,o=l._id,r=l.size();return new Promise(function(u,d){var g={value:d},p={value:function(){--r===0&&u()}};l.each(function(){var y=yn(this,o),m=y.on;m!==t&&(i=(t=m).copy(),i._.cancel.push(g),i._.interrupt.push(g),i._.end.push(p)),y.on=i}),r===0&&u()})}var sC=0;function Vn(t,i,l,o){this._groups=t,this._parents=i,this._name=l,this._id=o}function gv(){return++sC}var qn=Io.prototype;Vn.prototype={constructor:Vn,select:q2,selectAll:G2,selectChild:qn.selectChild,selectChildren:qn.selectChildren,filter:O2,merge:H2,selection:V2,transition:lC,call:qn.call,nodes:qn.nodes,node:qn.node,size:qn.size,empty:qn.empty,each:qn.each,on:L2,attr:v2,attrTween:N2,style:Q2,styleTween:J2,text:tC,textTween:iC,remove:U2,tween:d2,delay:C2,duration:M2,ease:z2,easeVarying:D2,end:oC,[Symbol.iterator]:qn[Symbol.iterator]};function rC(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}var cC={time:null,delay:0,duration:250,ease:rC};function uC(t,i){for(var l;!(l=t.__transition)||!(l=l[i]);)if(!(t=t.parentNode))throw new Error(`transition ${i} not found`);return l}function dC(t){var i,l;t instanceof Vn?(i=t._id,t=t._name):(i=gv(),(l=cC).time=wf(),t=t==null?null:t+"");for(var o=this._groups,r=o.length,u=0;u<r;++u)for(var d=o[u],g=d.length,p,y=0;y<g;++y)(p=d[y])&&Fr(p,t,i,y,d,l||uC(p,i));return new Vn(o,this._parents,t,i)}Io.prototype.interrupt=r2;Io.prototype.transition=dC;const br=t=>()=>t;function fC(t,{sourceEvent:i,target:l,transform:o,dispatch:r}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:i,enumerable:!0,configurable:!0},target:{value:l,enumerable:!0,configurable:!0},transform:{value:o,enumerable:!0,configurable:!0},_:{value:r}})}function Yn(t,i,l){this.k=t,this.x=i,this.y=l}Yn.prototype={constructor:Yn,scale:function(t){return t===1?this:new Yn(this.k*t,this.x,this.y)},translate:function(t,i){return t===0&i===0?this:new Yn(this.k,this.x+this.k*t,this.y+this.k*i)},apply:function(t){return[t[0]*this.k+this.x,t[1]*this.k+this.y]},applyX:function(t){return t*this.k+this.x},applyY:function(t){return t*this.k+this.y},invert:function(t){return[(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},invertX:function(t){return(t-this.x)/this.k},invertY:function(t){return(t-this.y)/this.k},rescaleX:function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},rescaleY:function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Pr=new Yn(1,0,0);mv.prototype=Yn.prototype;function mv(t){for(;!t.__zoom;)if(!(t=t.parentNode))return Pr;return t.__zoom}function qd(t){t.stopImmediatePropagation()}function go(t){t.preventDefault(),t.stopImmediatePropagation()}function hC(t){return(!t.ctrlKey||t.type==="wheel")&&!t.button}function gC(){var t=this;return t instanceof SVGElement?(t=t.ownerSVGElement||t,t.hasAttribute("viewBox")?(t=t.viewBox.baseVal,[[t.x,t.y],[t.x+t.width,t.y+t.height]]):[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]):[[0,0],[t.clientWidth,t.clientHeight]]}function xy(){return this.__zoom||Pr}function mC(t){return-t.deltaY*(t.deltaMode===1?.05:t.deltaMode?1:.002)*(t.ctrlKey?10:1)}function pC(){return navigator.maxTouchPoints||"ontouchstart"in this}function yC(t,i,l){var o=t.invertX(i[0][0])-l[0][0],r=t.invertX(i[1][0])-l[1][0],u=t.invertY(i[0][1])-l[0][1],d=t.invertY(i[1][1])-l[1][1];return t.translate(r>o?(o+r)/2:Math.min(0,o)||Math.max(0,r),d>u?(u+d)/2:Math.min(0,u)||Math.max(0,d))}function pv(){var t=hC,i=gC,l=yC,o=mC,r=pC,u=[0,1/0],d=[[-1/0,-1/0],[1/0,1/0]],g=250,p=jr,y=Zr("start","zoom","end"),m,v,x,S=500,w=150,j=0,E=10;function A(D){D.property("__zoom",xy).on("wheel.zoom",I,{passive:!1}).on("mousedown.zoom",X).on("dblclick.zoom",ce).filter(r).on("touchstart.zoom",K).on("touchmove.zoom",te).on("touchend.zoom touchcancel.zoom",ue).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}A.transform=function(D,Z,M,H){var q=D.selection?D.selection():D;q.property("__zoom",xy),D!==q?U(D,Z,M,H):q.interrupt().each(function(){R(this,arguments).event(H).start().zoom(null,typeof Z=="function"?Z.apply(this,arguments):Z).end()})},A.scaleBy=function(D,Z,M,H){A.scaleTo(D,function(){var q=this.__zoom.k,k=typeof Z=="function"?Z.apply(this,arguments):Z;return q*k},M,H)},A.scaleTo=function(D,Z,M,H){A.transform(D,function(){var q=i.apply(this,arguments),k=this.__zoom,J=M==null?_(q):typeof M=="function"?M.apply(this,arguments):M,T=k.invert(J),L=typeof Z=="function"?Z.apply(this,arguments):Z;return l(C(B(k,L),J,T),q,d)},M,H)},A.translateBy=function(D,Z,M,H){A.transform(D,function(){return l(this.__zoom.translate(typeof Z=="function"?Z.apply(this,arguments):Z,typeof M=="function"?M.apply(this,arguments):M),i.apply(this,arguments),d)},null,H)},A.translateTo=function(D,Z,M,H,q){A.transform(D,function(){var k=i.apply(this,arguments),J=this.__zoom,T=H==null?_(k):typeof H=="function"?H.apply(this,arguments):H;return l(Pr.translate(T[0],T[1]).scale(J.k).translate(typeof Z=="function"?-Z.apply(this,arguments):-Z,typeof M=="function"?-M.apply(this,arguments):-M),k,d)},H,q)};function B(D,Z){return Z=Math.max(u[0],Math.min(u[1],Z)),Z===D.k?D:new Yn(Z,D.x,D.y)}function C(D,Z,M){var H=Z[0]-M[0]*D.k,q=Z[1]-M[1]*D.k;return H===D.x&&q===D.y?D:new Yn(D.k,H,q)}function _(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function U(D,Z,M,H){D.on("start.zoom",function(){R(this,arguments).event(H).start()}).on("interrupt.zoom end.zoom",function(){R(this,arguments).event(H).end()}).tween("zoom",function(){var q=this,k=arguments,J=R(q,k).event(H),T=i.apply(q,k),L=M==null?_(T):typeof M=="function"?M.apply(q,k):M,ne=Math.max(T[1][0]-T[0][0],T[1][1]-T[0][1]),ae=q.__zoom,V=typeof Z=="function"?Z.apply(q,k):Z,se=p(ae.invert(L).concat(ne/ae.k),V.invert(L).concat(ne/V.k));return function(de){if(de===1)de=V;else{var le=se(de),fe=ne/le[2];de=new Yn(fe,L[0]-le[0]*fe,L[1]-le[1]*fe)}J.zoom(null,de)}})}function R(D,Z,M){return!M&&D.__zooming||new z(D,Z)}function z(D,Z){this.that=D,this.args=Z,this.active=0,this.sourceEvent=null,this.extent=i.apply(D,Z),this.taps=0}z.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,Z){return this.mouse&&D!=="mouse"&&(this.mouse[1]=Z.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=Z.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=Z.invert(this.touch1[0])),this.that.__zoom=Z,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var Z=kt(this.that).datum();y.call(D,this.that,new fC(D,{sourceEvent:this.sourceEvent,target:A,transform:this.that.__zoom,dispatch:y}),Z)}};function I(D,...Z){if(!t.apply(this,arguments))return;var M=R(this,Z).event(D),H=this.__zoom,q=Math.max(u[0],Math.min(u[1],H.k*Math.pow(2,o.apply(this,arguments)))),k=tn(D);if(M.wheel)(M.mouse[0][0]!==k[0]||M.mouse[0][1]!==k[1])&&(M.mouse[1]=H.invert(M.mouse[0]=k)),clearTimeout(M.wheel);else{if(H.k===q)return;M.mouse=[k,H.invert(k)],Dr(this),M.start()}go(D),M.wheel=setTimeout(J,w),M.zoom("mouse",l(C(B(H,q),M.mouse[0],M.mouse[1]),M.extent,d));function J(){M.wheel=null,M.end()}}function X(D,...Z){if(x||!t.apply(this,arguments))return;var M=D.currentTarget,H=R(this,Z,!0).event(D),q=kt(D.view).on("mousemove.zoom",L,!0).on("mouseup.zoom",ne,!0),k=tn(D,M),J=D.clientX,T=D.clientY;W0(D.view),qd(D),H.mouse=[k,this.__zoom.invert(k)],Dr(this),H.start();function L(ae){if(go(ae),!H.moved){var V=ae.clientX-J,se=ae.clientY-T;H.moved=V*V+se*se>j}H.event(ae).zoom("mouse",l(C(H.that.__zoom,H.mouse[0]=tn(ae,M),H.mouse[1]),H.extent,d))}function ne(ae){q.on("mousemove.zoom mouseup.zoom",null),ev(ae.view,H.moved),go(ae),H.event(ae).end()}}function ce(D,...Z){if(t.apply(this,arguments)){var M=this.__zoom,H=tn(D.changedTouches?D.changedTouches[0]:D,this),q=M.invert(H),k=M.k*(D.shiftKey?.5:2),J=l(C(B(M,k),H,q),i.apply(this,Z),d);go(D),g>0?kt(this).transition().duration(g).call(U,J,H,D):kt(this).call(A.transform,J,H,D)}}function K(D,...Z){if(t.apply(this,arguments)){var M=D.touches,H=M.length,q=R(this,Z,D.changedTouches.length===H).event(D),k,J,T,L;for(qd(D),J=0;J<H;++J)T=M[J],L=tn(T,this),L=[L,this.__zoom.invert(L),T.identifier],q.touch0?!q.touch1&&q.touch0[2]!==L[2]&&(q.touch1=L,q.taps=0):(q.touch0=L,k=!0,q.taps=1+!!m);m&&(m=clearTimeout(m)),k&&(q.taps<2&&(v=L[0],m=setTimeout(function(){m=null},S)),Dr(this),q.start())}}function te(D,...Z){if(this.__zooming){var M=R(this,Z).event(D),H=D.changedTouches,q=H.length,k,J,T,L;for(go(D),k=0;k<q;++k)J=H[k],T=tn(J,this),M.touch0&&M.touch0[2]===J.identifier?M.touch0[0]=T:M.touch1&&M.touch1[2]===J.identifier&&(M.touch1[0]=T);if(J=M.that.__zoom,M.touch1){var ne=M.touch0[0],ae=M.touch0[1],V=M.touch1[0],se=M.touch1[1],de=(de=V[0]-ne[0])*de+(de=V[1]-ne[1])*de,le=(le=se[0]-ae[0])*le+(le=se[1]-ae[1])*le;J=B(J,Math.sqrt(de/le)),T=[(ne[0]+V[0])/2,(ne[1]+V[1])/2],L=[(ae[0]+se[0])/2,(ae[1]+se[1])/2]}else if(M.touch0)T=M.touch0[0],L=M.touch0[1];else return;M.zoom("touch",l(C(J,T,L),M.extent,d))}}function ue(D,...Z){if(this.__zooming){var M=R(this,Z).event(D),H=D.changedTouches,q=H.length,k,J;for(qd(D),x&&clearTimeout(x),x=setTimeout(function(){x=null},S),k=0;k<q;++k)J=H[k],M.touch0&&M.touch0[2]===J.identifier?delete M.touch0:M.touch1&&M.touch1[2]===J.identifier&&delete M.touch1;if(M.touch1&&!M.touch0&&(M.touch0=M.touch1,delete M.touch1),M.touch0)M.touch0[1]=this.__zoom.invert(M.touch0[0]);else if(M.end(),M.taps===2&&(J=tn(J,this),Math.hypot(v[0]-J[0],v[1]-J[1])<E)){var T=kt(this).on("dblclick.zoom");T&&T.apply(this,arguments)}}}return A.wheelDelta=function(D){return arguments.length?(o=typeof D=="function"?D:br(+D),A):o},A.filter=function(D){return arguments.length?(t=typeof D=="function"?D:br(!!D),A):t},A.touchable=function(D){return arguments.length?(r=typeof D=="function"?D:br(!!D),A):r},A.extent=function(D){return arguments.length?(i=typeof D=="function"?D:br([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),A):i},A.scaleExtent=function(D){return arguments.length?(u[0]=+D[0],u[1]=+D[1],A):[u[0],u[1]]},A.translateExtent=function(D){return arguments.length?(d[0][0]=+D[0][0],d[1][0]=+D[1][0],d[0][1]=+D[0][1],d[1][1]=+D[1][1],A):[[d[0][0],d[0][1]],[d[1][0],d[1][1]]]},A.constrain=function(D){return arguments.length?(l=D,A):l},A.duration=function(D){return arguments.length?(g=+D,A):g},A.interpolate=function(D){return arguments.length?(p=D,A):p},A.on=function(){var D=y.on.apply(y,arguments);return D===y?A:D},A.clickDistance=function(D){return arguments.length?(j=(D=+D)*D,A):Math.sqrt(j)},A.tapDistance=function(D){return arguments.length?(E=+D,A):E},A}const pn={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:t=>`Node type "${t}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:t=>`The old edge with id=${t} does not exist.`,error009:t=>`Marker type "${t}" doesn't exist.`,error008:(t,{id:i,sourceHandle:l,targetHandle:o})=>`Couldn't create edge for ${t} handle id: "${t==="source"?l:o}", edge id: ${i}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:t=>`Edge type "${t}" not found. Using fallback type "default".`,error012:t=>`Node with id "${t}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(t="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${t}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},jo=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],yv=["Enter"," ","Escape"],vv={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:t,x:i,y:l})=>`Moved selected node ${t}. New position, x: ${i}, y: ${l}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var dl;(function(t){t.Strict="strict",t.Loose="loose"})(dl||(dl={}));var ii;(function(t){t.Free="free",t.Vertical="vertical",t.Horizontal="horizontal"})(ii||(ii={}));var zo;(function(t){t.Partial="partial",t.Full="full"})(zo||(zo={}));const xv={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Ea;(function(t){t.Bezier="default",t.Straight="straight",t.Step="step",t.SmoothStep="smoothstep",t.SimpleBezier="simplebezier"})(Ea||(Ea={}));var Yr;(function(t){t.Arrow="arrow",t.ArrowClosed="arrowclosed"})(Yr||(Yr={}));var me;(function(t){t.Left="left",t.Top="top",t.Right="right",t.Bottom="bottom"})(me||(me={}));const by={[me.Left]:me.Right,[me.Right]:me.Left,[me.Top]:me.Bottom,[me.Bottom]:me.Top};function bv(t){return t===null?null:t?"valid":"invalid"}const Sv=t=>"id"in t&&"source"in t&&"target"in t,vC=t=>"id"in t&&"position"in t&&!("source"in t)&&!("target"in t),Ef=t=>"id"in t&&"internals"in t&&!("source"in t)&&!("target"in t),Lo=(t,i=[0,0])=>{const{width:l,height:o}=Xn(t),r=t.origin??i,u=l*r[0],d=o*r[1];return{x:t.position.x-u,y:t.position.y-d}},xC=(t,i={nodeOrigin:[0,0]})=>{if(t.length===0)return{x:0,y:0,width:0,height:0};const l=t.reduce((o,r)=>{const u=typeof r=="string";let d=!i.nodeLookup&&!u?r:void 0;i.nodeLookup&&(d=u?i.nodeLookup.get(r):Ef(r)?r:i.nodeLookup.get(r.id));const g=d?Vr(d,i.nodeOrigin):{x:0,y:0,x2:0,y2:0};return Jr(o,g)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Wr(l)},ko=(t,i={})=>{let l={x:1/0,y:1/0,x2:-1/0,y2:-1/0},o=!1;return t.forEach(r=>{(i.filter===void 0||i.filter(r))&&(l=Jr(l,Vr(r)),o=!0)}),o?Wr(l):{x:0,y:0,width:0,height:0}},Cf=(t,i,[l,o,r]=[0,0,1],u=!1,d=!1)=>{const g={...qo(i,[l,o,r]),width:i.width/r,height:i.height/r},p=[];for(const y of t.values()){const{measured:m,selectable:v=!0,hidden:x=!1}=y;if(d&&!v||x)continue;const S=m.width??y.width??y.initialWidth??null,w=m.height??y.height??y.initialHeight??null,j=Ro(g,hl(y)),E=(S??0)*(w??0),A=u&&j>0;(!y.internals.handleBounds||A||j>=E||y.dragging)&&p.push(y)}return p},bC=(t,i)=>{const l=new Set;return t.forEach(o=>{l.add(o.id)}),i.filter(o=>l.has(o.source)||l.has(o.target))};function SC(t,i){const l=new Map,o=i?.nodes?new Set(i.nodes.map(r=>r.id)):null;return t.forEach(r=>{r.measured.width&&r.measured.height&&(i?.includeHiddenNodes||!r.hidden)&&(!o||o.has(r.id))&&l.set(r.id,r)}),l}async function wC({nodes:t,width:i,height:l,panZoom:o,minZoom:r,maxZoom:u},d){if(t.size===0)return Promise.resolve(!0);const g=SC(t,d),p=ko(g),y=Tf(p,i,l,d?.minZoom??r,d?.maxZoom??u,d?.padding??.1);return await o.setViewport(y,{duration:d?.duration,ease:d?.ease,interpolate:d?.interpolate}),Promise.resolve(!0)}function wv({nodeId:t,nextPosition:i,nodeLookup:l,nodeOrigin:o=[0,0],nodeExtent:r,onError:u}){const d=l.get(t),g=d.parentId?l.get(d.parentId):void 0,{x:p,y}=g?g.internals.positionAbsolute:{x:0,y:0},m=d.origin??o;let v=d.extent||r;if(d.extent==="parent"&&!d.expandParent)if(!g)u?.("005",pn.error005());else{const S=g.measured.width,w=g.measured.height;S&&w&&(v=[[p,y],[p+S,y+w]])}else g&&gl(d.extent)&&(v=[[d.extent[0][0]+p,d.extent[0][1]+y],[d.extent[1][0]+p,d.extent[1][1]+y]]);const x=gl(v)?si(i,v,d.measured):i;return(d.measured.width===void 0||d.measured.height===void 0)&&u?.("015",pn.error015()),{position:{x:x.x-p+(d.measured.width??0)*m[0],y:x.y-y+(d.measured.height??0)*m[1]},positionAbsolute:x}}async function NC({nodesToRemove:t=[],edgesToRemove:i=[],nodes:l,edges:o,onBeforeDelete:r}){const u=new Set(t.map(x=>x.id)),d=[];for(const x of l){if(x.deletable===!1)continue;const S=u.has(x.id),w=!S&&x.parentId&&d.find(j=>j.id===x.parentId);(S||w)&&d.push(x)}const g=new Set(i.map(x=>x.id)),p=o.filter(x=>x.deletable!==!1),m=bC(d,p);for(const x of p)g.has(x.id)&&!m.find(w=>w.id===x.id)&&m.push(x);if(!r)return{edges:m,nodes:d};const v=await r({nodes:d,edges:m});return typeof v=="boolean"?v?{edges:m,nodes:d}:{edges:[],nodes:[]}:v}const fl=(t,i=0,l=1)=>Math.min(Math.max(t,i),l),si=(t={x:0,y:0},i,l)=>({x:fl(t.x,i[0][0],i[1][0]-(l?.width??0)),y:fl(t.y,i[0][1],i[1][1]-(l?.height??0))});function Nv(t,i,l){const{width:o,height:r}=Xn(l),{x:u,y:d}=l.internals.positionAbsolute;return si(t,[[u,d],[u+o,d+r]],i)}const Sy=(t,i,l)=>t<i?fl(Math.abs(t-i),1,i)/i:t>l?-fl(Math.abs(t-l),1,i)/i:0,_v=(t,i,l=15,o=40)=>{const r=Sy(t.x,o,i.width-o)*l,u=Sy(t.y,o,i.height-o)*l;return[r,u]},Jr=(t,i)=>({x:Math.min(t.x,i.x),y:Math.min(t.y,i.y),x2:Math.max(t.x2,i.x2),y2:Math.max(t.y2,i.y2)}),cf=({x:t,y:i,width:l,height:o})=>({x:t,y:i,x2:t+l,y2:i+o}),Wr=({x:t,y:i,x2:l,y2:o})=>({x:t,y:i,width:l-t,height:o-i}),hl=(t,i=[0,0])=>{const{x:l,y:o}=Ef(t)?t.internals.positionAbsolute:Lo(t,i);return{x:l,y:o,width:t.measured?.width??t.width??t.initialWidth??0,height:t.measured?.height??t.height??t.initialHeight??0}},Vr=(t,i=[0,0])=>{const{x:l,y:o}=Ef(t)?t.internals.positionAbsolute:Lo(t,i);return{x:l,y:o,x2:l+(t.measured?.width??t.width??t.initialWidth??0),y2:o+(t.measured?.height??t.height??t.initialHeight??0)}},Ev=(t,i)=>Wr(Jr(cf(t),cf(i))),Ro=(t,i)=>{const l=Math.max(0,Math.min(t.x+t.width,i.x+i.width)-Math.max(t.x,i.x)),o=Math.max(0,Math.min(t.y+t.height,i.y+i.height)-Math.max(t.y,i.y));return Math.ceil(l*o)},wy=t=>an(t.width)&&an(t.height)&&an(t.x)&&an(t.y),an=t=>!isNaN(t)&&isFinite(t),_C=(t,i)=>{},Uo=(t,i=[1,1])=>({x:i[0]*Math.round(t.x/i[0]),y:i[1]*Math.round(t.y/i[1])}),qo=({x:t,y:i},[l,o,r],u=!1,d=[1,1])=>{const g={x:(t-l)/r,y:(i-o)/r};return u?Uo(g,d):g},Xr=({x:t,y:i},[l,o,r])=>({x:t*r+l,y:i*r+o});function el(t,i){if(typeof t=="number")return Math.floor((i-i/(1+t))*.5);if(typeof t=="string"&&t.endsWith("px")){const l=parseFloat(t);if(!Number.isNaN(l))return Math.floor(l)}if(typeof t=="string"&&t.endsWith("%")){const l=parseFloat(t);if(!Number.isNaN(l))return Math.floor(i*l*.01)}return console.error(`[React Flow] The padding value "${t}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function EC(t,i,l){if(typeof t=="string"||typeof t=="number"){const o=el(t,l),r=el(t,i);return{top:o,right:r,bottom:o,left:r,x:r*2,y:o*2}}if(typeof t=="object"){const o=el(t.top??t.y??0,l),r=el(t.bottom??t.y??0,l),u=el(t.left??t.x??0,i),d=el(t.right??t.x??0,i);return{top:o,right:d,bottom:r,left:u,x:u+d,y:o+r}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function CC(t,i,l,o,r,u){const{x:d,y:g}=Xr(t,[i,l,o]),{x:p,y}=Xr({x:t.x+t.width,y:t.y+t.height},[i,l,o]),m=r-p,v=u-y;return{left:Math.floor(d),top:Math.floor(g),right:Math.floor(m),bottom:Math.floor(v)}}const Tf=(t,i,l,o,r,u)=>{const d=EC(u,i,l),g=(i-d.x)/t.width,p=(l-d.y)/t.height,y=Math.min(g,p),m=fl(y,o,r),v=t.x+t.width/2,x=t.y+t.height/2,S=i/2-v*m,w=l/2-x*m,j=CC(t,S,w,m,i,l),E={left:Math.min(j.left-d.left,0),top:Math.min(j.top-d.top,0),right:Math.min(j.right-d.right,0),bottom:Math.min(j.bottom-d.bottom,0)};return{x:S-E.left+E.right,y:w-E.top+E.bottom,zoom:m}},Do=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function gl(t){return t!=null&&t!=="parent"}function Xn(t){return{width:t.measured?.width??t.width??t.initialWidth??0,height:t.measured?.height??t.height??t.initialHeight??0}}function Cv(t){return(t.measured?.width??t.width??t.initialWidth)!==void 0&&(t.measured?.height??t.height??t.initialHeight)!==void 0}function Tv(t,i={width:0,height:0},l,o,r){const u={...t},d=o.get(l);if(d){const g=d.origin||r;u.x+=d.internals.positionAbsolute.x-(i.width??0)*g[0],u.y+=d.internals.positionAbsolute.y-(i.height??0)*g[1]}return u}function Ny(t,i){if(t.size!==i.size)return!1;for(const l of t)if(!i.has(l))return!1;return!0}function TC(){let t,i;return{promise:new Promise((o,r)=>{t=o,i=r}),resolve:t,reject:i}}function AC(t){return{...vv,...t||{}}}function Eo(t,{snapGrid:i=[0,0],snapToGrid:l=!1,transform:o,containerBounds:r}){const{x:u,y:d}=ln(t),g=qo({x:u-(r?.left??0),y:d-(r?.top??0)},o),{x:p,y}=l?Uo(g,i):g;return{xSnapped:p,ySnapped:y,...g}}const Af=t=>({width:t.offsetWidth,height:t.offsetHeight}),Av=t=>t?.getRootNode?.()||window?.document,MC=["INPUT","SELECT","TEXTAREA"];function Mv(t){const i=t.composedPath?.()?.[0]||t.target;return i?.nodeType!==1?!1:MC.includes(i.nodeName)||i.hasAttribute("contenteditable")||!!i.closest(".nokey")}const jv=t=>"clientX"in t,ln=(t,i)=>{const l=jv(t),o=l?t.clientX:t.touches?.[0].clientX,r=l?t.clientY:t.touches?.[0].clientY;return{x:o-(i?.left??0),y:r-(i?.top??0)}},_y=(t,i,l,o,r)=>{const u=i.querySelectorAll(`.${t}`);return!u||!u.length?null:Array.from(u).map(d=>{const g=d.getBoundingClientRect();return{id:d.getAttribute("data-handleid"),type:t,nodeId:r,position:d.getAttribute("data-handlepos"),x:(g.left-l.left)/o,y:(g.top-l.top)/o,...Af(d)}})};function zv({sourceX:t,sourceY:i,targetX:l,targetY:o,sourceControlX:r,sourceControlY:u,targetControlX:d,targetControlY:g}){const p=t*.125+r*.375+d*.375+l*.125,y=i*.125+u*.375+g*.375+o*.125,m=Math.abs(p-t),v=Math.abs(y-i);return[p,y,m,v]}function Sr(t,i){return t>=0?.5*t:i*25*Math.sqrt(-t)}function Ey({pos:t,x1:i,y1:l,x2:o,y2:r,c:u}){switch(t){case me.Left:return[i-Sr(i-o,u),l];case me.Right:return[i+Sr(o-i,u),l];case me.Top:return[i,l-Sr(l-r,u)];case me.Bottom:return[i,l+Sr(r-l,u)]}}function Rv({sourceX:t,sourceY:i,sourcePosition:l=me.Bottom,targetX:o,targetY:r,targetPosition:u=me.Top,curvature:d=.25}){const[g,p]=Ey({pos:l,x1:t,y1:i,x2:o,y2:r,c:d}),[y,m]=Ey({pos:u,x1:o,y1:r,x2:t,y2:i,c:d}),[v,x,S,w]=zv({sourceX:t,sourceY:i,targetX:o,targetY:r,sourceControlX:g,sourceControlY:p,targetControlX:y,targetControlY:m});return[`M${t},${i} C${g},${p} ${y},${m} ${o},${r}`,v,x,S,w]}function Dv({sourceX:t,sourceY:i,targetX:l,targetY:o}){const r=Math.abs(l-t)/2,u=l<t?l+r:l-r,d=Math.abs(o-i)/2,g=o<i?o+d:o-d;return[u,g,r,d]}function jC({sourceNode:t,targetNode:i,selected:l=!1,zIndex:o=0,elevateOnSelect:r=!1,zIndexMode:u="basic"}){if(u==="manual")return o;const d=r&&l?o+1e3:o,g=Math.max(t.parentId||r&&t.selected?t.internals.z:0,i.parentId||r&&i.selected?i.internals.z:0);return d+g}function zC({sourceNode:t,targetNode:i,width:l,height:o,transform:r}){const u=Jr(Vr(t),Vr(i));u.x===u.x2&&(u.x2+=1),u.y===u.y2&&(u.y2+=1);const d={x:-r[0]/r[2],y:-r[1]/r[2],width:l/r[2],height:o/r[2]};return Ro(d,Wr(u))>0}const RC=({source:t,sourceHandle:i,target:l,targetHandle:o})=>`xy-edge__${t}${i||""}-${l}${o||""}`,DC=(t,i)=>i.some(l=>l.source===t.source&&l.target===t.target&&(l.sourceHandle===t.sourceHandle||!l.sourceHandle&&!t.sourceHandle)&&(l.targetHandle===t.targetHandle||!l.targetHandle&&!t.targetHandle)),OC=(t,i,l={})=>{if(!t.source||!t.target)return i;const o=l.getEdgeId||RC;let r;return Sv(t)?r={...t}:r={...t,id:o(t)},DC(r,i)?i:(r.sourceHandle===null&&delete r.sourceHandle,r.targetHandle===null&&delete r.targetHandle,i.concat(r))};function Ov({sourceX:t,sourceY:i,targetX:l,targetY:o}){const[r,u,d,g]=Dv({sourceX:t,sourceY:i,targetX:l,targetY:o});return[`M ${t},${i}L ${l},${o}`,r,u,d,g]}const Cy={[me.Left]:{x:-1,y:0},[me.Right]:{x:1,y:0},[me.Top]:{x:0,y:-1},[me.Bottom]:{x:0,y:1}},HC=({source:t,sourcePosition:i=me.Bottom,target:l})=>i===me.Left||i===me.Right?t.x<l.x?{x:1,y:0}:{x:-1,y:0}:t.y<l.y?{x:0,y:1}:{x:0,y:-1},Ty=(t,i)=>Math.sqrt(Math.pow(i.x-t.x,2)+Math.pow(i.y-t.y,2));function IC({source:t,sourcePosition:i=me.Bottom,target:l,targetPosition:o=me.Top,center:r,offset:u,stepPosition:d}){const g=Cy[i],p=Cy[o],y={x:t.x+g.x*u,y:t.y+g.y*u},m={x:l.x+p.x*u,y:l.y+p.y*u},v=HC({source:y,sourcePosition:i,target:m}),x=v.x!==0?"x":"y",S=v[x];let w=[],j,E;const A={x:0,y:0},B={x:0,y:0},[,,C,_]=Dv({sourceX:t.x,sourceY:t.y,targetX:l.x,targetY:l.y});if(g[x]*p[x]===-1){x==="x"?(j=r.x??y.x+(m.x-y.x)*d,E=r.y??(y.y+m.y)/2):(j=r.x??(y.x+m.x)/2,E=r.y??y.y+(m.y-y.y)*d);const I=[{x:j,y:y.y},{x:j,y:m.y}],X=[{x:y.x,y:E},{x:m.x,y:E}];g[x]===S?w=x==="x"?I:X:w=x==="x"?X:I}else{const I=[{x:y.x,y:m.y}],X=[{x:m.x,y:y.y}];if(x==="x"?w=g.x===S?X:I:w=g.y===S?I:X,i===o){const D=Math.abs(t[x]-l[x]);if(D<=u){const Z=Math.min(u-1,u-D);g[x]===S?A[x]=(y[x]>t[x]?-1:1)*Z:B[x]=(m[x]>l[x]?-1:1)*Z}}if(i!==o){const D=x==="x"?"y":"x",Z=g[x]===p[D],M=y[D]>m[D],H=y[D]<m[D];(g[x]===1&&(!Z&&M||Z&&H)||g[x]!==1&&(!Z&&H||Z&&M))&&(w=x==="x"?I:X)}const ce={x:y.x+A.x,y:y.y+A.y},K={x:m.x+B.x,y:m.y+B.y},te=Math.max(Math.abs(ce.x-w[0].x),Math.abs(K.x-w[0].x)),ue=Math.max(Math.abs(ce.y-w[0].y),Math.abs(K.y-w[0].y));te>=ue?(j=(ce.x+K.x)/2,E=w[0].y):(j=w[0].x,E=(ce.y+K.y)/2)}const U={x:y.x+A.x,y:y.y+A.y},R={x:m.x+B.x,y:m.y+B.y};return[[t,...U.x!==w[0].x||U.y!==w[0].y?[U]:[],...w,...R.x!==w[w.length-1].x||R.y!==w[w.length-1].y?[R]:[],l],j,E,C,_]}function BC(t,i,l,o){const r=Math.min(Ty(t,i)/2,Ty(i,l)/2,o),{x:u,y:d}=i;if(t.x===u&&u===l.x||t.y===d&&d===l.y)return`L${u} ${d}`;if(t.y===d){const y=t.x<l.x?-1:1,m=t.y<l.y?1:-1;return`L ${u+r*y},${d}Q ${u},${d} ${u},${d+r*m}`}const g=t.x<l.x?1:-1,p=t.y<l.y?-1:1;return`L ${u},${d+r*p}Q ${u},${d} ${u+r*g},${d}`}function uf({sourceX:t,sourceY:i,sourcePosition:l=me.Bottom,targetX:o,targetY:r,targetPosition:u=me.Top,borderRadius:d=5,centerX:g,centerY:p,offset:y=20,stepPosition:m=.5}){const[v,x,S,w,j]=IC({source:{x:t,y:i},sourcePosition:l,target:{x:o,y:r},targetPosition:u,center:{x:g,y:p},offset:y,stepPosition:m});let E=`M${v[0].x} ${v[0].y}`;for(let A=1;A<v.length-1;A++)E+=BC(v[A-1],v[A],v[A+1],d);return E+=`L${v[v.length-1].x} ${v[v.length-1].y}`,[E,x,S,w,j]}function Ay(t){return t&&!!(t.internals.handleBounds||t.handles?.length)&&!!(t.measured.width||t.width||t.initialWidth)}function LC(t){const{sourceNode:i,targetNode:l}=t;if(!Ay(i)||!Ay(l))return null;const o=i.internals.handleBounds||My(i.handles),r=l.internals.handleBounds||My(l.handles),u=jy(o?.source??[],t.sourceHandle),d=jy(t.connectionMode===dl.Strict?r?.target??[]:(r?.target??[]).concat(r?.source??[]),t.targetHandle);if(!u||!d)return t.onError?.("008",pn.error008(u?"target":"source",{id:t.id,sourceHandle:t.sourceHandle,targetHandle:t.targetHandle})),null;const g=u?.position||me.Bottom,p=d?.position||me.Top,y=ri(i,u,g),m=ri(l,d,p);return{sourceX:y.x,sourceY:y.y,targetX:m.x,targetY:m.y,sourcePosition:g,targetPosition:p}}function My(t){if(!t)return null;const i=[],l=[];for(const o of t)o.width=o.width??1,o.height=o.height??1,o.type==="source"?i.push(o):o.type==="target"&&l.push(o);return{source:i,target:l}}function ri(t,i,l=me.Left,o=!1){const r=(i?.x??0)+t.internals.positionAbsolute.x,u=(i?.y??0)+t.internals.positionAbsolute.y,{width:d,height:g}=i??Xn(t);if(o)return{x:r+d/2,y:u+g/2};switch(i?.position??l){case me.Top:return{x:r+d/2,y:u};case me.Right:return{x:r+d,y:u+g/2};case me.Bottom:return{x:r+d/2,y:u+g};case me.Left:return{x:r,y:u+g/2}}}function jy(t,i){return t&&(i?t.find(l=>l.id===i):t[0])||null}function df(t,i){return t?typeof t=="string"?t:`${i?`${i}__`:""}${Object.keys(t).sort().map(o=>`${o}=${t[o]}`).join("&")}`:""}function kC(t,{id:i,defaultColor:l,defaultMarkerStart:o,defaultMarkerEnd:r}){const u=new Set;return t.reduce((d,g)=>([g.markerStart||o,g.markerEnd||r].forEach(p=>{if(p&&typeof p=="object"){const y=df(p,i);u.has(y)||(d.push({id:y,color:p.color||l,...p}),u.add(y))}}),d),[]).sort((d,g)=>d.id.localeCompare(g.id))}const Hv=1e3,UC=10,Mf={nodeOrigin:[0,0],nodeExtent:jo,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},qC={...Mf,checkEquality:!0};function jf(t,i){const l={...t};for(const o in i)i[o]!==void 0&&(l[o]=i[o]);return l}function GC(t,i,l){const o=jf(Mf,l);for(const r of t.values())if(r.parentId)Rf(r,t,i,o);else{const u=Lo(r,o.nodeOrigin),d=gl(r.extent)?r.extent:o.nodeExtent,g=si(u,d,Xn(r));r.internals.positionAbsolute=g}}function YC(t,i){if(!t.handles)return t.measured?i?.internals.handleBounds:void 0;const l=[],o=[];for(const r of t.handles){const u={id:r.id,width:r.width??1,height:r.height??1,nodeId:t.id,x:r.x,y:r.y,position:r.position,type:r.type};r.type==="source"?l.push(u):r.type==="target"&&o.push(u)}return{source:l,target:o}}function zf(t){return t==="manual"}function ff(t,i,l,o={}){const r=jf(qC,o),u={i:0},d=new Map(i),g=r?.elevateNodesOnSelect&&!zf(r.zIndexMode)?Hv:0;let p=t.length>0,y=!1;i.clear(),l.clear();for(const m of t){let v=d.get(m.id);if(r.checkEquality&&m===v?.internals.userNode)i.set(m.id,v);else{const x=Lo(m,r.nodeOrigin),S=gl(m.extent)?m.extent:r.nodeExtent,w=si(x,S,Xn(m));v={...r.defaults,...m,measured:{width:m.measured?.width,height:m.measured?.height},internals:{positionAbsolute:w,handleBounds:YC(m,v),z:Iv(m,g,r.zIndexMode),userNode:m}},i.set(m.id,v)}(v.measured===void 0||v.measured.width===void 0||v.measured.height===void 0)&&!v.hidden&&(p=!1),m.parentId&&Rf(v,i,l,o,u),y||=m.selected??!1}return{nodesInitialized:p,hasSelectedNodes:y}}function VC(t,i){if(!t.parentId)return;const l=i.get(t.parentId);l?l.set(t.id,t):i.set(t.parentId,new Map([[t.id,t]]))}function Rf(t,i,l,o,r){const{elevateNodesOnSelect:u,nodeOrigin:d,nodeExtent:g,zIndexMode:p}=jf(Mf,o),y=t.parentId,m=i.get(y);if(!m){console.warn(`Parent node ${y} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}VC(t,l),r&&!m.parentId&&m.internals.rootParentIndex===void 0&&p==="auto"&&(m.internals.rootParentIndex=++r.i,m.internals.z=m.internals.z+r.i*UC),r&&m.internals.rootParentIndex!==void 0&&(r.i=m.internals.rootParentIndex);const v=u&&!zf(p)?Hv:0,{x,y:S,z:w}=XC(t,m,d,g,v,p),{positionAbsolute:j}=t.internals,E=x!==j.x||S!==j.y;(E||w!==t.internals.z)&&i.set(t.id,{...t,internals:{...t.internals,positionAbsolute:E?{x,y:S}:j,z:w}})}function Iv(t,i,l){const o=an(t.zIndex)?t.zIndex:0;return zf(l)?o:o+(t.selected?i:0)}function XC(t,i,l,o,r,u){const{x:d,y:g}=i.internals.positionAbsolute,p=Xn(t),y=Lo(t,l),m=gl(t.extent)?si(y,t.extent,p):y;let v=si({x:d+m.x,y:g+m.y},o,p);t.extent==="parent"&&(v=Nv(v,p,i));const x=Iv(t,r,u),S=i.internals.z??0;return{x:v.x,y:v.y,z:S>=x?S+1:x}}function Df(t,i,l,o=[0,0]){const r=[],u=new Map;for(const d of t){const g=i.get(d.parentId);if(!g)continue;const p=u.get(d.parentId)?.expandedRect??hl(g),y=Ev(p,d.rect);u.set(d.parentId,{expandedRect:y,parent:g})}return u.size>0&&u.forEach(({expandedRect:d,parent:g},p)=>{const y=g.internals.positionAbsolute,m=Xn(g),v=g.origin??o,x=d.x<y.x?Math.round(Math.abs(y.x-d.x)):0,S=d.y<y.y?Math.round(Math.abs(y.y-d.y)):0,w=Math.max(m.width,Math.round(d.width)),j=Math.max(m.height,Math.round(d.height)),E=(w-m.width)*v[0],A=(j-m.height)*v[1];(x>0||S>0||E||A)&&(r.push({id:p,type:"position",position:{x:g.position.x-x+E,y:g.position.y-S+A}}),l.get(p)?.forEach(B=>{t.some(C=>C.id===B.id)||r.push({id:B.id,type:"position",position:{x:B.position.x+x,y:B.position.y+S}})})),(m.width<d.width||m.height<d.height||x||S)&&r.push({id:p,type:"dimensions",setAttributes:!0,dimensions:{width:w+(x?v[0]*x-E:0),height:j+(S?v[1]*S-A:0)}})}),r}function $C(t,i,l,o,r,u,d){const g=o?.querySelector(".xyflow__viewport");let p=!1;if(!g)return{changes:[],updatedInternals:p};const y=[],m=window.getComputedStyle(g),{m22:v}=new window.DOMMatrixReadOnly(m.transform),x=[];for(const S of t.values()){const w=i.get(S.id);if(!w)continue;if(w.hidden){i.set(w.id,{...w,internals:{...w.internals,handleBounds:void 0}}),p=!0;continue}const j=Af(S.nodeElement),E=w.measured.width!==j.width||w.measured.height!==j.height;if(!!(j.width&&j.height&&(E||!w.internals.handleBounds||S.force))){const B=S.nodeElement.getBoundingClientRect(),C=gl(w.extent)?w.extent:u;let{positionAbsolute:_}=w.internals;w.parentId&&w.extent==="parent"?_=Nv(_,j,i.get(w.parentId)):C&&(_=si(_,C,j));const U={...w,measured:j,internals:{...w.internals,positionAbsolute:_,handleBounds:{source:_y("source",S.nodeElement,B,v,w.id),target:_y("target",S.nodeElement,B,v,w.id)}}};i.set(w.id,U),w.parentId&&Rf(U,i,l,{nodeOrigin:r,zIndexMode:d}),p=!0,E&&(y.push({id:w.id,type:"dimensions",dimensions:j}),w.expandParent&&w.parentId&&x.push({id:w.id,parentId:w.parentId,rect:hl(U,r)}))}}if(x.length>0){const S=Df(x,i,l,r);y.push(...S)}return{changes:y,updatedInternals:p}}async function ZC({delta:t,panZoom:i,transform:l,translateExtent:o,width:r,height:u}){if(!i||!t.x&&!t.y)return Promise.resolve(!1);const d=await i.setViewportConstrained({x:l[0]+t.x,y:l[1]+t.y,zoom:l[2]},[[0,0],[r,u]],o),g=!!d&&(d.x!==l[0]||d.y!==l[1]||d.k!==l[2]);return Promise.resolve(g)}function zy(t,i,l,o,r,u){let d=r;const g=o.get(d)||new Map;o.set(d,g.set(l,i)),d=`${r}-${t}`;const p=o.get(d)||new Map;if(o.set(d,p.set(l,i)),u){d=`${r}-${t}-${u}`;const y=o.get(d)||new Map;o.set(d,y.set(l,i))}}function Bv(t,i,l){t.clear(),i.clear();for(const o of l){const{source:r,target:u,sourceHandle:d=null,targetHandle:g=null}=o,p={edgeId:o.id,source:r,target:u,sourceHandle:d,targetHandle:g},y=`${r}-${d}--${u}-${g}`,m=`${u}-${g}--${r}-${d}`;zy("source",p,m,t,r,d),zy("target",p,y,t,u,g),i.set(o.id,o)}}function Lv(t,i){if(!t.parentId)return!1;const l=i.get(t.parentId);return l?l.selected?!0:Lv(l,i):!1}function Ry(t,i,l){let o=t;do{if(o?.matches?.(i))return!0;if(o===l)return!1;o=o?.parentElement}while(o);return!1}function KC(t,i,l,o){const r=new Map;for(const[u,d]of t)if((d.selected||d.id===o)&&(!d.parentId||!Lv(d,t))&&(d.draggable||i&&typeof d.draggable>"u")){const g=t.get(u);g&&r.set(u,{id:u,position:g.position||{x:0,y:0},distance:{x:l.x-g.internals.positionAbsolute.x,y:l.y-g.internals.positionAbsolute.y},extent:g.extent,parentId:g.parentId,origin:g.origin,expandParent:g.expandParent,internals:{positionAbsolute:g.internals.positionAbsolute||{x:0,y:0}},measured:{width:g.measured.width??0,height:g.measured.height??0}})}return r}function Gd({nodeId:t,dragItems:i,nodeLookup:l,dragging:o=!0}){const r=[];for(const[d,g]of i){const p=l.get(d)?.internals.userNode;p&&r.push({...p,position:g.position,dragging:o})}if(!t)return[r[0],r];const u=l.get(t)?.internals.userNode;return[u?{...u,position:i.get(t)?.position||u.position,dragging:o}:r[0],r]}function QC({dragItems:t,snapGrid:i,x:l,y:o}){const r=t.values().next().value;if(!r)return null;const u={x:l-r.distance.x,y:o-r.distance.y},d=Uo(u,i);return{x:d.x-u.x,y:d.y-u.y}}function FC({onNodeMouseDown:t,getStoreItems:i,onDragStart:l,onDrag:o,onDragStop:r}){let u={x:null,y:null},d=0,g=new Map,p=!1,y={x:0,y:0},m=null,v=!1,x=null,S=!1,w=!1,j=null;function E({noDragClassName:B,handleSelector:C,domNode:_,isSelectable:U,nodeId:R,nodeClickDistance:z=0}){x=kt(_);function I({x:te,y:ue}){const{nodeLookup:D,nodeExtent:Z,snapGrid:M,snapToGrid:H,nodeOrigin:q,onNodeDrag:k,onSelectionDrag:J,onError:T,updateNodePositions:L}=i();u={x:te,y:ue};let ne=!1;const ae=g.size>1,V=ae&&Z?cf(ko(g)):null,se=ae&&H?QC({dragItems:g,snapGrid:M,x:te,y:ue}):null;for(const[de,le]of g){if(!D.has(de))continue;let fe={x:te-le.distance.x,y:ue-le.distance.y};H&&(fe=se?{x:Math.round(fe.x+se.x),y:Math.round(fe.y+se.y)}:Uo(fe,M));let be=null;if(ae&&Z&&!le.extent&&V){const{positionAbsolute:we}=le.internals,je=we.x-V.x+Z[0][0],qe=we.x+le.measured.width-V.x2+Z[1][0],Le=we.y-V.y+Z[0][1],ut=we.y+le.measured.height-V.y2+Z[1][1];be=[[je,Le],[qe,ut]]}const{position:_e,positionAbsolute:ye}=wv({nodeId:de,nextPosition:fe,nodeLookup:D,nodeExtent:be||Z,nodeOrigin:q,onError:T});ne=ne||le.position.x!==_e.x||le.position.y!==_e.y,le.position=_e,le.internals.positionAbsolute=ye}if(w=w||ne,!!ne&&(L(g,!0),j&&(o||k||!R&&J))){const[de,le]=Gd({nodeId:R,dragItems:g,nodeLookup:D});o?.(j,g,de,le),k?.(j,de,le),R||J?.(j,le)}}async function X(){if(!m)return;const{transform:te,panBy:ue,autoPanSpeed:D,autoPanOnNodeDrag:Z}=i();if(!Z){p=!1,cancelAnimationFrame(d);return}const[M,H]=_v(y,m,D);(M!==0||H!==0)&&(u.x=(u.x??0)-M/te[2],u.y=(u.y??0)-H/te[2],await ue({x:M,y:H})&&I(u)),d=requestAnimationFrame(X)}function ce(te){const{nodeLookup:ue,multiSelectionActive:D,nodesDraggable:Z,transform:M,snapGrid:H,snapToGrid:q,selectNodesOnDrag:k,onNodeDragStart:J,onSelectionDragStart:T,unselectNodesAndEdges:L}=i();v=!0,(!k||!U)&&!D&&R&&(ue.get(R)?.selected||L()),U&&k&&R&&t?.(R);const ne=Eo(te.sourceEvent,{transform:M,snapGrid:H,snapToGrid:q,containerBounds:m});if(u=ne,g=KC(ue,Z,ne,R),g.size>0&&(l||J||!R&&T)){const[ae,V]=Gd({nodeId:R,dragItems:g,nodeLookup:ue});l?.(te.sourceEvent,g,ae,V),J?.(te.sourceEvent,ae,V),R||T?.(te.sourceEvent,V)}}const K=tv().clickDistance(z).on("start",te=>{const{domNode:ue,nodeDragThreshold:D,transform:Z,snapGrid:M,snapToGrid:H}=i();m=ue?.getBoundingClientRect()||null,S=!1,w=!1,j=te.sourceEvent,D===0&&ce(te),u=Eo(te.sourceEvent,{transform:Z,snapGrid:M,snapToGrid:H,containerBounds:m}),y=ln(te.sourceEvent,m)}).on("drag",te=>{const{autoPanOnNodeDrag:ue,transform:D,snapGrid:Z,snapToGrid:M,nodeDragThreshold:H,nodeLookup:q}=i(),k=Eo(te.sourceEvent,{transform:D,snapGrid:Z,snapToGrid:M,containerBounds:m});if(j=te.sourceEvent,(te.sourceEvent.type==="touchmove"&&te.sourceEvent.touches.length>1||R&&!q.has(R))&&(S=!0),!S){if(!p&&ue&&v&&(p=!0,X()),!v){const J=ln(te.sourceEvent,m),T=J.x-y.x,L=J.y-y.y;Math.sqrt(T*T+L*L)>H&&ce(te)}(u.x!==k.xSnapped||u.y!==k.ySnapped)&&g&&v&&(y=ln(te.sourceEvent,m),I(k))}}).on("end",te=>{if(!(!v||S)&&(p=!1,v=!1,cancelAnimationFrame(d),g.size>0)){const{nodeLookup:ue,updateNodePositions:D,onNodeDragStop:Z,onSelectionDragStop:M}=i();if(w&&(D(g,!1),w=!1),r||Z||!R&&M){const[H,q]=Gd({nodeId:R,dragItems:g,nodeLookup:ue,dragging:!1});r?.(te.sourceEvent,g,H,q),Z?.(te.sourceEvent,H,q),R||M?.(te.sourceEvent,q)}}}).filter(te=>{const ue=te.target;return!te.button&&(!B||!Ry(ue,`.${B}`,_))&&(!C||Ry(ue,C,_))});x.call(K)}function A(){x?.on(".drag",null)}return{update:E,destroy:A}}function PC(t,i,l){const o=[],r={x:t.x-l,y:t.y-l,width:l*2,height:l*2};for(const u of i.values())Ro(r,hl(u))>0&&o.push(u);return o}const JC=250;function WC(t,i,l,o){let r=[],u=1/0;const d=PC(t,l,i+JC);for(const g of d){const p=[...g.internals.handleBounds?.source??[],...g.internals.handleBounds?.target??[]];for(const y of p){if(o.nodeId===y.nodeId&&o.type===y.type&&o.id===y.id)continue;const{x:m,y:v}=ri(g,y,y.position,!0),x=Math.sqrt(Math.pow(m-t.x,2)+Math.pow(v-t.y,2));x>i||(x<u?(r=[{...y,x:m,y:v}],u=x):x===u&&r.push({...y,x:m,y:v}))}}if(!r.length)return null;if(r.length>1){const g=o.type==="source"?"target":"source";return r.find(p=>p.type===g)??r[0]}return r[0]}function kv(t,i,l,o,r,u=!1){const d=o.get(t);if(!d)return null;const g=r==="strict"?d.internals.handleBounds?.[i]:[...d.internals.handleBounds?.source??[],...d.internals.handleBounds?.target??[]],p=(l?g?.find(y=>y.id===l):g?.[0])??null;return p&&u?{...p,...ri(d,p,p.position,!0)}:p}function Uv(t,i){return t||(i?.classList.contains("target")?"target":i?.classList.contains("source")?"source":null)}function eT(t,i){let l=null;return i?l=!0:t&&!i&&(l=!1),l}const qv=()=>!0;function tT(t,{connectionMode:i,connectionRadius:l,handleId:o,nodeId:r,edgeUpdaterType:u,isTarget:d,domNode:g,nodeLookup:p,lib:y,autoPanOnConnect:m,flowId:v,panBy:x,cancelConnection:S,onConnectStart:w,onConnect:j,onConnectEnd:E,isValidConnection:A=qv,onReconnectEnd:B,updateConnection:C,getTransform:_,getFromHandle:U,autoPanSpeed:R,dragThreshold:z=1,handleDomNode:I}){const X=Av(t.target);let ce=0,K;const{x:te,y:ue}=ln(t),D=Uv(u,I),Z=g?.getBoundingClientRect();let M=!1;if(!Z||!D)return;const H=kv(r,D,o,p,i);if(!H)return;let q=ln(t,Z),k=!1,J=null,T=!1,L=null;function ne(){if(!m||!Z)return;const[_e,ye]=_v(q,Z,R);x({x:_e,y:ye}),ce=requestAnimationFrame(ne)}const ae={...H,nodeId:r,type:D,position:H.position},V=p.get(r);let de={inProgress:!0,isValid:null,from:ri(V,ae,me.Left,!0),fromHandle:ae,fromPosition:ae.position,fromNode:V,to:q,toHandle:null,toPosition:by[ae.position],toNode:null,pointer:q};function le(){M=!0,C(de),w?.(t,{nodeId:r,handleId:o,handleType:D})}z===0&&le();function fe(_e){if(!M){const{x:ut,y:Qt}=ln(_e),zt=ut-te,Ft=Qt-ue;if(!(zt*zt+Ft*Ft>z*z))return;le()}if(!U()||!ae){be(_e);return}const ye=_();q=ln(_e,Z),K=WC(qo(q,ye,!1,[1,1]),l,p,ae),k||(ne(),k=!0);const we=Gv(_e,{handle:K,connectionMode:i,fromNodeId:r,fromHandleId:o,fromType:d?"target":"source",isValidConnection:A,doc:X,lib:y,flowId:v,nodeLookup:p});L=we.handleDomNode,J=we.connection,T=eT(!!K,we.isValid);const je=p.get(r),qe=je?ri(je,ae,me.Left,!0):de.from,Le={...de,from:qe,isValid:T,to:we.toHandle&&T?Xr({x:we.toHandle.x,y:we.toHandle.y},ye):q,toHandle:we.toHandle,toPosition:T&&we.toHandle?we.toHandle.position:by[ae.position],toNode:we.toHandle?p.get(we.toHandle.nodeId):null,pointer:q};C(Le),de=Le}function be(_e){if(!("touches"in _e&&_e.touches.length>0)){if(M){(K||L)&&J&&T&&j?.(J);const{inProgress:ye,...we}=de,je={...we,toPosition:de.toHandle?de.toPosition:null};E?.(_e,je),u&&B?.(_e,je)}S(),cancelAnimationFrame(ce),k=!1,T=!1,J=null,L=null,X.removeEventListener("mousemove",fe),X.removeEventListener("mouseup",be),X.removeEventListener("touchmove",fe),X.removeEventListener("touchend",be)}}X.addEventListener("mousemove",fe),X.addEventListener("mouseup",be),X.addEventListener("touchmove",fe),X.addEventListener("touchend",be)}function Gv(t,{handle:i,connectionMode:l,fromNodeId:o,fromHandleId:r,fromType:u,doc:d,lib:g,flowId:p,isValidConnection:y=qv,nodeLookup:m}){const v=u==="target",x=i?d.querySelector(`.${g}-flow__handle[data-id="${p}-${i?.nodeId}-${i?.id}-${i?.type}"]`):null,{x:S,y:w}=ln(t),j=d.elementFromPoint(S,w),E=j?.classList.contains(`${g}-flow__handle`)?j:x,A={handleDomNode:E,isValid:!1,connection:null,toHandle:null};if(E){const B=Uv(void 0,E),C=E.getAttribute("data-nodeid"),_=E.getAttribute("data-handleid"),U=E.classList.contains("connectable"),R=E.classList.contains("connectableend");if(!C||!B)return A;const z={source:v?C:o,sourceHandle:v?_:r,target:v?o:C,targetHandle:v?r:_};A.connection=z;const X=U&&R&&(l===dl.Strict?v&&B==="source"||!v&&B==="target":C!==o||_!==r);A.isValid=X&&y(z),A.toHandle=kv(C,B,_,m,l,!0)}return A}const hf={onPointerDown:tT,isValid:Gv};function nT({domNode:t,panZoom:i,getTransform:l,getViewScale:o}){const r=kt(t);function u({translateExtent:g,width:p,height:y,zoomStep:m=1,pannable:v=!0,zoomable:x=!0,inversePan:S=!1}){const w=C=>{if(C.sourceEvent.type!=="wheel"||!i)return;const _=l(),U=C.sourceEvent.ctrlKey&&Do()?10:1,R=-C.sourceEvent.deltaY*(C.sourceEvent.deltaMode===1?.05:C.sourceEvent.deltaMode?1:.002)*m,z=_[2]*Math.pow(2,R*U);i.scaleTo(z)};let j=[0,0];const E=C=>{(C.sourceEvent.type==="mousedown"||C.sourceEvent.type==="touchstart")&&(j=[C.sourceEvent.clientX??C.sourceEvent.touches[0].clientX,C.sourceEvent.clientY??C.sourceEvent.touches[0].clientY])},A=C=>{const _=l();if(C.sourceEvent.type!=="mousemove"&&C.sourceEvent.type!=="touchmove"||!i)return;const U=[C.sourceEvent.clientX??C.sourceEvent.touches[0].clientX,C.sourceEvent.clientY??C.sourceEvent.touches[0].clientY],R=[U[0]-j[0],U[1]-j[1]];j=U;const z=o()*Math.max(_[2],Math.log(_[2]))*(S?-1:1),I={x:_[0]-R[0]*z,y:_[1]-R[1]*z},X=[[0,0],[p,y]];i.setViewportConstrained({x:I.x,y:I.y,zoom:_[2]},X,g)},B=pv().on("start",E).on("zoom",v?A:null).on("zoom.wheel",x?w:null);r.call(B,{})}function d(){r.on("zoom",null)}return{update:u,destroy:d,pointer:tn}}const ec=t=>({x:t.x,y:t.y,zoom:t.k}),Yd=({x:t,y:i,zoom:l})=>Pr.translate(t,i).scale(l),al=(t,i)=>t.target.closest(`.${i}`),Yv=(t,i)=>i===2&&Array.isArray(t)&&t.includes(2),aT=t=>((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2,Vd=(t,i=0,l=aT,o=()=>{})=>{const r=typeof i=="number"&&i>0;return r||o(),r?t.transition().duration(i).ease(l).on("end",o):t},Vv=t=>{const i=t.ctrlKey&&Do()?10:1;return-t.deltaY*(t.deltaMode===1?.05:t.deltaMode?1:.002)*i};function iT({zoomPanValues:t,noWheelClassName:i,d3Selection:l,d3Zoom:o,panOnScrollMode:r,panOnScrollSpeed:u,zoomOnPinch:d,onPanZoomStart:g,onPanZoom:p,onPanZoomEnd:y}){return m=>{if(al(m,i))return m.ctrlKey&&m.preventDefault(),!1;m.preventDefault(),m.stopImmediatePropagation();const v=l.property("__zoom").k||1;if(m.ctrlKey&&d){const E=tn(m),A=Vv(m),B=v*Math.pow(2,A);o.scaleTo(l,B,E,m);return}const x=m.deltaMode===1?20:1;let S=r===ii.Vertical?0:m.deltaX*x,w=r===ii.Horizontal?0:m.deltaY*x;!Do()&&m.shiftKey&&r!==ii.Vertical&&(S=m.deltaY*x,w=0),o.translateBy(l,-(S/v)*u,-(w/v)*u,{internal:!0});const j=ec(l.property("__zoom"));clearTimeout(t.panScrollTimeout),t.isPanScrolling?(p?.(m,j),t.panScrollTimeout=setTimeout(()=>{y?.(m,j),t.isPanScrolling=!1},150)):(t.isPanScrolling=!0,g?.(m,j))}}function lT({noWheelClassName:t,preventScrolling:i,d3ZoomHandler:l}){return function(o,r){const u=o.type==="wheel",d=!i&&u&&!o.ctrlKey,g=al(o,t);if(o.ctrlKey&&u&&g&&o.preventDefault(),d||g)return null;o.preventDefault(),l.call(this,o,r)}}function oT({zoomPanValues:t,onDraggingChange:i,onPanZoomStart:l}){return o=>{if(o.sourceEvent?.internal)return;const r=ec(o.transform);t.mouseButton=o.sourceEvent?.button||0,t.isZoomingOrPanning=!0,t.prevViewport=r,o.sourceEvent?.type==="mousedown"&&i(!0),l&&l?.(o.sourceEvent,r)}}function sT({zoomPanValues:t,panOnDrag:i,onPaneContextMenu:l,onTransformChange:o,onPanZoom:r}){return u=>{t.usedRightMouseButton=!!(l&&Yv(i,t.mouseButton??0)),u.sourceEvent?.sync||o([u.transform.x,u.transform.y,u.transform.k]),r&&!u.sourceEvent?.internal&&r?.(u.sourceEvent,ec(u.transform))}}function rT({zoomPanValues:t,panOnDrag:i,panOnScroll:l,onDraggingChange:o,onPanZoomEnd:r,onPaneContextMenu:u}){return d=>{if(!d.sourceEvent?.internal&&(t.isZoomingOrPanning=!1,u&&Yv(i,t.mouseButton??0)&&!t.usedRightMouseButton&&d.sourceEvent&&u(d.sourceEvent),t.usedRightMouseButton=!1,o(!1),r)){const g=ec(d.transform);t.prevViewport=g,clearTimeout(t.timerId),t.timerId=setTimeout(()=>{r?.(d.sourceEvent,g)},l?150:0)}}}function cT({zoomActivationKeyPressed:t,zoomOnScroll:i,zoomOnPinch:l,panOnDrag:o,panOnScroll:r,zoomOnDoubleClick:u,userSelectionActive:d,noWheelClassName:g,noPanClassName:p,lib:y,connectionInProgress:m}){return v=>{const x=t||i,S=l&&v.ctrlKey,w=v.type==="wheel";if(v.button===1&&v.type==="mousedown"&&(al(v,`${y}-flow__node`)||al(v,`${y}-flow__edge`)))return!0;if(!o&&!x&&!r&&!u&&!l||d||m&&!w||al(v,g)&&w||al(v,p)&&(!w||r&&w&&!t)||!l&&v.ctrlKey&&w)return!1;if(!l&&v.type==="touchstart"&&v.touches?.length>1)return v.preventDefault(),!1;if(!x&&!r&&!S&&w||!o&&(v.type==="mousedown"||v.type==="touchstart")||Array.isArray(o)&&!o.includes(v.button)&&v.type==="mousedown")return!1;const j=Array.isArray(o)&&o.includes(v.button)||!v.button||v.button<=1;return(!v.ctrlKey||w)&&j}}function uT({domNode:t,minZoom:i,maxZoom:l,translateExtent:o,viewport:r,onPanZoom:u,onPanZoomStart:d,onPanZoomEnd:g,onDraggingChange:p}){const y={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},m=t.getBoundingClientRect(),v=pv().scaleExtent([i,l]).translateExtent(o),x=kt(t).call(v);B({x:r.x,y:r.y,zoom:fl(r.zoom,i,l)},[[0,0],[m.width,m.height]],o);const S=x.on("wheel.zoom"),w=x.on("dblclick.zoom");v.wheelDelta(Vv);function j(K,te){return x?new Promise(ue=>{v?.interpolate(te?.interpolate==="linear"?_o:jr).transform(Vd(x,te?.duration,te?.ease,()=>ue(!0)),K)}):Promise.resolve(!1)}function E({noWheelClassName:K,noPanClassName:te,onPaneContextMenu:ue,userSelectionActive:D,panOnScroll:Z,panOnDrag:M,panOnScrollMode:H,panOnScrollSpeed:q,preventScrolling:k,zoomOnPinch:J,zoomOnScroll:T,zoomOnDoubleClick:L,zoomActivationKeyPressed:ne,lib:ae,onTransformChange:V,connectionInProgress:se,paneClickDistance:de,selectionOnDrag:le}){D&&!y.isZoomingOrPanning&&A();const fe=Z&&!ne&&!D;v.clickDistance(le?1/0:!an(de)||de<0?0:de);const be=fe?iT({zoomPanValues:y,noWheelClassName:K,d3Selection:x,d3Zoom:v,panOnScrollMode:H,panOnScrollSpeed:q,zoomOnPinch:J,onPanZoomStart:d,onPanZoom:u,onPanZoomEnd:g}):lT({noWheelClassName:K,preventScrolling:k,d3ZoomHandler:S});if(x.on("wheel.zoom",be,{passive:!1}),!D){const ye=oT({zoomPanValues:y,onDraggingChange:p,onPanZoomStart:d});v.on("start",ye);const we=sT({zoomPanValues:y,panOnDrag:M,onPaneContextMenu:!!ue,onPanZoom:u,onTransformChange:V});v.on("zoom",we);const je=rT({zoomPanValues:y,panOnDrag:M,panOnScroll:Z,onPaneContextMenu:ue,onPanZoomEnd:g,onDraggingChange:p});v.on("end",je)}const _e=cT({zoomActivationKeyPressed:ne,panOnDrag:M,zoomOnScroll:T,panOnScroll:Z,zoomOnDoubleClick:L,zoomOnPinch:J,userSelectionActive:D,noPanClassName:te,noWheelClassName:K,lib:ae,connectionInProgress:se});v.filter(_e),L?x.on("dblclick.zoom",w):x.on("dblclick.zoom",null)}function A(){v.on("zoom",null)}async function B(K,te,ue){const D=Yd(K),Z=v?.constrain()(D,te,ue);return Z&&await j(Z),new Promise(M=>M(Z))}async function C(K,te){const ue=Yd(K);return await j(ue,te),new Promise(D=>D(ue))}function _(K){if(x){const te=Yd(K),ue=x.property("__zoom");(ue.k!==K.zoom||ue.x!==K.x||ue.y!==K.y)&&v?.transform(x,te,null,{sync:!0})}}function U(){const K=x?mv(x.node()):{x:0,y:0,k:1};return{x:K.x,y:K.y,zoom:K.k}}function R(K,te){return x?new Promise(ue=>{v?.interpolate(te?.interpolate==="linear"?_o:jr).scaleTo(Vd(x,te?.duration,te?.ease,()=>ue(!0)),K)}):Promise.resolve(!1)}function z(K,te){return x?new Promise(ue=>{v?.interpolate(te?.interpolate==="linear"?_o:jr).scaleBy(Vd(x,te?.duration,te?.ease,()=>ue(!0)),K)}):Promise.resolve(!1)}function I(K){v?.scaleExtent(K)}function X(K){v?.translateExtent(K)}function ce(K){const te=!an(K)||K<0?0:K;v?.clickDistance(te)}return{update:E,destroy:A,setViewport:C,setViewportConstrained:B,getViewport:U,scaleTo:R,scaleBy:z,setScaleExtent:I,setTranslateExtent:X,syncViewport:_,setClickDistance:ce}}var ml;(function(t){t.Line="line",t.Handle="handle"})(ml||(ml={}));function dT({width:t,prevWidth:i,height:l,prevHeight:o,affectsX:r,affectsY:u}){const d=t-i,g=l-o,p=[d>0?1:d<0?-1:0,g>0?1:g<0?-1:0];return d&&r&&(p[0]=p[0]*-1),g&&u&&(p[1]=p[1]*-1),p}function Dy(t){const i=t.includes("right")||t.includes("left"),l=t.includes("bottom")||t.includes("top"),o=t.includes("left"),r=t.includes("top");return{isHorizontal:i,isVertical:l,affectsX:o,affectsY:r}}function wa(t,i){return Math.max(0,i-t)}function Na(t,i){return Math.max(0,t-i)}function wr(t,i,l){return Math.max(0,i-t,t-l)}function Oy(t,i){return t?!i:i}function fT(t,i,l,o,r,u,d,g){let{affectsX:p,affectsY:y}=i;const{isHorizontal:m,isVertical:v}=i,x=m&&v,{xSnapped:S,ySnapped:w}=l,{minWidth:j,maxWidth:E,minHeight:A,maxHeight:B}=o,{x:C,y:_,width:U,height:R,aspectRatio:z}=t;let I=Math.floor(m?S-t.pointerX:0),X=Math.floor(v?w-t.pointerY:0);const ce=U+(p?-I:I),K=R+(y?-X:X),te=-u[0]*U,ue=-u[1]*R;let D=wr(ce,j,E),Z=wr(K,A,B);if(d){let q=0,k=0;p&&I<0?q=wa(C+I+te,d[0][0]):!p&&I>0&&(q=Na(C+ce+te,d[1][0])),y&&X<0?k=wa(_+X+ue,d[0][1]):!y&&X>0&&(k=Na(_+K+ue,d[1][1])),D=Math.max(D,q),Z=Math.max(Z,k)}if(g){let q=0,k=0;p&&I>0?q=Na(C+I,g[0][0]):!p&&I<0&&(q=wa(C+ce,g[1][0])),y&&X>0?k=Na(_+X,g[0][1]):!y&&X<0&&(k=wa(_+K,g[1][1])),D=Math.max(D,q),Z=Math.max(Z,k)}if(r){if(m){const q=wr(ce/z,A,B)*z;if(D=Math.max(D,q),d){let k=0;!p&&!y||p&&!y&&x?k=Na(_+ue+ce/z,d[1][1])*z:k=wa(_+ue+(p?I:-I)/z,d[0][1])*z,D=Math.max(D,k)}if(g){let k=0;!p&&!y||p&&!y&&x?k=wa(_+ce/z,g[1][1])*z:k=Na(_+(p?I:-I)/z,g[0][1])*z,D=Math.max(D,k)}}if(v){const q=wr(K*z,j,E)/z;if(Z=Math.max(Z,q),d){let k=0;!p&&!y||y&&!p&&x?k=Na(C+K*z+te,d[1][0])/z:k=wa(C+(y?X:-X)*z+te,d[0][0])/z,Z=Math.max(Z,k)}if(g){let k=0;!p&&!y||y&&!p&&x?k=wa(C+K*z,g[1][0])/z:k=Na(C+(y?X:-X)*z,g[0][0])/z,Z=Math.max(Z,k)}}}X=X+(X<0?Z:-Z),I=I+(I<0?D:-D),r&&(x?ce>K*z?X=(Oy(p,y)?-I:I)/z:I=(Oy(p,y)?-X:X)*z:m?(X=I/z,y=p):(I=X*z,p=y));const M=p?C+I:C,H=y?_+X:_;return{width:U+(p?-I:I),height:R+(y?-X:X),x:u[0]*I*(p?-1:1)+M,y:u[1]*X*(y?-1:1)+H}}const Xv={width:0,height:0,x:0,y:0},hT={...Xv,pointerX:0,pointerY:0,aspectRatio:1};function gT(t){return[[0,0],[t.measured.width,t.measured.height]]}function mT(t,i,l){const o=i.position.x+t.position.x,r=i.position.y+t.position.y,u=t.measured.width??0,d=t.measured.height??0,g=l[0]*u,p=l[1]*d;return[[o-g,r-p],[o+u-g,r+d-p]]}function pT({domNode:t,nodeId:i,getStoreItems:l,onChange:o,onEnd:r}){const u=kt(t);let d={controlDirection:Dy("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function g({controlPosition:y,boundaries:m,keepAspectRatio:v,resizeDirection:x,onResizeStart:S,onResize:w,onResizeEnd:j,shouldResize:E}){let A={...Xv},B={...hT};d={boundaries:m,resizeDirection:x,keepAspectRatio:v,controlDirection:Dy(y)};let C,_=null,U=[],R,z,I,X=!1;const ce=tv().on("start",K=>{const{nodeLookup:te,transform:ue,snapGrid:D,snapToGrid:Z,nodeOrigin:M,paneDomNode:H}=l();if(C=te.get(i),!C)return;_=H?.getBoundingClientRect()??null;const{xSnapped:q,ySnapped:k}=Eo(K.sourceEvent,{transform:ue,snapGrid:D,snapToGrid:Z,containerBounds:_});A={width:C.measured.width??0,height:C.measured.height??0,x:C.position.x??0,y:C.position.y??0},B={...A,pointerX:q,pointerY:k,aspectRatio:A.width/A.height},R=void 0,C.parentId&&(C.extent==="parent"||C.expandParent)&&(R=te.get(C.parentId),z=R&&C.extent==="parent"?gT(R):void 0),U=[],I=void 0;for(const[J,T]of te)if(T.parentId===i&&(U.push({id:J,position:{...T.position},extent:T.extent}),T.extent==="parent"||T.expandParent)){const L=mT(T,C,T.origin??M);I?I=[[Math.min(L[0][0],I[0][0]),Math.min(L[0][1],I[0][1])],[Math.max(L[1][0],I[1][0]),Math.max(L[1][1],I[1][1])]]:I=L}S?.(K,{...A})}).on("drag",K=>{const{transform:te,snapGrid:ue,snapToGrid:D,nodeOrigin:Z}=l(),M=Eo(K.sourceEvent,{transform:te,snapGrid:ue,snapToGrid:D,containerBounds:_}),H=[];if(!C)return;const{x:q,y:k,width:J,height:T}=A,L={},ne=C.origin??Z,{width:ae,height:V,x:se,y:de}=fT(B,d.controlDirection,M,d.boundaries,d.keepAspectRatio,ne,z,I),le=ae!==J,fe=V!==T,be=se!==q&&le,_e=de!==k&&fe;if(!be&&!_e&&!le&&!fe)return;if((be||_e||ne[0]===1||ne[1]===1)&&(L.x=be?se:A.x,L.y=_e?de:A.y,A.x=L.x,A.y=L.y,U.length>0)){const qe=se-q,Le=de-k;for(const ut of U)ut.position={x:ut.position.x-qe+ne[0]*(ae-J),y:ut.position.y-Le+ne[1]*(V-T)},H.push(ut)}if((le||fe)&&(L.width=le&&(!d.resizeDirection||d.resizeDirection==="horizontal")?ae:A.width,L.height=fe&&(!d.resizeDirection||d.resizeDirection==="vertical")?V:A.height,A.width=L.width,A.height=L.height),R&&C.expandParent){const qe=ne[0]*(L.width??0);L.x&&L.x<qe&&(A.x=qe,B.x=B.x-(L.x-qe));const Le=ne[1]*(L.height??0);L.y&&L.y<Le&&(A.y=Le,B.y=B.y-(L.y-Le))}const ye=dT({width:A.width,prevWidth:J,height:A.height,prevHeight:T,affectsX:d.controlDirection.affectsX,affectsY:d.controlDirection.affectsY}),we={...A,direction:ye};E?.(K,we)!==!1&&(X=!0,w?.(K,we),o(L,H))}).on("end",K=>{X&&(j?.(K,{...A}),r?.({...A}),X=!1)});u.call(ce)}function p(){u.on(".drag",null)}return{update:g,destroy:p}}var Xd={exports:{}},$d={},Zd={exports:{}},Kd={};var Hy;function yT(){if(Hy)return Kd;Hy=1;var t=Ho();function i(v,x){return v===x&&(v!==0||1/v===1/x)||v!==v&&x!==x}var l=typeof Object.is=="function"?Object.is:i,o=t.useState,r=t.useEffect,u=t.useLayoutEffect,d=t.useDebugValue;function g(v,x){var S=x(),w=o({inst:{value:S,getSnapshot:x}}),j=w[0].inst,E=w[1];return u(function(){j.value=S,j.getSnapshot=x,p(j)&&E({inst:j})},[v,S,x]),r(function(){return p(j)&&E({inst:j}),v(function(){p(j)&&E({inst:j})})},[v]),d(S),S}function p(v){var x=v.getSnapshot;v=v.value;try{var S=x();return!l(v,S)}catch{return!0}}function y(v,x){return x()}var m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?y:g;return Kd.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:m,Kd}var Iy;function vT(){return Iy||(Iy=1,Zd.exports=yT()),Zd.exports}var By;function xT(){if(By)return $d;By=1;var t=Ho(),i=vT();function l(y,m){return y===m&&(y!==0||1/y===1/m)||y!==y&&m!==m}var o=typeof Object.is=="function"?Object.is:l,r=i.useSyncExternalStore,u=t.useRef,d=t.useEffect,g=t.useMemo,p=t.useDebugValue;return $d.useSyncExternalStoreWithSelector=function(y,m,v,x,S){var w=u(null);if(w.current===null){var j={hasValue:!1,value:null};w.current=j}else j=w.current;w=g(function(){function A(R){if(!B){if(B=!0,C=R,R=x(R),S!==void 0&&j.hasValue){var z=j.value;if(S(z,R))return _=z}return _=R}if(z=_,o(C,R))return z;var I=x(R);return S!==void 0&&S(z,I)?(C=R,z):(C=R,_=I)}var B=!1,C,_,U=v===void 0?null:v;return[function(){return A(m())},U===null?void 0:function(){return A(U())}]},[m,v,x,S]);var E=r(y,w[0],w[1]);return d(function(){j.hasValue=!0,j.value=E},[E]),p(E),E},$d}var Ly;function bT(){return Ly||(Ly=1,Xd.exports=xT()),Xd.exports}var ST=bT();const wT=f0(ST),NT={},ky=t=>{let i;const l=new Set,o=(m,v)=>{const x=typeof m=="function"?m(i):m;if(!Object.is(x,i)){const S=i;i=v??(typeof x!="object"||x===null)?x:Object.assign({},i,x),l.forEach(w=>w(i,S))}},r=()=>i,p={setState:o,getState:r,getInitialState:()=>y,subscribe:m=>(l.add(m),()=>l.delete(m)),destroy:()=>{(NT?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),l.clear()}},y=i=t(o,r,p);return p},_T=t=>t?ky(t):ky,{useDebugValue:ET}=yo,{useSyncExternalStoreWithSelector:CT}=wT,TT=t=>t;function $v(t,i=TT,l){const o=CT(t.subscribe,t.getState,t.getServerState||t.getInitialState,i,l);return ET(o),o}const Uy=(t,i)=>{const l=_T(t),o=(r,u=i)=>$v(l,r,u);return Object.assign(o,l),o},AT=(t,i)=>t?Uy(t,i):Uy;function Qe(t,i){if(Object.is(t,i))return!0;if(typeof t!="object"||t===null||typeof i!="object"||i===null)return!1;if(t instanceof Map&&i instanceof Map){if(t.size!==i.size)return!1;for(const[o,r]of t)if(!Object.is(r,i.get(o)))return!1;return!0}if(t instanceof Set&&i instanceof Set){if(t.size!==i.size)return!1;for(const o of t)if(!i.has(o))return!1;return!0}const l=Object.keys(t);if(l.length!==Object.keys(i).length)return!1;for(const o of l)if(!Object.prototype.hasOwnProperty.call(i,o)||!Object.is(t[o],i[o]))return!1;return!0}h0();const tc=Y.createContext(null),MT=tc.Provider,Zv=pn.error001();function Oe(t,i){const l=Y.useContext(tc);if(l===null)throw new Error(Zv);return $v(l,t,i)}function Fe(){const t=Y.useContext(tc);if(t===null)throw new Error(Zv);return Y.useMemo(()=>({getState:t.getState,setState:t.setState,subscribe:t.subscribe}),[t])}const qy={display:"none"},jT={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Kv="react-flow__node-desc",Qv="react-flow__edge-desc",zT="react-flow__aria-live",RT=t=>t.ariaLiveMessage,DT=t=>t.ariaLabelConfig;function OT({rfId:t}){const i=Oe(RT);return h.jsx("div",{id:`${zT}-${t}`,"aria-live":"assertive","aria-atomic":"true",style:jT,children:i})}function HT({rfId:t,disableKeyboardA11y:i}){const l=Oe(DT);return h.jsxs(h.Fragment,{children:[h.jsx("div",{id:`${Kv}-${t}`,style:qy,children:i?l["node.a11yDescription.default"]:l["node.a11yDescription.keyboardDisabled"]}),h.jsx("div",{id:`${Qv}-${t}`,style:qy,children:l["edge.a11yDescription.default"]}),!i&&h.jsx(OT,{rfId:t})]})}const Go=Y.forwardRef(({position:t="top-left",children:i,className:l,style:o,...r},u)=>{const d=`${t}`.split("-");return h.jsx("div",{className:st(["react-flow__panel",l,...d]),style:o,ref:u,...r,children:i})});Go.displayName="Panel";function IT({proOptions:t,position:i="bottom-right"}){return t?.hideAttribution?null:h.jsx(Go,{position:i,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:h.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const BT=t=>{const i=[],l=[];for(const[,o]of t.nodeLookup)o.selected&&i.push(o.internals.userNode);for(const[,o]of t.edgeLookup)o.selected&&l.push(o);return{selectedNodes:i,selectedEdges:l}},Nr=t=>t.id;function LT(t,i){return Qe(t.selectedNodes.map(Nr),i.selectedNodes.map(Nr))&&Qe(t.selectedEdges.map(Nr),i.selectedEdges.map(Nr))}function kT({onSelectionChange:t}){const i=Fe(),{selectedNodes:l,selectedEdges:o}=Oe(BT,LT);return Y.useEffect(()=>{const r={nodes:l,edges:o};t?.(r),i.getState().onSelectionChangeHandlers.forEach(u=>u(r))},[l,o,t]),null}const UT=t=>!!t.onSelectionChangeHandlers;function qT({onSelectionChange:t}){const i=Oe(UT);return t||i?h.jsx(kT,{onSelectionChange:t}):null}const gf=typeof window<"u"?Y.useLayoutEffect:Y.useEffect,Fv=[0,0],GT={x:0,y:0,zoom:1},YT=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],Gy=[...YT,"rfId"],VT=t=>({setNodes:t.setNodes,setEdges:t.setEdges,setMinZoom:t.setMinZoom,setMaxZoom:t.setMaxZoom,setTranslateExtent:t.setTranslateExtent,setNodeExtent:t.setNodeExtent,reset:t.reset,setDefaultNodesAndEdges:t.setDefaultNodesAndEdges}),Yy={translateExtent:jo,nodeOrigin:Fv,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function XT(t){const{setNodes:i,setEdges:l,setMinZoom:o,setMaxZoom:r,setTranslateExtent:u,setNodeExtent:d,reset:g,setDefaultNodesAndEdges:p}=Oe(VT,Qe),y=Fe();gf(()=>(p(t.defaultNodes,t.defaultEdges),()=>{m.current=Yy,g()}),[]);const m=Y.useRef(Yy);return gf(()=>{for(const v of Gy){const x=t[v],S=m.current[v];x!==S&&(typeof t[v]>"u"||(v==="nodes"?i(x):v==="edges"?l(x):v==="minZoom"?o(x):v==="maxZoom"?r(x):v==="translateExtent"?u(x):v==="nodeExtent"?d(x):v==="ariaLabelConfig"?y.setState({ariaLabelConfig:AC(x)}):v==="fitView"?y.setState({fitViewQueued:x}):v==="fitViewOptions"?y.setState({fitViewOptions:x}):y.setState({[v]:x})))}m.current=t},Gy.map(v=>t[v])),null}function Vy(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function $T(t){const[i,l]=Y.useState(t==="system"?null:t);return Y.useEffect(()=>{if(t!=="system"){l(t);return}const o=Vy(),r=()=>l(o?.matches?"dark":"light");return r(),o?.addEventListener("change",r),()=>{o?.removeEventListener("change",r)}},[t]),i!==null?i:Vy()?.matches?"dark":"light"}const Xy=typeof document<"u"?document:null;function Oo(t=null,i={target:Xy,actInsideInputWithModifier:!0}){const[l,o]=Y.useState(!1),r=Y.useRef(!1),u=Y.useRef(new Set([])),[d,g]=Y.useMemo(()=>{if(t!==null){const y=(Array.isArray(t)?t:[t]).filter(v=>typeof v=="string").map(v=>v.replace("+",`
|
|
15
|
+
`)}}if(!g)throw new Error("Node stream ended without a final image");return g}function n1(){return ot("/api/sessions")}function a1(t){return ot("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t})})}function m0(t){return ot(`/api/sessions/${encodeURIComponent(t)}`)}function i1(t,i){return ot(`/api/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:i})})}function l1(t){return ot(`/api/sessions/${encodeURIComponent(t)}`,{method:"DELETE"})}function o1(t,i,l,o,r={}){const u={"Content-Type":"application/json","If-Match":String(i)};return r.saveId&&(u["X-Ima2-Graph-Save-Id"]=r.saveId),r.saveReason&&(u["X-Ima2-Graph-Save-Reason"]=r.saveReason),r.tabId&&(u["X-Ima2-Tab-Id"]=r.tabId),ot(`/api/sessions/${encodeURIComponent(t)}/graph`,{method:"PUT",headers:u,body:JSON.stringify({nodes:l,edges:o})})}function s1(t){return ot(`/api/sessions/${encodeURIComponent(t)}/style-sheet`)}function r1(t,i,l){return ot(`/api/sessions/${encodeURIComponent(t)}/style-sheet`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({styleSheet:i,enabled:l})})}function c1(t,i){return ot(`/api/sessions/${encodeURIComponent(t)}/style-sheet/enabled`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:i})})}function u1(t,i,l){return ot(`/api/sessions/${encodeURIComponent(t)}/style-sheet/extract`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:i,referenceDataUrl:l})})}function d1(t,i=256){return new Promise(l=>{const o=new Image;o.onload=()=>{const r=Math.min(1,i/Math.max(o.width,o.height)),u=document.createElement("canvas");u.width=o.width*r,u.height=o.height*r;const d=u.getContext("2d");if(!d)return l(t);d.drawImage(o,0,0,u.width,u.height),l(u.toDataURL("image/jpeg",.6))},o.onerror=()=>l(t),o.src=t})}const f1={maxB64Bytes:6e6,preserveTransparency:!1,maxEdge:4096,qualityLadder:[.85,.7,.55]},zp=16777216;function h1(t,i,l){let o=t,r=i;if(o<=0||r<=0)return{w:1,h:1};const u=Math.max(o,r);if(u>l){const d=l/u;o=Math.round(o*d),r=Math.round(r*d)}if(o*r>zp){const d=Math.sqrt(zp/(o*r));o=Math.max(1,Math.floor(o*d)),r=Math.max(1,Math.floor(r*d))}return{w:o,h:r}}function Md(t){return new Promise((i,l)=>{const o=new FileReader;o.onload=()=>{typeof o.result=="string"?i(o.result):l(new Error("FileReader returned non-string"))},o.onerror=()=>l(o.error??new Error("FileReader failed")),o.readAsDataURL(t)})}function Rp(t,i,l){return new Promise((o,r)=>{t.toBlob(u=>u?o(u):r(new Error("canvas.toBlob returned null")),i,l)})}function jd(t){const i=t.indexOf(",");return i<0?t.length:t.length-i-1}async function Dp(t,i={}){const l={...f1,...i},o=await Md(t);if(jd(o)<=l.maxB64Bytes)return o;let r;try{r=await createImageBitmap(t)}catch(u){throw new Error("이미지 디코드 실패. JPEG/PNG로 변환 후 다시 시도해 주세요.",{cause:u})}try{const{w:u,h:d}=h1(r.width,r.height,l.maxEdge),g=document.createElement("canvas");g.width=u,g.height=d;const p=g.getContext("2d");if(!p)throw new Error("canvas 2d context unavailable");if(p.drawImage(r,0,0,u,d),l.preserveTransparency){const y=await Rp(g,"image/png"),m=await Md(y);if(jd(m)>l.maxB64Bytes)throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.");return m}for(const y of l.qualityLadder){const m=await Rp(g,"image/jpeg",y),v=await Md(m);if(jd(v)<=l.maxB64Bytes)return v}throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.")}finally{r.close?.()}}function fr(t){const i=(t.type||"").toLowerCase();if(i.includes("heic")||i.includes("heif"))return!0;const l=(t.name||"").toLowerCase();return l.endsWith(".heic")||l.endsWith(".heif")}function Op(t){return(t.type||"").toLowerCase()==="image/png"}const g1={ok:"확인",cancel:"취소",delete:"삭제",close:"닫기"},m1={localStorageFull:"로컬 저장소가 가득 차서 최근 상태가 저장되지 않을 수 있습니다.",refLimitExceeded:"참조 이미지는 최대 5장까지 추가할 수 있습니다. 초과한 이미지는 제외되었습니다.",refTooLarge:"이미지가 너무 큽니다. JPEG/PNG로 미리 변환하거나 해상도를 낮춰 다시 시도해 주세요.",refNotBase64:"이미지 파일이 손상되었거나 지원하지 않는 형식입니다.",refEmpty:"빈 이미지 파일입니다. 다른 파일을 선택해 주세요.",refHeicUnsupported:"HEIC/HEIF는 지원하지 않습니다. JPEG 또는 PNG로 변환 후 다시 시도해 주세요.",noCurrentImageForRef:"참조로 사용할 현재 이미지가 없습니다.",refSlotFull:"참조 이미지 슬롯이 가득 찼습니다. 최대 5장까지 가능합니다.",currentImageLoadFailed:"현재 이미지를 불러오지 못했습니다.",addedCurrentAsRef:"현재 이미지를 참조에 추가했습니다.",sessionLoadFailed:"세션을 불러오지 못했습니다.",sessionCreateFailed:"세션을 만들지 못했습니다.",sessionRenameFailed:"세션 이름을 바꾸지 못했습니다.",sessionDeleteFailed:"세션을 삭제하지 못했습니다.",promptRequired:"프롬프트를 입력하세요.",nodeCreated:"노드 {id} 생성 완료 ({elapsed}초)",nodeCreateFailed:"노드 생성에 실패했습니다.",generatedBatch:"{count}장을 {elapsed}초 만에 생성했습니다.",generatedSingle:"{elapsed}초 만에 생성했습니다.",generateFailed:"생성에 실패했습니다.",sessionReloadedElsewhere:"그래프 버전이 달라져 최신 그래프를 다시 불러왔습니다.",promptCopied:"프롬프트를 복사했습니다",imageCopied:"클립보드에 복사했습니다",copyFailed:"복사에 실패했습니다",openGeneratedDirFailed:"이미지 폴더를 열지 못했습니다. ima2 doctor로 저장 경로를 확인해 주세요.",noPromptToFork:"가져올 프롬프트가 없습니다",forkStarted:"이 이미지의 프롬프트를 가져왔습니다. 수정 후 다시 생성하세요"},p1={queued:"대기 중",streaming:"생성 중",decoding:"마무리 중"},y1={title:"크기",width:"가로",height:"세로",hint:"한 변 최소 1024, 최대 3824, 16의 배수, 비율은 최대 3:1",autoLabel:"자동",autoSub:"모델 추천",customLabel:"직접 입력",customSub:"자유 설정"},v1={title:"크기 조정이 필요합니다",body:"입력한 크기가 이미지 생성 제한을 벗어나 자동 조정이 필요합니다.",requested:"요청한 크기",adjusted:"조정될 크기",approve:"승인 후 생성",cancel:"취소",reasonRatio:"비율 제한 3:1을 초과했습니다.",reasonPixels:"최대 픽셀 수 제한을 초과했습니다.",reasonMin:"최소 크기보다 작습니다.",reasonMax:"최대 크기보다 큽니다.",reasonSnap:"16px 단위에 맞춰야 합니다."},x1={title:"품질",lowLabel:"낮음",lowSub:"빠름",mediumLabel:"중간",mediumSub:"균형",highLabel:"높음",highSub:"최상"},b1={title:"모더레이션",autoLabel:"자동",autoSub:"표준 필터",lowLabel:"낮음",lowSub:"완화 필터",explain:"자동은 표준 안전 필터를 사용합니다. 낮음은 제한을 조금 완화해 경계선 프롬프트가 더 통과할 수 있습니다."},S1={title:"포맷"},w1={title:"개수"},N1={button:"생성",buttonLoading:"생성 중 ({n})"},_1={label:"API 상태",checking:"확인 중...",offline:"오프라인",remaining:"${remaining} 남음",thisMonth:"이번 달 ${amount}",oauthFree:"OAuth 무료 사용 가능",apiDisabled:"API 키 비활성화됨 (OAuth 전용)",oauthMode:"OAuth 모드"},E1={openGalleryAria:"갤러리 열기",openGalleryTitle:"전체 갤러리 열기"},C1={closeSettings:"설정 닫기",detailSettings:"세부 설정",toggleShow:"세부 설정 보기",toggleHide:"세부 설정 숨기기",open:"열기",close:"닫기"},T1={label:"프롬프트",refCount:"참조 {count}/{max}",refChipTitle:"참조 이미지 {n}",refChipAlt:"참조 이미지 {n}",refRemoveAria:"참조 이미지 {n} 제거",placeholder:"원하는 이미지를 설명하고, 드래그 앤 드롭이나 붙여넣기로 참조 이미지를 추가할 수 있어요...",placeholderWithRefs:"첨부한 이미지로 무엇을 만들지 설명해 주세요...",attach:"첨부",attachTitle:"참조 이미지 첨부",useCurrent:"현재 결과 사용",useCurrentTitle:"현재 결과를 참조로 사용",style:"스타일",styleTitle:"스타일 일관성 설정 열기",directMode:"Direct",directModeTitle:"프롬프트를 원문 그대로 전달 (Direct 모드)",hint:"Ctrl + Enter로 생성",dropHere:"놓아서 참조 이미지로 추가 ({max}장까지)"},A1={resultAlt:"생성 결과",imageViewerAria:"생성 이미지 뷰어. 좌우 방향키로 이전 또는 다음 이미지를 볼 수 있습니다.",tokens:"{n} 토큰"},M1={today:"오늘",yesterday:"어제",thisWeek:"이번 주",earlier:"이전",imageAltFallback:"생성 이미지",deleteTitle:"삭제 (10초 내 복구 가능)",deleteAria:"이미지 삭제",ariaLabel:"이미지 갤러리",title:"갤러리",total:"총 {n}장",totalFiltered:" / 전체 {n}장",sortByAria:"정렬 기준",sortByDate:"날짜",sortBySession:"세션",searchPlaceholder:"프롬프트나 파일명을 검색",searchDisabledPlaceholder:"세션 보기에서는 검색이 비활성화됩니다",closeAria:"갤러리 닫기",closeTitle:"닫기 (Esc)",sessionLabel:"세션 {name}",standalone:"독립 이미지",emptySessions:"아직 저장된 세션이 없습니다.",emptyAll:"아직 생성된 이미지가 없습니다. 먼저 하나 만들어보세요.",noResults:"검색 결과가 없습니다.",storageNoticeTitle:"저장 위치 안내",storageNoticeRecoverable:"놀라게 해드려 죄송합니다. 최근 버전에서 갤러리 저장 위치가 설치 폴더에서 사용자 데이터 폴더로 바뀌었습니다. 예전 이미지가 이전 generated 폴더에 남아 있을 수 있어요. ima2 doctor를 실행하거나 복구 안내를 확인해 주세요.",storageNoticeNotFound:"놀라게 해드려 죄송합니다. 현재 이 컴퓨터에서 이전 generated 폴더를 찾지 못했습니다. 업데이트 중 예전 전역 설치 폴더가 교체된 경우 자동 복구가 어려울 수 있습니다. ima2 doctor와 복구 안내의 수동 검색 방법을 확인해 주세요.",storageNoticeUnknown:"저장 위치 상태를 확인하지 못했습니다. 업데이트 후 갤러리가 비어 보인다면 ima2 doctor로 이미지 폴더를 확인해 주세요.",openGeneratedDir:"폴더 열기",openGeneratedDirTitle:"생성 이미지 폴더 열기",cardNewsSet:"카드뉴스 세트",cardNewsCard:"카드뉴스 카드",openCardNewsSet:"세트 열기",openCardNewsSetFailed:"카드뉴스 세트를 열지 못했습니다.",copyCardNewsSetPath:"경로 복사",cardNewsPathCopied:"카드뉴스 세트 경로를 복사했습니다.",downloadCardNewsManifest:"매니페스트",cardNewsCount:"{n}장",deleted:"삭제됨: {filename}",undo:"되돌리기",secondsSuffix:"{n}초"},j1={empty:"비어 있음",pending:"생성 중",reconciling:"동기화 중",reconcilingPhase:"동기화 중 · {phase}",ready:"완료 · {elapsed}s",readyWithSearch:"완료 · {elapsed}s · 검색 {searches}",stale:"오래된 상태",staleWithError:"오래된 상태: {error}",assetMissing:"에셋 누락",assetMissingWithError:"에셋 누락: {error}",error:"오류: {error}",errorUnknown:"알 수 없음",nodeImageAlt:"노드 이미지",partialImageAlt:"노드 중간 이미지 미리보기",noAsset:"에셋 없음",stateStale:"상태 오래됨",noImage:"이미지 없음",editPromptPlaceholder:"수정 프롬프트...",promptPlaceholder:"프롬프트...",regenerate:"재생성",newVariation:"새 변형",generate:"생성",generateTitle:"노드 이미지 생성",addChild:"자식",addChildTitle:"자식 노드 추가",duplicateBranch:"복제",duplicateBranchTitle:"새 브랜치 루트로 복제",deleteTitle:"삭제",regenerateTitle:"현재 노드 이미지를 제자리에서 다시 생성",newVariationTitle:"같은 부모 아래 새 변형 노드를 생성",parentImageRequired:"부모 이미지를 먼저 생성해야 합니다.",attachRef:"첨부",attachRefTitle:"노드 참조 이미지 첨부",refAlt:"노드 참조 이미지 {n}",removeRef:"참조 이미지 {n} 제거",dropRefs:"이미지를 여기에 놓기",nodeRefsUnsupportedForEdit:"추가 참조 이미지는 현재 루트 노드에서만 지원합니다.",nodeRefsUsedWithParent:"부모 이미지와 함께 참조로 사용됩니다.",classicRefsParkedTitle:"클래식 참조 이미지가 보관 중입니다",classicRefsParkedBody:"이 이미지는 클래식 작성창용이라 노드 모드 생성에는 사용되지 않습니다.",clearParkedRefs:"보관된 참조 비우기",styleSheetActive:"세션 스타일 시트 적용 중"},z1={selectionOn:"선택 중",selectionOff:"선택",selectAll:"전체 선택",summary:"선택 {selected} · 미생성 {missing} · 영향 {stale}",generateMissing:"없는 것만 생성",regenerateSelected:"선택 재생성",stopRemaining:"남은 작업 중단",stopping:"중단 중",clear:"해제",noneSelected:"선택된 노드가 없습니다.",parentRequired:"부모 이미지가 준비되지 않은 선택 노드가 {count}개 있습니다.",nothingToRun:"생성할 선택 노드가 없습니다.",stopQueued:"현재 노드가 끝나면 남은 작업을 중단합니다.",failed:"{done}/{total} 완료 후 중단되었습니다.",finished:"{done}/{total} 노드 작업 완료",staleBecauseParentChanged:"상위 노드가 재생성되어 다시 확인이 필요합니다."},R1={disconnected:"연결선을 끊었습니다.",parentConflict:"한 노드에는 부모 연결을 하나만 둘 수 있습니다."},D1={authTitle:"인증 방식",apiLabel:"API 키",oauthNotReady:"OAuth 프록시가 아직 준비되지 않았습니다.",codexLoginRequired:"Codex 로그인이 필요합니다.",codexLoginHint:"터미널에서 `codex login`을 실행한 뒤 이 페이지를 새로고침하세요.",oauthStarting:"OAuth 프록시가 시작 중입니다. 몇 초 후 다시 시도하세요.",serverUnreachable:"서버에 연결할 수 없습니다. 백엔드가 실행 중인지 확인하세요.",apiInvalid:"API 키가 없거나 유효하지 않습니다. 서버의 .env 파일에서 OPENAI_API_KEY를 확인하세요.",availableTitle:"{name} 사용 가능",availableAria:"{name}: 사용 가능",unavailableAria:"{name}: 사용 불가",availableSr:"(사용 가능)",unavailableSr:"(사용 불가)"},O1={free:"무료",approx:"약 ${amount}",label:"예상 비용"},H1={download:"다운로드",copyImage:"이미지 복사",copyPrompt:"프롬프트 복사",continueHere:"여기서 이어서",continueHereTitle:"이 이미지의 프롬프트를 가져와 이어서 작업"},I1={switchTitle:"세션 전환",loading:"불러오는 중...",newSession:"새 세션",newSessionTitle:"새 세션",renameTitle:"이름 변경",renamePrompt:"세션 이름",deleteTitle:"삭제",deleteConfirm:'"{title}" 세션을 삭제할까요? 이 작업은 되돌릴 수 없습니다.',empty:"아직 세션이 없습니다",firstGraph:"첫 번째 그래프",untitled:"제목 없는 세션",assetAbortedError:"생성이 정상적으로 끝나지 않았습니다. 이 노드에서 다시 시도하세요."},B1={ariaLabel:"UI 모드",classic:"기본",node:"노드",cardNews:"카드뉴스"},L1={workspace:"카드뉴스 작업공간",composer:"카드뉴스",composerHint:"템플릿은 스냅샷 기준이고, 출력 크기는 별도로 지정합니다.",topic:"주제",topicPlaceholder:"예: 중간고사 역전 플랜",audience:"대상",audiencePlaceholder:"예: 학부모",goal:"목표",goalPlaceholder:"예: 상담 신청",brief:"내용",briefPlaceholder:"카드뉴스에 들어갈 핵심 내용과 금지사항을 적어주세요.",outputSize:"출력 크기",customSize:"직접",draft:"초안 만들기",drafting:"초안 작성 중...",generateSet:"세트 생성",batchGenerate:"일괄 생성",generating:"생성 중...",generated:"{count}장 생성 완료.",missingGeneratedCard:"생성 응답에 이 카드가 포함되지 않았습니다.",error:"카드 생성에 실패했습니다.",imageTemplate:"이미지 템플릿",roleTemplate:"카드 구조",newTemplateLater:"커스텀 템플릿은 dev MVP 이후에 지원합니다",emptyTitle:"초안 대기 중",emptyBody:"왼쪽 설정으로 카드 덱을 준비합니다.",inspector:"카드 편집",cardTitle:"카드 제목",headline:"제목",body:"본문",visualPrompt:"이미지 프롬프트",summaryCopy:"요약 문구",designPrompt:"장면 / 디자인 프롬프트",textFields:"텍스트 박스",addTextField:"텍스트 박스 추가",removeTextField:"삭제",noTextFields:"아직 텍스트 박스가 없습니다.",textFieldText:"텍스트",textKind:"종류",placement:"위치",renderMode:"표시 방식",hierarchyLabel:"위계",textTooLong:"권장 길이를 초과했습니다.",selectTextField:"텍스트 박스 선택: {text}",textKinds:{headline:"제목",body:"설명 텍스트",caption:"캡션",cta:"행동 유도",badge:"배지",number:"숫자"},renderModes:{"in-image":"이미지에 표시","ui-only":"메모만"},hierarchy:{primary:"주요",secondary:"보조",supporting:"부가"},placements:{"top-left":"좌측 상단","top-center":"상단 중앙","top-right":"우측 상단","center-left":"좌측 중앙",center:"중앙","center-right":"우측 중앙","bottom-left":"좌측 하단","bottom-center":"하단 중앙","bottom-right":"우측 하단",free:"직접 지정"},roles:{cover:"표지",hook:"후킹",problem:"문제",insight:"인사이트",example:"예시",data:"데이터",summary:"요약",cta:"행동 유도"},locked:"잠김",unlocked:"열림",noCard:"선택된 카드 없음",generatedMeta:"생성 메타데이터",lockedHelp:"잠긴 카드는 일괄 생성과 재시도에서 제외됩니다.",retryCard:"이 카드 재시도",actions:{copyPrompt:"프롬프트 복사",copyCopy:"문구 복사",openImage:"이미지 열기",downloadCard:"다운로드"},status:{draft:"초안",queued:"대기",generating:"생성 중",generated:"완료",error:"오류",skipped:"제외",locked:"잠김"},progress:{generating:"생성 중 {done}/{total}",summary:"완료 {done}/{total}",detail:"대기 {queued} · 오류 {errors} · 제외 {skipped}",cardGenerating:"이 카드를 생성 중입니다."},planner:{structured:"구조화 JSON",jsonMode:"JSON 모드",repaired:"보정됨",fallback:"기본 초안",jsonOnlyHelp:"초안은 JSON만 만들고 이미지는 나중에 생성합니다.",error:"초안 생성 실패"}},k1={appName:"이미지 생성기",imageModelLabel:"모델",imageModelAria:"이미지 모델 선택",nodeModeHint:"노드 모드에서는 노드를 눌러 프롬프트를 수정한 뒤 생성하세요. 오른쪽 패널의 설정 (품질/크기)은 새로 만드는 모든 결과에 적용됩니다."},U1={openAria:"설정 열기",openTitle:"설정",closeAria:"설정 닫기",closeTitle:"캔버스로 돌아가기",navAria:"설정 섹션",contentAria:"설정 내용",jumpTo:"{section} 섹션으로 이동",eyebrow:"작업공간 설정",title:"설정",subtitle:"계정, 화면, 앞으로 늘어날 작업공간 옵션을 이곳에 모아 생성 흐름은 가볍게 유지합니다.",sections:{account:{title:"계정",hint:"OAuth 상태"},generation:{title:"생성",hint:"모델 기본값"},appearance:{title:"화면",hint:"라이트/다크"},language:{title:"언어",hint:"UI 문구"},future:{title:"예정",hint:"확장 공간"}},account:{primaryEyebrow:"현재 공급자",oauthTitle:"OAuth 사용 중",oauthBody:"현재 생성은 Codex OAuth 세션으로 실행됩니다. 이 빌드에서는 API-Key 생성 모드가 비활성화되어 있습니다.",apiSourceEnv:"OPENAI_API_KEY 감지됨",apiSourceConfig:"config.json API 키 감지됨",apiTitle:"Configured but disabled",apiBody:"env/config에서 API 키를 찾았지만, 지금 ima2-gen은 OAuth 전용으로 동작합니다. 이 상태 표시를 숨기고 싶을 때만 키를 제거하세요.",apiDisabled:"비활성화",apiUnknown:"상태 불명"},imageModel:{title:"이미지 모델",body:"앞으로 생성 요청에 사용할 OAuth 이미지 모델을 선택합니다.",gpt54Mini:"GPT-5.4 Mini",gpt54:"GPT-5.4",gpt55:"GPT-5.5",gpt53CodexSpark:"GPT-5.3 Codex Spark — 이미지 생성 미지원",unsupportedHelp:"기본값은 GPT-5.4 Mini입니다. GPT-5.3 Codex Spark는 OAuth 모델 상태에 보일 수 있지만 image_generation 도구를 지원하지 않습니다."},appearance:{themeTitle:"테마",themeBody:"이 기기에서 작업공간을 어떤 톤으로 볼지 선택합니다."},language:{title:"언어",body:"생성 프롬프트와 무관하게 인터페이스 언어만 바꿉니다."},future:{title:"나중을 위한 자리",body:"OAuth 복구 도구나 작업공간 옵션이 실제로 필요해지면 이곳에 추가합니다."}},q1={loading:"세션 불러오는 중...",addFirst:"+ 첫 노드 추가",addRootTitle:"루트 노드 추가",hint:"핸들을 빈 공간으로 드래그하면 새 브랜치가 생깁니다. Delete 또는 Backspace로 삭제할 수 있습니다."},G1={title:"{provider} 사용 불가",ariaLabel:"{provider} 사용 불가"},Y1={label:"언어",ko:"한국어",en:"English"},V1={label:"테마",system:"시스템",dark:"다크",light:"라이트"},X1={toggle:"스타일 일관성 적용",extract:"프롬프트에서 추출",extracting:"추출 중…",edit:"편집",save:"저장",cancel:"취소",emptyHint:"아직 스타일 시트가 없어요. 현재 프롬프트에서 추출해서 룩을 고정하세요.",noPrompt:"먼저 프롬프트를 입력하세요",extracted:"스타일 시트가 추출됐어요",editorTitle:"스타일 시트 편집",saved:"스타일 시트를 저장했어요",errNoKey:"스타일 시트 추출에는 OpenAI API 키가 필요해요. setup에서 연결해주세요.",errBadOutput:"모델이 사용 가능한 시트를 못 만들었어요 — 프롬프트를 더 구체적으로 적어주세요.",placeholderMedium:"예: 유화, 시네마틱 사진",placeholderComposition:"예: 중앙 인물, 와이드 풍경",placeholderMood:"예: 시네마틱, 몽환적",placeholderSubject:"예: 빨간 재킷 입은 젊은 여성",placeholderPalette:"#0a0a0a, #f97316, 따뜻한 앰버",placeholderNegative:"blur, 워터마크, 텍스트",fields:{medium:"매체",composition:"구도",mood:"분위기",subject:"피사체 디테일",palette:"팔레트 (쉼표로 구분된 hex 또는 이름)",negative:"네거티브 (쉼표로 구분)"}},$1={close:"닫기",details:"자세한 원본 오류 보기",unknown:{title:"알 수 없는 오류가 발생했어요",body:"잠시 후 다시 시도해 주세요. 문제가 계속되면 원본 오류 메시지를 복사해 제보해 주세요."},moderationRefused:{title:"프롬프트가 모더레이션에 걸렸어요",body:"표현 수위를 낮추거나 다른 문구로 바꿔 보세요. 레퍼런스 이미지의 선정적/폭력적 요소도 영향을 줄 수 있어요.",cta:"프롬프트 수정"},upstream5xx:{title:"OpenAI 서버가 혼잡합니다",body:"잠시 후 다시 시도하면 대부분 해결돼요. 상태 페이지(status.openai.com)도 확인해 보세요.",cta:"다시 시도"},authChatgptExpired:{title:"Codex ChatGPT 로그인이 만료됐어요",body:"터미널에서 `npx @openai/codex login`을 다시 실행한 뒤 앱을 새로고침해 주세요.",cta:"새로고침"},authApiKeyInvalid:{title:"API 키 인증 실패",body:"키가 잘못됐거나 한도/조직 권한 문제예요. 본 앱은 API-Key 모드가 비활성화되어 있어 OAuth(ChatGPT 로그인)로 전환하는 편이 좋아요.",cta:"확인"},networkFailed:{title:"네트워크 연결 실패",body:"OpenAI 또는 로컬 런타임 서비스에 연결하지 못했어요. 먼저 새로고침하고, 계속되면 VPN/방화벽과 `ima2 doctor`에 표시되는 포트를 확인해 주세요.",cta:"새로고침"},oauthUnavailable:{title:"OAuth 프록시를 사용할 수 없어요",body:"OAuth 프록시가 아직 시작 중이거나, 사용할 수 없거나, fallback 포트로 이동했을 수 있어요. 먼저 새로고침하고, 계속되면 `ima2 doctor`의 OAuth URL을 확인해 주세요.",cta:"새로고침"},apikeyDisabled:{title:"API-Key 모드가 비활성화되어 있어요",body:"본 앱은 OAuth(ChatGPT 로그인) 전용으로 동작합니다. 공급자를 OAuth로 전환해 주세요.",cta:"확인"}},Z1={common:g1,toast:m1,inflight:p1,size:y1,sizeConfirm:v1,quality:x1,moderation:b1,format:S1,count:w1,generate:N1,billing:_1,history:E1,panel:C1,prompt:T1,canvas:A1,gallery:M1,node:j1,nodeBatch:z1,edge:R1,provider:D1,cost:O1,result:H1,session:I1,uiMode:B1,cardNews:L1,sidebar:k1,settings:U1,nodeCanvas:q1,apiDisabled:G1,language:Y1,theme:V1,styleSheet:X1,errorCard:$1},K1={ok:"OK",cancel:"Cancel",delete:"Delete",close:"Close"},Q1={localStorageFull:"Local storage is full — recent state may not persist.",refLimitExceeded:"References are capped at 5. Extra images were dropped.",refTooLarge:"Image is too large. Convert to JPEG/PNG or lower the resolution and try again.",refNotBase64:"Image file is corrupted or uses an unsupported encoding.",refEmpty:"Empty image file. Please pick a different file.",refHeicUnsupported:"HEIC/HEIF is not supported. Convert to JPEG or PNG and try again.",noCurrentImageForRef:"No current image to use as reference.",refSlotFull:"Reference slots are full (max 5).",currentImageLoadFailed:"Failed to load current image.",addedCurrentAsRef:"Added current image as a reference.",sessionLoadFailed:"Failed to load session.",sessionCreateFailed:"Failed to create session.",sessionRenameFailed:"Failed to rename session.",sessionDeleteFailed:"Failed to delete session.",promptRequired:"Enter a prompt.",nodeCreated:"Node {id} created ({elapsed}s)",nodeCreateFailed:"Node generation failed.",generatedBatch:"Generated {count} images in {elapsed}s.",generatedSingle:"Generated in {elapsed}s.",generateFailed:"Generation failed.",sessionReloadedElsewhere:"Graph version changed, so the latest graph was reloaded.",promptCopied:"Prompt copied",imageCopied:"Copied to clipboard",copyFailed:"Copy failed",openGeneratedDirFailed:"Could not open the image folder. Run ima2 doctor to check the storage path.",noPromptToFork:"No prompt to fork",forkStarted:"Prompt imported. Edit and generate again."},F1={queued:"Queued",streaming:"Generating",decoding:"Finalizing"},P1={title:"Size",width:"Width",height:"Height",hint:"Each side 1024–3824, multiple of 16, ratio up to 3:1",autoLabel:"Auto",autoSub:"Model pick",customLabel:"Custom",customSub:"Free form"},J1={title:"Size adjustment required",body:"The requested size is outside the image generation limits.",requested:"Requested size",adjusted:"Adjusted size",approve:"Approve and generate",cancel:"Cancel",reasonRatio:"The ratio exceeds the 3:1 limit.",reasonPixels:"The maximum pixel limit is exceeded.",reasonMin:"The size is below the minimum.",reasonMax:"The size is above the maximum.",reasonSnap:"The size must align to 16px increments."},W1={title:"Quality",lowLabel:"Low",lowSub:"Fast",mediumLabel:"Medium",mediumSub:"Balanced",highLabel:"High",highSub:"Best"},ew={title:"Moderation",autoLabel:"Auto",autoSub:"Standard filter",lowLabel:"Low",lowSub:"Relaxed filter",explain:"Auto uses the standard safety filter. Low relaxes limits so borderline prompts may pass through."},tw={title:"Format"},nw={title:"Count"},aw={button:"Generate",buttonLoading:"Generating ({n})"},iw={label:"API Status",checking:"Checking...",offline:"Offline",remaining:"${remaining} remaining",thisMonth:"${amount} this month",oauthFree:"OAuth · free via codex",apiDisabled:"API key disabled (OAuth only)",oauthMode:"OAuth mode"},lw={openGalleryAria:"Open gallery",openGalleryTitle:"Open full gallery"},ow={closeSettings:"Close settings",detailSettings:"Settings",toggleShow:"Show settings",toggleHide:"Hide settings",open:"Open",close:"Close"},sw={label:"Prompt",refCount:"Refs {count}/{max}",refChipTitle:"Reference {n}",refChipAlt:"Reference {n}",refRemoveAria:"Remove reference {n}",placeholder:"Describe the image you want. Drag & drop or paste to attach reference images...",placeholderWithRefs:"Describe what to do with the attached images...",attach:"Attach",attachTitle:"Attach reference images",useCurrent:"Use current",useCurrentTitle:"Use current result as a reference",style:"Style",styleTitle:"Open style consistency settings",directMode:"Direct",directModeTitle:"Pass prompt through verbatim (Direct mode)",hint:"Ctrl + Enter to generate",dropHere:"Drop to attach as reference (up to {max})"},rw={resultAlt:"result",imageViewerAria:"Generated image viewer. Use left and right arrow keys to move between images.",tokens:"{n} tokens"},cw={today:"Today",yesterday:"Yesterday",thisWeek:"This week",earlier:"Earlier",imageAltFallback:"Generated image",deleteTitle:"Delete (10s undo)",deleteAria:"Delete image",ariaLabel:"Image gallery",title:"Gallery",total:"{n} total",totalFiltered:" / {n} total",sortByAria:"Sort by",sortByDate:"Date",sortBySession:"Session",searchPlaceholder:"Search prompts or filenames",searchDisabledPlaceholder:"Search is disabled in session view",closeAria:"Close gallery",closeTitle:"Close (Esc)",sessionLabel:"Session {name}",standalone:"Standalone images",emptySessions:"No sessions saved yet.",emptyAll:"No images yet. Create one first.",noResults:"No results.",storageNoticeTitle:"Storage notice",storageNoticeRecoverable:"Sorry for the scare. Recent versions moved the gallery folder from the installed package to your user data folder. Your old images may still be in the previous generated folder. Run ima2 doctor or open the recovery guide.",storageNoticeNotFound:"Sorry for the scare. We could not find a previous generated folder on this machine. If the old global install folder was replaced during update, automatic recovery may not be possible. Run ima2 doctor and check the recovery guide for manual search steps.",storageNoticeUnknown:"Storage status could not be checked. If the gallery looks empty after an update, run ima2 doctor to inspect the image folder.",openGeneratedDir:"Open folder",openGeneratedDirTitle:"Open generated image folder",cardNewsSet:"Card News set",cardNewsCard:"Card News card",openCardNewsSet:"Open set",openCardNewsSetFailed:"Could not open the Card News set.",copyCardNewsSetPath:"Copy path",cardNewsPathCopied:"Card News set path copied.",downloadCardNewsManifest:"Manifest",cardNewsCount:"{n} cards",deleted:"Deleted: {filename}",undo:"Undo",secondsSuffix:"{n}s"},uw={empty:"Empty",pending:"Generating",reconciling:"Syncing",reconcilingPhase:"Syncing · {phase}",ready:"Done · {elapsed}s",readyWithSearch:"Done · {elapsed}s · searched {searches}",stale:"Stale",staleWithError:"Stale: {error}",assetMissing:"Asset missing",assetMissingWithError:"Asset missing: {error}",error:"Error: {error}",errorUnknown:"unknown",nodeImageAlt:"Node image",partialImageAlt:"Partial node image preview",noAsset:"No asset",stateStale:"State stale",noImage:"No image",editPromptPlaceholder:"Edit prompt...",promptPlaceholder:"Prompt...",regenerate:"Regen",newVariation:"New variant",generate:"Gen",generateTitle:"Generate node image",addChild:"Child",addChildTitle:"Add child node",duplicateBranch:"Branch",duplicateBranchTitle:"Duplicate as a new branch root",deleteTitle:"Delete",regenerateTitle:"Regenerate this node in place",newVariationTitle:"Create a new sibling variant under the same parent",parentImageRequired:"Generate the parent image first.",attachRef:"Attach",attachRefTitle:"Attach node reference images",refAlt:"Node reference {n}",removeRef:"Remove reference {n}",dropRefs:"Drop images here",nodeRefsUnsupportedForEdit:"Extra references are only supported on root nodes for now.",nodeRefsUsedWithParent:"Used together with the parent image.",classicRefsParkedTitle:"Classic references are parked",classicRefsParkedBody:"These images belong to the classic composer and are inactive in node mode.",clearParkedRefs:"Clear parked references",styleSheetActive:"Session style sheet active"},dw={selectionOn:"Selecting",selectionOff:"Select",selectAll:"Select all",summary:"{selected} selected · {missing} missing · {stale} affected",generateMissing:"Generate missing",regenerateSelected:"Regenerate selected",stopRemaining:"Stop remaining",stopping:"Stopping",clear:"Clear",noneSelected:"No nodes selected.",parentRequired:"{count} selected node(s) need a ready parent image first.",nothingToRun:"No selected nodes need generation.",stopQueued:"The current node will finish, then the remaining queue will stop.",failed:"Stopped after {done}/{total} node(s).",finished:"Finished {done}/{total} node(s).",staleBecauseParentChanged:"An upstream node was regenerated; refresh this node when needed."},fw={disconnected:"Connection removed.",parentConflict:"A node can only have one parent connection."},hw={authTitle:"Authentication",apiLabel:"API Key",oauthNotReady:"OAuth proxy is not ready yet.",codexLoginRequired:"Codex login required.",codexLoginHint:"Run `codex login` in your terminal, then refresh this page.",oauthStarting:"OAuth proxy is starting. Try again in a few seconds.",serverUnreachable:"Cannot reach the server. Make sure the backend is running.",apiInvalid:"API key is missing or invalid. Check OPENAI_API_KEY in the server's .env.",availableTitle:"{name} available",availableAria:"{name}: available",unavailableAria:"{name}: unavailable",availableSr:"(available)",unavailableSr:"(unavailable)"},gw={free:"free",approx:"~${amount}",label:"Est. cost"},mw={download:"Download",copyImage:"Copy image",copyPrompt:"Copy prompt",continueHere:"Continue here",continueHereTitle:"Import this image's prompt and keep working"},pw={switchTitle:"Switch session",loading:"Loading...",newSession:"New session",newSessionTitle:"New session",renameTitle:"Rename",renamePrompt:"Session name",deleteTitle:"Delete",deleteConfirm:'Delete session "{title}"? This cannot be undone.',empty:"No sessions yet",firstGraph:"My first graph",untitled:"Untitled session",assetAbortedError:"Generation did not finish cleanly. Retry from this node."},yw={ariaLabel:"UI mode",classic:"Classic",node:"Node",cardNews:"Card News"},vw={workspace:"Card News workspace",composer:"Card News",composerHint:"Templates are visual snapshots; output size is set separately.",topic:"Topic",topicPlaceholder:"e.g. Exam comeback plan",audience:"Audience",audiencePlaceholder:"e.g. Parents",goal:"Goal",goalPlaceholder:"e.g. Book a consultation",brief:"Brief",briefPlaceholder:"Describe the card news content, required points, and exclusions.",outputSize:"Output size",customSize:"Custom",draft:"Draft outline",drafting:"Drafting...",generateSet:"Generate set",batchGenerate:"Batch generate",generating:"Generating...",generated:"Generated {count} cards.",missingGeneratedCard:"The generation response did not include this card.",error:"Card generation failed.",imageTemplate:"Image template",roleTemplate:"Card structure",newTemplateLater:"Custom templates are planned after the dev MVP",emptyTitle:"Waiting for a draft",emptyBody:"Use the left setup panel to prepare the card deck.",inspector:"Card inspector",cardTitle:"Card title",headline:"Headline",body:"Body",visualPrompt:"Image prompt",summaryCopy:"Summary copy",designPrompt:"Scene / design prompt",textFields:"Text boxes",addTextField:"Add text box",removeTextField:"Remove",noTextFields:"No text boxes yet.",textFieldText:"Text",textKind:"Kind",placement:"Placement",renderMode:"Render mode",hierarchyLabel:"Hierarchy",textTooLong:"Text exceeds the suggested length.",selectTextField:"Select text box: {text}",textKinds:{headline:"Headline",body:"Supporting text",caption:"Caption",cta:"CTA",badge:"Badge",number:"Number"},renderModes:{"in-image":"In image","ui-only":"UI only"},hierarchy:{primary:"Primary",secondary:"Secondary",supporting:"Supporting"},placements:{"top-left":"Top-left","top-center":"Top-center","top-right":"Top-right","center-left":"Center-left",center:"Center","center-right":"Center-right","bottom-left":"Bottom-left","bottom-center":"Bottom-center","bottom-right":"Bottom-right",free:"Free"},roles:{cover:"Cover",hook:"Hook",problem:"Problem",insight:"Insight",example:"Example",data:"Data",summary:"Summary",cta:"CTA"},locked:"Locked",unlocked:"Unlocked",noCard:"No card selected",generatedMeta:"Generated metadata",lockedHelp:"Locked cards are excluded from batch generation and retry.",retryCard:"Retry this card",actions:{copyPrompt:"Copy prompt",copyCopy:"Copy copy",openImage:"Open image",downloadCard:"Download"},status:{draft:"Draft",queued:"Queued",generating:"Generating",generated:"Done",error:"Error",skipped:"Skipped",locked:"Locked"},progress:{generating:"Generating {done}/{total}",summary:"Done {done}/{total}",detail:"{queued} queued · {errors} errors · {skipped} skipped",cardGenerating:"Generating this card."},planner:{structured:"Structured JSON",jsonMode:"JSON mode",repaired:"Repaired",fallback:"Fallback draft",jsonOnlyHelp:"Draft creates JSON only. Images are generated later.",error:"Draft failed"}},xw={appName:"Image Generator",imageModelLabel:"Model",imageModelAria:"Choose image model",nodeModeHint:"In node mode, click a node to edit its prompt and generate. Settings on the right panel (quality/size) apply to every new result."},bw={openAria:"Open settings",openTitle:"Settings",closeAria:"Close settings",closeTitle:"Return to canvas",navAria:"Settings sections",contentAria:"Settings content",jumpTo:"Jump to {section}",eyebrow:"Workspace settings",title:"Settings",subtitle:"Account, display, and future workspace controls live here so the generator stays focused.",sections:{account:{title:"Account",hint:"OAuth status"},generation:{title:"Generation",hint:"Model defaults"},appearance:{title:"Appearance",hint:"Light and dark"},language:{title:"Language",hint:"Interface copy"},future:{title:"Future",hint:"Reserved"}},account:{primaryEyebrow:"Active provider",oauthTitle:"OAuth is active",oauthBody:"Generation currently runs through your Codex OAuth session. API-key generation remains disabled in this build.",apiSourceEnv:"OPENAI_API_KEY detected",apiSourceConfig:"config.json API key detected",apiTitle:"Configured but disabled",apiBody:"ima2-gen found an API key in env/config, but the app is OAuth-only right now. Remove the key only if you do not want this status shown.",apiDisabled:"Disabled",apiUnknown:"Status unknown"},imageModel:{title:"Image model",body:"Choose the OAuth model used for future image generations.",gpt54Mini:"GPT-5.4 Mini",gpt54:"GPT-5.4",gpt55:"GPT-5.5",gpt53CodexSpark:"GPT-5.3 Codex Spark — unsupported for images",unsupportedHelp:"Default is GPT-5.4 Mini. GPT-5.3 Codex Spark may appear in OAuth model status, but it does not support the image_generation tool."},appearance:{themeTitle:"Theme",themeBody:"Choose how the workspace should look on this device."},language:{title:"Language",body:"Switch the UI language without changing generated content."},future:{title:"Reserved for later",body:"Future provider repair and workspace controls will appear here when they become useful."}},Sw={loading:"Loading session...",addFirst:"+ Add first node",addRootTitle:"Add root node",hint:"Drag a handle into empty space to branch. Press Delete or Backspace to remove."},ww={title:"{provider} unavailable",ariaLabel:"{provider} unavailable"},Nw={label:"Language",ko:"한국어",en:"English"},_w={label:"Theme",system:"System",dark:"Dark",light:"Light"},Ew={toggle:"Apply style consistency",extract:"Extract from prompt",extracting:"Extracting…",edit:"Edit",save:"Save",cancel:"Cancel",emptyHint:"No style sheet yet. Extract from the current prompt to lock in a look.",noPrompt:"Enter a prompt first",extracted:"Style sheet extracted",editorTitle:"Edit style sheet",saved:"Style sheet saved",errNoKey:"Style-sheet extraction needs an OpenAI API key. Connect one via setup.",errBadOutput:"Model returned an unusable sheet — try a more specific prompt.",placeholderMedium:"e.g. oil painting, cinematic photo",placeholderComposition:"e.g. centered portrait, wide landscape",placeholderMood:"e.g. cinematic, dreamlike",placeholderSubject:"e.g. young woman in red jacket",placeholderPalette:"#0a0a0a, #f97316, warm amber",placeholderNegative:"blur, watermark, text",fields:{medium:"Medium",composition:"Composition",mood:"Mood",subject:"Subject details",palette:"Palette (comma-separated hex or names)",negative:"Negative (comma-separated)"}},Cw={close:"Close",details:"Show raw error details",unknown:{title:"An unexpected error occurred",body:"Please try again shortly. If it persists, copy the raw error message below and report it."},moderationRefused:{title:"Prompt blocked by moderation",body:"Soften the wording or rephrase. Sensitive/violent content in reference images can also trigger this.",cta:"Edit prompt"},upstream5xx:{title:"OpenAI is currently busy",body:"Retrying usually resolves this. Check status.openai.com if it persists.",cta:"Retry"},authChatgptExpired:{title:"Codex ChatGPT session expired",body:"Run `npx @openai/codex login` in your terminal, then reload this app.",cta:"Reload"},authApiKeyInvalid:{title:"API key authentication failed",body:"The key is invalid, revoked, out of quota, or tied to the wrong org. This app runs in OAuth mode, so switch to ChatGPT login.",cta:"OK"},networkFailed:{title:"Network connection failed",body:"Could not reach OpenAI or the local runtime service. Reload first; if it persists, check VPN/firewall and the port shown by `ima2 doctor`.",cta:"Reload"},oauthUnavailable:{title:"OAuth proxy unavailable",body:"The OAuth proxy is starting, unavailable, or moved to a fallback port. Reload first; if it persists, run `ima2 doctor` and check the reported OAuth URL.",cta:"Reload"},apikeyDisabled:{title:"API-key mode is disabled",body:"This app is OAuth-only (ChatGPT login). Switch the provider to OAuth.",cta:"OK"}},Tw={common:K1,toast:Q1,inflight:F1,size:P1,sizeConfirm:J1,quality:W1,moderation:ew,format:tw,count:nw,generate:aw,billing:iw,history:lw,panel:ow,prompt:sw,canvas:rw,gallery:cw,node:uw,nodeBatch:dw,edge:fw,provider:hw,cost:gw,result:mw,session:pw,uiMode:yw,cardNews:vw,sidebar:xw,settings:bw,nodeCanvas:Sw,apiDisabled:ww,language:Nw,theme:_w,styleSheet:Ew,errorCard:Cw},Hp={ko:Z1,en:Tw};function Ip(t,i){return i.split(".").reduce((l,o)=>{if(l!=null)return l[o]},t)}function Aw(t,i){return t.replace(/\{(\w+)\}/g,(l,o)=>o in i?String(i[o]):`{${o}}`)}function ve(t,i){const l=W.getState().locale;return p0(l,t,i)}function p0(t,i,l){const o=Ip(Hp[t],i),r=typeof o=="string"?o:Ip(Hp.en,i),u=typeof r=="string"?r:i;return l?Aw(u,l):u}function Te(){const t=W(i=>i.locale);return{locale:t,t:(i,l)=>p0(t,i,l)}}const Mw=["ko","en"];function jw(){try{const t=localStorage.getItem("ima2.locale");if(t==="ko"||t==="en")return t}catch{}return typeof navigator<"u"&&(navigator.language||"").toLowerCase().startsWith("ko")?"ko":"en"}function zw(t){try{localStorage.setItem("ima2.locale",t)}catch{}}function Rw(t){return Math.round(t/16)*16}const y0=1024,v0=3824,hr=3,zd=8294400;function Bp(t){return Math.floor(t/16)*16}function Lp(t){return Math.ceil(t/16)*16}function ti(t){return Math.min(v0,Math.max(y0,t))}function sl(t,i){const l=typeof t=="number"?t:Number.parseInt(t,10);return Number.isFinite(l)?l:i}function rl(t,i){t.includes(i)||t.push(i)}function kp(t,i){const l=Rw(t);return l!==t&&rl(i,"snap"),l}function Up(t,i){return t<y0&&rl(i,"min"),t>v0&&rl(i,"max"),ti(t)}function qp(t,i,l){return t>i*hr?(rl(l,"ratio"),{w:t,h:ti(Lp(t/hr))}):i>t*hr?(rl(l,"ratio"),{w:ti(Lp(i/hr)),h:i}):{w:t,h:i}}function Dw(t,i,l){if(t*i<=zd)return{w:t,h:i};rl(l,"pixels");const o=Math.sqrt(zd/(t*i));let r=ti(Bp(t*o)),u=ti(Bp(i*o));for(;r*u>zd;)r>=u?r=ti(r-16):u=ti(u-16);return{w:r,h:u}}function Ow(t,i,l,o){const r=[],u=sl(t,l),d=sl(i,o);let g=Up(kp(u,r),r),p=Up(kp(d,r),r);return{w:g,h:p}=qp(g,p,r),{w:g,h:p}=Dw(g,p,r),{w:g,h:p}=qp(g,p,r),{requestedW:u,requestedH:d,w:g,h:p,adjusted:g!==u||p!==d,reasons:r}}const Hw=[{value:"1024x1024",label:"1024×1024",sub:"1:1"},{value:"1536x1024",label:"1536×1024",sub:"3:2"},{value:"1024x1536",label:"1024×1536",sub:"2:3"}],Iw=[{value:"1360x1024",label:"1360×1024",sub:"4:3"},{value:"1024x1360",label:"1024×1360",sub:"3:4"},{value:"1824x1024",label:"1824×1024",sub:"16:9"}],Bw=[{value:"1024x1824",label:"1024×1824",sub:"9:16"},{value:"2048x2048",label:"2048×2048",sub:"2K 1:1"},{value:"2048x1152",label:"2048×1152",sub:"2K 16:9"}],Lw=[{value:"1152x2048",label:"1152×2048",sub:"2K 9:16"},{value:"3824x2160",label:"3824×2160",sub:"4K 16:9"},{value:"2160x3824",label:"2160×3824",sub:"4K 9:16"}];function kw(){return[{value:"auto",label:ve("size.autoLabel"),sub:ve("size.autoSub")},{value:"custom",label:ve("size.customLabel"),sub:ve("size.customSub")}]}const Uw="gpt-5.4-mini",x0="ima2.imageModel",tl=[{value:"gpt-5.4-mini",shortLabel:"5.4m",fullLabelKey:"settings.imageModel.gpt54Mini"},{value:"gpt-5.4",shortLabel:"5.4",fullLabelKey:"settings.imageModel.gpt54"},{value:"gpt-5.5",shortLabel:"5.5",fullLabelKey:"settings.imageModel.gpt55"}],qw=[{value:"gpt-5.3-codex-spark",fullLabelKey:"settings.imageModel.gpt53CodexSpark"}];function Gw(t){return tl.some(i=>i.value===t)}function b0(t){return t?tl.find(i=>i.value===t)?.shortLabel??t:null}const Ji=()=>"nc_"+Math.random().toString(36).slice(2,10);function Gp(t,i){return{x:t*360,y:i*320}}function Yw(t,i){return t.find(l=>l.target===i)??null}function Vw(t,i,l){return t.some(o=>o.target===l&&o.source!==i)}function _a(t,i){const l=new Map(t.map(o=>[o.id,o]));return t.map(o=>{const r=Yw(i,o.id),d=(r?l.get(r.source):null)?.data.serverNodeId??null;return o.data.parentServerNodeId===d?o:{...o,data:{...o.data,parentServerNodeId:d}}})}const Xw=360,S0=320;function $w(t,i,l){const o=new Set(l.filter(r=>r.source===t).map(r=>r.target));return i.filter(r=>o.has(r.id))}function Yp(t){const i=t.filter(o=>!o.data.parentServerNodeId);if(i.length===0)return Gp(0,0);const l=Math.max(...i.map(o=>o.position.y));return{x:Gp(0,0).x,y:l+S0}}function Vp(t,i,l){const o=$w(t.id,i,l),r=t.position.x+Xw;if(o.length===0)return{x:r,y:t.position.y};const u=Math.max(...o.map(d=>d.position.y));return{x:r,y:u+S0}}const w0="ima2.nodeRefs.v1";function pf(){try{const t=localStorage.getItem(w0);if(!t)return{};const i=JSON.parse(t);return i&&typeof i=="object"?i:{}}catch{return{}}}function N0(t){try{localStorage.setItem(w0,JSON.stringify(t))}catch{}}function Zw(t,i){if(!t)return[];const l=pf()[t]?.[i];return Array.isArray(l)?l.filter(o=>typeof o=="string"):[]}function Cr(t,i,l){if(!t)return;const o=pf(),r={...o[t]??{}};l.length===0?delete r[i]:r[i]=l,o[t]=r,N0(o)}function Rd(t,i){Cr(t,i,[])}function Kw(t,i){if(!t)return;const l=pf(),o=l[t];if(!o)return;const r=new Set(i);for(const u of Object.keys(o))r.has(u)||delete o[u];l[t]=o,N0(l)}function Qw(t,i,l){const o=new Set(t.map(g=>g.id));if(!o.has(l))return[];const r=new Map;for(const g of o)r.set(g,new Set);for(const g of i)!o.has(g.source)||!o.has(g.target)||(r.get(g.source)?.add(g.target),r.get(g.target)?.add(g.source));const u=new Set,d=[l];for(let g=0;g<d.length;g++){const p=d[g];if(!u.has(p)){u.add(p);for(const y of r.get(p)??[])u.has(y)||d.push(y)}}return t.filter(g=>u.has(g.id)).map(g=>g.id)}function _0(t){return t.filter(i=>i.selected).map(i=>i.id)}function So(t,i){const l=new Set(i);return t.map(o=>({...o,selected:l.has(o.id)}))}function Fw(t,i,l,o){const r=new Set(Qw(t,i,l));if(!r.size)return t;if(!o)return So(t,r);const u=t.find(p=>p.id===l),d=t.some(p=>r.has(p.id)&&p.selected),g=new Set(_0(t));if(d)u?.selected?g.delete(l):g.add(l);else for(const p of r)g.add(p);return So(t,g)}function E0(t){return t.data.status==="ready"&&!!t.data.imageUrl}function Pw(t,i,l){const o=new Set(l),r=new Set(t.map(v=>v.id)),u=new Map,d=new Map;for(const v of o)r.has(v)&&(u.set(v,0),d.set(v,[]));for(const v of i)!o.has(v.source)||!o.has(v.target)||(d.get(v.source)?.push(v.target),u.set(v.target,(u.get(v.target)??0)+1));const g=t.map(v=>v.id),p=g.filter(v=>o.has(v)&&(u.get(v)??0)===0),y=[];for(let v=0;v<p.length;v++){const x=p[v];y.push(x);for(const S of d.get(x)??[])u.set(S,(u.get(S)??0)-1),(u.get(S)??0)===0&&p.push(S)}const m=new Set(y);return y.concat(g.filter(v=>o.has(v)&&!m.has(v)))}function C0(t,i){const l=new Set(i),o=new Set,r=new Map;for(const d of t){const g=r.get(d.source)??[];g.push(d.target),r.set(d.source,g)}const u=[...l];for(let d=0;d<u.length;d++)for(const g of r.get(u[d])??[])l.has(g)||o.has(g)||(o.add(g),u.push(g));return[...o]}function Jw(t,i,l){const o=new Set(l);return t.filter(r=>r.source===i&&!o.has(r.target)).map(r=>r.target)}function Ww(t,i,l){const o=new Set(l),r=new Map(t.map(d=>[d.id,d])),u=[];for(const d of i){if(!o.has(d.target)||o.has(d.source))continue;r.get(d.source)?.data.serverNodeId||u.push(d.target)}return u}const wo={REF_TOO_LARGE:{surface:"toast",toastKey:"toast.refTooLarge"},REF_NOT_BASE64:{surface:"toast",toastKey:"toast.refNotBase64"},REF_EMPTY:{surface:"toast",toastKey:"toast.refEmpty"},REF_TOO_MANY:{surface:"toast",toastKey:"toast.refLimitExceeded"},MODERATION_REFUSED:{surface:"card",cardKey:"errorCard.moderationRefused",cta:"dismiss"},SAFETY_REFUSAL:{surface:"card",cardKey:"errorCard.moderationRefused",cta:"dismiss"},UPSTREAM_5XX:{surface:"card",cardKey:"errorCard.upstream5xx",cta:"retry"},AUTH_CHATGPT_EXPIRED:{surface:"card",cardKey:"errorCard.authChatgptExpired",cta:"reauth"},AUTH_API_KEY_INVALID:{surface:"card",cardKey:"errorCard.authApiKeyInvalid",cta:"dismiss"},NETWORK_FAILED:{surface:"card",cardKey:"errorCard.networkFailed",cta:"reload"},OAUTH_UNAVAILABLE:{surface:"card",cardKey:"errorCard.oauthUnavailable",cta:"reload"},INVALID_MODERATION:{surface:"toast",toastKey:"toast.generateFailed"},APIKEY_DISABLED:{surface:"card",cardKey:"errorCard.apikeyDisabled",cta:"dismiss"},DB_ERROR:{surface:"toast",toastKey:"toast.generateFailed"},UNKNOWN:{surface:"toast",toastKey:"toast.generateFailed"}};function eN(t){const i=(t||"").toLowerCase();return i?i.includes("moderation_blocked")||i.includes("moderation refused")?"MODERATION_REFUSED":i.includes("token is expired")||i.includes("sign in again")||i.includes("access token")&&i.includes("expired")||i.includes("token")&&i.includes("expired")&&!i.includes("api key")?"AUTH_CHATGPT_EXPIRED":i.includes("incorrect api key")||i.includes("invalid authentication")||i.includes("exceeded your current quota")||i.includes("incorrect organization")?"AUTH_API_KEY_INVALID":i.includes("failed to fetch")||i.includes("econnrefused")||i.includes("econnreset")||i.includes("enotfound")||i.includes("etimedout")||i.includes("network error")?"NETWORK_FAILED":i.includes("oauth")&&(i.includes("not running")||i.includes("unavailable")||i.includes("not ready"))?"OAUTH_UNAVAILABLE":i.includes("an error occurred while processing")||/\b5\d\d\b/.test(i)?"UPSTREAM_5XX":"UNKNOWN":"UNKNOWN"}function tN(t){const i=t,l=typeof i?.message=="string"?i.message:String(t??""),o=typeof i?.code=="string"?i.code:"",r=o&&o in wo?o:eN(l),u=wo[r]??wo.UNKNOWN;return{code:r,spec:u,message:l}}function Xp(t,i){const{code:l,spec:o,message:r}=tN(t);if(o.surface==="card")i.showErrorCard(l,{fallbackMessage:r});else{const u=o.toastKey?ve(o.toastKey):r||ve("toast.generateFailed");i.showToast(u,!0)}return{code:l,message:r}}const yf=!0,T0=!1;function nN(){try{const t=localStorage.getItem("ima2.rightPanelOpen");return t===null?!0:JSON.parse(t)===!0}catch{return!0}}function aN(){try{const t=localStorage.getItem("ima2.uiMode");if(t==="card-news")return T0?t:"classic";if(t==="node")return yf?t:"classic";if(t==="classic")return t}catch{}return"classic"}function Dd(){try{const t=localStorage.getItem("ima2:theme");if(t==="system"||t==="dark"||t==="light")return t}catch{}return"system"}function $p(){try{const t=localStorage.getItem(x0);if(Gw(t))return t}catch{}return Uw}function iN(t){try{localStorage.setItem(x0,t)}catch{}}function gr(t){return t==="dark"||t==="light"?t:typeof window>"u"||typeof window.matchMedia!="function"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}const A0=18e4;function Od(t){const i=t.meta??{},l=t.kind==="classic"||t.kind==="node"?t.kind:i.kind==="classic"||i.kind==="node"?i.kind:void 0;return{id:t.requestId,prompt:typeof t.prompt=="string"?t.prompt:"",startedAt:t.startedAt,phase:typeof t.phase=="string"?t.phase:void 0,sessionId:typeof i.sessionId=="string"?i.sessionId:null,parentNodeId:typeof i.parentNodeId=="string"?i.parentNodeId:null,clientNodeId:typeof i.clientNodeId=="string"?i.clientNodeId:null,kind:l}}function Hd(){try{const t=localStorage.getItem("ima2.inFlight");if(!t)return[];const i=JSON.parse(t);if(!Array.isArray(i))return[];const l=Date.now();return i.filter(o=>o&&typeof o.id=="string"&&typeof o.prompt=="string"&&typeof o.startedAt=="number"&&l-o.startedAt<A0).map(o=>({id:o.id,prompt:o.prompt,startedAt:o.startedAt,phase:typeof o.phase=="string"?o.phase:void 0,sessionId:typeof o.sessionId=="string"?o.sessionId:null,parentNodeId:typeof o.parentNodeId=="string"?o.parentNodeId:null,clientNodeId:typeof o.clientNodeId=="string"?o.clientNodeId:null,kind:o.kind==="classic"||o.kind==="node"?o.kind:void 0}))}catch{return[]}}function Ja(t){try{localStorage.setItem("ima2.inFlight",JSON.stringify(t))}catch(i){const l=window;if(!l.__ima2QuotaWarned){l.__ima2QuotaWarned=!0,console.warn("[ima2] localStorage write failed:",i);try{W.getState().showToast(ve("toast.localStorageFull"),!0)}catch{}}}}function Zp(){try{const t=localStorage.getItem("ima2.selectedFilename");return typeof t=="string"&&t.length>0?t:null}catch{return null}}function vo(t){try{t?localStorage.setItem("ima2.selectedFilename",t):localStorage.removeItem("ima2.selectedFilename")}catch{}}function lN(){try{const t=localStorage.getItem("ima2.activeSessionId");return typeof t=="string"&&t.length>0?t:null}catch{return null}}function Id(t){try{t?localStorage.setItem("ima2.activeSessionId",t):localStorage.removeItem("ima2.activeSessionId")}catch{}}const nl=500,Sa=5;function oN(t){return t==="classic"||t==="edit"||t==="generate"||t==="card-news-card"||t==="card-news-set"?t:null}function Kp(t){return{image:t.url,url:t.url,filename:t.filename,thumb:t.url,prompt:t.prompt??void 0,size:t.size??void 0,quality:t.quality??void 0,format:t.format,model:t.model??void 0,provider:t.provider,usage:t.usage??void 0,createdAt:t.createdAt,sessionId:t.sessionId??null,nodeId:t.nodeId??null,clientNodeId:t.clientNodeId??null,requestId:t.requestId??null,kind:oN(t.kind),setId:t.setId??null,cardId:t.cardId??null,cardOrder:t.cardOrder??null,headline:t.headline??null,body:t.body??null,cards:t.cards,refsCount:t.refsCount??0}}function Qp(t){return t.replace(/^data:[^;]+;base64,/,"")}function M0(t){const i=t.nodes.map(o=>{const r=o.data??{},u=typeof r.imageUrl=="string"&&r.imageUrl.length>0?r.imageUrl:null,d=typeof r.serverNodeId=="string"&&r.serverNodeId.length>0?`/generated/${r.serverNodeId}.png`:null,g=u??d,p={clientId:o.id,serverNodeId:r.serverNodeId??null,parentServerNodeId:r.parentServerNodeId??null,prompt:typeof r.prompt=="string"?r.prompt:"",imageUrl:g,status:r.status??(g?"ready":"empty"),pendingRequestId:r.pendingRequestId??null,recoveryRequestId:r.recoveryRequestId??null,pendingPhase:r.pendingPhase??null,pendingStartedAt:typeof r.pendingStartedAt=="number"?r.pendingStartedAt:null,partialImageUrl:null,error:r.error,elapsed:r.elapsed,webSearchCalls:r.webSearchCalls,model:r.model??null,size:r.size??null,referenceImages:Zw(t.id,o.id)};return{id:o.id,type:"imageNode",position:{x:o.x,y:o.y},data:p}}),l=t.edges.map(o=>({id:o.id,source:o.source,target:o.target}));return{graphNodes:_a(i,l),graphEdges:l,graphVersion:t.graphVersion}}function sN(t,i){return`${t}x${i}`}function mr(t,i){if(t.sizePreset!=="custom")return null;const l=Ow(t.customW,t.customH,t.customW,t.customH);return l.adjusted?{requestedW:l.requestedW,requestedH:l.requestedH,adjustedW:l.w,adjustedH:l.h,reasons:l.reasons,continuation:i}:null}const W=g0((t,i)=>({provider:"oauth",quality:"medium",sizePreset:"1024x1024",customW:1920,customH:1088,format:"png",moderation:"low",count:1,promptMode:"auto",prompt:"",referenceImages:[],addReferences:async l=>{const o=Sa-i().referenceImages.length,r=l.slice(0,Math.max(0,o)),u=r.filter(fr),d=r.filter(m=>!fr(m)),p=(await Promise.all(d.map(async m=>{try{return await Dp(m,{preserveTransparency:Op(m)})}catch(v){return console.warn("[addReferences] compress failed",v),null}}))).filter(m=>!!m);t(m=>({referenceImages:[...m.referenceImages,...p].slice(0,Sa)})),u.length>0&&i().showToast(ve("toast.refHeicUnsupported"),!0),d.length-p.length>0&&i().showToast(ve("toast.refTooLarge"),!0),l.length>o&&i().showToast(ve("toast.refLimitExceeded"),!0)},addReferenceDataUrl:l=>{t(o=>o.referenceImages.length>=Sa?o:{referenceImages:[...o.referenceImages,l]})},removeReference:l=>{t(o=>({referenceImages:o.referenceImages.filter((r,u)=>u!==l)}))},clearReferences:()=>t({referenceImages:[]}),useCurrentAsReference:async()=>{const l=i().currentImage;if(!l){i().showToast(ve("toast.noCurrentImageForRef"),!0);return}if(i().referenceImages.length>=Sa){i().showToast(ve("toast.refSlotFull"),!0);return}let o=l.image;if(!o.startsWith("data:"))try{const u=await(await fetch(o)).blob();o=await new Promise((d,g)=>{const p=new FileReader;p.onload=()=>typeof p.result=="string"?d(p.result):g(new Error("read failed")),p.onerror=()=>g(p.error??new Error("read failed")),p.readAsDataURL(u)})}catch{i().showToast(ve("toast.currentImageLoadFailed"),!0);return}t(r=>({referenceImages:[...r.referenceImages,o].slice(0,Sa)})),i().showToast(ve("toast.addedCurrentAsRef"))},activeGenerations:Hd().length,inFlight:Hd(),startInFlightPolling:()=>{if(typeof window>"u")return;const l=window;if(l.__ima2InflightTimer)return;const o=async()=>{if(i().inFlight.length===0){l.__ima2InflightTimer&&(clearInterval(l.__ima2InflightTimer),l.__ima2InflightTimer=void 0);return}try{const u=i().uiMode==="node"?"node":"classic",d=u==="node"?i().activeSessionId??void 0:void 0,{jobs:g}=await Ad({kind:u,sessionId:d}),p=new Map(g.map(S=>[S.requestId,S]));let y=!1;const m=Date.now(),v=5e3,x=[];for(const S of i().inFlight){if(!((S.kind??"classic")===u&&(u!=="node"||(S.sessionId??null)===(d??null)))){x.push(S);continue}if(!p.has(S.id)&&m-S.startedAt>v){y=!0;continue}const E=p.get(S.id);if(E){const A=Od(E),B={...S,phase:A.phase,sessionId:A.sessionId,parentNodeId:A.parentNodeId,clientNodeId:A.clientNodeId,kind:A.kind};(B.phase!==S.phase||B.sessionId!==S.sessionId||B.parentNodeId!==S.parentNodeId||B.clientNodeId!==S.clientNodeId||B.kind!==S.kind)&&(y=!0),x.push(B)}else x.push(S)}y&&(Ja(x),t({inFlight:x,activeGenerations:x.length}))}catch{}try{const u=i().history.reduce((x,S)=>S.createdAt&&S.createdAt>x?S.createdAt:x,0),{items:d}=await Wd({limit:nl,since:u}),g=d.map(Kp),p=i().history,y=g.filter(x=>!p.some(S=>S.filename===x.filename));y.length>0&&t(x=>{const S=x.currentImage??y[0];return!x.currentImage&&y[0]?.filename&&vo(y[0].filename),{history:[...y,...x.history].slice(0,nl),currentImage:S}});const m=Date.now(),v=i().inFlight.filter(x=>m-x.startedAt<A0);v.length!==i().inFlight.length&&(Ja(v),t({inFlight:v,activeGenerations:v.length}))}catch{}};l.__ima2InflightTimer=window.setInterval(o,1500)},reconcileInflight:async()=>{try{const l=i().uiMode==="node"?"node":"classic",o=l==="node"?i().activeSessionId??void 0:void 0,{jobs:r}=await Ad({kind:l,sessionId:o}),u=new Map(r.map(m=>[m.requestId,m])),d=Date.now(),p=i().inFlight.flatMap(m=>{const v=u.get(m.id);if(v){const w=Od(v);return[{...m,...w,prompt:m.prompt||w.prompt}]}return(m.kind??"classic")===l&&(l!=="node"||(m.sessionId??null)===(o??null))?d-m.startedAt<1e4?[m]:[]:[m]}),y=new Set(p.map(m=>m.id));for(const m of r)y.has(m.requestId)||p.push(Od(m));Ja(p),t({inFlight:p,activeGenerations:p.length}),p.length>0&&i().startInFlightPolling()}catch{}},syncFromStorage:()=>{const l=Hd(),o=Zp(),r=$p();t(u=>({inFlight:l,activeGenerations:l.length,imageModel:r,currentImage:o&&u.currentImage?.filename!==o?u.history.find(d=>d.filename===o)??u.currentImage:u.currentImage})),l.length>0&&i().startInFlightPolling()},currentImage:null,history:[],toast:null,customSizeConfirm:null,errorCard:null,rightPanelOpen:nN(),toggleRightPanel:()=>t(l=>{const o=!l.rightPanelOpen;try{localStorage.setItem("ima2.rightPanelOpen",JSON.stringify(o))}catch{}return{rightPanelOpen:o}}),galleryOpen:!1,openGallery:()=>t({galleryOpen:!0}),closeGallery:()=>t({galleryOpen:!1}),imageModel:$p(),settingsOpen:!1,activeSettingsSection:"account",openSettings:(l="account")=>t({settingsOpen:!0,activeSettingsSection:l}),closeSettings:()=>t({settingsOpen:!1}),toggleSettings:()=>t(l=>({settingsOpen:!l.settingsOpen,activeSettingsSection:l.settingsOpen?l.activeSettingsSection:"account"})),setActiveSettingsSection:l=>t({activeSettingsSection:l}),uiMode:aN(),setUIMode:l=>{const o=l==="card-news"&&!T0?"classic":l;try{localStorage.setItem("ima2.uiMode",o)}catch{}t({uiMode:o})},theme:Dd(),resolvedTheme:gr(Dd()),setTheme:l=>{try{localStorage.setItem("ima2:theme",l)}catch{}t({theme:l,resolvedTheme:gr(l)})},syncThemeFromStorage:()=>{const l=Dd();t({theme:l,resolvedTheme:gr(l)})},refreshResolvedTheme:()=>{t(l=>({resolvedTheme:gr(l.theme)}))},locale:jw(),setLocale:l=>{zw(l),t({locale:l})},graphNodes:[],graphEdges:[],setGraphNodes:l=>{t({graphNodes:_a(l,i().graphEdges)}),i().scheduleGraphSave()},setGraphEdges:l=>{t({graphEdges:l,graphNodes:_a(i().graphNodes,l)}),i().scheduleGraphSave()},disconnectEdge:l=>{i().disconnectEdges([l])},disconnectEdges:l=>{const o=new Set(l);if(o.size===0)return;const r=i().graphEdges.filter(p=>o.has(p.id));if(r.length===0)return;const u=i().graphEdges.filter(p=>!o.has(p.id)),d=new Set(r.map(p=>p.target)),g=i().graphNodes.map(p=>{if(!d.has(p.id))return p;const y=u.find(v=>v.target===p.id),m=y?i().graphNodes.find(v=>v.id===y.source):null;return{...p,data:{...p.data,parentServerNodeId:m?.data.serverNodeId??null}}});t({graphNodes:_a(g,u),graphEdges:u}),i().scheduleGraphSave(),i().showToast(ve("edge.disconnected"))},nodeSelectionMode:!1,nodeBatchRunning:!1,nodeBatchStopping:!1,toggleNodeSelectionMode:()=>{const l=!i().nodeSelectionMode;t({nodeSelectionMode:l,...l?{}:{graphNodes:So(i().graphNodes,[])}})},selectAllGraphNodes:()=>{t({graphNodes:So(i().graphNodes,i().graphNodes.map(l=>l.id))})},selectNodeGraph:(l,o)=>{t({graphNodes:Fw(i().graphNodes,i().graphEdges,l,o)})},clearNodeSelection:()=>{t({graphNodes:So(i().graphNodes,[])})},cancelNodeBatch:()=>{i().nodeBatchRunning&&(t({nodeBatchStopping:!0}),i().showToast(ve("nodeBatch.stopQueued")))},sessions:[],activeSessionId:null,activeSessionGraphVersion:null,sessionLoading:!1,styleSheet:null,styleSheetEnabled:!1,styleSheetExtracting:!1,async loadStyleSheet(){const l=i().activeSessionId;if(!l){t({styleSheet:null,styleSheetEnabled:!1});return}try{const o=await s1(l);if(i().activeSessionId!==l)return;t({styleSheet:o.styleSheet,styleSheetEnabled:!!o.enabled})}catch(o){console.warn("[styleSheet] load failed:",o)}},async saveStyleSheet(l,o){const r=i().activeSessionId;if(r)try{if(await r1(r,l,o),i().activeSessionId!==r)return;t({styleSheet:l,...typeof o=="boolean"?{styleSheetEnabled:o}:{}}),i().showToast(ve("styleSheet.saved"))}catch(u){console.warn("[styleSheet] save failed:",u),i().showToast(u.message,!0)}},async toggleStyleSheetEnabled(){const l=i().activeSessionId;if(!l)return;const o=!i().styleSheetEnabled;try{if(await c1(l,o),i().activeSessionId!==l)return;t({styleSheetEnabled:o})}catch(r){console.warn("[styleSheet] toggle failed:",r),i().showToast(r.message,!0)}},async extractStyleSheet(){const l=i().activeSessionId;if(!l)return;const o=i().prompt.trim();if(!o){i().showToast(ve("styleSheet.noPrompt"),!0);return}const r=i().referenceImages[0];t({styleSheetExtracting:!0});try{const{styleSheet:u}=await u1(l,o,r);if(i().activeSessionId!==l){t({styleSheetExtracting:!1});return}t({styleSheet:u,styleSheetEnabled:!0,styleSheetExtracting:!1}),i().showToast(ve("styleSheet.extracted"))}catch(u){t({styleSheetExtracting:!1}),console.warn("[styleSheet] extract failed:",u);const d=u.code,g=d==="STYLE_SHEET_NO_KEY"?ve("styleSheet.errNoKey"):d==="STYLE_SHEET_EMPTY"||d==="STYLE_SHEET_PARSE"||d==="STYLE_SHEET_SHAPE"?ve("styleSheet.errBadOutput"):u.message;i().showToast(g,!0)}},async loadSessions(){try{const{sessions:l}=await n1();if(t({sessions:l}),!i().activeSessionId){const r=lN(),u=r?l.some(d=>d.id===r):!1;r&&u?await i().switchSession(r):await i().createAndSwitchSession(ve("session.firstGraph"))}}catch(l){console.warn("[sessions] load failed:",l)}},async switchSession(l){t({sessionLoading:!0}),await i().flushGraphSave("switch-session");try{const{session:o}=await m0(l),{graphNodes:r,graphEdges:u,graphVersion:d}=M0(o);t({activeSessionId:l,activeSessionGraphVersion:d,graphNodes:r,graphEdges:u,sessionLoading:!1}),Id(l),await i().reconcileGraphPending().catch(()=>{}),i().loadStyleSheet().catch(()=>{})}catch(o){console.warn("[sessions] switch failed:",o),t({sessionLoading:!1}),i().showToast(ve("toast.sessionLoadFailed"),!0)}},async reconcileGraphPending(){const l=i().activeSessionId;if(!l)return;if(i().graphNodes.filter(r=>r.data?.pendingRequestId&&(r.data.status==="pending"||r.data.status==="reconciling")).length>0){let r=[];try{r=(await Ad({kind:"node",sessionId:l})).jobs}catch{r=[]}const u=new Map(r.map(y=>[y.requestId,y.phase])),d=Date.now(),g=1e4,p=i().graphNodes.map(y=>{const m=y.data?.pendingRequestId;if(!m||y.data.status!=="pending"&&y.data.status!=="reconciling")return y;if(u.has(m)){const S=u.get(m)??null;return{...y,data:{...y.data,status:"reconciling",pendingPhase:S}}}const v=y.data.pendingStartedAt??0;if(v&&d-v<g)return{...y,data:{...y.data,status:"reconciling"}};const x=!!y.data.imageUrl||!!y.data.serverNodeId;return{...y,data:{...y.data,pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,status:x?"ready":"stale",error:x?void 0:ve("session.assetAbortedError")}}});t({graphNodes:p})}await D0(i,t).catch(()=>{})},async createAndSwitchSession(l){l==null&&(l=ve("session.untitled"));try{const{session:o}=await a1(l);t({sessions:[o,...i().sessions],activeSessionId:o.id,activeSessionGraphVersion:o.graphVersion,graphNodes:[],graphEdges:[]}),Id(o.id)}catch(o){console.warn("[sessions] create failed:",o),i().showToast(ve("toast.sessionCreateFailed"),!0)}},async renameCurrentSession(l){const o=i().activeSessionId;if(o)try{await i1(o,l),t({sessions:i().sessions.map(r=>r.id===o?{...r,title:l,updatedAt:Date.now()}:r)})}catch{i().showToast(ve("toast.sessionRenameFailed"),!0)}},async deleteSessionById(l){try{await l1(l);const o=i().sessions.filter(r=>r.id!==l);t({sessions:o}),i().activeSessionId===l&&(t({activeSessionId:null,activeSessionGraphVersion:null,graphNodes:[],graphEdges:[]}),Id(null),o.length>0?await i().switchSession(o[0].id):await i().createAndSwitchSession(ve("session.firstGraph")))}catch{i().showToast(ve("toast.sessionDeleteFailed"),!0)}},scheduleGraphSave(){H0(i,t)},async flushGraphSave(l="manual"){await dN(i,t,l)},addRootNode:()=>{const l=Ji(),o={id:l,type:"imageNode",position:Yp(i().graphNodes),data:{clientId:l,serverNodeId:null,parentServerNodeId:null,prompt:"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};return t({graphNodes:[...i().graphNodes,o]}),i().scheduleGraphSave(),l},addChildNode:l=>{const o=i().graphNodes.find(g=>g.id===l);if(!o)return l;const r=Ji(),u={id:r,type:"imageNode",position:Vp(o,i().graphNodes,i().graphEdges),data:{clientId:r,serverNodeId:null,parentServerNodeId:o.data.serverNodeId,prompt:"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},d={id:`${l}->${r}`,source:l,target:r};return t({graphNodes:[...i().graphNodes,u],graphEdges:[...i().graphEdges,d]}),i().scheduleGraphSave(),r},addSiblingNode:l=>{const o=i().graphNodes.find(m=>m.id===l);if(!o)return l;const r=i().graphEdges.find(m=>m.target===l);if(!r){const m=Ji(),v={id:m,type:"imageNode",position:Yp(i().graphNodes),data:{clientId:m,serverNodeId:null,parentServerNodeId:null,prompt:o.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};return t({graphNodes:[...i().graphNodes,v]}),i().scheduleGraphSave(),m}const u=r.source,d=i().graphNodes.find(m=>m.id===u);if(!d)return l;const g=Ji(),p={id:g,type:"imageNode",position:Vp(d,i().graphNodes,i().graphEdges),data:{clientId:g,serverNodeId:null,parentServerNodeId:o.data.parentServerNodeId,prompt:o.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},y={id:`${u}->${g}`,source:u,target:g};return t({graphNodes:[...i().graphNodes,p],graphEdges:[...i().graphEdges,y]}),i().scheduleGraphSave(),g},updateNodePrompt:(l,o)=>{t({graphNodes:i().graphNodes.map(r=>r.id===l?{...r,data:{...r.data,prompt:o}}:r)}),i().scheduleGraphSave()},addNodeReferences:async(l,o)=>{const r=i().graphNodes.find(S=>S.id===l);if(!r)return;const u=r.data.referenceImages??[],d=Sa-u.length;if(d<=0){i().showToast(ve("toast.refLimitExceeded"),!0);return}const g=o.slice(0,Math.max(0,d)),p=g.filter(fr),y=g.filter(S=>!fr(S)),v=(await Promise.all(y.map(async S=>{try{return await Dp(S,{preserveTransparency:Op(S)})}catch(w){return console.warn("[addNodeReferences] compress failed",w),null}}))).filter(S=>!!S);if(v.length>0){const S=i().activeSessionId;t({graphNodes:i().graphNodes.map(w=>{if(w.id!==l)return w;const j=[...w.data.referenceImages??[],...v].slice(0,Sa);return Cr(S,l,j),{...w,data:{...w.data,referenceImages:j}}})}),i().scheduleGraphSave()}p.length>0&&i().showToast(ve("toast.refHeicUnsupported"),!0),y.length-v.length>0&&i().showToast(ve("toast.refTooLarge"),!0),o.length>d&&i().showToast(ve("toast.refLimitExceeded"),!0)},addNodeReferenceDataUrl:(l,o)=>{i().graphNodes.find(u=>u.id===l)&&(t({graphNodes:i().graphNodes.map(u=>{if(u.id!==l)return u;const d=u.data.referenceImages??[];if(d.length>=Sa)return u;const g=[...d,o];return Cr(i().activeSessionId,l,g),{...u,data:{...u.data,referenceImages:g}}})}),i().scheduleGraphSave())},removeNodeReference:(l,o)=>{t({graphNodes:i().graphNodes.map(r=>{if(r.id!==l)return r;const u=(r.data.referenceImages??[]).filter((d,g)=>g!==o);return Cr(i().activeSessionId,l,u),{...r,data:{...r.data,referenceImages:u}}})}),i().scheduleGraphSave()},clearNodeReferences:l=>{Rd(i().activeSessionId,l),t({graphNodes:i().graphNodes.map(o=>o.id===l?{...o,data:{...o.data,referenceImages:void 0}}:o)}),i().scheduleGraphSave()},duplicateBranchRoot:l=>{const o=i().graphNodes.find(d=>d.id===l);if(!o)return l;const r=Ji();i().graphNodes.filter(d=>!d.data.parentServerNodeId).length;const u={id:r,type:"imageNode",position:{x:o.position.x+420,y:o.position.y+40},data:{clientId:r,serverNodeId:null,parentServerNodeId:null,prompt:o.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};if(t({graphNodes:[...i().graphNodes,u]}),i().scheduleGraphSave(),o.data.imageUrl){const d=o.data.imageUrl;(async()=>{try{const p=await(await fetch(d)).blob(),y=await new Promise((m,v)=>{const x=new FileReader;x.onload=()=>typeof x.result=="string"?m(x.result):v(new Error("read failed")),x.onerror=()=>v(x.error??new Error("read failed")),x.readAsDataURL(p)});t({graphNodes:i().graphNodes.map(m=>m.id===r?{...m,data:{...m.data,referenceImages:[y]}}:m)})}catch{}})()}return r},async generateNode(l){const o=i().graphNodes.find(d=>d.id===l);if(!o)return;const{prompt:r}=o.data;if(!r.trim()){i().showToast(ve("toast.promptRequired"),!0);return}const u=mr(i(),{kind:"node",clientId:l});if(u){t({customSizeConfirm:u});return}await i().runGenerateNode(l)},async generateNodeInPlace(l){const o=i().graphNodes.find(u=>u.id===l);if(!o)return;if(!o.data.prompt.trim()){i().showToast(ve("toast.promptRequired"),!0);return}const r=mr(i(),{kind:"node-in-place",clientId:l});if(r){t({customSizeConfirm:r});return}await i().runGenerateNodeInPlace(l)},async generateNodeVariation(l,o){const r=i().graphNodes.find(d=>d.id===l);if(!r)return;if(!r.data.prompt.trim()){i().showToast(ve("toast.promptRequired"),!0);return}if(!o){const d=mr(i(),{kind:"node-variation",clientId:l});if(d){t({customSizeConfirm:d});return}}const u=i().addSiblingNode(l);await i().runGenerateNodeInPlace(u,{sizeOverride:o})},async runGenerateNode(l,o){const u=i().graphNodes.find(d=>d.id===l)?.data.status==="ready"?i().addSiblingNode(l):l;await i().runGenerateNodeInPlace(u,{sizeOverride:o})},async runGenerateNodeInPlace(l,o={}){const r=i().graphNodes,u=_a(r,i().graphEdges);u.some((_,U)=>_.data.parentServerNodeId!==r[U]?.data.parentServerNodeId)&&t({graphNodes:u});const d=u.find(_=>_.id===l);if(!d)return null;const{prompt:g,parentServerNodeId:p}=d.data;if(!g.trim())return i().showToast(ve("toast.promptRequired"),!0),null;const y=d.data.referenceImages??[],m=i(),v=o.sizeOverride??m.getResolvedSize(),x=o.parentServerNodeIdOverride!==void 0?o.parentServerNodeIdOverride:p;if(i().graphEdges.find(_=>_.target===l)&&!x)return i().showToast(ve("node.parentImageRequired"),!0),null;const w=m.activeSessionId,j=Date.now(),E=Math.random().toString(36).slice(2,6),A=`fn_${l}_${j}_${E}`,B=[...m.inFlight,{id:A,prompt:g,startedAt:j,kind:"node",sessionId:w,clientNodeId:l}];Ja(B),t({graphNodes:i().graphNodes.map(_=>_.id===l?{..._,data:{..._.data,status:"pending",pendingRequestId:A,recoveryRequestId:A,pendingPhase:"queued",pendingStartedAt:j,partialImageUrl:null,error:void 0,size:v}}:_),activeGenerations:m.activeGenerations+1,inFlight:B}),i().startInFlightPolling();let C=!0;try{const _=await t1({parentNodeId:x,prompt:g,quality:m.quality,size:v,format:m.format,moderation:m.moderation,model:m.imageModel,requestId:A,sessionId:w,clientNodeId:l,contextMode:"parent-plus-refs",searchMode:"off",...y.length?{references:y.map(Qp)}:{}},{onPartial:U=>{i().activeSessionId===w&&t({graphNodes:i().graphNodes.map(R=>R.id===l?{...R,data:{...R.data,status:"pending",partialImageUrl:U.image,pendingPhase:"partial"}}:R)})},onPhase:U=>{i().activeSessionId===w&&U.phase&&t({graphNodes:i().graphNodes.map(R=>R.id===l?{...R,data:{...R.data,pendingPhase:U.phase??R.data.pendingPhase}}:R)})}});return i().activeSessionId===w&&(t({graphNodes:i().graphNodes.map(U=>{if(U.id!==l)return U;const R={...U.data};return delete R.partialImageUrl,{...U,data:{...R,serverNodeId:_.nodeId,imageUrl:_.url,status:"ready",pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,elapsed:_.elapsed,webSearchCalls:_.webSearchCalls,model:_.model??null,size:_.size??v}}})}),C=!0,o.suppressToast||i().showToast(ve("toast.nodeCreated",{id:_.nodeId.slice(0,8),elapsed:_.elapsed}))),_.nodeId}catch(_){const U=_ instanceof Error?_.message:ve("toast.nodeCreateFailed");return i().activeSessionId===w&&(t({graphNodes:i().graphNodes.map(R=>R.id===l?{...R,data:{...R.data,status:"error",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:U}}:R)}),C=!0,Xp(_,i())),null}finally{const _=i().inFlight.filter(U=>U.id!==A);Ja(_),t({activeGenerations:Math.max(0,i().activeGenerations-1),inFlight:_}),i().activeSessionId===w&&C&&i().scheduleGraphSave()}},async runNodeBatch(l){if(i().nodeBatchRunning)return;const o=_0(i().graphNodes);if(o.length===0){i().showToast(ve("nodeBatch.noneSelected"),!0);return}const r=Ww(i().graphNodes,i().graphEdges,o);if(r.length>0){i().showToast(ve("nodeBatch.parentRequired",{count:r.length}),!0);return}const u=Pw(i().graphNodes,i().graphEdges,o),d=new Set(o),g=u.filter(m=>{if(l==="regenerate-all")return!0;const v=i().graphNodes.find(x=>x.id===m);return v?!E0(v):!1});if(g.length===0){i().showToast(ve("nodeBatch.nothingToRun"));return}t({nodeBatchRunning:!0,nodeBatchStopping:!1});const p=new Map;let y=0;try{for(const m of g){if(i().nodeBatchStopping)break;const v=i().graphEdges.find(E=>E.target===m),x=v?p.get(v.source)??i().graphNodes.find(E=>E.id===m)?.data.parentServerNodeId??null:null,S=await i().runGenerateNodeInPlace(m,{parentServerNodeIdOverride:x,suppressToast:!0});if(!S){i().showToast(ve("nodeBatch.failed",{done:y,total:g.length}),!0);break}y+=1,p.set(m,S);const w=Jw(i().graphEdges,m,d),j=new Set(C0(i().graphEdges,d));t({graphNodes:i().graphNodes.map(E=>j.has(E.id)?{...E,data:{...E.data,status:"stale",parentServerNodeId:w.includes(E.id)?S:E.data.parentServerNodeId,error:ve("nodeBatch.staleBecauseParentChanged")}}:E)})}i().showToast(ve("nodeBatch.finished",{done:y,total:g.length})),i().scheduleGraphSave()}finally{t({nodeBatchRunning:!1,nodeBatchStopping:!1})}},deleteNode:l=>{const r=i().graphNodes.find(g=>g.id===l)?.data?.pendingRequestId;r&&jp(r),Rd(i().activeSessionId,l);const u=i().graphNodes.filter(g=>g.id!==l),d=i().graphEdges.filter(g=>g.source!==l&&g.target!==l);t({graphNodes:_a(u,d),graphEdges:d}),i().scheduleGraphSave()},deleteNodes:l=>{const o=new Set(l);for(const d of o)Rd(i().activeSessionId,d);for(const d of i().graphNodes)o.has(d.id)&&d.data?.pendingRequestId&&jp(d.data.pendingRequestId);const r=i().graphNodes.filter(d=>!o.has(d.id)),u=i().graphEdges.filter(d=>!o.has(d.source)&&!o.has(d.target));t({graphNodes:_a(r,u),graphEdges:u}),i().scheduleGraphSave()},addChildNodeAt:(l,o)=>{const r=i().graphNodes.find(p=>p.id===l);if(!r)return l;const u=Ji(),d={id:u,type:"imageNode",position:o,data:{clientId:u,serverNodeId:null,parentServerNodeId:r.data.serverNodeId,prompt:"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},g={id:`${l}->${u}`,source:l,target:u};return t({graphNodes:[...i().graphNodes,d],graphEdges:[...i().graphEdges,g]}),i().scheduleGraphSave(),u},connectNodes:(l,o)=>{if(l===o||i().graphEdges.find(g=>g.source===l&&g.target===o))return;if(Vw(i().graphEdges,l,o)){i().showToast(ve("edge.parentConflict"),!0);return}if(!i().graphNodes.find(g=>g.id===l))return;const d=[...i().graphEdges,{id:`${l}->${o}`,source:l,target:o}];t({graphNodes:_a(i().graphNodes,d),graphEdges:d}),i().scheduleGraphSave()},setProvider:l=>t({provider:l}),setQuality:l=>t({quality:l}),setSizePreset:l=>t({sizePreset:l}),setCustomSize:(l,o)=>t(r=>({customW:sl(l,r.customW),customH:sl(o,r.customH)})),setFormat:l=>t({format:l}),setModeration:l=>t({moderation:l}),setImageModel:l=>{iN(l),t({imageModel:l})},setCount:l=>t({count:l}),setPromptMode:l=>t({promptMode:l}),setPrompt:l=>t({prompt:l}),selectHistory:l=>{vo(l.filename??null),t({currentImage:l})},removeFromHistory:l=>{const o=i(),r=o.history.filter(d=>d.filename!==l),u=o.currentImage&&o.currentImage.filename===l?null:o.currentImage;t({history:r,currentImage:u}),u===null&&vo(null)},addHistoryItem:l=>{const o=i();if(o.history.some(d=>l.filename&&d.filename===l.filename))return;const u={...l,createdAt:l.createdAt||Date.now()};t({history:[u,...o.history].slice(0,nl)})},getResolvedSize:()=>{const{sizePreset:l,customW:o,customH:r}=i();return l==="custom"?`${o}x${r}`:l},async generate(){const l=i();if(!l.prompt.trim())return;const r=mr(l,{kind:"classic"});if(r){t({customSizeConfirm:r});return}await i().runGenerate()},async runGenerate(l){const o=i(),r=o.prompt.trim();if(!r)return;const u=l??o.getResolvedSize(),d=`f_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,g=Date.now(),p=[...o.inFlight,{id:d,prompt:r,startedAt:g}];Ja(p),t({activeGenerations:o.activeGenerations+1,inFlight:p}),i().startInFlightPolling();try{const y={prompt:r,quality:o.quality,size:u,format:o.format,moderation:o.moderation,provider:o.provider,n:o.count,model:o.imageModel,requestId:d,mode:o.promptMode,...o.referenceImages.length?{references:o.referenceImages.map(Qp)}:{}},m=await KS(y);if(Mp(m)&&m.images.length>1){for(const v of m.images){const x={image:v.image,filename:v.filename,prompt:r,elapsed:m.elapsed,provider:m.provider,usage:m.usage,quality:m.quality??o.quality,size:m.size??u,model:m.model??o.imageModel};await Pp(x,t,i)}i().showToast(ve("toast.generatedBatch",{count:m.images.length,elapsed:m.elapsed}))}else{let v;if(Mp(m)){const x=m.images[0];v={image:x.image,filename:x.filename,prompt:r,elapsed:m.elapsed,provider:m.provider,usage:m.usage,quality:m.quality??o.quality,size:m.size??u,model:m.model??o.imageModel}}else v={image:m.image,filename:m.filename,prompt:r,elapsed:m.elapsed,provider:m.provider,usage:m.usage,quality:m.quality??o.quality,size:m.size??u,model:m.model??o.imageModel};await Pp(v,t,i),i().showToast(ve("toast.generatedSingle",{elapsed:m.elapsed}))}}catch(y){Xp(y,i())}finally{const y=i().inFlight.filter(m=>m.id!==d);Ja(y),t({activeGenerations:Math.max(0,i().activeGenerations-1),inFlight:y})}},async confirmCustomSizeAdjustment(){const l=i().customSizeConfirm;if(!l)return;const o=sN(l.adjustedW,l.adjustedH);if(t({customW:l.adjustedW,customH:l.adjustedH,customSizeConfirm:null}),l.continuation.kind==="classic"){await i().runGenerate(o);return}if(l.continuation.kind==="node-in-place"){await i().runGenerateNodeInPlace(l.continuation.clientId,{sizeOverride:o});return}if(l.continuation.kind==="node-variation"){await i().generateNodeVariation(l.continuation.clientId,o);return}await i().runGenerateNode(l.continuation.clientId,o)},cancelCustomSizeAdjustment:()=>t({customSizeConfirm:null}),hydrateHistory(){(async()=>{try{const o=(await Wd({limit:nl})).items.map(Kp);if(o.length>0){const r=Zp(),u=r?o.find(d=>d.filename===r):null;t({history:o,currentImage:u??o[0]}),u||vo(o[0]?.filename??null)}}catch(l){console.warn("[history] load failed:",l)}})()},showToast(l,o=!1){t({toast:{message:l,error:o,id:Date.now()+Math.random()}})},showErrorCard(l,o){t({errorCard:{code:l,fallbackMessage:o?.fallbackMessage,id:Date.now()+Math.random()}})},dismissErrorCard(){t({errorCard:null})}})),rN=800,Fp="ima2.graphTabId";let gn=null,Tr=!1,Ar=!1,ei=null,j0=0;function z0(){try{const t=sessionStorage.getItem(Fp);if(t)return t;const i=`tab_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;return sessionStorage.setItem(Fp,i),i}catch{return"tab_unavailable"}}function R0(t){const i={...t};return delete i.referenceImages,delete i.partialImageUrl,t.status==="pending"||t.status==="reconciling"?{...i,status:"empty",pendingRequestId:null,recoveryRequestId:t.pendingRequestId??t.recoveryRequestId??null,pendingPhase:null,pendingStartedAt:null,error:void 0}:i}async function D0(t,i){const l=t().activeSessionId;if(!l||t().graphNodes.filter(g=>!g.data.imageUrl&&!g.data.serverNodeId).length===0)return;let r=[];try{r=(await Wd({sessionId:l,limit:nl})).items}catch{return}let u=!1;const d=t().graphNodes.map(g=>{if(g.data.imageUrl||g.data.serverNodeId)return g;const p=g.data.pendingStartedAt??0,y=g.data.pendingRequestId??g.data.recoveryRequestId??null,v=(y?r.find(x=>(x.sessionId??null)===l&&(x.requestId??null)===y):null)??r.find(x=>(x.sessionId??null)===l&&(x.clientNodeId??null)===g.id&&(!p||(x.createdAt??0)>=p));return v?(u=!0,{...g,data:{...g.data,status:"ready",imageUrl:v.url,serverNodeId:v.nodeId??g.data.serverNodeId,size:v.size??g.data.size??null,pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:void 0}}):g});u&&(i({graphNodes:d}),H0(t,i,"recovery"))}async function cN(t,i){const l=t().activeSessionId;if(!l)return;const{session:o}=await m0(l),{graphNodes:r,graphEdges:u,graphVersion:d}=M0(o);i({graphNodes:r,graphEdges:u,activeSessionGraphVersion:d}),t().showToast(ve("toast.sessionReloadedElsewhere"),!0),await D0(t,i).catch(()=>{})}async function uN(t,i,l){const o=t().activeSessionId,r=t().activeSessionGraphVersion;if(!o||r==null)return"skipped";const{graphNodes:u,graphEdges:d}=t(),g=u.map(m=>({id:m.id,x:m.position.x,y:m.position.y,data:R0(m.data)})),p=d.map(m=>({id:m.id,source:m.source,target:m.target,data:{}})),y=`gs_${Date.now().toString(36)}_${++j0}`;try{const m=await o1(o,r,g,p,{saveId:y,saveReason:l,tabId:z0()});return t().activeSessionId!==o?"skipped":(Kw(o,t().graphNodes.map(v=>v.id)),i({activeSessionGraphVersion:m.graphVersion}),"saved")}catch(m){return m.status===409?(await cN(t,i),"conflict"):(console.warn("[sessions] save failed:",m),"failed")}}async function O0(t,i,l){if(Tr){Ar=!0,ei&&await ei;return}Tr=!0,ei=(async()=>{let o=l;do{Ar=!1;const r=await uN(t,i,o);if(r==="conflict"||r==="failed")break;o="queued"}while(Ar)})().finally(()=>{Tr=!1,ei=null}),await ei}function H0(t,i,l="debounced"){const o=t();o.activeSessionId&&(o.sessionLoading||(gn&&clearTimeout(gn),gn=setTimeout(()=>{gn=null,O0(t,i,l)},rN)))}async function dN(t,i,l="manual"){let o=!1;if(gn&&(clearTimeout(gn),gn=null,o=!0),Tr){Ar=!0,ei&&await ei;return}o&&await O0(t,i,l)}function fN(t){const i=t();if(!i.activeSessionId||i.activeSessionGraphVersion==null)return;gn&&(clearTimeout(gn),gn=null);const l=i.graphNodes.map(d=>({id:d.id,x:d.position.x,y:d.position.y,data:R0(d.data)})),o=i.graphEdges.map(d=>({id:d.id,source:d.source,target:d.target,data:{}})),r=`/api/sessions/${encodeURIComponent(i.activeSessionId)}/graph`,u=JSON.stringify({nodes:l,edges:o});try{fetch(r,{method:"PUT",headers:{"Content-Type":"application/json","If-Match":String(i.activeSessionGraphVersion),"X-Ima2-Graph-Save-Id":`gs_${Date.now().toString(36)}_${++j0}`,"X-Ima2-Graph-Save-Reason":"beforeunload","X-Ima2-Tab-Id":z0()},body:u,keepalive:!0})}catch{}}async function Pp(t,i,l){const o=await d1(t.image).catch(()=>t.image),r=t.filename?`/generated/${t.filename}`:t.image,u={...t,thumb:o,url:r,createdAt:t.createdAt||Date.now()},d=[u,...l().history].slice(0,nl);vo(u.filename??null),i({history:d,currentImage:u})}function hN(){const{t}=Te(),i=W(o=>o.uiMode),l=W(o=>o.setUIMode);return h.jsxs("div",{className:"ui-mode-switch",role:"tablist","aria-label":t("uiMode.ariaLabel"),children:[h.jsx("button",{type:"button",role:"tab","aria-selected":i==="classic",className:`ui-mode-switch__tab${i==="classic"?" active":""}`,onClick:()=>l("classic"),children:t("uiMode.classic")}),h.jsx("button",{type:"button",role:"tab","aria-selected":i==="node",className:`ui-mode-switch__tab${i==="node"?" active":""}`,onClick:()=>l("node"),children:t("uiMode.node")}),null]})}const Jp={palette:[],composition:"",mood:"",medium:"",subject_details:"",negative:[]};function I0({open:t,onClose:i}){const{t:l}=Te(),o=W(R=>R.styleSheet),r=W(R=>R.styleSheetEnabled),u=W(R=>R.styleSheetExtracting),d=W(R=>R.activeSessionId),g=W(R=>R.toggleStyleSheetEnabled),p=W(R=>R.extractStyleSheet),y=W(R=>R.saveStyleSheet),[m,v]=Y.useState(!1),[x,S]=Y.useState(o??Jp),[w,j]=Y.useState(!1),[E,A]=Y.useState(!1);if(Y.useEffect(()=>{t?S(o??Jp):(v(!1),j(!1))},[t,o]),Y.useEffect(()=>{if(!t)return;const R=z=>{z.key==="Escape"&&!w&&i()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[t,w,i]),!t||!d)return null;const B=!!o&&(o.composition||o.mood||o.medium||o.subject_details||o.palette.length>0),C=async()=>{if(!w){j(!0);try{await y(x,r),v(!1)}finally{j(!1)}}},_=async()=>{if(!E){A(!0);try{await g()}finally{A(!1)}}},U=R=>S(z=>({...z,...R}));return h.jsx("div",{className:"style-sheet-editor__backdrop",onClick:w?void 0:i,role:"presentation",children:h.jsxs("div",{className:"style-sheet-editor",role:"dialog","aria-modal":"true","aria-label":l("styleSheet.editorTitle"),onClick:R=>R.stopPropagation(),children:[h.jsxs("div",{className:"style-sheet-panel__header",children:[h.jsx("h3",{style:{margin:0,fontSize:16},children:l("styleSheet.editorTitle")}),h.jsxs("label",{className:"style-sheet-panel__toggle",style:{marginLeft:"auto"},children:[h.jsx("input",{type:"checkbox",checked:r,disabled:!B||E,onChange:()=>{_()}}),h.jsx("span",{children:l("styleSheet.toggle")})]})]}),!m&&h.jsxs(h.Fragment,{children:[B?h.jsxs("div",{className:"style-sheet-panel__summary",children:[o.medium&&h.jsxs("div",{children:[h.jsxs("b",{children:[l("styleSheet.fields.medium"),":"]})," ",o.medium]}),o.palette.length>0&&h.jsx("div",{className:"style-sheet-panel__chips",children:o.palette.slice(0,6).map((R,z)=>h.jsx("span",{className:"style-sheet-panel__chip",title:R,children:R},z))}),o.mood&&h.jsxs("div",{className:"style-sheet-panel__muted",children:[l("styleSheet.fields.mood"),": ",o.mood]})]}):h.jsx("div",{className:"style-sheet-panel__muted",children:l("styleSheet.emptyHint")}),h.jsxs("div",{className:"style-sheet-panel__actions",children:[h.jsx("button",{type:"button",className:"btn btn--secondary btn--sm",onClick:()=>{p()},disabled:u,children:l(u?"styleSheet.extracting":"styleSheet.extract")}),h.jsx("button",{type:"button",className:"btn btn--ghost btn--sm",onClick:()=>v(!0),disabled:u,children:l("styleSheet.edit")}),h.jsx("button",{type:"button",className:"btn btn--ghost btn--sm",style:{marginLeft:"auto"},onClick:i,children:l("styleSheet.cancel")})]})]}),m&&h.jsxs(h.Fragment,{children:[h.jsxs("label",{children:[l("styleSheet.fields.medium"),h.jsx("input",{value:x.medium,onChange:R=>U({medium:R.target.value}),placeholder:l("styleSheet.placeholderMedium")})]}),h.jsxs("label",{children:[l("styleSheet.fields.composition"),h.jsx("textarea",{rows:2,value:x.composition,onChange:R=>U({composition:R.target.value}),placeholder:l("styleSheet.placeholderComposition")})]}),h.jsxs("label",{children:[l("styleSheet.fields.mood"),h.jsx("input",{value:x.mood,onChange:R=>U({mood:R.target.value}),placeholder:l("styleSheet.placeholderMood")})]}),h.jsxs("label",{children:[l("styleSheet.fields.subject"),h.jsx("textarea",{rows:2,value:x.subject_details,onChange:R=>U({subject_details:R.target.value}),placeholder:l("styleSheet.placeholderSubject")})]}),h.jsxs("label",{children:[l("styleSheet.fields.palette"),h.jsx("input",{value:x.palette.join(", "),onChange:R=>U({palette:R.target.value.split(",").map(z=>z.trim()).filter(Boolean).slice(0,6)}),placeholder:l("styleSheet.placeholderPalette")})]}),h.jsxs("label",{children:[l("styleSheet.fields.negative"),h.jsx("input",{value:x.negative.join(", "),onChange:R=>U({negative:R.target.value.split(",").map(z=>z.trim()).filter(Boolean).slice(0,4)}),placeholder:l("styleSheet.placeholderNegative")})]}),h.jsxs("div",{className:"style-sheet-editor__actions",children:[h.jsx("button",{type:"button",className:"btn btn--ghost",onClick:()=>v(!1),disabled:w,children:l("styleSheet.cancel")}),h.jsx("button",{type:"button",className:"btn btn--primary",onClick:()=>{C()},disabled:w,children:l(w?"styleSheet.extracting":"styleSheet.save")})]})]})]})})}const Wi=5;function gN(){const t=W(I=>I.prompt),i=W(I=>I.setPrompt),l=W(I=>I.generate),{t:o}=Te(),r=W(I=>I.referenceImages),u=W(I=>I.addReferences),d=W(I=>I.removeReference),g=W(I=>I.useCurrentAsReference),p=W(I=>I.currentImage),y=Y.useRef(null),[m,v]=Y.useState(!1),[x,S]=Y.useState(!1),w=W(I=>I.activeSessionId),j=W(I=>I.styleSheetEnabled),E=W(I=>I.promptMode),A=W(I=>I.setPromptMode),B=r.length<Wi,C=I=>{I.preventDefault(),v(!1);const X=Array.from(I.dataTransfer.files).filter(ce=>ce.type.startsWith("image/"));X.length>0&&u(X)},_=I=>{I.preventDefault(),m||v(!0)},U=I=>{I.currentTarget.contains(I.relatedTarget)||v(!1)},R=I=>{if(!I)return[];const X=[];for(const ce of Array.from(I)){if(ce.kind!=="file"||!ce.type.startsWith("image/"))continue;const K=ce.getAsFile();K&&X.push(K)}return X},z=I=>{if(!B)return;const X=R(I.clipboardData?.items??null);if(X.length===0)return;I.preventDefault();const ce=Wi-r.length;u(X.slice(0,ce))};return Y.useEffect(()=>{const I=X=>{const ce=X.target,K=ce?.tagName;if(K==="INPUT"||K==="TEXTAREA"||ce?.isContentEditable)return;const te=R(X.clipboardData?.items??null);if(te.length===0||r.length>=Wi)return;X.preventDefault();const ue=Wi-r.length;u(te.slice(0,ue))};return window.addEventListener("paste",I),()=>window.removeEventListener("paste",I)},[r.length,u]),h.jsxs("div",{className:`composer${m?" composer--drag":""}`,onDrop:C,onDragOver:_,onDragLeave:U,onPaste:z,children:[h.jsxs("div",{className:"composer__header",children:[h.jsx("span",{className:"section-title composer__label",children:o("prompt.label")}),r.length>0&&h.jsx("span",{className:"composer__count",children:o("prompt.refCount",{count:r.length,max:Wi})})]}),r.length>0&&h.jsx("div",{className:"composer__chips",children:r.map((I,X)=>h.jsxs("div",{className:"composer__chip",title:o("prompt.refChipTitle",{n:X+1}),children:[h.jsx("img",{src:I,alt:o("prompt.refChipAlt",{n:X+1})}),h.jsx("button",{type:"button",className:"composer__chip-remove",onClick:()=>d(X),"aria-label":o("prompt.refRemoveAria",{n:X+1}),children:"×"})]},X))}),h.jsx("textarea",{className:"prompt-area composer__textarea",value:t,placeholder:r.length>0?o("prompt.placeholderWithRefs"):o("prompt.placeholder"),onChange:I=>i(I.target.value),onKeyDown:I=>{I.key==="Enter"&&(I.metaKey||I.ctrlKey)&&(I.preventDefault(),l())}}),h.jsxs("div",{className:"composer__toolbar",children:[h.jsxs("button",{type:"button",className:"composer__tool",onClick:()=>B&&y.current?.click(),disabled:!B,title:o("prompt.attachTitle"),"aria-label":o("prompt.attachTitle"),children:[h.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:h.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),h.jsx("span",{children:o("prompt.attach")})]}),h.jsxs("button",{type:"button",className:"composer__tool",onClick:()=>{g()},disabled:!p||!B,title:o("prompt.useCurrentTitle"),children:[h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[h.jsx("polyline",{points:"23 4 23 10 17 10"}),h.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]}),h.jsx("span",{children:o("prompt.useCurrent")})]}),w&&h.jsxs("button",{type:"button",className:`composer__tool${j?" composer__tool--on":""}`,onClick:()=>S(!0),title:o("prompt.styleTitle"),"aria-label":o("prompt.styleTitle"),"aria-pressed":j,children:[h.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[h.jsx("circle",{cx:"12",cy:"12",r:"9"}),h.jsx("circle",{cx:"8",cy:"10",r:"1",fill:"currentColor"}),h.jsx("circle",{cx:"12",cy:"8",r:"1",fill:"currentColor"}),h.jsx("circle",{cx:"16",cy:"10",r:"1",fill:"currentColor"}),h.jsx("path",{d:"M14 14c2 0 3 1 3 3 0 1-1 2-2 2-2 0-3-2-5-2"})]}),h.jsx("span",{children:o("prompt.style")})]}),h.jsxs("button",{type:"button",className:`composer__tool${E==="direct"?" composer__tool--on":""}`,onClick:()=>A(E==="direct"?"auto":"direct"),title:o("prompt.directModeTitle"),"aria-label":o("prompt.directModeTitle"),"aria-pressed":E==="direct",children:[h.jsx("span",{"aria-hidden":"true",style:{fontWeight:700,fontSize:11},children:"1:1"}),h.jsx("span",{children:o("prompt.directMode")})]}),h.jsx("span",{className:"composer__hint",children:o("prompt.hint")})]}),m&&h.jsx("div",{className:"composer__dropzone","aria-hidden":"true",children:o("prompt.dropHere",{max:Wi})}),h.jsx("input",{ref:y,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:I=>{const X=Array.from(I.target.files??[]);X.length>0&&u(X),I.target.value=""}}),h.jsx(I0,{open:x,onClose:()=>S(!1)})]})}function mN(){const t=W(u=>u.activeGenerations),i=W(u=>u.generate),{t:l}=Te(),o=t>0,r=o?l("generate.buttonLoading",{n:t}):l("generate.button");return h.jsx("button",{type:"button",className:`generate-btn${o?" loading":""}`,onClick:()=>{i()},children:r})}function pN(t,i=28){const l=t.trim().replace(/\s+/g," ");return l.length>i?`${l.slice(0,i)}...`:l}function Wp(){const t=W(o=>o.inFlight),{t:i}=Te(),l={queued:i("inflight.queued"),streaming:i("inflight.streaming"),decoding:i("inflight.decoding")};return t.length===0?null:h.jsx("ul",{className:"in-flight-list",children:t.map(o=>{const r=o.phase?l[o.phase]??o.phase:i("inflight.queued");return h.jsxs("li",{className:"in-flight-item","data-phase":o.phase??"queued",children:[h.jsx("span",{className:"in-flight-prompt",children:pN(o.prompt)}),h.jsx("span",{className:"in-flight-phase",children:r}),h.jsx("span",{className:"in-flight-spinner","aria-hidden":"true"})]},o.id)})})}function B0(t){const i=t.currentTarget;if(i.scrollWidth<=i.clientWidth||!(Math.abs(t.deltaY)>Math.abs(t.deltaX)))return;const o=i.scrollLeft<=0,r=i.scrollLeft+i.clientWidth>=i.scrollWidth-1,u=t.deltaY<0,d=t.deltaY>0;u&&o||d&&r||(t.preventDefault(),i.scrollLeft+=t.deltaY)}function yN(){const t=W(u=>u.history),i=W(u=>u.currentImage),l=W(u=>u.selectHistory),o=W(u=>u.openGallery),{t:r}=Te();return h.jsxs("div",{className:"history-strip",onWheel:B0,children:[h.jsx("button",{type:"button",className:"history-thumb history-thumb--add",onClick:o,"aria-label":r("history.openGalleryAria"),title:r("history.openGalleryTitle"),children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),h.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),h.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),h.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}),t.map((u,d)=>{const g=u.filename?i?.filename===u.filename:i?.image===u.image;return h.jsx("img",{src:u.thumb||u.url||u.image,alt:"",className:`history-thumb${g?" active":""}`,onClick:()=>l(u)},u.filename??`${d}-${u.image}`)})]})}function vN(){const{t}=Te(),i=W(x=>x.sessions),l=W(x=>x.activeSessionId),o=W(x=>x.switchSession),r=W(x=>x.createAndSwitchSession),u=W(x=>x.renameCurrentSession),d=W(x=>x.deleteSessionById),[g,p]=Y.useState(!1),y=i.find(x=>x.id===l),m=()=>{const x=window.prompt(t("session.renamePrompt"),y?.title??t("session.newSession"));x&&x.trim()&&u(x.trim())},v=(x,S)=>{window.confirm(t("session.deleteConfirm",{title:S}))&&d(x)};return h.jsxs("div",{className:"session-picker",children:[h.jsxs("div",{className:"session-picker-row",children:[h.jsxs("button",{type:"button",className:"session-current",onClick:()=>p(x=>!x),title:t("session.switchTitle"),children:[h.jsx("span",{className:"session-title",children:y?.title??t("session.loading")}),h.jsx("span",{className:"session-caret",children:g?"▴":"▾"})]}),h.jsx("button",{type:"button",className:"session-btn",onClick:()=>{r(t("session.newSession"))},title:t("session.newSessionTitle"),children:"+"}),h.jsx("button",{type:"button",className:"session-btn",onClick:m,title:t("session.renameTitle"),disabled:!y,children:"✎"})]}),g&&h.jsxs("ul",{className:"session-list",children:[i.map(x=>h.jsxs("li",{className:x.id===l?"is-active":"",children:[h.jsxs("button",{type:"button",className:"session-item",onClick:()=>{p(!1),o(x.id)},children:[h.jsx("span",{className:"session-item-title",children:x.title}),h.jsx("span",{className:"session-item-count",children:x.nodeCount})]}),h.jsx("button",{type:"button",className:"session-del",onClick:()=>v(x.id,x.title),title:t("session.deleteTitle"),children:"×"})]},x.id)),i.length===0&&h.jsx("li",{className:"session-empty",children:t("session.empty")})]})]})}function xN(){const{t}=Te(),i=W(u=>u.activeSessionId),l=W(u=>u.styleSheetEnabled),[o,r]=Y.useState(!1);return i?h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",className:`btn btn--secondary btn--sm${l?" is-on":""}`,onClick:()=>r(!0),"aria-pressed":l,title:t("prompt.styleTitle"),children:t("prompt.style")}),h.jsx(I0,{open:o,onClose:()=>r(!1)})]}):null}function bN(){const{t}=Te(),i=W(o=>o.settingsOpen),l=W(o=>o.toggleSettings);return h.jsx("button",{type:"button",className:`settings-button${i?" is-active":""}`,onClick:l,"aria-label":t("settings.openAria"),"aria-pressed":i,title:t("settings.openTitle"),children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[h.jsx("path",{d:"M12 8.2a3.8 3.8 0 1 0 0 7.6 3.8 3.8 0 0 0 0-7.6Zm0 5.7a1.9 1.9 0 1 1 0-3.8 1.9 1.9 0 0 1 0 3.8Z"}),h.jsx("path",{d:"m20.3 13.4.1-1.4-.1-1.4-2.2-.5a6.9 6.9 0 0 0-.6-1.3l1.2-1.9a9.6 9.6 0 0 0-2-2l-1.9 1.2c-.4-.2-.9-.4-1.3-.6L13 3.3a9.5 9.5 0 0 0-2.8 0l-.5 2.2c-.5.2-.9.3-1.3.6L6.5 4.9a9.6 9.6 0 0 0-2 2l1.2 1.9c-.2.4-.4.9-.6 1.3l-2.2.5a9.5 9.5 0 0 0 0 2.8l2.2.5c.2.5.3.9.6 1.3l-1.2 1.9a9.6 9.6 0 0 0 2 2l1.9-1.2c.4.2.9.4 1.3.6l.5 2.2a9.5 9.5 0 0 0 2.8 0l.5-2.2c.5-.2.9-.3 1.3-.6l1.9 1.2a9.6 9.6 0 0 0 2-2l-1.2-1.9c.2-.4.4-.9.6-1.3l2.2-.5Z"})]})})}function L0({variant:t}){const{t:i}=Te(),[l,o]=Y.useState(!1),r=Y.useRef(null),u=W(m=>m.imageModel),d=W(m=>m.setImageModel),g=t==="settings"?"settings-image-model":"sidebar-image-model",p=tl.find(m=>m.value===u)??tl[0],y=m=>{d(m.target.value)};return Y.useEffect(()=>{if(t!=="sidebar"||!l)return;const m=x=>{const S=x.target;S instanceof Node&&(r.current?.contains(S)||o(!1))},v=x=>{x.key==="Escape"&&o(!1)};return document.addEventListener("pointerdown",m),document.addEventListener("keydown",v),()=>{document.removeEventListener("pointerdown",m),document.removeEventListener("keydown",v)}},[l,t]),t==="sidebar"?h.jsxs("div",{ref:r,className:"image-model-select image-model-select--sidebar",children:[h.jsx("button",{id:g,type:"button",className:"image-model-select__trigger","aria-haspopup":"listbox","aria-expanded":l,"aria-label":i("sidebar.imageModelAria"),onClick:()=>o(m=>!m),children:p.shortLabel}),l?h.jsx("div",{className:"image-model-select__menu",role:"listbox","aria-label":i("sidebar.imageModelAria"),children:tl.map(m=>h.jsxs("button",{type:"button",className:`image-model-select__item${m.value===u?" is-active":""}`,role:"option","aria-selected":m.value===u,onClick:()=>{d(m.value),o(!1)},children:[h.jsx("span",{children:m.shortLabel}),h.jsx("small",{children:i(m.fullLabelKey)})]},m.value))}):null]}):h.jsx("div",{className:"image-model-select image-model-select--settings",children:h.jsxs("select",{id:g,value:u,onChange:y,children:[tl.map(m=>h.jsx("option",{value:m.value,children:i(m.fullLabelKey)},m.value)),qw.map(m=>h.jsx("option",{value:m.value,disabled:!0,children:i(m.fullLabelKey)},m.value))]})})}function k0(t){return{...t,textFields:Array.isArray(t.textFields)?t.textFields:[]}}function No(t){return{...t,cards:Array.isArray(t.cards)?t.cards.map(k0):[]}}async function ci(t,i){const l=await fetch(t,i),o=await l.json().catch(()=>({}));if(!l.ok){const r=o,u=typeof r.error=="string"?r.error:r.error?.message||`Request failed: ${l.status}`,d=new Error(u);throw typeof r.error!="string"&&(d.code=r.error?.code),d}return o}function SN(){return ci("/api/cardnews/image-templates")}function wN(){return ci("/api/cardnews/role-templates")}async function NN(t){const i=await ci("/api/cardnews/draft",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return{...i,plan:No(i.plan)}}function _N(t){return ci("/api/cardnews/jobs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}function EN(t){return ci(`/api/cardnews/jobs/${encodeURIComponent(t)}`)}async function CN(t){const l=(await ci(`/api/cardnews/cards/${encodeURIComponent(t.card.id)}/regenerate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,cards:[t.card]})})).cards.find(o=>o.id===t.card.id);if(!l)throw new Error("Regenerated card not found");return{card:l}}function ey(t){return ci(`/api/cardnews/sets/${encodeURIComponent(t)}`).then(i=>({...i,plan:No(i.plan)}))}function TN(t){return`/api/cardnews/sets/${encodeURIComponent(t)}/manifest?download=1`}function AN(t){return t[0]?.id||"academy-lesson-square"}function MN(t){return t.find(i=>i.id==="mid-5")?.id||t[0]?.id||"mid-5"}function jN(t){return Math.round(t/16)*16}function Hr(t){return Math.min(3824,Math.max(1024,jN(t)))}function ty(t){return t.outputSizePreset!=="custom"?t.outputSizePreset:`${Hr(t.customW)}x${Hr(t.customH)}`}function U0(t){if(t){if(typeof t=="string")return t;if(typeof t=="object"&&"message"in t){const i=t.message;return typeof i=="string"?i:void 0}return String(t)}}function zN(t,i){const l=i.status||"generated";return{...t,...i,textFields:Array.isArray(i.textFields)?i.textFields:t.textFields,status:l,error:l==="error"?U0(i.error)||ve("cardNews.error"):void 0}}function RN(t){return new Promise(i=>setTimeout(i,t))}function Bd(t,i){const l=new Map(i.cards.map(o=>[o.id,o]));return{...t,cards:t.cards.map(o=>{const r=l.get(o.id);return r?{...o,...r,textFields:Array.isArray(r.textFields)?r.textFields:o.textFields,status:r.status||o.status,error:U0(r.error)}:o})}}const Se=g0((t,i)=>({templates:[],roleTemplates:[],activePlan:null,selectedCardId:null,selectedTextFieldId:null,topic:"",audience:"",goal:"",contentBrief:"",imageTemplateId:"academy-lesson-square",roleTemplateId:"mid-5",outputSizePreset:"2048x2048",customW:2048,customH:2048,loading:!1,generating:!1,error:null,draftError:null,plannerMeta:null,async hydrate(){if(!(i().loading||i().templates.length>0)){t({loading:!0,error:null});try{const[l,o]=await Promise.all([SN(),wN()]);t({templates:l.templates,roleTemplates:o.templates,imageTemplateId:AN(l.templates),roleTemplateId:MN(o.templates),loading:!1})}catch(l){t({loading:!1,error:l instanceof Error?l.message:String(l)})}}},setBriefField(l,o){t({[l]:o})},setImageTemplate(l){t({imageTemplateId:l})},setRoleTemplate(l){t({roleTemplateId:l})},setOutputSizePreset(l){t({outputSizePreset:l})},setCustomSize(l,o){t({customW:Hr(l),customH:Hr(o)})},async draft(){const l=i();t({loading:!0,error:null,draftError:null});try{const{plan:o,planner:r}=await NN({topic:l.topic,audience:l.audience,goal:l.goal,contentBrief:l.contentBrief,imageTemplateId:l.imageTemplateId,roleTemplateId:l.roleTemplateId,size:ty(l)});t({activePlan:No(o),selectedCardId:o.cards[0]?.id||null,selectedTextFieldId:null,plannerMeta:r||null,loading:!1})}catch(o){const r=o instanceof Error?o.message:String(o);t({loading:!1,draftError:r,error:r})}},updateCard(l,o){t(r=>({activePlan:r.activePlan?{...r.activePlan,cards:r.activePlan.cards.map(u=>u.id===l?{...u,...o}:u)}:null}))},updateTextField(l,o,r){t(u=>({activePlan:u.activePlan?{...u.activePlan,cards:u.activePlan.cards.map(d=>d.id!==l||d.locked?d:{...d,textFields:d.textFields.map(g=>g.id===o?{...g,...r,source:r.source||"user"}:g)})}:null}))},addTextField(l,o){t(r=>({activePlan:r.activePlan?{...r.activePlan,cards:r.activePlan.cards.map(u=>u.id===l&&!u.locked?{...u,textFields:[...u.textFields,{...o,source:"user"}]}:u)}:null,selectedTextFieldId:o.id}))},removeTextField(l,o){t(r=>({activePlan:r.activePlan?{...r.activePlan,cards:r.activePlan.cards.map(u=>u.id===l&&!u.locked?{...u,textFields:u.textFields.filter(d=>d.id!==o)}:u)}:null,selectedTextFieldId:r.selectedTextFieldId===o?null:r.selectedTextFieldId}))},selectCard(l){t({selectedCardId:l,selectedTextFieldId:null})},selectTextField(l){t({selectedTextFieldId:l})},getGenerationSummary(){const l=i().activePlan?.cards||[];return{total:l.length,done:l.filter(o=>o.status==="generated").length,queued:l.filter(o=>o.status==="queued").length,generating:l.filter(o=>o.status==="generating").length,errors:l.filter(o=>o.status==="error").length,skipped:l.filter(o=>o.locked||o.status==="skipped").length}},async generateSet(){const l=i();if(!l.activePlan)return;const o=W.getState();t({generating:!0,error:null,activePlan:{...l.activePlan,cards:l.activePlan.cards.map(r=>r.locked?{...r,status:"skipped"}:{...r,status:"queued",error:void 0})}});try{const r=i().activePlan||l.activePlan;let d=await _N({...r,size:ty(l),quality:o.quality,moderation:o.moderation,model:o.imageModel,sessionId:o.activeSessionId});for(t(p=>({activePlan:p.activePlan?Bd(p.activePlan,d):p.activePlan}));["queued","running"].includes(d.status);)await RN(900),d=await EN(d.jobId),t(p=>({activePlan:p.activePlan?Bd(p.activePlan,d):p.activePlan}));const g=await ey(d.setId).catch(()=>null);t(p=>({generating:!1,activePlan:g?.plan?No(g.plan):p.activePlan?Bd(p.activePlan,d):p.activePlan,selectedTextFieldId:null})),o.showToast(ve("cardNews.generated",{count:d.generated}))}catch(r){const u=r instanceof Error?r.message:String(r);t(d=>({generating:!1,error:u,activePlan:d.activePlan?{...d.activePlan,cards:d.activePlan.cards.map(g=>g.status==="queued"||g.status==="generating"?{...g,status:"error",error:u}:g)}:d.activePlan}))}},async retryCard(l){const r=i().activePlan,u=r?.cards.find(g=>g.id===l);if(!r||!u||u.locked||!["draft","error"].includes(u.status))return;const d=W.getState();t({error:null,activePlan:{...r,cards:r.cards.map(g=>g.id===l?{...g,status:"generating",error:void 0}:g)}});try{const{card:g}=await CN({setId:r.setId,card:u,quality:d.quality,moderation:d.moderation,model:d.imageModel});t(p=>({activePlan:p.activePlan?{...p.activePlan,cards:p.activePlan.cards.map(y=>y.id===l?zN(y,k0(g)):y)}:p.activePlan}))}catch(g){const p=g instanceof Error?g.message:String(g);t(y=>({error:p,activePlan:y.activePlan?{...y.activePlan,cards:y.activePlan.cards.map(m=>m.id===l?{...m,status:"error",error:p}:m)}:y.activePlan}))}},async loadSet(l){t({loading:!0,error:null,selectedTextFieldId:null});try{const{plan:o}=await ey(l);t({activePlan:No(o),selectedCardId:o.cards[0]?.id||null,selectedTextFieldId:null,loading:!1})}catch(o){t({loading:!1,error:o instanceof Error?o.message:String(o)})}}}));function DN(){const{t}=Te(),i=Se(_=>_.hydrate),l=Se(_=>_.topic),o=Se(_=>_.audience),r=Se(_=>_.goal),u=Se(_=>_.contentBrief),d=Se(_=>_.outputSizePreset),g=Se(_=>_.customW),p=Se(_=>_.customH),y=Se(_=>_.setBriefField),m=Se(_=>_.setOutputSizePreset),v=Se(_=>_.setCustomSize),x=Se(_=>_.draft),S=Se(_=>_.loading),w=Se(_=>_.generating),j=Se(_=>_.draftError),E=Se(_=>_.generateSet),A=Se(_=>_.activePlan),B=A?.cards||[],C={total:B.length,done:B.filter(_=>_.status==="generated").length};return Y.useEffect(()=>{i()},[i]),h.jsxs("section",{className:"card-news-composer","aria-label":t("cardNews.composer"),children:[h.jsx("div",{className:"card-news-composer__head",children:h.jsxs("div",{children:[h.jsx("div",{className:"section-title",children:t("cardNews.composer")}),h.jsx("p",{children:t("cardNews.composerHint")})]})}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.topic")}),h.jsx("input",{value:l,placeholder:t("cardNews.topicPlaceholder"),onChange:_=>y("topic",_.target.value)})]}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.audience")}),h.jsx("input",{value:o,placeholder:t("cardNews.audiencePlaceholder"),onChange:_=>y("audience",_.target.value)})]}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.goal")}),h.jsx("input",{value:r,placeholder:t("cardNews.goalPlaceholder"),onChange:_=>y("goal",_.target.value)})]}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.brief")}),h.jsx("textarea",{value:u,placeholder:t("cardNews.briefPlaceholder"),onChange:_=>y("contentBrief",_.target.value)})]}),h.jsxs("div",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.outputSize")}),h.jsx("div",{className:"card-news-size-row",role:"group","aria-label":t("cardNews.outputSize"),children:["1024x1024","2048x2048","custom"].map(_=>h.jsx("button",{type:"button",className:`option-btn${d===_?" active":""}`,onClick:()=>m(_),children:_==="custom"?t("cardNews.customSize"):_==="1024x1024"?"1024²":"2048²"},_))}),d==="custom"?h.jsxs("div",{className:"card-news-custom-size",children:[h.jsx("input",{className:"custom-size-input",type:"text",inputMode:"numeric",value:g,onChange:_=>v(Number.parseInt(_.target.value,10)||g,p),"aria-label":t("size.width")}),h.jsx("span",{children:"×"}),h.jsx("input",{className:"custom-size-input",type:"text",inputMode:"numeric",value:p,onChange:_=>v(g,Number.parseInt(_.target.value,10)||p),"aria-label":t("size.height")})]}):null]}),h.jsxs("button",{type:"button",className:"generate-btn card-news-draft-btn",onClick:()=>{x()},disabled:S||!l.trim(),children:[S?h.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,t(S?"cardNews.drafting":"cardNews.draft")]}),j?h.jsx("div",{className:"card-news-error",role:"alert",children:j}):null,S?h.jsxs("div",{className:"card-news-inline-status",role:"status",children:[h.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}),h.jsx("span",{children:t("cardNews.drafting")})]}):null,h.jsxs("button",{type:"button",className:"composer__tool card-news-generate-btn",onClick:()=>{E()},disabled:!A||w||A.cards.every(_=>_.locked),children:[w?h.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,w?t("cardNews.progress.generating",{done:C.done,total:C.total}):t("cardNews.batchGenerate")]})]})}function ON(){const{t}=Te(),i=W(d=>d.uiMode),l=W(d=>d.referenceImages),o=W(d=>d.clearReferences),r=W(d=>d.styleSheetEnabled),u=i==="node"&&yf?"node":"classic";return h.jsxs("aside",{className:"sidebar",children:[h.jsxs("div",{className:"sidebar__scroll",children:[h.jsxs("div",{className:"logo",children:[h.jsx("div",{className:"logo-mark","aria-hidden":"true"}),h.jsxs("div",{className:"logo-copy",children:[h.jsx("div",{className:"logo-title",children:"ima2-gen"}),h.jsx("div",{className:"logo-subtitle",children:"gpt-image-2 studio"})]}),h.jsxs("div",{className:"logo-actions",children:[h.jsx(L0,{variant:"sidebar"}),h.jsx(bN,{})]})]}),h.jsx(hN,{}),u==="classic"?h.jsxs(h.Fragment,{children:[h.jsx(gN,{}),h.jsx(mN,{}),h.jsx(Wp,{})]}):u==="card-news"?h.jsx(h.Fragment,{children:h.jsx(DN,{})}):h.jsxs(h.Fragment,{children:[h.jsx(vN,{}),h.jsx(xN,{}),l.length>0?h.jsxs("div",{className:"node-mode-ref-warning",role:"status",children:[h.jsx("strong",{children:t("node.classicRefsParkedTitle")}),h.jsx("span",{children:t("node.classicRefsParkedBody")}),h.jsx("button",{type:"button",onClick:o,children:t("node.clearParkedRefs")})]}):null,r?h.jsx("div",{className:"node-mode-style-badge",role:"status",children:t("node.styleSheetActive")}):null,h.jsx("div",{className:"sidebar__node-hint",children:t("sidebar.nodeModeHint")}),h.jsx(Wp,{})]})]}),h.jsx(yN,{})]})}function HN(){const{t}=Te(),i=W(p=>p.currentImage),l=W(p=>p.showToast),o=W(p=>p.setPrompt);if(!i)return null;const r=()=>{const p=document.createElement("a");p.href=i.image,p.download=i.filename||"generated.png",p.click()},u=async()=>{try{const y=await(await fetch(i.image)).blob();await navigator.clipboard.write([new ClipboardItem({[y.type]:y})]),l(t("toast.imageCopied"))}catch{l(t("toast.copyFailed"),!0)}},d=()=>{i.prompt&&(navigator.clipboard.writeText(i.prompt),l(t("toast.promptCopied")))},g=async()=>{if(!i.prompt){l(t("toast.noPromptToFork"),!0);return}o(i.prompt);try{await W.getState().useCurrentAsReference()}catch{}const p=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');p&&(p.focus(),p.setSelectionRange(p.value.length,p.value.length)),l(t("toast.forkStarted"))};return h.jsxs("div",{className:"result-actions",children:[h.jsx("button",{type:"button",className:"action-btn",onClick:r,children:t("result.download")}),h.jsx("button",{type:"button",className:"action-btn",onClick:u,children:t("result.copyImage")}),h.jsx("button",{type:"button",className:"action-btn",onClick:d,children:t("result.copyPrompt")}),h.jsx("button",{type:"button",className:"action-btn action-btn--primary",onClick:g,title:t("result.continueHereTitle"),children:t("result.continueHere")})]})}function IN(t){return t instanceof HTMLElement?t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t.isContentEditable:!1}function BN(t){return t==="low"?"l":t==="medium"?"m":t==="high"?"h":t??null}function LN(t){if(!t)return null;const i=t.match(/^(\d+)x\1$/);return i?`${i[1]}²`:t.replace("x","×")}function ny(){const t=W(S=>S.currentImage),i=W(S=>S.history),l=W(S=>S.selectHistory),o=W(S=>S.activeGenerations),r=W(S=>S.quality),u=W(S=>S.getResolvedSize),d=W(S=>S.showToast),{t:g}=Te(),p=()=>{t?.prompt&&(navigator.clipboard.writeText(t.prompt),d(g("toast.promptCopied")))},y=BN(t?.quality??r),m=LN(t?.size??u()),v=b0(t?.model),x=S=>{if(S.key!=="ArrowLeft"&&S.key!=="ArrowRight"||S.target!==S.currentTarget||IN(S.target))return;const w=i.findIndex(A=>t?.filename?A.filename===t.filename:A.image===t?.image);if(w<0)return;const j=S.key==="ArrowLeft"?w-1:w+1,E=i[j];E&&(S.preventDefault(),l(E))};return h.jsxs("main",{className:"canvas",children:[h.jsx("div",{className:`progress-bar${o>0?" active":""}`}),t?h.jsxs("div",{className:"result-container visible",tabIndex:0,onKeyDown:x,"aria-label":g("canvas.imageViewerAria"),children:[h.jsx("img",{className:"result-img",src:t.url??t.image,alt:g("canvas.resultAlt")},t.filename??t.url??t.image),t.prompt?h.jsx("div",{className:"result-prompt",onClick:p,children:t.prompt}):null,h.jsx("div",{className:"result-meta",children:[t.elapsed!=null?`${t.elapsed}s`:null,t.usage?g("canvas.tokens",{n:t.usage.total_tokens??"?"}):null,y,m,v,t.provider??null].filter(S=>!!S).join(" · ")}),h.jsx(HN,{})]}):null]})}function st(t){if(typeof t=="string"||typeof t=="number")return""+t;let i="";if(Array.isArray(t))for(let l=0,o;l<t.length;l++)(o=st(t[l]))!==""&&(i+=(i&&" ")+o);else for(let l in t)t[l]&&(i+=(i&&" ")+l);return i}var kN={value:()=>{}};function Zr(){for(var t=0,i=arguments.length,l={},o;t<i;++t){if(!(o=arguments[t]+"")||o in l||/[\s.]/.test(o))throw new Error("illegal type: "+o);l[o]=[]}return new Mr(l)}function Mr(t){this._=t}function UN(t,i){return t.trim().split(/^|\s+/).map(function(l){var o="",r=l.indexOf(".");if(r>=0&&(o=l.slice(r+1),l=l.slice(0,r)),l&&!i.hasOwnProperty(l))throw new Error("unknown type: "+l);return{type:l,name:o}})}Mr.prototype=Zr.prototype={constructor:Mr,on:function(t,i){var l=this._,o=UN(t+"",l),r,u=-1,d=o.length;if(arguments.length<2){for(;++u<d;)if((r=(t=o[u]).type)&&(r=qN(l[r],t.name)))return r;return}if(i!=null&&typeof i!="function")throw new Error("invalid callback: "+i);for(;++u<d;)if(r=(t=o[u]).type)l[r]=ay(l[r],t.name,i);else if(i==null)for(r in l)l[r]=ay(l[r],t.name,null);return this},copy:function(){var t={},i=this._;for(var l in i)t[l]=i[l].slice();return new Mr(t)},call:function(t,i){if((r=arguments.length-2)>0)for(var l=new Array(r),o=0,r,u;o<r;++o)l[o]=arguments[o+2];if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(u=this._[t],o=0,r=u.length;o<r;++o)u[o].value.apply(i,l)},apply:function(t,i,l){if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(var o=this._[t],r=0,u=o.length;r<u;++r)o[r].value.apply(i,l)}};function qN(t,i){for(var l=0,o=t.length,r;l<o;++l)if((r=t[l]).name===i)return r.value}function ay(t,i,l){for(var o=0,r=t.length;o<r;++o)if(t[o].name===i){t[o]=kN,t=t.slice(0,o).concat(t.slice(o+1));break}return l!=null&&t.push({name:i,value:l}),t}var ef="http://www.w3.org/1999/xhtml";const iy={svg:"http://www.w3.org/2000/svg",xhtml:ef,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Kr(t){var i=t+="",l=i.indexOf(":");return l>=0&&(i=t.slice(0,l))!=="xmlns"&&(t=t.slice(l+1)),iy.hasOwnProperty(i)?{space:iy[i],local:t}:t}function GN(t){return function(){var i=this.ownerDocument,l=this.namespaceURI;return l===ef&&i.documentElement.namespaceURI===ef?i.createElement(t):i.createElementNS(l,t)}}function YN(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function q0(t){var i=Kr(t);return(i.local?YN:GN)(i)}function VN(){}function vf(t){return t==null?VN:function(){return this.querySelector(t)}}function XN(t){typeof t!="function"&&(t=vf(t));for(var i=this._groups,l=i.length,o=new Array(l),r=0;r<l;++r)for(var u=i[r],d=u.length,g=o[r]=new Array(d),p,y,m=0;m<d;++m)(p=u[m])&&(y=t.call(p,p.__data__,m,u))&&("__data__"in p&&(y.__data__=p.__data__),g[m]=y);return new Ut(o,this._parents)}function $N(t){return t==null?[]:Array.isArray(t)?t:Array.from(t)}function ZN(){return[]}function G0(t){return t==null?ZN:function(){return this.querySelectorAll(t)}}function KN(t){return function(){return $N(t.apply(this,arguments))}}function QN(t){typeof t=="function"?t=KN(t):t=G0(t);for(var i=this._groups,l=i.length,o=[],r=[],u=0;u<l;++u)for(var d=i[u],g=d.length,p,y=0;y<g;++y)(p=d[y])&&(o.push(t.call(p,p.__data__,y,d)),r.push(p));return new Ut(o,r)}function Y0(t){return function(){return this.matches(t)}}function V0(t){return function(i){return i.matches(t)}}var FN=Array.prototype.find;function PN(t){return function(){return FN.call(this.children,t)}}function JN(){return this.firstElementChild}function WN(t){return this.select(t==null?JN:PN(typeof t=="function"?t:V0(t)))}var e_=Array.prototype.filter;function t_(){return Array.from(this.children)}function n_(t){return function(){return e_.call(this.children,t)}}function a_(t){return this.selectAll(t==null?t_:n_(typeof t=="function"?t:V0(t)))}function i_(t){typeof t!="function"&&(t=Y0(t));for(var i=this._groups,l=i.length,o=new Array(l),r=0;r<l;++r)for(var u=i[r],d=u.length,g=o[r]=[],p,y=0;y<d;++y)(p=u[y])&&t.call(p,p.__data__,y,u)&&g.push(p);return new Ut(o,this._parents)}function X0(t){return new Array(t.length)}function l_(){return new Ut(this._enter||this._groups.map(X0),this._parents)}function Ir(t,i){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=i}Ir.prototype={constructor:Ir,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,i){return this._parent.insertBefore(t,i)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};function o_(t){return function(){return t}}function s_(t,i,l,o,r,u){for(var d=0,g,p=i.length,y=u.length;d<y;++d)(g=i[d])?(g.__data__=u[d],o[d]=g):l[d]=new Ir(t,u[d]);for(;d<p;++d)(g=i[d])&&(r[d]=g)}function r_(t,i,l,o,r,u,d){var g,p,y=new Map,m=i.length,v=u.length,x=new Array(m),S;for(g=0;g<m;++g)(p=i[g])&&(x[g]=S=d.call(p,p.__data__,g,i)+"",y.has(S)?r[g]=p:y.set(S,p));for(g=0;g<v;++g)S=d.call(t,u[g],g,u)+"",(p=y.get(S))?(o[g]=p,p.__data__=u[g],y.delete(S)):l[g]=new Ir(t,u[g]);for(g=0;g<m;++g)(p=i[g])&&y.get(x[g])===p&&(r[g]=p)}function c_(t){return t.__data__}function u_(t,i){if(!arguments.length)return Array.from(this,c_);var l=i?r_:s_,o=this._parents,r=this._groups;typeof t!="function"&&(t=o_(t));for(var u=r.length,d=new Array(u),g=new Array(u),p=new Array(u),y=0;y<u;++y){var m=o[y],v=r[y],x=v.length,S=d_(t.call(m,m&&m.__data__,y,o)),w=S.length,j=g[y]=new Array(w),E=d[y]=new Array(w),A=p[y]=new Array(x);l(m,v,j,E,A,S,i);for(var B=0,C=0,_,U;B<w;++B)if(_=j[B]){for(B>=C&&(C=B+1);!(U=E[C])&&++C<w;);_._next=U||null}}return d=new Ut(d,o),d._enter=g,d._exit=p,d}function d_(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function f_(){return new Ut(this._exit||this._groups.map(X0),this._parents)}function h_(t,i,l){var o=this.enter(),r=this,u=this.exit();return typeof t=="function"?(o=t(o),o&&(o=o.selection())):o=o.append(t+""),i!=null&&(r=i(r),r&&(r=r.selection())),l==null?u.remove():l(u),o&&r?o.merge(r).order():r}function g_(t){for(var i=t.selection?t.selection():t,l=this._groups,o=i._groups,r=l.length,u=o.length,d=Math.min(r,u),g=new Array(r),p=0;p<d;++p)for(var y=l[p],m=o[p],v=y.length,x=g[p]=new Array(v),S,w=0;w<v;++w)(S=y[w]||m[w])&&(x[w]=S);for(;p<r;++p)g[p]=l[p];return new Ut(g,this._parents)}function m_(){for(var t=this._groups,i=-1,l=t.length;++i<l;)for(var o=t[i],r=o.length-1,u=o[r],d;--r>=0;)(d=o[r])&&(u&&d.compareDocumentPosition(u)^4&&u.parentNode.insertBefore(d,u),u=d);return this}function p_(t){t||(t=y_);function i(v,x){return v&&x?t(v.__data__,x.__data__):!v-!x}for(var l=this._groups,o=l.length,r=new Array(o),u=0;u<o;++u){for(var d=l[u],g=d.length,p=r[u]=new Array(g),y,m=0;m<g;++m)(y=d[m])&&(p[m]=y);p.sort(i)}return new Ut(r,this._parents).order()}function y_(t,i){return t<i?-1:t>i?1:t>=i?0:NaN}function v_(){var t=arguments[0];return arguments[0]=this,t.apply(null,arguments),this}function x_(){return Array.from(this)}function b_(){for(var t=this._groups,i=0,l=t.length;i<l;++i)for(var o=t[i],r=0,u=o.length;r<u;++r){var d=o[r];if(d)return d}return null}function S_(){let t=0;for(const i of this)++t;return t}function w_(){return!this.node()}function N_(t){for(var i=this._groups,l=0,o=i.length;l<o;++l)for(var r=i[l],u=0,d=r.length,g;u<d;++u)(g=r[u])&&t.call(g,g.__data__,u,r);return this}function __(t){return function(){this.removeAttribute(t)}}function E_(t){return function(){this.removeAttributeNS(t.space,t.local)}}function C_(t,i){return function(){this.setAttribute(t,i)}}function T_(t,i){return function(){this.setAttributeNS(t.space,t.local,i)}}function A_(t,i){return function(){var l=i.apply(this,arguments);l==null?this.removeAttribute(t):this.setAttribute(t,l)}}function M_(t,i){return function(){var l=i.apply(this,arguments);l==null?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,l)}}function j_(t,i){var l=Kr(t);if(arguments.length<2){var o=this.node();return l.local?o.getAttributeNS(l.space,l.local):o.getAttribute(l)}return this.each((i==null?l.local?E_:__:typeof i=="function"?l.local?M_:A_:l.local?T_:C_)(l,i))}function $0(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function z_(t){return function(){this.style.removeProperty(t)}}function R_(t,i,l){return function(){this.style.setProperty(t,i,l)}}function D_(t,i,l){return function(){var o=i.apply(this,arguments);o==null?this.style.removeProperty(t):this.style.setProperty(t,o,l)}}function O_(t,i,l){return arguments.length>1?this.each((i==null?z_:typeof i=="function"?D_:R_)(t,i,l??"")):cl(this.node(),t)}function cl(t,i){return t.style.getPropertyValue(i)||$0(t).getComputedStyle(t,null).getPropertyValue(i)}function H_(t){return function(){delete this[t]}}function I_(t,i){return function(){this[t]=i}}function B_(t,i){return function(){var l=i.apply(this,arguments);l==null?delete this[t]:this[t]=l}}function L_(t,i){return arguments.length>1?this.each((i==null?H_:typeof i=="function"?B_:I_)(t,i)):this.node()[t]}function Z0(t){return t.trim().split(/^|\s+/)}function xf(t){return t.classList||new K0(t)}function K0(t){this._node=t,this._names=Z0(t.getAttribute("class")||"")}K0.prototype={add:function(t){var i=this._names.indexOf(t);i<0&&(this._names.push(t),this._node.setAttribute("class",this._names.join(" ")))},remove:function(t){var i=this._names.indexOf(t);i>=0&&(this._names.splice(i,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};function Q0(t,i){for(var l=xf(t),o=-1,r=i.length;++o<r;)l.add(i[o])}function F0(t,i){for(var l=xf(t),o=-1,r=i.length;++o<r;)l.remove(i[o])}function k_(t){return function(){Q0(this,t)}}function U_(t){return function(){F0(this,t)}}function q_(t,i){return function(){(i.apply(this,arguments)?Q0:F0)(this,t)}}function G_(t,i){var l=Z0(t+"");if(arguments.length<2){for(var o=xf(this.node()),r=-1,u=l.length;++r<u;)if(!o.contains(l[r]))return!1;return!0}return this.each((typeof i=="function"?q_:i?k_:U_)(l,i))}function Y_(){this.textContent=""}function V_(t){return function(){this.textContent=t}}function X_(t){return function(){var i=t.apply(this,arguments);this.textContent=i??""}}function $_(t){return arguments.length?this.each(t==null?Y_:(typeof t=="function"?X_:V_)(t)):this.node().textContent}function Z_(){this.innerHTML=""}function K_(t){return function(){this.innerHTML=t}}function Q_(t){return function(){var i=t.apply(this,arguments);this.innerHTML=i??""}}function F_(t){return arguments.length?this.each(t==null?Z_:(typeof t=="function"?Q_:K_)(t)):this.node().innerHTML}function P_(){this.nextSibling&&this.parentNode.appendChild(this)}function J_(){return this.each(P_)}function W_(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function eE(){return this.each(W_)}function tE(t){var i=typeof t=="function"?t:q0(t);return this.select(function(){return this.appendChild(i.apply(this,arguments))})}function nE(){return null}function aE(t,i){var l=typeof t=="function"?t:q0(t),o=i==null?nE:typeof i=="function"?i:vf(i);return this.select(function(){return this.insertBefore(l.apply(this,arguments),o.apply(this,arguments)||null)})}function iE(){var t=this.parentNode;t&&t.removeChild(this)}function lE(){return this.each(iE)}function oE(){var t=this.cloneNode(!1),i=this.parentNode;return i?i.insertBefore(t,this.nextSibling):t}function sE(){var t=this.cloneNode(!0),i=this.parentNode;return i?i.insertBefore(t,this.nextSibling):t}function rE(t){return this.select(t?sE:oE)}function cE(t){return arguments.length?this.property("__data__",t):this.node().__data__}function uE(t){return function(i){t.call(this,i,this.__data__)}}function dE(t){return t.trim().split(/^|\s+/).map(function(i){var l="",o=i.indexOf(".");return o>=0&&(l=i.slice(o+1),i=i.slice(0,o)),{type:i,name:l}})}function fE(t){return function(){var i=this.__on;if(i){for(var l=0,o=-1,r=i.length,u;l<r;++l)u=i[l],(!t.type||u.type===t.type)&&u.name===t.name?this.removeEventListener(u.type,u.listener,u.options):i[++o]=u;++o?i.length=o:delete this.__on}}}function hE(t,i,l){return function(){var o=this.__on,r,u=uE(i);if(o){for(var d=0,g=o.length;d<g;++d)if((r=o[d]).type===t.type&&r.name===t.name){this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=u,r.options=l),r.value=i;return}}this.addEventListener(t.type,u,l),r={type:t.type,name:t.name,value:i,listener:u,options:l},o?o.push(r):this.__on=[r]}}function gE(t,i,l){var o=dE(t+""),r,u=o.length,d;if(arguments.length<2){var g=this.node().__on;if(g){for(var p=0,y=g.length,m;p<y;++p)for(r=0,m=g[p];r<u;++r)if((d=o[r]).type===m.type&&d.name===m.name)return m.value}return}for(g=i?hE:fE,r=0;r<u;++r)this.each(g(o[r],i,l));return this}function P0(t,i,l){var o=$0(t),r=o.CustomEvent;typeof r=="function"?r=new r(i,l):(r=o.document.createEvent("Event"),l?(r.initEvent(i,l.bubbles,l.cancelable),r.detail=l.detail):r.initEvent(i,!1,!1)),t.dispatchEvent(r)}function mE(t,i){return function(){return P0(this,t,i)}}function pE(t,i){return function(){return P0(this,t,i.apply(this,arguments))}}function yE(t,i){return this.each((typeof i=="function"?pE:mE)(t,i))}function*vE(){for(var t=this._groups,i=0,l=t.length;i<l;++i)for(var o=t[i],r=0,u=o.length,d;r<u;++r)(d=o[r])&&(yield d)}var J0=[null];function Ut(t,i){this._groups=t,this._parents=i}function Io(){return new Ut([[document.documentElement]],J0)}function xE(){return this}Ut.prototype=Io.prototype={constructor:Ut,select:XN,selectAll:QN,selectChild:WN,selectChildren:a_,filter:i_,data:u_,enter:l_,exit:f_,join:h_,merge:g_,selection:xE,order:m_,sort:p_,call:v_,nodes:x_,node:b_,size:S_,empty:w_,each:N_,attr:j_,style:O_,property:L_,classed:G_,text:$_,html:F_,raise:J_,lower:eE,append:tE,insert:aE,remove:lE,clone:rE,datum:cE,on:gE,dispatch:yE,[Symbol.iterator]:vE};function kt(t){return typeof t=="string"?new Ut([[document.querySelector(t)]],[document.documentElement]):new Ut([[t]],J0)}function bE(t){let i;for(;i=t.sourceEvent;)t=i;return t}function tn(t,i){if(t=bE(t),i===void 0&&(i=t.currentTarget),i){var l=i.ownerSVGElement||i;if(l.createSVGPoint){var o=l.createSVGPoint();return o.x=t.clientX,o.y=t.clientY,o=o.matrixTransform(i.getScreenCTM().inverse()),[o.x,o.y]}if(i.getBoundingClientRect){var r=i.getBoundingClientRect();return[t.clientX-r.left-i.clientLeft,t.clientY-r.top-i.clientTop]}}return[t.pageX,t.pageY]}const SE={passive:!1},Co={capture:!0,passive:!1};function Ld(t){t.stopImmediatePropagation()}function ll(t){t.preventDefault(),t.stopImmediatePropagation()}function W0(t){var i=t.document.documentElement,l=kt(t).on("dragstart.drag",ll,Co);"onselectstart"in i?l.on("selectstart.drag",ll,Co):(i.__noselect=i.style.MozUserSelect,i.style.MozUserSelect="none")}function ev(t,i){var l=t.document.documentElement,o=kt(t).on("dragstart.drag",null);i&&(o.on("click.drag",ll,Co),setTimeout(function(){o.on("click.drag",null)},0)),"onselectstart"in l?o.on("selectstart.drag",null):(l.style.MozUserSelect=l.__noselect,delete l.__noselect)}const pr=t=>()=>t;function tf(t,{sourceEvent:i,subject:l,target:o,identifier:r,active:u,x:d,y:g,dx:p,dy:y,dispatch:m}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:i,enumerable:!0,configurable:!0},subject:{value:l,enumerable:!0,configurable:!0},target:{value:o,enumerable:!0,configurable:!0},identifier:{value:r,enumerable:!0,configurable:!0},active:{value:u,enumerable:!0,configurable:!0},x:{value:d,enumerable:!0,configurable:!0},y:{value:g,enumerable:!0,configurable:!0},dx:{value:p,enumerable:!0,configurable:!0},dy:{value:y,enumerable:!0,configurable:!0},_:{value:m}})}tf.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t};function wE(t){return!t.ctrlKey&&!t.button}function NE(){return this.parentNode}function _E(t,i){return i??{x:t.x,y:t.y}}function EE(){return navigator.maxTouchPoints||"ontouchstart"in this}function tv(){var t=wE,i=NE,l=_E,o=EE,r={},u=Zr("start","drag","end"),d=0,g,p,y,m,v=0;function x(_){_.on("mousedown.drag",S).filter(o).on("touchstart.drag",E).on("touchmove.drag",A,SE).on("touchend.drag touchcancel.drag",B).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function S(_,U){if(!(m||!t.call(this,_,U))){var R=C(this,i.call(this,_,U),_,U,"mouse");R&&(kt(_.view).on("mousemove.drag",w,Co).on("mouseup.drag",j,Co),W0(_.view),Ld(_),y=!1,g=_.clientX,p=_.clientY,R("start",_))}}function w(_){if(ll(_),!y){var U=_.clientX-g,R=_.clientY-p;y=U*U+R*R>v}r.mouse("drag",_)}function j(_){kt(_.view).on("mousemove.drag mouseup.drag",null),ev(_.view,y),ll(_),r.mouse("end",_)}function E(_,U){if(t.call(this,_,U)){var R=_.changedTouches,z=i.call(this,_,U),I=R.length,X,ce;for(X=0;X<I;++X)(ce=C(this,z,_,U,R[X].identifier,R[X]))&&(Ld(_),ce("start",_,R[X]))}}function A(_){var U=_.changedTouches,R=U.length,z,I;for(z=0;z<R;++z)(I=r[U[z].identifier])&&(ll(_),I("drag",_,U[z]))}function B(_){var U=_.changedTouches,R=U.length,z,I;for(m&&clearTimeout(m),m=setTimeout(function(){m=null},500),z=0;z<R;++z)(I=r[U[z].identifier])&&(Ld(_),I("end",_,U[z]))}function C(_,U,R,z,I,X){var ce=u.copy(),K=tn(X||R,U),te,ue,D;if((D=l.call(_,new tf("beforestart",{sourceEvent:R,target:x,identifier:I,active:d,x:K[0],y:K[1],dx:0,dy:0,dispatch:ce}),z))!=null)return te=D.x-K[0]||0,ue=D.y-K[1]||0,function Z(M,H,q){var k=K,J;switch(M){case"start":r[I]=Z,J=d++;break;case"end":delete r[I],--d;case"drag":K=tn(q||H,U),J=d;break}ce.call(M,_,new tf(M,{sourceEvent:H,subject:D,target:x,identifier:I,active:J,x:K[0]+te,y:K[1]+ue,dx:K[0]-k[0],dy:K[1]-k[1],dispatch:ce}),z)}}return x.filter=function(_){return arguments.length?(t=typeof _=="function"?_:pr(!!_),x):t},x.container=function(_){return arguments.length?(i=typeof _=="function"?_:pr(_),x):i},x.subject=function(_){return arguments.length?(l=typeof _=="function"?_:pr(_),x):l},x.touchable=function(_){return arguments.length?(o=typeof _=="function"?_:pr(!!_),x):o},x.on=function(){var _=u.on.apply(u,arguments);return _===u?x:_},x.clickDistance=function(_){return arguments.length?(v=(_=+_)*_,x):Math.sqrt(v)},x}function bf(t,i,l){t.prototype=i.prototype=l,l.constructor=t}function nv(t,i){var l=Object.create(t.prototype);for(var o in i)l[o]=i[o];return l}function Bo(){}var To=.7,Br=1/To,ol="\\s*([+-]?\\d+)\\s*",Ao="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",mn="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",CE=/^#([0-9a-f]{3,8})$/,TE=new RegExp(`^rgb\\(${ol},${ol},${ol}\\)$`),AE=new RegExp(`^rgb\\(${mn},${mn},${mn}\\)$`),ME=new RegExp(`^rgba\\(${ol},${ol},${ol},${Ao}\\)$`),jE=new RegExp(`^rgba\\(${mn},${mn},${mn},${Ao}\\)$`),zE=new RegExp(`^hsl\\(${Ao},${mn},${mn}\\)$`),RE=new RegExp(`^hsla\\(${Ao},${mn},${mn},${Ao}\\)$`),ly={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};bf(Bo,li,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:oy,formatHex:oy,formatHex8:DE,formatHsl:OE,formatRgb:sy,toString:sy});function oy(){return this.rgb().formatHex()}function DE(){return this.rgb().formatHex8()}function OE(){return av(this).formatHsl()}function sy(){return this.rgb().formatRgb()}function li(t){var i,l;return t=(t+"").trim().toLowerCase(),(i=CE.exec(t))?(l=i[1].length,i=parseInt(i[1],16),l===6?ry(i):l===3?new jt(i>>8&15|i>>4&240,i>>4&15|i&240,(i&15)<<4|i&15,1):l===8?yr(i>>24&255,i>>16&255,i>>8&255,(i&255)/255):l===4?yr(i>>12&15|i>>8&240,i>>8&15|i>>4&240,i>>4&15|i&240,((i&15)<<4|i&15)/255):null):(i=TE.exec(t))?new jt(i[1],i[2],i[3],1):(i=AE.exec(t))?new jt(i[1]*255/100,i[2]*255/100,i[3]*255/100,1):(i=ME.exec(t))?yr(i[1],i[2],i[3],i[4]):(i=jE.exec(t))?yr(i[1]*255/100,i[2]*255/100,i[3]*255/100,i[4]):(i=zE.exec(t))?dy(i[1],i[2]/100,i[3]/100,1):(i=RE.exec(t))?dy(i[1],i[2]/100,i[3]/100,i[4]):ly.hasOwnProperty(t)?ry(ly[t]):t==="transparent"?new jt(NaN,NaN,NaN,0):null}function ry(t){return new jt(t>>16&255,t>>8&255,t&255,1)}function yr(t,i,l,o){return o<=0&&(t=i=l=NaN),new jt(t,i,l,o)}function HE(t){return t instanceof Bo||(t=li(t)),t?(t=t.rgb(),new jt(t.r,t.g,t.b,t.opacity)):new jt}function nf(t,i,l,o){return arguments.length===1?HE(t):new jt(t,i,l,o??1)}function jt(t,i,l,o){this.r=+t,this.g=+i,this.b=+l,this.opacity=+o}bf(jt,nf,nv(Bo,{brighter(t){return t=t==null?Br:Math.pow(Br,t),new jt(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?To:Math.pow(To,t),new jt(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new jt(ai(this.r),ai(this.g),ai(this.b),Lr(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:cy,formatHex:cy,formatHex8:IE,formatRgb:uy,toString:uy}));function cy(){return`#${ni(this.r)}${ni(this.g)}${ni(this.b)}`}function IE(){return`#${ni(this.r)}${ni(this.g)}${ni(this.b)}${ni((isNaN(this.opacity)?1:this.opacity)*255)}`}function uy(){const t=Lr(this.opacity);return`${t===1?"rgb(":"rgba("}${ai(this.r)}, ${ai(this.g)}, ${ai(this.b)}${t===1?")":`, ${t})`}`}function Lr(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function ai(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function ni(t){return t=ai(t),(t<16?"0":"")+t.toString(16)}function dy(t,i,l,o){return o<=0?t=i=l=NaN:l<=0||l>=1?t=i=NaN:i<=0&&(t=NaN),new nn(t,i,l,o)}function av(t){if(t instanceof nn)return new nn(t.h,t.s,t.l,t.opacity);if(t instanceof Bo||(t=li(t)),!t)return new nn;if(t instanceof nn)return t;t=t.rgb();var i=t.r/255,l=t.g/255,o=t.b/255,r=Math.min(i,l,o),u=Math.max(i,l,o),d=NaN,g=u-r,p=(u+r)/2;return g?(i===u?d=(l-o)/g+(l<o)*6:l===u?d=(o-i)/g+2:d=(i-l)/g+4,g/=p<.5?u+r:2-u-r,d*=60):g=p>0&&p<1?0:d,new nn(d,g,p,t.opacity)}function BE(t,i,l,o){return arguments.length===1?av(t):new nn(t,i,l,o??1)}function nn(t,i,l,o){this.h=+t,this.s=+i,this.l=+l,this.opacity=+o}bf(nn,BE,nv(Bo,{brighter(t){return t=t==null?Br:Math.pow(Br,t),new nn(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?To:Math.pow(To,t),new nn(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,i=isNaN(t)||isNaN(this.s)?0:this.s,l=this.l,o=l+(l<.5?l:1-l)*i,r=2*l-o;return new jt(kd(t>=240?t-240:t+120,r,o),kd(t,r,o),kd(t<120?t+240:t-120,r,o),this.opacity)},clamp(){return new nn(fy(this.h),vr(this.s),vr(this.l),Lr(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=Lr(this.opacity);return`${t===1?"hsl(":"hsla("}${fy(this.h)}, ${vr(this.s)*100}%, ${vr(this.l)*100}%${t===1?")":`, ${t})`}`}}));function fy(t){return t=(t||0)%360,t<0?t+360:t}function vr(t){return Math.max(0,Math.min(1,t||0))}function kd(t,i,l){return(t<60?i+(l-i)*t/60:t<180?l:t<240?i+(l-i)*(240-t)/60:i)*255}const Sf=t=>()=>t;function LE(t,i){return function(l){return t+l*i}}function kE(t,i,l){return t=Math.pow(t,l),i=Math.pow(i,l)-t,l=1/l,function(o){return Math.pow(t+o*i,l)}}function UE(t){return(t=+t)==1?iv:function(i,l){return l-i?kE(i,l,t):Sf(isNaN(i)?l:i)}}function iv(t,i){var l=i-t;return l?LE(t,l):Sf(isNaN(t)?i:t)}const kr=(function t(i){var l=UE(i);function o(r,u){var d=l((r=nf(r)).r,(u=nf(u)).r),g=l(r.g,u.g),p=l(r.b,u.b),y=iv(r.opacity,u.opacity);return function(m){return r.r=d(m),r.g=g(m),r.b=p(m),r.opacity=y(m),r+""}}return o.gamma=t,o})(1);function qE(t,i){i||(i=[]);var l=t?Math.min(i.length,t.length):0,o=i.slice(),r;return function(u){for(r=0;r<l;++r)o[r]=t[r]*(1-u)+i[r]*u;return o}}function GE(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function YE(t,i){var l=i?i.length:0,o=t?Math.min(l,t.length):0,r=new Array(o),u=new Array(l),d;for(d=0;d<o;++d)r[d]=_o(t[d],i[d]);for(;d<l;++d)u[d]=i[d];return function(g){for(d=0;d<o;++d)u[d]=r[d](g);return u}}function VE(t,i){var l=new Date;return t=+t,i=+i,function(o){return l.setTime(t*(1-o)+i*o),l}}function hn(t,i){return t=+t,i=+i,function(l){return t*(1-l)+i*l}}function XE(t,i){var l={},o={},r;(t===null||typeof t!="object")&&(t={}),(i===null||typeof i!="object")&&(i={});for(r in i)r in t?l[r]=_o(t[r],i[r]):o[r]=i[r];return function(u){for(r in l)o[r]=l[r](u);return o}}var af=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ud=new RegExp(af.source,"g");function $E(t){return function(){return t}}function ZE(t){return function(i){return t(i)+""}}function lv(t,i){var l=af.lastIndex=Ud.lastIndex=0,o,r,u,d=-1,g=[],p=[];for(t=t+"",i=i+"";(o=af.exec(t))&&(r=Ud.exec(i));)(u=r.index)>l&&(u=i.slice(l,u),g[d]?g[d]+=u:g[++d]=u),(o=o[0])===(r=r[0])?g[d]?g[d]+=r:g[++d]=r:(g[++d]=null,p.push({i:d,x:hn(o,r)})),l=Ud.lastIndex;return l<i.length&&(u=i.slice(l),g[d]?g[d]+=u:g[++d]=u),g.length<2?p[0]?ZE(p[0].x):$E(i):(i=p.length,function(y){for(var m=0,v;m<i;++m)g[(v=p[m]).i]=v.x(y);return g.join("")})}function _o(t,i){var l=typeof i,o;return i==null||l==="boolean"?Sf(i):(l==="number"?hn:l==="string"?(o=li(i))?(i=o,kr):lv:i instanceof li?kr:i instanceof Date?VE:GE(i)?qE:Array.isArray(i)?YE:typeof i.valueOf!="function"&&typeof i.toString!="function"||isNaN(i)?XE:hn)(t,i)}var hy=180/Math.PI,lf={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function ov(t,i,l,o,r,u){var d,g,p;return(d=Math.sqrt(t*t+i*i))&&(t/=d,i/=d),(p=t*l+i*o)&&(l-=t*p,o-=i*p),(g=Math.sqrt(l*l+o*o))&&(l/=g,o/=g,p/=g),t*o<i*l&&(t=-t,i=-i,p=-p,d=-d),{translateX:r,translateY:u,rotate:Math.atan2(i,t)*hy,skewX:Math.atan(p)*hy,scaleX:d,scaleY:g}}var xr;function KE(t){const i=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(t+"");return i.isIdentity?lf:ov(i.a,i.b,i.c,i.d,i.e,i.f)}function QE(t){return t==null||(xr||(xr=document.createElementNS("http://www.w3.org/2000/svg","g")),xr.setAttribute("transform",t),!(t=xr.transform.baseVal.consolidate()))?lf:(t=t.matrix,ov(t.a,t.b,t.c,t.d,t.e,t.f))}function sv(t,i,l,o){function r(y){return y.length?y.pop()+" ":""}function u(y,m,v,x,S,w){if(y!==v||m!==x){var j=S.push("translate(",null,i,null,l);w.push({i:j-4,x:hn(y,v)},{i:j-2,x:hn(m,x)})}else(v||x)&&S.push("translate("+v+i+x+l)}function d(y,m,v,x){y!==m?(y-m>180?m+=360:m-y>180&&(y+=360),x.push({i:v.push(r(v)+"rotate(",null,o)-2,x:hn(y,m)})):m&&v.push(r(v)+"rotate("+m+o)}function g(y,m,v,x){y!==m?x.push({i:v.push(r(v)+"skewX(",null,o)-2,x:hn(y,m)}):m&&v.push(r(v)+"skewX("+m+o)}function p(y,m,v,x,S,w){if(y!==v||m!==x){var j=S.push(r(S)+"scale(",null,",",null,")");w.push({i:j-4,x:hn(y,v)},{i:j-2,x:hn(m,x)})}else(v!==1||x!==1)&&S.push(r(S)+"scale("+v+","+x+")")}return function(y,m){var v=[],x=[];return y=t(y),m=t(m),u(y.translateX,y.translateY,m.translateX,m.translateY,v,x),d(y.rotate,m.rotate,v,x),g(y.skewX,m.skewX,v,x),p(y.scaleX,y.scaleY,m.scaleX,m.scaleY,v,x),y=m=null,function(S){for(var w=-1,j=x.length,E;++w<j;)v[(E=x[w]).i]=E.x(S);return v.join("")}}}var FE=sv(KE,"px, ","px)","deg)"),PE=sv(QE,", ",")",")"),JE=1e-12;function gy(t){return((t=Math.exp(t))+1/t)/2}function WE(t){return((t=Math.exp(t))-1/t)/2}function e2(t){return((t=Math.exp(2*t))-1)/(t+1)}const jr=(function t(i,l,o){function r(u,d){var g=u[0],p=u[1],y=u[2],m=d[0],v=d[1],x=d[2],S=m-g,w=v-p,j=S*S+w*w,E,A;if(j<JE)A=Math.log(x/y)/i,E=function(z){return[g+z*S,p+z*w,y*Math.exp(i*z*A)]};else{var B=Math.sqrt(j),C=(x*x-y*y+o*j)/(2*y*l*B),_=(x*x-y*y-o*j)/(2*x*l*B),U=Math.log(Math.sqrt(C*C+1)-C),R=Math.log(Math.sqrt(_*_+1)-_);A=(R-U)/i,E=function(z){var I=z*A,X=gy(U),ce=y/(l*B)*(X*e2(i*I+U)-WE(U));return[g+ce*S,p+ce*w,y*X/gy(i*I+U)]}}return E.duration=A*1e3*i/Math.SQRT2,E}return r.rho=function(u){var d=Math.max(.001,+u),g=d*d,p=g*g;return t(d,g,p)},r})(Math.SQRT2,2,4);var ul=0,xo=0,ho=0,rv=1e3,Ur,bo,qr=0,oi=0,Qr=0,Mo=typeof performance=="object"&&performance.now?performance:Date,cv=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17)};function wf(){return oi||(cv(t2),oi=Mo.now()+Qr)}function t2(){oi=0}function Gr(){this._call=this._time=this._next=null}Gr.prototype=uv.prototype={constructor:Gr,restart:function(t,i,l){if(typeof t!="function")throw new TypeError("callback is not a function");l=(l==null?wf():+l)+(i==null?0:+i),!this._next&&bo!==this&&(bo?bo._next=this:Ur=this,bo=this),this._call=t,this._time=l,of()},stop:function(){this._call&&(this._call=null,this._time=1/0,of())}};function uv(t,i,l){var o=new Gr;return o.restart(t,i,l),o}function n2(){wf(),++ul;for(var t=Ur,i;t;)(i=oi-t._time)>=0&&t._call.call(void 0,i),t=t._next;--ul}function my(){oi=(qr=Mo.now())+Qr,ul=xo=0;try{n2()}finally{ul=0,i2(),oi=0}}function a2(){var t=Mo.now(),i=t-qr;i>rv&&(Qr-=i,qr=t)}function i2(){for(var t,i=Ur,l,o=1/0;i;)i._call?(o>i._time&&(o=i._time),t=i,i=i._next):(l=i._next,i._next=null,i=t?t._next=l:Ur=l);bo=t,of(o)}function of(t){if(!ul){xo&&(xo=clearTimeout(xo));var i=t-oi;i>24?(t<1/0&&(xo=setTimeout(my,t-Mo.now()-Qr)),ho&&(ho=clearInterval(ho))):(ho||(qr=Mo.now(),ho=setInterval(a2,rv)),ul=1,cv(my))}}function py(t,i,l){var o=new Gr;return i=i==null?0:+i,o.restart(r=>{o.stop(),t(r+i)},i,l),o}var l2=Zr("start","end","cancel","interrupt"),o2=[],dv=0,yy=1,sf=2,zr=3,vy=4,rf=5,Rr=6;function Fr(t,i,l,o,r,u){var d=t.__transition;if(!d)t.__transition={};else if(l in d)return;s2(t,l,{name:i,index:o,group:r,on:l2,tween:o2,time:u.time,delay:u.delay,duration:u.duration,ease:u.ease,timer:null,state:dv})}function Nf(t,i){var l=on(t,i);if(l.state>dv)throw new Error("too late; already scheduled");return l}function yn(t,i){var l=on(t,i);if(l.state>zr)throw new Error("too late; already running");return l}function on(t,i){var l=t.__transition;if(!l||!(l=l[i]))throw new Error("transition not found");return l}function s2(t,i,l){var o=t.__transition,r;o[i]=l,l.timer=uv(u,0,l.time);function u(y){l.state=yy,l.timer.restart(d,l.delay,l.time),l.delay<=y&&d(y-l.delay)}function d(y){var m,v,x,S;if(l.state!==yy)return p();for(m in o)if(S=o[m],S.name===l.name){if(S.state===zr)return py(d);S.state===vy?(S.state=Rr,S.timer.stop(),S.on.call("interrupt",t,t.__data__,S.index,S.group),delete o[m]):+m<i&&(S.state=Rr,S.timer.stop(),S.on.call("cancel",t,t.__data__,S.index,S.group),delete o[m])}if(py(function(){l.state===zr&&(l.state=vy,l.timer.restart(g,l.delay,l.time),g(y))}),l.state=sf,l.on.call("start",t,t.__data__,l.index,l.group),l.state===sf){for(l.state=zr,r=new Array(x=l.tween.length),m=0,v=-1;m<x;++m)(S=l.tween[m].value.call(t,t.__data__,l.index,l.group))&&(r[++v]=S);r.length=v+1}}function g(y){for(var m=y<l.duration?l.ease.call(null,y/l.duration):(l.timer.restart(p),l.state=rf,1),v=-1,x=r.length;++v<x;)r[v].call(t,m);l.state===rf&&(l.on.call("end",t,t.__data__,l.index,l.group),p())}function p(){l.state=Rr,l.timer.stop(),delete o[i];for(var y in o)return;delete t.__transition}}function Dr(t,i){var l=t.__transition,o,r,u=!0,d;if(l){i=i==null?null:i+"";for(d in l){if((o=l[d]).name!==i){u=!1;continue}r=o.state>sf&&o.state<rf,o.state=Rr,o.timer.stop(),o.on.call(r?"interrupt":"cancel",t,t.__data__,o.index,o.group),delete l[d]}u&&delete t.__transition}}function r2(t){return this.each(function(){Dr(this,t)})}function c2(t,i){var l,o;return function(){var r=yn(this,t),u=r.tween;if(u!==l){o=l=u;for(var d=0,g=o.length;d<g;++d)if(o[d].name===i){o=o.slice(),o.splice(d,1);break}}r.tween=o}}function u2(t,i,l){var o,r;if(typeof l!="function")throw new Error;return function(){var u=yn(this,t),d=u.tween;if(d!==o){r=(o=d).slice();for(var g={name:i,value:l},p=0,y=r.length;p<y;++p)if(r[p].name===i){r[p]=g;break}p===y&&r.push(g)}u.tween=r}}function d2(t,i){var l=this._id;if(t+="",arguments.length<2){for(var o=on(this.node(),l).tween,r=0,u=o.length,d;r<u;++r)if((d=o[r]).name===t)return d.value;return null}return this.each((i==null?c2:u2)(l,t,i))}function _f(t,i,l){var o=t._id;return t.each(function(){var r=yn(this,o);(r.value||(r.value={}))[i]=l.apply(this,arguments)}),function(r){return on(r,o).value[i]}}function fv(t,i){var l;return(typeof i=="number"?hn:i instanceof li?kr:(l=li(i))?(i=l,kr):lv)(t,i)}function f2(t){return function(){this.removeAttribute(t)}}function h2(t){return function(){this.removeAttributeNS(t.space,t.local)}}function g2(t,i,l){var o,r=l+"",u;return function(){var d=this.getAttribute(t);return d===r?null:d===o?u:u=i(o=d,l)}}function m2(t,i,l){var o,r=l+"",u;return function(){var d=this.getAttributeNS(t.space,t.local);return d===r?null:d===o?u:u=i(o=d,l)}}function p2(t,i,l){var o,r,u;return function(){var d,g=l(this),p;return g==null?void this.removeAttribute(t):(d=this.getAttribute(t),p=g+"",d===p?null:d===o&&p===r?u:(r=p,u=i(o=d,g)))}}function y2(t,i,l){var o,r,u;return function(){var d,g=l(this),p;return g==null?void this.removeAttributeNS(t.space,t.local):(d=this.getAttributeNS(t.space,t.local),p=g+"",d===p?null:d===o&&p===r?u:(r=p,u=i(o=d,g)))}}function v2(t,i){var l=Kr(t),o=l==="transform"?PE:fv;return this.attrTween(t,typeof i=="function"?(l.local?y2:p2)(l,o,_f(this,"attr."+t,i)):i==null?(l.local?h2:f2)(l):(l.local?m2:g2)(l,o,i))}function x2(t,i){return function(l){this.setAttribute(t,i.call(this,l))}}function b2(t,i){return function(l){this.setAttributeNS(t.space,t.local,i.call(this,l))}}function S2(t,i){var l,o;function r(){var u=i.apply(this,arguments);return u!==o&&(l=(o=u)&&b2(t,u)),l}return r._value=i,r}function w2(t,i){var l,o;function r(){var u=i.apply(this,arguments);return u!==o&&(l=(o=u)&&x2(t,u)),l}return r._value=i,r}function N2(t,i){var l="attr."+t;if(arguments.length<2)return(l=this.tween(l))&&l._value;if(i==null)return this.tween(l,null);if(typeof i!="function")throw new Error;var o=Kr(t);return this.tween(l,(o.local?S2:w2)(o,i))}function _2(t,i){return function(){Nf(this,t).delay=+i.apply(this,arguments)}}function E2(t,i){return i=+i,function(){Nf(this,t).delay=i}}function C2(t){var i=this._id;return arguments.length?this.each((typeof t=="function"?_2:E2)(i,t)):on(this.node(),i).delay}function T2(t,i){return function(){yn(this,t).duration=+i.apply(this,arguments)}}function A2(t,i){return i=+i,function(){yn(this,t).duration=i}}function M2(t){var i=this._id;return arguments.length?this.each((typeof t=="function"?T2:A2)(i,t)):on(this.node(),i).duration}function j2(t,i){if(typeof i!="function")throw new Error;return function(){yn(this,t).ease=i}}function z2(t){var i=this._id;return arguments.length?this.each(j2(i,t)):on(this.node(),i).ease}function R2(t,i){return function(){var l=i.apply(this,arguments);if(typeof l!="function")throw new Error;yn(this,t).ease=l}}function D2(t){if(typeof t!="function")throw new Error;return this.each(R2(this._id,t))}function O2(t){typeof t!="function"&&(t=Y0(t));for(var i=this._groups,l=i.length,o=new Array(l),r=0;r<l;++r)for(var u=i[r],d=u.length,g=o[r]=[],p,y=0;y<d;++y)(p=u[y])&&t.call(p,p.__data__,y,u)&&g.push(p);return new Vn(o,this._parents,this._name,this._id)}function H2(t){if(t._id!==this._id)throw new Error;for(var i=this._groups,l=t._groups,o=i.length,r=l.length,u=Math.min(o,r),d=new Array(o),g=0;g<u;++g)for(var p=i[g],y=l[g],m=p.length,v=d[g]=new Array(m),x,S=0;S<m;++S)(x=p[S]||y[S])&&(v[S]=x);for(;g<o;++g)d[g]=i[g];return new Vn(d,this._parents,this._name,this._id)}function I2(t){return(t+"").trim().split(/^|\s+/).every(function(i){var l=i.indexOf(".");return l>=0&&(i=i.slice(0,l)),!i||i==="start"})}function B2(t,i,l){var o,r,u=I2(i)?Nf:yn;return function(){var d=u(this,t),g=d.on;g!==o&&(r=(o=g).copy()).on(i,l),d.on=r}}function L2(t,i){var l=this._id;return arguments.length<2?on(this.node(),l).on.on(t):this.each(B2(l,t,i))}function k2(t){return function(){var i=this.parentNode;for(var l in this.__transition)if(+l!==t)return;i&&i.removeChild(this)}}function U2(){return this.on("end.remove",k2(this._id))}function q2(t){var i=this._name,l=this._id;typeof t!="function"&&(t=vf(t));for(var o=this._groups,r=o.length,u=new Array(r),d=0;d<r;++d)for(var g=o[d],p=g.length,y=u[d]=new Array(p),m,v,x=0;x<p;++x)(m=g[x])&&(v=t.call(m,m.__data__,x,g))&&("__data__"in m&&(v.__data__=m.__data__),y[x]=v,Fr(y[x],i,l,x,y,on(m,l)));return new Vn(u,this._parents,i,l)}function G2(t){var i=this._name,l=this._id;typeof t!="function"&&(t=G0(t));for(var o=this._groups,r=o.length,u=[],d=[],g=0;g<r;++g)for(var p=o[g],y=p.length,m,v=0;v<y;++v)if(m=p[v]){for(var x=t.call(m,m.__data__,v,p),S,w=on(m,l),j=0,E=x.length;j<E;++j)(S=x[j])&&Fr(S,i,l,j,x,w);u.push(x),d.push(m)}return new Vn(u,d,i,l)}var Y2=Io.prototype.constructor;function V2(){return new Y2(this._groups,this._parents)}function X2(t,i){var l,o,r;return function(){var u=cl(this,t),d=(this.style.removeProperty(t),cl(this,t));return u===d?null:u===l&&d===o?r:r=i(l=u,o=d)}}function hv(t){return function(){this.style.removeProperty(t)}}function $2(t,i,l){var o,r=l+"",u;return function(){var d=cl(this,t);return d===r?null:d===o?u:u=i(o=d,l)}}function Z2(t,i,l){var o,r,u;return function(){var d=cl(this,t),g=l(this),p=g+"";return g==null&&(p=g=(this.style.removeProperty(t),cl(this,t))),d===p?null:d===o&&p===r?u:(r=p,u=i(o=d,g))}}function K2(t,i){var l,o,r,u="style."+i,d="end."+u,g;return function(){var p=yn(this,t),y=p.on,m=p.value[u]==null?g||(g=hv(i)):void 0;(y!==l||r!==m)&&(o=(l=y).copy()).on(d,r=m),p.on=o}}function Q2(t,i,l){var o=(t+="")=="transform"?FE:fv;return i==null?this.styleTween(t,X2(t,o)).on("end.style."+t,hv(t)):typeof i=="function"?this.styleTween(t,Z2(t,o,_f(this,"style."+t,i))).each(K2(this._id,t)):this.styleTween(t,$2(t,o,i),l).on("end.style."+t,null)}function F2(t,i,l){return function(o){this.style.setProperty(t,i.call(this,o),l)}}function P2(t,i,l){var o,r;function u(){var d=i.apply(this,arguments);return d!==r&&(o=(r=d)&&F2(t,d,l)),o}return u._value=i,u}function J2(t,i,l){var o="style."+(t+="");if(arguments.length<2)return(o=this.tween(o))&&o._value;if(i==null)return this.tween(o,null);if(typeof i!="function")throw new Error;return this.tween(o,P2(t,i,l??""))}function W2(t){return function(){this.textContent=t}}function eC(t){return function(){var i=t(this);this.textContent=i??""}}function tC(t){return this.tween("text",typeof t=="function"?eC(_f(this,"text",t)):W2(t==null?"":t+""))}function nC(t){return function(i){this.textContent=t.call(this,i)}}function aC(t){var i,l;function o(){var r=t.apply(this,arguments);return r!==l&&(i=(l=r)&&nC(r)),i}return o._value=t,o}function iC(t){var i="text";if(arguments.length<1)return(i=this.tween(i))&&i._value;if(t==null)return this.tween(i,null);if(typeof t!="function")throw new Error;return this.tween(i,aC(t))}function lC(){for(var t=this._name,i=this._id,l=gv(),o=this._groups,r=o.length,u=0;u<r;++u)for(var d=o[u],g=d.length,p,y=0;y<g;++y)if(p=d[y]){var m=on(p,i);Fr(p,t,l,y,d,{time:m.time+m.delay+m.duration,delay:0,duration:m.duration,ease:m.ease})}return new Vn(o,this._parents,t,l)}function oC(){var t,i,l=this,o=l._id,r=l.size();return new Promise(function(u,d){var g={value:d},p={value:function(){--r===0&&u()}};l.each(function(){var y=yn(this,o),m=y.on;m!==t&&(i=(t=m).copy(),i._.cancel.push(g),i._.interrupt.push(g),i._.end.push(p)),y.on=i}),r===0&&u()})}var sC=0;function Vn(t,i,l,o){this._groups=t,this._parents=i,this._name=l,this._id=o}function gv(){return++sC}var qn=Io.prototype;Vn.prototype={constructor:Vn,select:q2,selectAll:G2,selectChild:qn.selectChild,selectChildren:qn.selectChildren,filter:O2,merge:H2,selection:V2,transition:lC,call:qn.call,nodes:qn.nodes,node:qn.node,size:qn.size,empty:qn.empty,each:qn.each,on:L2,attr:v2,attrTween:N2,style:Q2,styleTween:J2,text:tC,textTween:iC,remove:U2,tween:d2,delay:C2,duration:M2,ease:z2,easeVarying:D2,end:oC,[Symbol.iterator]:qn[Symbol.iterator]};function rC(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}var cC={time:null,delay:0,duration:250,ease:rC};function uC(t,i){for(var l;!(l=t.__transition)||!(l=l[i]);)if(!(t=t.parentNode))throw new Error(`transition ${i} not found`);return l}function dC(t){var i,l;t instanceof Vn?(i=t._id,t=t._name):(i=gv(),(l=cC).time=wf(),t=t==null?null:t+"");for(var o=this._groups,r=o.length,u=0;u<r;++u)for(var d=o[u],g=d.length,p,y=0;y<g;++y)(p=d[y])&&Fr(p,t,i,y,d,l||uC(p,i));return new Vn(o,this._parents,t,i)}Io.prototype.interrupt=r2;Io.prototype.transition=dC;const br=t=>()=>t;function fC(t,{sourceEvent:i,target:l,transform:o,dispatch:r}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:i,enumerable:!0,configurable:!0},target:{value:l,enumerable:!0,configurable:!0},transform:{value:o,enumerable:!0,configurable:!0},_:{value:r}})}function Yn(t,i,l){this.k=t,this.x=i,this.y=l}Yn.prototype={constructor:Yn,scale:function(t){return t===1?this:new Yn(this.k*t,this.x,this.y)},translate:function(t,i){return t===0&i===0?this:new Yn(this.k,this.x+this.k*t,this.y+this.k*i)},apply:function(t){return[t[0]*this.k+this.x,t[1]*this.k+this.y]},applyX:function(t){return t*this.k+this.x},applyY:function(t){return t*this.k+this.y},invert:function(t){return[(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},invertX:function(t){return(t-this.x)/this.k},invertY:function(t){return(t-this.y)/this.k},rescaleX:function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},rescaleY:function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Pr=new Yn(1,0,0);mv.prototype=Yn.prototype;function mv(t){for(;!t.__zoom;)if(!(t=t.parentNode))return Pr;return t.__zoom}function qd(t){t.stopImmediatePropagation()}function go(t){t.preventDefault(),t.stopImmediatePropagation()}function hC(t){return(!t.ctrlKey||t.type==="wheel")&&!t.button}function gC(){var t=this;return t instanceof SVGElement?(t=t.ownerSVGElement||t,t.hasAttribute("viewBox")?(t=t.viewBox.baseVal,[[t.x,t.y],[t.x+t.width,t.y+t.height]]):[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]):[[0,0],[t.clientWidth,t.clientHeight]]}function xy(){return this.__zoom||Pr}function mC(t){return-t.deltaY*(t.deltaMode===1?.05:t.deltaMode?1:.002)*(t.ctrlKey?10:1)}function pC(){return navigator.maxTouchPoints||"ontouchstart"in this}function yC(t,i,l){var o=t.invertX(i[0][0])-l[0][0],r=t.invertX(i[1][0])-l[1][0],u=t.invertY(i[0][1])-l[0][1],d=t.invertY(i[1][1])-l[1][1];return t.translate(r>o?(o+r)/2:Math.min(0,o)||Math.max(0,r),d>u?(u+d)/2:Math.min(0,u)||Math.max(0,d))}function pv(){var t=hC,i=gC,l=yC,o=mC,r=pC,u=[0,1/0],d=[[-1/0,-1/0],[1/0,1/0]],g=250,p=jr,y=Zr("start","zoom","end"),m,v,x,S=500,w=150,j=0,E=10;function A(D){D.property("__zoom",xy).on("wheel.zoom",I,{passive:!1}).on("mousedown.zoom",X).on("dblclick.zoom",ce).filter(r).on("touchstart.zoom",K).on("touchmove.zoom",te).on("touchend.zoom touchcancel.zoom",ue).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}A.transform=function(D,Z,M,H){var q=D.selection?D.selection():D;q.property("__zoom",xy),D!==q?U(D,Z,M,H):q.interrupt().each(function(){R(this,arguments).event(H).start().zoom(null,typeof Z=="function"?Z.apply(this,arguments):Z).end()})},A.scaleBy=function(D,Z,M,H){A.scaleTo(D,function(){var q=this.__zoom.k,k=typeof Z=="function"?Z.apply(this,arguments):Z;return q*k},M,H)},A.scaleTo=function(D,Z,M,H){A.transform(D,function(){var q=i.apply(this,arguments),k=this.__zoom,J=M==null?_(q):typeof M=="function"?M.apply(this,arguments):M,T=k.invert(J),L=typeof Z=="function"?Z.apply(this,arguments):Z;return l(C(B(k,L),J,T),q,d)},M,H)},A.translateBy=function(D,Z,M,H){A.transform(D,function(){return l(this.__zoom.translate(typeof Z=="function"?Z.apply(this,arguments):Z,typeof M=="function"?M.apply(this,arguments):M),i.apply(this,arguments),d)},null,H)},A.translateTo=function(D,Z,M,H,q){A.transform(D,function(){var k=i.apply(this,arguments),J=this.__zoom,T=H==null?_(k):typeof H=="function"?H.apply(this,arguments):H;return l(Pr.translate(T[0],T[1]).scale(J.k).translate(typeof Z=="function"?-Z.apply(this,arguments):-Z,typeof M=="function"?-M.apply(this,arguments):-M),k,d)},H,q)};function B(D,Z){return Z=Math.max(u[0],Math.min(u[1],Z)),Z===D.k?D:new Yn(Z,D.x,D.y)}function C(D,Z,M){var H=Z[0]-M[0]*D.k,q=Z[1]-M[1]*D.k;return H===D.x&&q===D.y?D:new Yn(D.k,H,q)}function _(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function U(D,Z,M,H){D.on("start.zoom",function(){R(this,arguments).event(H).start()}).on("interrupt.zoom end.zoom",function(){R(this,arguments).event(H).end()}).tween("zoom",function(){var q=this,k=arguments,J=R(q,k).event(H),T=i.apply(q,k),L=M==null?_(T):typeof M=="function"?M.apply(q,k):M,ne=Math.max(T[1][0]-T[0][0],T[1][1]-T[0][1]),ae=q.__zoom,V=typeof Z=="function"?Z.apply(q,k):Z,se=p(ae.invert(L).concat(ne/ae.k),V.invert(L).concat(ne/V.k));return function(de){if(de===1)de=V;else{var le=se(de),fe=ne/le[2];de=new Yn(fe,L[0]-le[0]*fe,L[1]-le[1]*fe)}J.zoom(null,de)}})}function R(D,Z,M){return!M&&D.__zooming||new z(D,Z)}function z(D,Z){this.that=D,this.args=Z,this.active=0,this.sourceEvent=null,this.extent=i.apply(D,Z),this.taps=0}z.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,Z){return this.mouse&&D!=="mouse"&&(this.mouse[1]=Z.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=Z.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=Z.invert(this.touch1[0])),this.that.__zoom=Z,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var Z=kt(this.that).datum();y.call(D,this.that,new fC(D,{sourceEvent:this.sourceEvent,target:A,transform:this.that.__zoom,dispatch:y}),Z)}};function I(D,...Z){if(!t.apply(this,arguments))return;var M=R(this,Z).event(D),H=this.__zoom,q=Math.max(u[0],Math.min(u[1],H.k*Math.pow(2,o.apply(this,arguments)))),k=tn(D);if(M.wheel)(M.mouse[0][0]!==k[0]||M.mouse[0][1]!==k[1])&&(M.mouse[1]=H.invert(M.mouse[0]=k)),clearTimeout(M.wheel);else{if(H.k===q)return;M.mouse=[k,H.invert(k)],Dr(this),M.start()}go(D),M.wheel=setTimeout(J,w),M.zoom("mouse",l(C(B(H,q),M.mouse[0],M.mouse[1]),M.extent,d));function J(){M.wheel=null,M.end()}}function X(D,...Z){if(x||!t.apply(this,arguments))return;var M=D.currentTarget,H=R(this,Z,!0).event(D),q=kt(D.view).on("mousemove.zoom",L,!0).on("mouseup.zoom",ne,!0),k=tn(D,M),J=D.clientX,T=D.clientY;W0(D.view),qd(D),H.mouse=[k,this.__zoom.invert(k)],Dr(this),H.start();function L(ae){if(go(ae),!H.moved){var V=ae.clientX-J,se=ae.clientY-T;H.moved=V*V+se*se>j}H.event(ae).zoom("mouse",l(C(H.that.__zoom,H.mouse[0]=tn(ae,M),H.mouse[1]),H.extent,d))}function ne(ae){q.on("mousemove.zoom mouseup.zoom",null),ev(ae.view,H.moved),go(ae),H.event(ae).end()}}function ce(D,...Z){if(t.apply(this,arguments)){var M=this.__zoom,H=tn(D.changedTouches?D.changedTouches[0]:D,this),q=M.invert(H),k=M.k*(D.shiftKey?.5:2),J=l(C(B(M,k),H,q),i.apply(this,Z),d);go(D),g>0?kt(this).transition().duration(g).call(U,J,H,D):kt(this).call(A.transform,J,H,D)}}function K(D,...Z){if(t.apply(this,arguments)){var M=D.touches,H=M.length,q=R(this,Z,D.changedTouches.length===H).event(D),k,J,T,L;for(qd(D),J=0;J<H;++J)T=M[J],L=tn(T,this),L=[L,this.__zoom.invert(L),T.identifier],q.touch0?!q.touch1&&q.touch0[2]!==L[2]&&(q.touch1=L,q.taps=0):(q.touch0=L,k=!0,q.taps=1+!!m);m&&(m=clearTimeout(m)),k&&(q.taps<2&&(v=L[0],m=setTimeout(function(){m=null},S)),Dr(this),q.start())}}function te(D,...Z){if(this.__zooming){var M=R(this,Z).event(D),H=D.changedTouches,q=H.length,k,J,T,L;for(go(D),k=0;k<q;++k)J=H[k],T=tn(J,this),M.touch0&&M.touch0[2]===J.identifier?M.touch0[0]=T:M.touch1&&M.touch1[2]===J.identifier&&(M.touch1[0]=T);if(J=M.that.__zoom,M.touch1){var ne=M.touch0[0],ae=M.touch0[1],V=M.touch1[0],se=M.touch1[1],de=(de=V[0]-ne[0])*de+(de=V[1]-ne[1])*de,le=(le=se[0]-ae[0])*le+(le=se[1]-ae[1])*le;J=B(J,Math.sqrt(de/le)),T=[(ne[0]+V[0])/2,(ne[1]+V[1])/2],L=[(ae[0]+se[0])/2,(ae[1]+se[1])/2]}else if(M.touch0)T=M.touch0[0],L=M.touch0[1];else return;M.zoom("touch",l(C(J,T,L),M.extent,d))}}function ue(D,...Z){if(this.__zooming){var M=R(this,Z).event(D),H=D.changedTouches,q=H.length,k,J;for(qd(D),x&&clearTimeout(x),x=setTimeout(function(){x=null},S),k=0;k<q;++k)J=H[k],M.touch0&&M.touch0[2]===J.identifier?delete M.touch0:M.touch1&&M.touch1[2]===J.identifier&&delete M.touch1;if(M.touch1&&!M.touch0&&(M.touch0=M.touch1,delete M.touch1),M.touch0)M.touch0[1]=this.__zoom.invert(M.touch0[0]);else if(M.end(),M.taps===2&&(J=tn(J,this),Math.hypot(v[0]-J[0],v[1]-J[1])<E)){var T=kt(this).on("dblclick.zoom");T&&T.apply(this,arguments)}}}return A.wheelDelta=function(D){return arguments.length?(o=typeof D=="function"?D:br(+D),A):o},A.filter=function(D){return arguments.length?(t=typeof D=="function"?D:br(!!D),A):t},A.touchable=function(D){return arguments.length?(r=typeof D=="function"?D:br(!!D),A):r},A.extent=function(D){return arguments.length?(i=typeof D=="function"?D:br([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),A):i},A.scaleExtent=function(D){return arguments.length?(u[0]=+D[0],u[1]=+D[1],A):[u[0],u[1]]},A.translateExtent=function(D){return arguments.length?(d[0][0]=+D[0][0],d[1][0]=+D[1][0],d[0][1]=+D[0][1],d[1][1]=+D[1][1],A):[[d[0][0],d[0][1]],[d[1][0],d[1][1]]]},A.constrain=function(D){return arguments.length?(l=D,A):l},A.duration=function(D){return arguments.length?(g=+D,A):g},A.interpolate=function(D){return arguments.length?(p=D,A):p},A.on=function(){var D=y.on.apply(y,arguments);return D===y?A:D},A.clickDistance=function(D){return arguments.length?(j=(D=+D)*D,A):Math.sqrt(j)},A.tapDistance=function(D){return arguments.length?(E=+D,A):E},A}const pn={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:t=>`Node type "${t}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:t=>`The old edge with id=${t} does not exist.`,error009:t=>`Marker type "${t}" doesn't exist.`,error008:(t,{id:i,sourceHandle:l,targetHandle:o})=>`Couldn't create edge for ${t} handle id: "${t==="source"?l:o}", edge id: ${i}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:t=>`Edge type "${t}" not found. Using fallback type "default".`,error012:t=>`Node with id "${t}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(t="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${t}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},jo=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],yv=["Enter"," ","Escape"],vv={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:t,x:i,y:l})=>`Moved selected node ${t}. New position, x: ${i}, y: ${l}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var dl;(function(t){t.Strict="strict",t.Loose="loose"})(dl||(dl={}));var ii;(function(t){t.Free="free",t.Vertical="vertical",t.Horizontal="horizontal"})(ii||(ii={}));var zo;(function(t){t.Partial="partial",t.Full="full"})(zo||(zo={}));const xv={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Ea;(function(t){t.Bezier="default",t.Straight="straight",t.Step="step",t.SmoothStep="smoothstep",t.SimpleBezier="simplebezier"})(Ea||(Ea={}));var Yr;(function(t){t.Arrow="arrow",t.ArrowClosed="arrowclosed"})(Yr||(Yr={}));var me;(function(t){t.Left="left",t.Top="top",t.Right="right",t.Bottom="bottom"})(me||(me={}));const by={[me.Left]:me.Right,[me.Right]:me.Left,[me.Top]:me.Bottom,[me.Bottom]:me.Top};function bv(t){return t===null?null:t?"valid":"invalid"}const Sv=t=>"id"in t&&"source"in t&&"target"in t,vC=t=>"id"in t&&"position"in t&&!("source"in t)&&!("target"in t),Ef=t=>"id"in t&&"internals"in t&&!("source"in t)&&!("target"in t),Lo=(t,i=[0,0])=>{const{width:l,height:o}=Xn(t),r=t.origin??i,u=l*r[0],d=o*r[1];return{x:t.position.x-u,y:t.position.y-d}},xC=(t,i={nodeOrigin:[0,0]})=>{if(t.length===0)return{x:0,y:0,width:0,height:0};const l=t.reduce((o,r)=>{const u=typeof r=="string";let d=!i.nodeLookup&&!u?r:void 0;i.nodeLookup&&(d=u?i.nodeLookup.get(r):Ef(r)?r:i.nodeLookup.get(r.id));const g=d?Vr(d,i.nodeOrigin):{x:0,y:0,x2:0,y2:0};return Jr(o,g)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Wr(l)},ko=(t,i={})=>{let l={x:1/0,y:1/0,x2:-1/0,y2:-1/0},o=!1;return t.forEach(r=>{(i.filter===void 0||i.filter(r))&&(l=Jr(l,Vr(r)),o=!0)}),o?Wr(l):{x:0,y:0,width:0,height:0}},Cf=(t,i,[l,o,r]=[0,0,1],u=!1,d=!1)=>{const g={...qo(i,[l,o,r]),width:i.width/r,height:i.height/r},p=[];for(const y of t.values()){const{measured:m,selectable:v=!0,hidden:x=!1}=y;if(d&&!v||x)continue;const S=m.width??y.width??y.initialWidth??null,w=m.height??y.height??y.initialHeight??null,j=Ro(g,hl(y)),E=(S??0)*(w??0),A=u&&j>0;(!y.internals.handleBounds||A||j>=E||y.dragging)&&p.push(y)}return p},bC=(t,i)=>{const l=new Set;return t.forEach(o=>{l.add(o.id)}),i.filter(o=>l.has(o.source)||l.has(o.target))};function SC(t,i){const l=new Map,o=i?.nodes?new Set(i.nodes.map(r=>r.id)):null;return t.forEach(r=>{r.measured.width&&r.measured.height&&(i?.includeHiddenNodes||!r.hidden)&&(!o||o.has(r.id))&&l.set(r.id,r)}),l}async function wC({nodes:t,width:i,height:l,panZoom:o,minZoom:r,maxZoom:u},d){if(t.size===0)return Promise.resolve(!0);const g=SC(t,d),p=ko(g),y=Tf(p,i,l,d?.minZoom??r,d?.maxZoom??u,d?.padding??.1);return await o.setViewport(y,{duration:d?.duration,ease:d?.ease,interpolate:d?.interpolate}),Promise.resolve(!0)}function wv({nodeId:t,nextPosition:i,nodeLookup:l,nodeOrigin:o=[0,0],nodeExtent:r,onError:u}){const d=l.get(t),g=d.parentId?l.get(d.parentId):void 0,{x:p,y}=g?g.internals.positionAbsolute:{x:0,y:0},m=d.origin??o;let v=d.extent||r;if(d.extent==="parent"&&!d.expandParent)if(!g)u?.("005",pn.error005());else{const S=g.measured.width,w=g.measured.height;S&&w&&(v=[[p,y],[p+S,y+w]])}else g&&gl(d.extent)&&(v=[[d.extent[0][0]+p,d.extent[0][1]+y],[d.extent[1][0]+p,d.extent[1][1]+y]]);const x=gl(v)?si(i,v,d.measured):i;return(d.measured.width===void 0||d.measured.height===void 0)&&u?.("015",pn.error015()),{position:{x:x.x-p+(d.measured.width??0)*m[0],y:x.y-y+(d.measured.height??0)*m[1]},positionAbsolute:x}}async function NC({nodesToRemove:t=[],edgesToRemove:i=[],nodes:l,edges:o,onBeforeDelete:r}){const u=new Set(t.map(x=>x.id)),d=[];for(const x of l){if(x.deletable===!1)continue;const S=u.has(x.id),w=!S&&x.parentId&&d.find(j=>j.id===x.parentId);(S||w)&&d.push(x)}const g=new Set(i.map(x=>x.id)),p=o.filter(x=>x.deletable!==!1),m=bC(d,p);for(const x of p)g.has(x.id)&&!m.find(w=>w.id===x.id)&&m.push(x);if(!r)return{edges:m,nodes:d};const v=await r({nodes:d,edges:m});return typeof v=="boolean"?v?{edges:m,nodes:d}:{edges:[],nodes:[]}:v}const fl=(t,i=0,l=1)=>Math.min(Math.max(t,i),l),si=(t={x:0,y:0},i,l)=>({x:fl(t.x,i[0][0],i[1][0]-(l?.width??0)),y:fl(t.y,i[0][1],i[1][1]-(l?.height??0))});function Nv(t,i,l){const{width:o,height:r}=Xn(l),{x:u,y:d}=l.internals.positionAbsolute;return si(t,[[u,d],[u+o,d+r]],i)}const Sy=(t,i,l)=>t<i?fl(Math.abs(t-i),1,i)/i:t>l?-fl(Math.abs(t-l),1,i)/i:0,_v=(t,i,l=15,o=40)=>{const r=Sy(t.x,o,i.width-o)*l,u=Sy(t.y,o,i.height-o)*l;return[r,u]},Jr=(t,i)=>({x:Math.min(t.x,i.x),y:Math.min(t.y,i.y),x2:Math.max(t.x2,i.x2),y2:Math.max(t.y2,i.y2)}),cf=({x:t,y:i,width:l,height:o})=>({x:t,y:i,x2:t+l,y2:i+o}),Wr=({x:t,y:i,x2:l,y2:o})=>({x:t,y:i,width:l-t,height:o-i}),hl=(t,i=[0,0])=>{const{x:l,y:o}=Ef(t)?t.internals.positionAbsolute:Lo(t,i);return{x:l,y:o,width:t.measured?.width??t.width??t.initialWidth??0,height:t.measured?.height??t.height??t.initialHeight??0}},Vr=(t,i=[0,0])=>{const{x:l,y:o}=Ef(t)?t.internals.positionAbsolute:Lo(t,i);return{x:l,y:o,x2:l+(t.measured?.width??t.width??t.initialWidth??0),y2:o+(t.measured?.height??t.height??t.initialHeight??0)}},Ev=(t,i)=>Wr(Jr(cf(t),cf(i))),Ro=(t,i)=>{const l=Math.max(0,Math.min(t.x+t.width,i.x+i.width)-Math.max(t.x,i.x)),o=Math.max(0,Math.min(t.y+t.height,i.y+i.height)-Math.max(t.y,i.y));return Math.ceil(l*o)},wy=t=>an(t.width)&&an(t.height)&&an(t.x)&&an(t.y),an=t=>!isNaN(t)&&isFinite(t),_C=(t,i)=>{},Uo=(t,i=[1,1])=>({x:i[0]*Math.round(t.x/i[0]),y:i[1]*Math.round(t.y/i[1])}),qo=({x:t,y:i},[l,o,r],u=!1,d=[1,1])=>{const g={x:(t-l)/r,y:(i-o)/r};return u?Uo(g,d):g},Xr=({x:t,y:i},[l,o,r])=>({x:t*r+l,y:i*r+o});function el(t,i){if(typeof t=="number")return Math.floor((i-i/(1+t))*.5);if(typeof t=="string"&&t.endsWith("px")){const l=parseFloat(t);if(!Number.isNaN(l))return Math.floor(l)}if(typeof t=="string"&&t.endsWith("%")){const l=parseFloat(t);if(!Number.isNaN(l))return Math.floor(i*l*.01)}return console.error(`[React Flow] The padding value "${t}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function EC(t,i,l){if(typeof t=="string"||typeof t=="number"){const o=el(t,l),r=el(t,i);return{top:o,right:r,bottom:o,left:r,x:r*2,y:o*2}}if(typeof t=="object"){const o=el(t.top??t.y??0,l),r=el(t.bottom??t.y??0,l),u=el(t.left??t.x??0,i),d=el(t.right??t.x??0,i);return{top:o,right:d,bottom:r,left:u,x:u+d,y:o+r}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function CC(t,i,l,o,r,u){const{x:d,y:g}=Xr(t,[i,l,o]),{x:p,y}=Xr({x:t.x+t.width,y:t.y+t.height},[i,l,o]),m=r-p,v=u-y;return{left:Math.floor(d),top:Math.floor(g),right:Math.floor(m),bottom:Math.floor(v)}}const Tf=(t,i,l,o,r,u)=>{const d=EC(u,i,l),g=(i-d.x)/t.width,p=(l-d.y)/t.height,y=Math.min(g,p),m=fl(y,o,r),v=t.x+t.width/2,x=t.y+t.height/2,S=i/2-v*m,w=l/2-x*m,j=CC(t,S,w,m,i,l),E={left:Math.min(j.left-d.left,0),top:Math.min(j.top-d.top,0),right:Math.min(j.right-d.right,0),bottom:Math.min(j.bottom-d.bottom,0)};return{x:S-E.left+E.right,y:w-E.top+E.bottom,zoom:m}},Do=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function gl(t){return t!=null&&t!=="parent"}function Xn(t){return{width:t.measured?.width??t.width??t.initialWidth??0,height:t.measured?.height??t.height??t.initialHeight??0}}function Cv(t){return(t.measured?.width??t.width??t.initialWidth)!==void 0&&(t.measured?.height??t.height??t.initialHeight)!==void 0}function Tv(t,i={width:0,height:0},l,o,r){const u={...t},d=o.get(l);if(d){const g=d.origin||r;u.x+=d.internals.positionAbsolute.x-(i.width??0)*g[0],u.y+=d.internals.positionAbsolute.y-(i.height??0)*g[1]}return u}function Ny(t,i){if(t.size!==i.size)return!1;for(const l of t)if(!i.has(l))return!1;return!0}function TC(){let t,i;return{promise:new Promise((o,r)=>{t=o,i=r}),resolve:t,reject:i}}function AC(t){return{...vv,...t||{}}}function Eo(t,{snapGrid:i=[0,0],snapToGrid:l=!1,transform:o,containerBounds:r}){const{x:u,y:d}=ln(t),g=qo({x:u-(r?.left??0),y:d-(r?.top??0)},o),{x:p,y}=l?Uo(g,i):g;return{xSnapped:p,ySnapped:y,...g}}const Af=t=>({width:t.offsetWidth,height:t.offsetHeight}),Av=t=>t?.getRootNode?.()||window?.document,MC=["INPUT","SELECT","TEXTAREA"];function Mv(t){const i=t.composedPath?.()?.[0]||t.target;return i?.nodeType!==1?!1:MC.includes(i.nodeName)||i.hasAttribute("contenteditable")||!!i.closest(".nokey")}const jv=t=>"clientX"in t,ln=(t,i)=>{const l=jv(t),o=l?t.clientX:t.touches?.[0].clientX,r=l?t.clientY:t.touches?.[0].clientY;return{x:o-(i?.left??0),y:r-(i?.top??0)}},_y=(t,i,l,o,r)=>{const u=i.querySelectorAll(`.${t}`);return!u||!u.length?null:Array.from(u).map(d=>{const g=d.getBoundingClientRect();return{id:d.getAttribute("data-handleid"),type:t,nodeId:r,position:d.getAttribute("data-handlepos"),x:(g.left-l.left)/o,y:(g.top-l.top)/o,...Af(d)}})};function zv({sourceX:t,sourceY:i,targetX:l,targetY:o,sourceControlX:r,sourceControlY:u,targetControlX:d,targetControlY:g}){const p=t*.125+r*.375+d*.375+l*.125,y=i*.125+u*.375+g*.375+o*.125,m=Math.abs(p-t),v=Math.abs(y-i);return[p,y,m,v]}function Sr(t,i){return t>=0?.5*t:i*25*Math.sqrt(-t)}function Ey({pos:t,x1:i,y1:l,x2:o,y2:r,c:u}){switch(t){case me.Left:return[i-Sr(i-o,u),l];case me.Right:return[i+Sr(o-i,u),l];case me.Top:return[i,l-Sr(l-r,u)];case me.Bottom:return[i,l+Sr(r-l,u)]}}function Rv({sourceX:t,sourceY:i,sourcePosition:l=me.Bottom,targetX:o,targetY:r,targetPosition:u=me.Top,curvature:d=.25}){const[g,p]=Ey({pos:l,x1:t,y1:i,x2:o,y2:r,c:d}),[y,m]=Ey({pos:u,x1:o,y1:r,x2:t,y2:i,c:d}),[v,x,S,w]=zv({sourceX:t,sourceY:i,targetX:o,targetY:r,sourceControlX:g,sourceControlY:p,targetControlX:y,targetControlY:m});return[`M${t},${i} C${g},${p} ${y},${m} ${o},${r}`,v,x,S,w]}function Dv({sourceX:t,sourceY:i,targetX:l,targetY:o}){const r=Math.abs(l-t)/2,u=l<t?l+r:l-r,d=Math.abs(o-i)/2,g=o<i?o+d:o-d;return[u,g,r,d]}function jC({sourceNode:t,targetNode:i,selected:l=!1,zIndex:o=0,elevateOnSelect:r=!1,zIndexMode:u="basic"}){if(u==="manual")return o;const d=r&&l?o+1e3:o,g=Math.max(t.parentId||r&&t.selected?t.internals.z:0,i.parentId||r&&i.selected?i.internals.z:0);return d+g}function zC({sourceNode:t,targetNode:i,width:l,height:o,transform:r}){const u=Jr(Vr(t),Vr(i));u.x===u.x2&&(u.x2+=1),u.y===u.y2&&(u.y2+=1);const d={x:-r[0]/r[2],y:-r[1]/r[2],width:l/r[2],height:o/r[2]};return Ro(d,Wr(u))>0}const RC=({source:t,sourceHandle:i,target:l,targetHandle:o})=>`xy-edge__${t}${i||""}-${l}${o||""}`,DC=(t,i)=>i.some(l=>l.source===t.source&&l.target===t.target&&(l.sourceHandle===t.sourceHandle||!l.sourceHandle&&!t.sourceHandle)&&(l.targetHandle===t.targetHandle||!l.targetHandle&&!t.targetHandle)),OC=(t,i,l={})=>{if(!t.source||!t.target)return i;const o=l.getEdgeId||RC;let r;return Sv(t)?r={...t}:r={...t,id:o(t)},DC(r,i)?i:(r.sourceHandle===null&&delete r.sourceHandle,r.targetHandle===null&&delete r.targetHandle,i.concat(r))};function Ov({sourceX:t,sourceY:i,targetX:l,targetY:o}){const[r,u,d,g]=Dv({sourceX:t,sourceY:i,targetX:l,targetY:o});return[`M ${t},${i}L ${l},${o}`,r,u,d,g]}const Cy={[me.Left]:{x:-1,y:0},[me.Right]:{x:1,y:0},[me.Top]:{x:0,y:-1},[me.Bottom]:{x:0,y:1}},HC=({source:t,sourcePosition:i=me.Bottom,target:l})=>i===me.Left||i===me.Right?t.x<l.x?{x:1,y:0}:{x:-1,y:0}:t.y<l.y?{x:0,y:1}:{x:0,y:-1},Ty=(t,i)=>Math.sqrt(Math.pow(i.x-t.x,2)+Math.pow(i.y-t.y,2));function IC({source:t,sourcePosition:i=me.Bottom,target:l,targetPosition:o=me.Top,center:r,offset:u,stepPosition:d}){const g=Cy[i],p=Cy[o],y={x:t.x+g.x*u,y:t.y+g.y*u},m={x:l.x+p.x*u,y:l.y+p.y*u},v=HC({source:y,sourcePosition:i,target:m}),x=v.x!==0?"x":"y",S=v[x];let w=[],j,E;const A={x:0,y:0},B={x:0,y:0},[,,C,_]=Dv({sourceX:t.x,sourceY:t.y,targetX:l.x,targetY:l.y});if(g[x]*p[x]===-1){x==="x"?(j=r.x??y.x+(m.x-y.x)*d,E=r.y??(y.y+m.y)/2):(j=r.x??(y.x+m.x)/2,E=r.y??y.y+(m.y-y.y)*d);const I=[{x:j,y:y.y},{x:j,y:m.y}],X=[{x:y.x,y:E},{x:m.x,y:E}];g[x]===S?w=x==="x"?I:X:w=x==="x"?X:I}else{const I=[{x:y.x,y:m.y}],X=[{x:m.x,y:y.y}];if(x==="x"?w=g.x===S?X:I:w=g.y===S?I:X,i===o){const D=Math.abs(t[x]-l[x]);if(D<=u){const Z=Math.min(u-1,u-D);g[x]===S?A[x]=(y[x]>t[x]?-1:1)*Z:B[x]=(m[x]>l[x]?-1:1)*Z}}if(i!==o){const D=x==="x"?"y":"x",Z=g[x]===p[D],M=y[D]>m[D],H=y[D]<m[D];(g[x]===1&&(!Z&&M||Z&&H)||g[x]!==1&&(!Z&&H||Z&&M))&&(w=x==="x"?I:X)}const ce={x:y.x+A.x,y:y.y+A.y},K={x:m.x+B.x,y:m.y+B.y},te=Math.max(Math.abs(ce.x-w[0].x),Math.abs(K.x-w[0].x)),ue=Math.max(Math.abs(ce.y-w[0].y),Math.abs(K.y-w[0].y));te>=ue?(j=(ce.x+K.x)/2,E=w[0].y):(j=w[0].x,E=(ce.y+K.y)/2)}const U={x:y.x+A.x,y:y.y+A.y},R={x:m.x+B.x,y:m.y+B.y};return[[t,...U.x!==w[0].x||U.y!==w[0].y?[U]:[],...w,...R.x!==w[w.length-1].x||R.y!==w[w.length-1].y?[R]:[],l],j,E,C,_]}function BC(t,i,l,o){const r=Math.min(Ty(t,i)/2,Ty(i,l)/2,o),{x:u,y:d}=i;if(t.x===u&&u===l.x||t.y===d&&d===l.y)return`L${u} ${d}`;if(t.y===d){const y=t.x<l.x?-1:1,m=t.y<l.y?1:-1;return`L ${u+r*y},${d}Q ${u},${d} ${u},${d+r*m}`}const g=t.x<l.x?1:-1,p=t.y<l.y?-1:1;return`L ${u},${d+r*p}Q ${u},${d} ${u+r*g},${d}`}function uf({sourceX:t,sourceY:i,sourcePosition:l=me.Bottom,targetX:o,targetY:r,targetPosition:u=me.Top,borderRadius:d=5,centerX:g,centerY:p,offset:y=20,stepPosition:m=.5}){const[v,x,S,w,j]=IC({source:{x:t,y:i},sourcePosition:l,target:{x:o,y:r},targetPosition:u,center:{x:g,y:p},offset:y,stepPosition:m});let E=`M${v[0].x} ${v[0].y}`;for(let A=1;A<v.length-1;A++)E+=BC(v[A-1],v[A],v[A+1],d);return E+=`L${v[v.length-1].x} ${v[v.length-1].y}`,[E,x,S,w,j]}function Ay(t){return t&&!!(t.internals.handleBounds||t.handles?.length)&&!!(t.measured.width||t.width||t.initialWidth)}function LC(t){const{sourceNode:i,targetNode:l}=t;if(!Ay(i)||!Ay(l))return null;const o=i.internals.handleBounds||My(i.handles),r=l.internals.handleBounds||My(l.handles),u=jy(o?.source??[],t.sourceHandle),d=jy(t.connectionMode===dl.Strict?r?.target??[]:(r?.target??[]).concat(r?.source??[]),t.targetHandle);if(!u||!d)return t.onError?.("008",pn.error008(u?"target":"source",{id:t.id,sourceHandle:t.sourceHandle,targetHandle:t.targetHandle})),null;const g=u?.position||me.Bottom,p=d?.position||me.Top,y=ri(i,u,g),m=ri(l,d,p);return{sourceX:y.x,sourceY:y.y,targetX:m.x,targetY:m.y,sourcePosition:g,targetPosition:p}}function My(t){if(!t)return null;const i=[],l=[];for(const o of t)o.width=o.width??1,o.height=o.height??1,o.type==="source"?i.push(o):o.type==="target"&&l.push(o);return{source:i,target:l}}function ri(t,i,l=me.Left,o=!1){const r=(i?.x??0)+t.internals.positionAbsolute.x,u=(i?.y??0)+t.internals.positionAbsolute.y,{width:d,height:g}=i??Xn(t);if(o)return{x:r+d/2,y:u+g/2};switch(i?.position??l){case me.Top:return{x:r+d/2,y:u};case me.Right:return{x:r+d,y:u+g/2};case me.Bottom:return{x:r+d/2,y:u+g};case me.Left:return{x:r,y:u+g/2}}}function jy(t,i){return t&&(i?t.find(l=>l.id===i):t[0])||null}function df(t,i){return t?typeof t=="string"?t:`${i?`${i}__`:""}${Object.keys(t).sort().map(o=>`${o}=${t[o]}`).join("&")}`:""}function kC(t,{id:i,defaultColor:l,defaultMarkerStart:o,defaultMarkerEnd:r}){const u=new Set;return t.reduce((d,g)=>([g.markerStart||o,g.markerEnd||r].forEach(p=>{if(p&&typeof p=="object"){const y=df(p,i);u.has(y)||(d.push({id:y,color:p.color||l,...p}),u.add(y))}}),d),[]).sort((d,g)=>d.id.localeCompare(g.id))}const Hv=1e3,UC=10,Mf={nodeOrigin:[0,0],nodeExtent:jo,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},qC={...Mf,checkEquality:!0};function jf(t,i){const l={...t};for(const o in i)i[o]!==void 0&&(l[o]=i[o]);return l}function GC(t,i,l){const o=jf(Mf,l);for(const r of t.values())if(r.parentId)Rf(r,t,i,o);else{const u=Lo(r,o.nodeOrigin),d=gl(r.extent)?r.extent:o.nodeExtent,g=si(u,d,Xn(r));r.internals.positionAbsolute=g}}function YC(t,i){if(!t.handles)return t.measured?i?.internals.handleBounds:void 0;const l=[],o=[];for(const r of t.handles){const u={id:r.id,width:r.width??1,height:r.height??1,nodeId:t.id,x:r.x,y:r.y,position:r.position,type:r.type};r.type==="source"?l.push(u):r.type==="target"&&o.push(u)}return{source:l,target:o}}function zf(t){return t==="manual"}function ff(t,i,l,o={}){const r=jf(qC,o),u={i:0},d=new Map(i),g=r?.elevateNodesOnSelect&&!zf(r.zIndexMode)?Hv:0;let p=t.length>0,y=!1;i.clear(),l.clear();for(const m of t){let v=d.get(m.id);if(r.checkEquality&&m===v?.internals.userNode)i.set(m.id,v);else{const x=Lo(m,r.nodeOrigin),S=gl(m.extent)?m.extent:r.nodeExtent,w=si(x,S,Xn(m));v={...r.defaults,...m,measured:{width:m.measured?.width,height:m.measured?.height},internals:{positionAbsolute:w,handleBounds:YC(m,v),z:Iv(m,g,r.zIndexMode),userNode:m}},i.set(m.id,v)}(v.measured===void 0||v.measured.width===void 0||v.measured.height===void 0)&&!v.hidden&&(p=!1),m.parentId&&Rf(v,i,l,o,u),y||=m.selected??!1}return{nodesInitialized:p,hasSelectedNodes:y}}function VC(t,i){if(!t.parentId)return;const l=i.get(t.parentId);l?l.set(t.id,t):i.set(t.parentId,new Map([[t.id,t]]))}function Rf(t,i,l,o,r){const{elevateNodesOnSelect:u,nodeOrigin:d,nodeExtent:g,zIndexMode:p}=jf(Mf,o),y=t.parentId,m=i.get(y);if(!m){console.warn(`Parent node ${y} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}VC(t,l),r&&!m.parentId&&m.internals.rootParentIndex===void 0&&p==="auto"&&(m.internals.rootParentIndex=++r.i,m.internals.z=m.internals.z+r.i*UC),r&&m.internals.rootParentIndex!==void 0&&(r.i=m.internals.rootParentIndex);const v=u&&!zf(p)?Hv:0,{x,y:S,z:w}=XC(t,m,d,g,v,p),{positionAbsolute:j}=t.internals,E=x!==j.x||S!==j.y;(E||w!==t.internals.z)&&i.set(t.id,{...t,internals:{...t.internals,positionAbsolute:E?{x,y:S}:j,z:w}})}function Iv(t,i,l){const o=an(t.zIndex)?t.zIndex:0;return zf(l)?o:o+(t.selected?i:0)}function XC(t,i,l,o,r,u){const{x:d,y:g}=i.internals.positionAbsolute,p=Xn(t),y=Lo(t,l),m=gl(t.extent)?si(y,t.extent,p):y;let v=si({x:d+m.x,y:g+m.y},o,p);t.extent==="parent"&&(v=Nv(v,p,i));const x=Iv(t,r,u),S=i.internals.z??0;return{x:v.x,y:v.y,z:S>=x?S+1:x}}function Df(t,i,l,o=[0,0]){const r=[],u=new Map;for(const d of t){const g=i.get(d.parentId);if(!g)continue;const p=u.get(d.parentId)?.expandedRect??hl(g),y=Ev(p,d.rect);u.set(d.parentId,{expandedRect:y,parent:g})}return u.size>0&&u.forEach(({expandedRect:d,parent:g},p)=>{const y=g.internals.positionAbsolute,m=Xn(g),v=g.origin??o,x=d.x<y.x?Math.round(Math.abs(y.x-d.x)):0,S=d.y<y.y?Math.round(Math.abs(y.y-d.y)):0,w=Math.max(m.width,Math.round(d.width)),j=Math.max(m.height,Math.round(d.height)),E=(w-m.width)*v[0],A=(j-m.height)*v[1];(x>0||S>0||E||A)&&(r.push({id:p,type:"position",position:{x:g.position.x-x+E,y:g.position.y-S+A}}),l.get(p)?.forEach(B=>{t.some(C=>C.id===B.id)||r.push({id:B.id,type:"position",position:{x:B.position.x+x,y:B.position.y+S}})})),(m.width<d.width||m.height<d.height||x||S)&&r.push({id:p,type:"dimensions",setAttributes:!0,dimensions:{width:w+(x?v[0]*x-E:0),height:j+(S?v[1]*S-A:0)}})}),r}function $C(t,i,l,o,r,u,d){const g=o?.querySelector(".xyflow__viewport");let p=!1;if(!g)return{changes:[],updatedInternals:p};const y=[],m=window.getComputedStyle(g),{m22:v}=new window.DOMMatrixReadOnly(m.transform),x=[];for(const S of t.values()){const w=i.get(S.id);if(!w)continue;if(w.hidden){i.set(w.id,{...w,internals:{...w.internals,handleBounds:void 0}}),p=!0;continue}const j=Af(S.nodeElement),E=w.measured.width!==j.width||w.measured.height!==j.height;if(!!(j.width&&j.height&&(E||!w.internals.handleBounds||S.force))){const B=S.nodeElement.getBoundingClientRect(),C=gl(w.extent)?w.extent:u;let{positionAbsolute:_}=w.internals;w.parentId&&w.extent==="parent"?_=Nv(_,j,i.get(w.parentId)):C&&(_=si(_,C,j));const U={...w,measured:j,internals:{...w.internals,positionAbsolute:_,handleBounds:{source:_y("source",S.nodeElement,B,v,w.id),target:_y("target",S.nodeElement,B,v,w.id)}}};i.set(w.id,U),w.parentId&&Rf(U,i,l,{nodeOrigin:r,zIndexMode:d}),p=!0,E&&(y.push({id:w.id,type:"dimensions",dimensions:j}),w.expandParent&&w.parentId&&x.push({id:w.id,parentId:w.parentId,rect:hl(U,r)}))}}if(x.length>0){const S=Df(x,i,l,r);y.push(...S)}return{changes:y,updatedInternals:p}}async function ZC({delta:t,panZoom:i,transform:l,translateExtent:o,width:r,height:u}){if(!i||!t.x&&!t.y)return Promise.resolve(!1);const d=await i.setViewportConstrained({x:l[0]+t.x,y:l[1]+t.y,zoom:l[2]},[[0,0],[r,u]],o),g=!!d&&(d.x!==l[0]||d.y!==l[1]||d.k!==l[2]);return Promise.resolve(g)}function zy(t,i,l,o,r,u){let d=r;const g=o.get(d)||new Map;o.set(d,g.set(l,i)),d=`${r}-${t}`;const p=o.get(d)||new Map;if(o.set(d,p.set(l,i)),u){d=`${r}-${t}-${u}`;const y=o.get(d)||new Map;o.set(d,y.set(l,i))}}function Bv(t,i,l){t.clear(),i.clear();for(const o of l){const{source:r,target:u,sourceHandle:d=null,targetHandle:g=null}=o,p={edgeId:o.id,source:r,target:u,sourceHandle:d,targetHandle:g},y=`${r}-${d}--${u}-${g}`,m=`${u}-${g}--${r}-${d}`;zy("source",p,m,t,r,d),zy("target",p,y,t,u,g),i.set(o.id,o)}}function Lv(t,i){if(!t.parentId)return!1;const l=i.get(t.parentId);return l?l.selected?!0:Lv(l,i):!1}function Ry(t,i,l){let o=t;do{if(o?.matches?.(i))return!0;if(o===l)return!1;o=o?.parentElement}while(o);return!1}function KC(t,i,l,o){const r=new Map;for(const[u,d]of t)if((d.selected||d.id===o)&&(!d.parentId||!Lv(d,t))&&(d.draggable||i&&typeof d.draggable>"u")){const g=t.get(u);g&&r.set(u,{id:u,position:g.position||{x:0,y:0},distance:{x:l.x-g.internals.positionAbsolute.x,y:l.y-g.internals.positionAbsolute.y},extent:g.extent,parentId:g.parentId,origin:g.origin,expandParent:g.expandParent,internals:{positionAbsolute:g.internals.positionAbsolute||{x:0,y:0}},measured:{width:g.measured.width??0,height:g.measured.height??0}})}return r}function Gd({nodeId:t,dragItems:i,nodeLookup:l,dragging:o=!0}){const r=[];for(const[d,g]of i){const p=l.get(d)?.internals.userNode;p&&r.push({...p,position:g.position,dragging:o})}if(!t)return[r[0],r];const u=l.get(t)?.internals.userNode;return[u?{...u,position:i.get(t)?.position||u.position,dragging:o}:r[0],r]}function QC({dragItems:t,snapGrid:i,x:l,y:o}){const r=t.values().next().value;if(!r)return null;const u={x:l-r.distance.x,y:o-r.distance.y},d=Uo(u,i);return{x:d.x-u.x,y:d.y-u.y}}function FC({onNodeMouseDown:t,getStoreItems:i,onDragStart:l,onDrag:o,onDragStop:r}){let u={x:null,y:null},d=0,g=new Map,p=!1,y={x:0,y:0},m=null,v=!1,x=null,S=!1,w=!1,j=null;function E({noDragClassName:B,handleSelector:C,domNode:_,isSelectable:U,nodeId:R,nodeClickDistance:z=0}){x=kt(_);function I({x:te,y:ue}){const{nodeLookup:D,nodeExtent:Z,snapGrid:M,snapToGrid:H,nodeOrigin:q,onNodeDrag:k,onSelectionDrag:J,onError:T,updateNodePositions:L}=i();u={x:te,y:ue};let ne=!1;const ae=g.size>1,V=ae&&Z?cf(ko(g)):null,se=ae&&H?QC({dragItems:g,snapGrid:M,x:te,y:ue}):null;for(const[de,le]of g){if(!D.has(de))continue;let fe={x:te-le.distance.x,y:ue-le.distance.y};H&&(fe=se?{x:Math.round(fe.x+se.x),y:Math.round(fe.y+se.y)}:Uo(fe,M));let be=null;if(ae&&Z&&!le.extent&&V){const{positionAbsolute:we}=le.internals,je=we.x-V.x+Z[0][0],qe=we.x+le.measured.width-V.x2+Z[1][0],Le=we.y-V.y+Z[0][1],ut=we.y+le.measured.height-V.y2+Z[1][1];be=[[je,Le],[qe,ut]]}const{position:_e,positionAbsolute:ye}=wv({nodeId:de,nextPosition:fe,nodeLookup:D,nodeExtent:be||Z,nodeOrigin:q,onError:T});ne=ne||le.position.x!==_e.x||le.position.y!==_e.y,le.position=_e,le.internals.positionAbsolute=ye}if(w=w||ne,!!ne&&(L(g,!0),j&&(o||k||!R&&J))){const[de,le]=Gd({nodeId:R,dragItems:g,nodeLookup:D});o?.(j,g,de,le),k?.(j,de,le),R||J?.(j,le)}}async function X(){if(!m)return;const{transform:te,panBy:ue,autoPanSpeed:D,autoPanOnNodeDrag:Z}=i();if(!Z){p=!1,cancelAnimationFrame(d);return}const[M,H]=_v(y,m,D);(M!==0||H!==0)&&(u.x=(u.x??0)-M/te[2],u.y=(u.y??0)-H/te[2],await ue({x:M,y:H})&&I(u)),d=requestAnimationFrame(X)}function ce(te){const{nodeLookup:ue,multiSelectionActive:D,nodesDraggable:Z,transform:M,snapGrid:H,snapToGrid:q,selectNodesOnDrag:k,onNodeDragStart:J,onSelectionDragStart:T,unselectNodesAndEdges:L}=i();v=!0,(!k||!U)&&!D&&R&&(ue.get(R)?.selected||L()),U&&k&&R&&t?.(R);const ne=Eo(te.sourceEvent,{transform:M,snapGrid:H,snapToGrid:q,containerBounds:m});if(u=ne,g=KC(ue,Z,ne,R),g.size>0&&(l||J||!R&&T)){const[ae,V]=Gd({nodeId:R,dragItems:g,nodeLookup:ue});l?.(te.sourceEvent,g,ae,V),J?.(te.sourceEvent,ae,V),R||T?.(te.sourceEvent,V)}}const K=tv().clickDistance(z).on("start",te=>{const{domNode:ue,nodeDragThreshold:D,transform:Z,snapGrid:M,snapToGrid:H}=i();m=ue?.getBoundingClientRect()||null,S=!1,w=!1,j=te.sourceEvent,D===0&&ce(te),u=Eo(te.sourceEvent,{transform:Z,snapGrid:M,snapToGrid:H,containerBounds:m}),y=ln(te.sourceEvent,m)}).on("drag",te=>{const{autoPanOnNodeDrag:ue,transform:D,snapGrid:Z,snapToGrid:M,nodeDragThreshold:H,nodeLookup:q}=i(),k=Eo(te.sourceEvent,{transform:D,snapGrid:Z,snapToGrid:M,containerBounds:m});if(j=te.sourceEvent,(te.sourceEvent.type==="touchmove"&&te.sourceEvent.touches.length>1||R&&!q.has(R))&&(S=!0),!S){if(!p&&ue&&v&&(p=!0,X()),!v){const J=ln(te.sourceEvent,m),T=J.x-y.x,L=J.y-y.y;Math.sqrt(T*T+L*L)>H&&ce(te)}(u.x!==k.xSnapped||u.y!==k.ySnapped)&&g&&v&&(y=ln(te.sourceEvent,m),I(k))}}).on("end",te=>{if(!(!v||S)&&(p=!1,v=!1,cancelAnimationFrame(d),g.size>0)){const{nodeLookup:ue,updateNodePositions:D,onNodeDragStop:Z,onSelectionDragStop:M}=i();if(w&&(D(g,!1),w=!1),r||Z||!R&&M){const[H,q]=Gd({nodeId:R,dragItems:g,nodeLookup:ue,dragging:!1});r?.(te.sourceEvent,g,H,q),Z?.(te.sourceEvent,H,q),R||M?.(te.sourceEvent,q)}}}).filter(te=>{const ue=te.target;return!te.button&&(!B||!Ry(ue,`.${B}`,_))&&(!C||Ry(ue,C,_))});x.call(K)}function A(){x?.on(".drag",null)}return{update:E,destroy:A}}function PC(t,i,l){const o=[],r={x:t.x-l,y:t.y-l,width:l*2,height:l*2};for(const u of i.values())Ro(r,hl(u))>0&&o.push(u);return o}const JC=250;function WC(t,i,l,o){let r=[],u=1/0;const d=PC(t,l,i+JC);for(const g of d){const p=[...g.internals.handleBounds?.source??[],...g.internals.handleBounds?.target??[]];for(const y of p){if(o.nodeId===y.nodeId&&o.type===y.type&&o.id===y.id)continue;const{x:m,y:v}=ri(g,y,y.position,!0),x=Math.sqrt(Math.pow(m-t.x,2)+Math.pow(v-t.y,2));x>i||(x<u?(r=[{...y,x:m,y:v}],u=x):x===u&&r.push({...y,x:m,y:v}))}}if(!r.length)return null;if(r.length>1){const g=o.type==="source"?"target":"source";return r.find(p=>p.type===g)??r[0]}return r[0]}function kv(t,i,l,o,r,u=!1){const d=o.get(t);if(!d)return null;const g=r==="strict"?d.internals.handleBounds?.[i]:[...d.internals.handleBounds?.source??[],...d.internals.handleBounds?.target??[]],p=(l?g?.find(y=>y.id===l):g?.[0])??null;return p&&u?{...p,...ri(d,p,p.position,!0)}:p}function Uv(t,i){return t||(i?.classList.contains("target")?"target":i?.classList.contains("source")?"source":null)}function eT(t,i){let l=null;return i?l=!0:t&&!i&&(l=!1),l}const qv=()=>!0;function tT(t,{connectionMode:i,connectionRadius:l,handleId:o,nodeId:r,edgeUpdaterType:u,isTarget:d,domNode:g,nodeLookup:p,lib:y,autoPanOnConnect:m,flowId:v,panBy:x,cancelConnection:S,onConnectStart:w,onConnect:j,onConnectEnd:E,isValidConnection:A=qv,onReconnectEnd:B,updateConnection:C,getTransform:_,getFromHandle:U,autoPanSpeed:R,dragThreshold:z=1,handleDomNode:I}){const X=Av(t.target);let ce=0,K;const{x:te,y:ue}=ln(t),D=Uv(u,I),Z=g?.getBoundingClientRect();let M=!1;if(!Z||!D)return;const H=kv(r,D,o,p,i);if(!H)return;let q=ln(t,Z),k=!1,J=null,T=!1,L=null;function ne(){if(!m||!Z)return;const[_e,ye]=_v(q,Z,R);x({x:_e,y:ye}),ce=requestAnimationFrame(ne)}const ae={...H,nodeId:r,type:D,position:H.position},V=p.get(r);let de={inProgress:!0,isValid:null,from:ri(V,ae,me.Left,!0),fromHandle:ae,fromPosition:ae.position,fromNode:V,to:q,toHandle:null,toPosition:by[ae.position],toNode:null,pointer:q};function le(){M=!0,C(de),w?.(t,{nodeId:r,handleId:o,handleType:D})}z===0&&le();function fe(_e){if(!M){const{x:ut,y:Qt}=ln(_e),zt=ut-te,Ft=Qt-ue;if(!(zt*zt+Ft*Ft>z*z))return;le()}if(!U()||!ae){be(_e);return}const ye=_();q=ln(_e,Z),K=WC(qo(q,ye,!1,[1,1]),l,p,ae),k||(ne(),k=!0);const we=Gv(_e,{handle:K,connectionMode:i,fromNodeId:r,fromHandleId:o,fromType:d?"target":"source",isValidConnection:A,doc:X,lib:y,flowId:v,nodeLookup:p});L=we.handleDomNode,J=we.connection,T=eT(!!K,we.isValid);const je=p.get(r),qe=je?ri(je,ae,me.Left,!0):de.from,Le={...de,from:qe,isValid:T,to:we.toHandle&&T?Xr({x:we.toHandle.x,y:we.toHandle.y},ye):q,toHandle:we.toHandle,toPosition:T&&we.toHandle?we.toHandle.position:by[ae.position],toNode:we.toHandle?p.get(we.toHandle.nodeId):null,pointer:q};C(Le),de=Le}function be(_e){if(!("touches"in _e&&_e.touches.length>0)){if(M){(K||L)&&J&&T&&j?.(J);const{inProgress:ye,...we}=de,je={...we,toPosition:de.toHandle?de.toPosition:null};E?.(_e,je),u&&B?.(_e,je)}S(),cancelAnimationFrame(ce),k=!1,T=!1,J=null,L=null,X.removeEventListener("mousemove",fe),X.removeEventListener("mouseup",be),X.removeEventListener("touchmove",fe),X.removeEventListener("touchend",be)}}X.addEventListener("mousemove",fe),X.addEventListener("mouseup",be),X.addEventListener("touchmove",fe),X.addEventListener("touchend",be)}function Gv(t,{handle:i,connectionMode:l,fromNodeId:o,fromHandleId:r,fromType:u,doc:d,lib:g,flowId:p,isValidConnection:y=qv,nodeLookup:m}){const v=u==="target",x=i?d.querySelector(`.${g}-flow__handle[data-id="${p}-${i?.nodeId}-${i?.id}-${i?.type}"]`):null,{x:S,y:w}=ln(t),j=d.elementFromPoint(S,w),E=j?.classList.contains(`${g}-flow__handle`)?j:x,A={handleDomNode:E,isValid:!1,connection:null,toHandle:null};if(E){const B=Uv(void 0,E),C=E.getAttribute("data-nodeid"),_=E.getAttribute("data-handleid"),U=E.classList.contains("connectable"),R=E.classList.contains("connectableend");if(!C||!B)return A;const z={source:v?C:o,sourceHandle:v?_:r,target:v?o:C,targetHandle:v?r:_};A.connection=z;const X=U&&R&&(l===dl.Strict?v&&B==="source"||!v&&B==="target":C!==o||_!==r);A.isValid=X&&y(z),A.toHandle=kv(C,B,_,m,l,!0)}return A}const hf={onPointerDown:tT,isValid:Gv};function nT({domNode:t,panZoom:i,getTransform:l,getViewScale:o}){const r=kt(t);function u({translateExtent:g,width:p,height:y,zoomStep:m=1,pannable:v=!0,zoomable:x=!0,inversePan:S=!1}){const w=C=>{if(C.sourceEvent.type!=="wheel"||!i)return;const _=l(),U=C.sourceEvent.ctrlKey&&Do()?10:1,R=-C.sourceEvent.deltaY*(C.sourceEvent.deltaMode===1?.05:C.sourceEvent.deltaMode?1:.002)*m,z=_[2]*Math.pow(2,R*U);i.scaleTo(z)};let j=[0,0];const E=C=>{(C.sourceEvent.type==="mousedown"||C.sourceEvent.type==="touchstart")&&(j=[C.sourceEvent.clientX??C.sourceEvent.touches[0].clientX,C.sourceEvent.clientY??C.sourceEvent.touches[0].clientY])},A=C=>{const _=l();if(C.sourceEvent.type!=="mousemove"&&C.sourceEvent.type!=="touchmove"||!i)return;const U=[C.sourceEvent.clientX??C.sourceEvent.touches[0].clientX,C.sourceEvent.clientY??C.sourceEvent.touches[0].clientY],R=[U[0]-j[0],U[1]-j[1]];j=U;const z=o()*Math.max(_[2],Math.log(_[2]))*(S?-1:1),I={x:_[0]-R[0]*z,y:_[1]-R[1]*z},X=[[0,0],[p,y]];i.setViewportConstrained({x:I.x,y:I.y,zoom:_[2]},X,g)},B=pv().on("start",E).on("zoom",v?A:null).on("zoom.wheel",x?w:null);r.call(B,{})}function d(){r.on("zoom",null)}return{update:u,destroy:d,pointer:tn}}const ec=t=>({x:t.x,y:t.y,zoom:t.k}),Yd=({x:t,y:i,zoom:l})=>Pr.translate(t,i).scale(l),al=(t,i)=>t.target.closest(`.${i}`),Yv=(t,i)=>i===2&&Array.isArray(t)&&t.includes(2),aT=t=>((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2,Vd=(t,i=0,l=aT,o=()=>{})=>{const r=typeof i=="number"&&i>0;return r||o(),r?t.transition().duration(i).ease(l).on("end",o):t},Vv=t=>{const i=t.ctrlKey&&Do()?10:1;return-t.deltaY*(t.deltaMode===1?.05:t.deltaMode?1:.002)*i};function iT({zoomPanValues:t,noWheelClassName:i,d3Selection:l,d3Zoom:o,panOnScrollMode:r,panOnScrollSpeed:u,zoomOnPinch:d,onPanZoomStart:g,onPanZoom:p,onPanZoomEnd:y}){return m=>{if(al(m,i))return m.ctrlKey&&m.preventDefault(),!1;m.preventDefault(),m.stopImmediatePropagation();const v=l.property("__zoom").k||1;if(m.ctrlKey&&d){const E=tn(m),A=Vv(m),B=v*Math.pow(2,A);o.scaleTo(l,B,E,m);return}const x=m.deltaMode===1?20:1;let S=r===ii.Vertical?0:m.deltaX*x,w=r===ii.Horizontal?0:m.deltaY*x;!Do()&&m.shiftKey&&r!==ii.Vertical&&(S=m.deltaY*x,w=0),o.translateBy(l,-(S/v)*u,-(w/v)*u,{internal:!0});const j=ec(l.property("__zoom"));clearTimeout(t.panScrollTimeout),t.isPanScrolling?(p?.(m,j),t.panScrollTimeout=setTimeout(()=>{y?.(m,j),t.isPanScrolling=!1},150)):(t.isPanScrolling=!0,g?.(m,j))}}function lT({noWheelClassName:t,preventScrolling:i,d3ZoomHandler:l}){return function(o,r){const u=o.type==="wheel",d=!i&&u&&!o.ctrlKey,g=al(o,t);if(o.ctrlKey&&u&&g&&o.preventDefault(),d||g)return null;o.preventDefault(),l.call(this,o,r)}}function oT({zoomPanValues:t,onDraggingChange:i,onPanZoomStart:l}){return o=>{if(o.sourceEvent?.internal)return;const r=ec(o.transform);t.mouseButton=o.sourceEvent?.button||0,t.isZoomingOrPanning=!0,t.prevViewport=r,o.sourceEvent?.type==="mousedown"&&i(!0),l&&l?.(o.sourceEvent,r)}}function sT({zoomPanValues:t,panOnDrag:i,onPaneContextMenu:l,onTransformChange:o,onPanZoom:r}){return u=>{t.usedRightMouseButton=!!(l&&Yv(i,t.mouseButton??0)),u.sourceEvent?.sync||o([u.transform.x,u.transform.y,u.transform.k]),r&&!u.sourceEvent?.internal&&r?.(u.sourceEvent,ec(u.transform))}}function rT({zoomPanValues:t,panOnDrag:i,panOnScroll:l,onDraggingChange:o,onPanZoomEnd:r,onPaneContextMenu:u}){return d=>{if(!d.sourceEvent?.internal&&(t.isZoomingOrPanning=!1,u&&Yv(i,t.mouseButton??0)&&!t.usedRightMouseButton&&d.sourceEvent&&u(d.sourceEvent),t.usedRightMouseButton=!1,o(!1),r)){const g=ec(d.transform);t.prevViewport=g,clearTimeout(t.timerId),t.timerId=setTimeout(()=>{r?.(d.sourceEvent,g)},l?150:0)}}}function cT({zoomActivationKeyPressed:t,zoomOnScroll:i,zoomOnPinch:l,panOnDrag:o,panOnScroll:r,zoomOnDoubleClick:u,userSelectionActive:d,noWheelClassName:g,noPanClassName:p,lib:y,connectionInProgress:m}){return v=>{const x=t||i,S=l&&v.ctrlKey,w=v.type==="wheel";if(v.button===1&&v.type==="mousedown"&&(al(v,`${y}-flow__node`)||al(v,`${y}-flow__edge`)))return!0;if(!o&&!x&&!r&&!u&&!l||d||m&&!w||al(v,g)&&w||al(v,p)&&(!w||r&&w&&!t)||!l&&v.ctrlKey&&w)return!1;if(!l&&v.type==="touchstart"&&v.touches?.length>1)return v.preventDefault(),!1;if(!x&&!r&&!S&&w||!o&&(v.type==="mousedown"||v.type==="touchstart")||Array.isArray(o)&&!o.includes(v.button)&&v.type==="mousedown")return!1;const j=Array.isArray(o)&&o.includes(v.button)||!v.button||v.button<=1;return(!v.ctrlKey||w)&&j}}function uT({domNode:t,minZoom:i,maxZoom:l,translateExtent:o,viewport:r,onPanZoom:u,onPanZoomStart:d,onPanZoomEnd:g,onDraggingChange:p}){const y={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},m=t.getBoundingClientRect(),v=pv().scaleExtent([i,l]).translateExtent(o),x=kt(t).call(v);B({x:r.x,y:r.y,zoom:fl(r.zoom,i,l)},[[0,0],[m.width,m.height]],o);const S=x.on("wheel.zoom"),w=x.on("dblclick.zoom");v.wheelDelta(Vv);function j(K,te){return x?new Promise(ue=>{v?.interpolate(te?.interpolate==="linear"?_o:jr).transform(Vd(x,te?.duration,te?.ease,()=>ue(!0)),K)}):Promise.resolve(!1)}function E({noWheelClassName:K,noPanClassName:te,onPaneContextMenu:ue,userSelectionActive:D,panOnScroll:Z,panOnDrag:M,panOnScrollMode:H,panOnScrollSpeed:q,preventScrolling:k,zoomOnPinch:J,zoomOnScroll:T,zoomOnDoubleClick:L,zoomActivationKeyPressed:ne,lib:ae,onTransformChange:V,connectionInProgress:se,paneClickDistance:de,selectionOnDrag:le}){D&&!y.isZoomingOrPanning&&A();const fe=Z&&!ne&&!D;v.clickDistance(le?1/0:!an(de)||de<0?0:de);const be=fe?iT({zoomPanValues:y,noWheelClassName:K,d3Selection:x,d3Zoom:v,panOnScrollMode:H,panOnScrollSpeed:q,zoomOnPinch:J,onPanZoomStart:d,onPanZoom:u,onPanZoomEnd:g}):lT({noWheelClassName:K,preventScrolling:k,d3ZoomHandler:S});if(x.on("wheel.zoom",be,{passive:!1}),!D){const ye=oT({zoomPanValues:y,onDraggingChange:p,onPanZoomStart:d});v.on("start",ye);const we=sT({zoomPanValues:y,panOnDrag:M,onPaneContextMenu:!!ue,onPanZoom:u,onTransformChange:V});v.on("zoom",we);const je=rT({zoomPanValues:y,panOnDrag:M,panOnScroll:Z,onPaneContextMenu:ue,onPanZoomEnd:g,onDraggingChange:p});v.on("end",je)}const _e=cT({zoomActivationKeyPressed:ne,panOnDrag:M,zoomOnScroll:T,panOnScroll:Z,zoomOnDoubleClick:L,zoomOnPinch:J,userSelectionActive:D,noPanClassName:te,noWheelClassName:K,lib:ae,connectionInProgress:se});v.filter(_e),L?x.on("dblclick.zoom",w):x.on("dblclick.zoom",null)}function A(){v.on("zoom",null)}async function B(K,te,ue){const D=Yd(K),Z=v?.constrain()(D,te,ue);return Z&&await j(Z),new Promise(M=>M(Z))}async function C(K,te){const ue=Yd(K);return await j(ue,te),new Promise(D=>D(ue))}function _(K){if(x){const te=Yd(K),ue=x.property("__zoom");(ue.k!==K.zoom||ue.x!==K.x||ue.y!==K.y)&&v?.transform(x,te,null,{sync:!0})}}function U(){const K=x?mv(x.node()):{x:0,y:0,k:1};return{x:K.x,y:K.y,zoom:K.k}}function R(K,te){return x?new Promise(ue=>{v?.interpolate(te?.interpolate==="linear"?_o:jr).scaleTo(Vd(x,te?.duration,te?.ease,()=>ue(!0)),K)}):Promise.resolve(!1)}function z(K,te){return x?new Promise(ue=>{v?.interpolate(te?.interpolate==="linear"?_o:jr).scaleBy(Vd(x,te?.duration,te?.ease,()=>ue(!0)),K)}):Promise.resolve(!1)}function I(K){v?.scaleExtent(K)}function X(K){v?.translateExtent(K)}function ce(K){const te=!an(K)||K<0?0:K;v?.clickDistance(te)}return{update:E,destroy:A,setViewport:C,setViewportConstrained:B,getViewport:U,scaleTo:R,scaleBy:z,setScaleExtent:I,setTranslateExtent:X,syncViewport:_,setClickDistance:ce}}var ml;(function(t){t.Line="line",t.Handle="handle"})(ml||(ml={}));function dT({width:t,prevWidth:i,height:l,prevHeight:o,affectsX:r,affectsY:u}){const d=t-i,g=l-o,p=[d>0?1:d<0?-1:0,g>0?1:g<0?-1:0];return d&&r&&(p[0]=p[0]*-1),g&&u&&(p[1]=p[1]*-1),p}function Dy(t){const i=t.includes("right")||t.includes("left"),l=t.includes("bottom")||t.includes("top"),o=t.includes("left"),r=t.includes("top");return{isHorizontal:i,isVertical:l,affectsX:o,affectsY:r}}function wa(t,i){return Math.max(0,i-t)}function Na(t,i){return Math.max(0,t-i)}function wr(t,i,l){return Math.max(0,i-t,t-l)}function Oy(t,i){return t?!i:i}function fT(t,i,l,o,r,u,d,g){let{affectsX:p,affectsY:y}=i;const{isHorizontal:m,isVertical:v}=i,x=m&&v,{xSnapped:S,ySnapped:w}=l,{minWidth:j,maxWidth:E,minHeight:A,maxHeight:B}=o,{x:C,y:_,width:U,height:R,aspectRatio:z}=t;let I=Math.floor(m?S-t.pointerX:0),X=Math.floor(v?w-t.pointerY:0);const ce=U+(p?-I:I),K=R+(y?-X:X),te=-u[0]*U,ue=-u[1]*R;let D=wr(ce,j,E),Z=wr(K,A,B);if(d){let q=0,k=0;p&&I<0?q=wa(C+I+te,d[0][0]):!p&&I>0&&(q=Na(C+ce+te,d[1][0])),y&&X<0?k=wa(_+X+ue,d[0][1]):!y&&X>0&&(k=Na(_+K+ue,d[1][1])),D=Math.max(D,q),Z=Math.max(Z,k)}if(g){let q=0,k=0;p&&I>0?q=Na(C+I,g[0][0]):!p&&I<0&&(q=wa(C+ce,g[1][0])),y&&X>0?k=Na(_+X,g[0][1]):!y&&X<0&&(k=wa(_+K,g[1][1])),D=Math.max(D,q),Z=Math.max(Z,k)}if(r){if(m){const q=wr(ce/z,A,B)*z;if(D=Math.max(D,q),d){let k=0;!p&&!y||p&&!y&&x?k=Na(_+ue+ce/z,d[1][1])*z:k=wa(_+ue+(p?I:-I)/z,d[0][1])*z,D=Math.max(D,k)}if(g){let k=0;!p&&!y||p&&!y&&x?k=wa(_+ce/z,g[1][1])*z:k=Na(_+(p?I:-I)/z,g[0][1])*z,D=Math.max(D,k)}}if(v){const q=wr(K*z,j,E)/z;if(Z=Math.max(Z,q),d){let k=0;!p&&!y||y&&!p&&x?k=Na(C+K*z+te,d[1][0])/z:k=wa(C+(y?X:-X)*z+te,d[0][0])/z,Z=Math.max(Z,k)}if(g){let k=0;!p&&!y||y&&!p&&x?k=wa(C+K*z,g[1][0])/z:k=Na(C+(y?X:-X)*z,g[0][0])/z,Z=Math.max(Z,k)}}}X=X+(X<0?Z:-Z),I=I+(I<0?D:-D),r&&(x?ce>K*z?X=(Oy(p,y)?-I:I)/z:I=(Oy(p,y)?-X:X)*z:m?(X=I/z,y=p):(I=X*z,p=y));const M=p?C+I:C,H=y?_+X:_;return{width:U+(p?-I:I),height:R+(y?-X:X),x:u[0]*I*(p?-1:1)+M,y:u[1]*X*(y?-1:1)+H}}const Xv={width:0,height:0,x:0,y:0},hT={...Xv,pointerX:0,pointerY:0,aspectRatio:1};function gT(t){return[[0,0],[t.measured.width,t.measured.height]]}function mT(t,i,l){const o=i.position.x+t.position.x,r=i.position.y+t.position.y,u=t.measured.width??0,d=t.measured.height??0,g=l[0]*u,p=l[1]*d;return[[o-g,r-p],[o+u-g,r+d-p]]}function pT({domNode:t,nodeId:i,getStoreItems:l,onChange:o,onEnd:r}){const u=kt(t);let d={controlDirection:Dy("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function g({controlPosition:y,boundaries:m,keepAspectRatio:v,resizeDirection:x,onResizeStart:S,onResize:w,onResizeEnd:j,shouldResize:E}){let A={...Xv},B={...hT};d={boundaries:m,resizeDirection:x,keepAspectRatio:v,controlDirection:Dy(y)};let C,_=null,U=[],R,z,I,X=!1;const ce=tv().on("start",K=>{const{nodeLookup:te,transform:ue,snapGrid:D,snapToGrid:Z,nodeOrigin:M,paneDomNode:H}=l();if(C=te.get(i),!C)return;_=H?.getBoundingClientRect()??null;const{xSnapped:q,ySnapped:k}=Eo(K.sourceEvent,{transform:ue,snapGrid:D,snapToGrid:Z,containerBounds:_});A={width:C.measured.width??0,height:C.measured.height??0,x:C.position.x??0,y:C.position.y??0},B={...A,pointerX:q,pointerY:k,aspectRatio:A.width/A.height},R=void 0,C.parentId&&(C.extent==="parent"||C.expandParent)&&(R=te.get(C.parentId),z=R&&C.extent==="parent"?gT(R):void 0),U=[],I=void 0;for(const[J,T]of te)if(T.parentId===i&&(U.push({id:J,position:{...T.position},extent:T.extent}),T.extent==="parent"||T.expandParent)){const L=mT(T,C,T.origin??M);I?I=[[Math.min(L[0][0],I[0][0]),Math.min(L[0][1],I[0][1])],[Math.max(L[1][0],I[1][0]),Math.max(L[1][1],I[1][1])]]:I=L}S?.(K,{...A})}).on("drag",K=>{const{transform:te,snapGrid:ue,snapToGrid:D,nodeOrigin:Z}=l(),M=Eo(K.sourceEvent,{transform:te,snapGrid:ue,snapToGrid:D,containerBounds:_}),H=[];if(!C)return;const{x:q,y:k,width:J,height:T}=A,L={},ne=C.origin??Z,{width:ae,height:V,x:se,y:de}=fT(B,d.controlDirection,M,d.boundaries,d.keepAspectRatio,ne,z,I),le=ae!==J,fe=V!==T,be=se!==q&&le,_e=de!==k&&fe;if(!be&&!_e&&!le&&!fe)return;if((be||_e||ne[0]===1||ne[1]===1)&&(L.x=be?se:A.x,L.y=_e?de:A.y,A.x=L.x,A.y=L.y,U.length>0)){const qe=se-q,Le=de-k;for(const ut of U)ut.position={x:ut.position.x-qe+ne[0]*(ae-J),y:ut.position.y-Le+ne[1]*(V-T)},H.push(ut)}if((le||fe)&&(L.width=le&&(!d.resizeDirection||d.resizeDirection==="horizontal")?ae:A.width,L.height=fe&&(!d.resizeDirection||d.resizeDirection==="vertical")?V:A.height,A.width=L.width,A.height=L.height),R&&C.expandParent){const qe=ne[0]*(L.width??0);L.x&&L.x<qe&&(A.x=qe,B.x=B.x-(L.x-qe));const Le=ne[1]*(L.height??0);L.y&&L.y<Le&&(A.y=Le,B.y=B.y-(L.y-Le))}const ye=dT({width:A.width,prevWidth:J,height:A.height,prevHeight:T,affectsX:d.controlDirection.affectsX,affectsY:d.controlDirection.affectsY}),we={...A,direction:ye};E?.(K,we)!==!1&&(X=!0,w?.(K,we),o(L,H))}).on("end",K=>{X&&(j?.(K,{...A}),r?.({...A}),X=!1)});u.call(ce)}function p(){u.on(".drag",null)}return{update:g,destroy:p}}var Xd={exports:{}},$d={},Zd={exports:{}},Kd={};var Hy;function yT(){if(Hy)return Kd;Hy=1;var t=Ho();function i(v,x){return v===x&&(v!==0||1/v===1/x)||v!==v&&x!==x}var l=typeof Object.is=="function"?Object.is:i,o=t.useState,r=t.useEffect,u=t.useLayoutEffect,d=t.useDebugValue;function g(v,x){var S=x(),w=o({inst:{value:S,getSnapshot:x}}),j=w[0].inst,E=w[1];return u(function(){j.value=S,j.getSnapshot=x,p(j)&&E({inst:j})},[v,S,x]),r(function(){return p(j)&&E({inst:j}),v(function(){p(j)&&E({inst:j})})},[v]),d(S),S}function p(v){var x=v.getSnapshot;v=v.value;try{var S=x();return!l(v,S)}catch{return!0}}function y(v,x){return x()}var m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?y:g;return Kd.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:m,Kd}var Iy;function vT(){return Iy||(Iy=1,Zd.exports=yT()),Zd.exports}var By;function xT(){if(By)return $d;By=1;var t=Ho(),i=vT();function l(y,m){return y===m&&(y!==0||1/y===1/m)||y!==y&&m!==m}var o=typeof Object.is=="function"?Object.is:l,r=i.useSyncExternalStore,u=t.useRef,d=t.useEffect,g=t.useMemo,p=t.useDebugValue;return $d.useSyncExternalStoreWithSelector=function(y,m,v,x,S){var w=u(null);if(w.current===null){var j={hasValue:!1,value:null};w.current=j}else j=w.current;w=g(function(){function A(R){if(!B){if(B=!0,C=R,R=x(R),S!==void 0&&j.hasValue){var z=j.value;if(S(z,R))return _=z}return _=R}if(z=_,o(C,R))return z;var I=x(R);return S!==void 0&&S(z,I)?(C=R,z):(C=R,_=I)}var B=!1,C,_,U=v===void 0?null:v;return[function(){return A(m())},U===null?void 0:function(){return A(U())}]},[m,v,x,S]);var E=r(y,w[0],w[1]);return d(function(){j.hasValue=!0,j.value=E},[E]),p(E),E},$d}var Ly;function bT(){return Ly||(Ly=1,Xd.exports=xT()),Xd.exports}var ST=bT();const wT=f0(ST),NT={},ky=t=>{let i;const l=new Set,o=(m,v)=>{const x=typeof m=="function"?m(i):m;if(!Object.is(x,i)){const S=i;i=v??(typeof x!="object"||x===null)?x:Object.assign({},i,x),l.forEach(w=>w(i,S))}},r=()=>i,p={setState:o,getState:r,getInitialState:()=>y,subscribe:m=>(l.add(m),()=>l.delete(m)),destroy:()=>{(NT?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),l.clear()}},y=i=t(o,r,p);return p},_T=t=>t?ky(t):ky,{useDebugValue:ET}=yo,{useSyncExternalStoreWithSelector:CT}=wT,TT=t=>t;function $v(t,i=TT,l){const o=CT(t.subscribe,t.getState,t.getServerState||t.getInitialState,i,l);return ET(o),o}const Uy=(t,i)=>{const l=_T(t),o=(r,u=i)=>$v(l,r,u);return Object.assign(o,l),o},AT=(t,i)=>t?Uy(t,i):Uy;function Qe(t,i){if(Object.is(t,i))return!0;if(typeof t!="object"||t===null||typeof i!="object"||i===null)return!1;if(t instanceof Map&&i instanceof Map){if(t.size!==i.size)return!1;for(const[o,r]of t)if(!Object.is(r,i.get(o)))return!1;return!0}if(t instanceof Set&&i instanceof Set){if(t.size!==i.size)return!1;for(const o of t)if(!i.has(o))return!1;return!0}const l=Object.keys(t);if(l.length!==Object.keys(i).length)return!1;for(const o of l)if(!Object.prototype.hasOwnProperty.call(i,o)||!Object.is(t[o],i[o]))return!1;return!0}h0();const tc=Y.createContext(null),MT=tc.Provider,Zv=pn.error001();function Oe(t,i){const l=Y.useContext(tc);if(l===null)throw new Error(Zv);return $v(l,t,i)}function Fe(){const t=Y.useContext(tc);if(t===null)throw new Error(Zv);return Y.useMemo(()=>({getState:t.getState,setState:t.setState,subscribe:t.subscribe}),[t])}const qy={display:"none"},jT={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Kv="react-flow__node-desc",Qv="react-flow__edge-desc",zT="react-flow__aria-live",RT=t=>t.ariaLiveMessage,DT=t=>t.ariaLabelConfig;function OT({rfId:t}){const i=Oe(RT);return h.jsx("div",{id:`${zT}-${t}`,"aria-live":"assertive","aria-atomic":"true",style:jT,children:i})}function HT({rfId:t,disableKeyboardA11y:i}){const l=Oe(DT);return h.jsxs(h.Fragment,{children:[h.jsx("div",{id:`${Kv}-${t}`,style:qy,children:i?l["node.a11yDescription.default"]:l["node.a11yDescription.keyboardDisabled"]}),h.jsx("div",{id:`${Qv}-${t}`,style:qy,children:l["edge.a11yDescription.default"]}),!i&&h.jsx(OT,{rfId:t})]})}const Go=Y.forwardRef(({position:t="top-left",children:i,className:l,style:o,...r},u)=>{const d=`${t}`.split("-");return h.jsx("div",{className:st(["react-flow__panel",l,...d]),style:o,ref:u,...r,children:i})});Go.displayName="Panel";function IT({proOptions:t,position:i="bottom-right"}){return t?.hideAttribution?null:h.jsx(Go,{position:i,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:h.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const BT=t=>{const i=[],l=[];for(const[,o]of t.nodeLookup)o.selected&&i.push(o.internals.userNode);for(const[,o]of t.edgeLookup)o.selected&&l.push(o);return{selectedNodes:i,selectedEdges:l}},Nr=t=>t.id;function LT(t,i){return Qe(t.selectedNodes.map(Nr),i.selectedNodes.map(Nr))&&Qe(t.selectedEdges.map(Nr),i.selectedEdges.map(Nr))}function kT({onSelectionChange:t}){const i=Fe(),{selectedNodes:l,selectedEdges:o}=Oe(BT,LT);return Y.useEffect(()=>{const r={nodes:l,edges:o};t?.(r),i.getState().onSelectionChangeHandlers.forEach(u=>u(r))},[l,o,t]),null}const UT=t=>!!t.onSelectionChangeHandlers;function qT({onSelectionChange:t}){const i=Oe(UT);return t||i?h.jsx(kT,{onSelectionChange:t}):null}const gf=typeof window<"u"?Y.useLayoutEffect:Y.useEffect,Fv=[0,0],GT={x:0,y:0,zoom:1},YT=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],Gy=[...YT,"rfId"],VT=t=>({setNodes:t.setNodes,setEdges:t.setEdges,setMinZoom:t.setMinZoom,setMaxZoom:t.setMaxZoom,setTranslateExtent:t.setTranslateExtent,setNodeExtent:t.setNodeExtent,reset:t.reset,setDefaultNodesAndEdges:t.setDefaultNodesAndEdges}),Yy={translateExtent:jo,nodeOrigin:Fv,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function XT(t){const{setNodes:i,setEdges:l,setMinZoom:o,setMaxZoom:r,setTranslateExtent:u,setNodeExtent:d,reset:g,setDefaultNodesAndEdges:p}=Oe(VT,Qe),y=Fe();gf(()=>(p(t.defaultNodes,t.defaultEdges),()=>{m.current=Yy,g()}),[]);const m=Y.useRef(Yy);return gf(()=>{for(const v of Gy){const x=t[v],S=m.current[v];x!==S&&(typeof t[v]>"u"||(v==="nodes"?i(x):v==="edges"?l(x):v==="minZoom"?o(x):v==="maxZoom"?r(x):v==="translateExtent"?u(x):v==="nodeExtent"?d(x):v==="ariaLabelConfig"?y.setState({ariaLabelConfig:AC(x)}):v==="fitView"?y.setState({fitViewQueued:x}):v==="fitViewOptions"?y.setState({fitViewOptions:x}):y.setState({[v]:x})))}m.current=t},Gy.map(v=>t[v])),null}function Vy(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function $T(t){const[i,l]=Y.useState(t==="system"?null:t);return Y.useEffect(()=>{if(t!=="system"){l(t);return}const o=Vy(),r=()=>l(o?.matches?"dark":"light");return r(),o?.addEventListener("change",r),()=>{o?.removeEventListener("change",r)}},[t]),i!==null?i:Vy()?.matches?"dark":"light"}const Xy=typeof document<"u"?document:null;function Oo(t=null,i={target:Xy,actInsideInputWithModifier:!0}){const[l,o]=Y.useState(!1),r=Y.useRef(!1),u=Y.useRef(new Set([])),[d,g]=Y.useMemo(()=>{if(t!==null){const y=(Array.isArray(t)?t:[t]).filter(v=>typeof v=="string").map(v=>v.replace("+",`
|
|
16
16
|
`).replace(`
|
|
17
17
|
|
|
18
18
|
`,`
|
|
19
19
|
+`).split(`
|
|
20
20
|
`)),m=y.reduce((v,x)=>v.concat(...x),[]);return[y,m]}return[[],[]]},[t]);return Y.useEffect(()=>{const p=i?.target??Xy,y=i?.actInsideInputWithModifier??!0;if(t!==null){const m=S=>{if(r.current=S.ctrlKey||S.metaKey||S.shiftKey||S.altKey,(!r.current||r.current&&!y)&&Mv(S))return!1;const j=Zy(S.code,g);if(u.current.add(S[j]),$y(d,u.current,!1)){const E=S.composedPath?.()?.[0]||S.target,A=E?.nodeName==="BUTTON"||E?.nodeName==="A";i.preventDefault!==!1&&(r.current||!A)&&S.preventDefault(),o(!0)}},v=S=>{const w=Zy(S.code,g);$y(d,u.current,!0)?(o(!1),u.current.clear()):u.current.delete(S[w]),S.key==="Meta"&&u.current.clear(),r.current=!1},x=()=>{u.current.clear(),o(!1)};return p?.addEventListener("keydown",m),p?.addEventListener("keyup",v),window.addEventListener("blur",x),window.addEventListener("contextmenu",x),()=>{p?.removeEventListener("keydown",m),p?.removeEventListener("keyup",v),window.removeEventListener("blur",x),window.removeEventListener("contextmenu",x)}}},[t,o]),l}function $y(t,i,l){return t.filter(o=>l||o.length===i.size).some(o=>o.every(r=>i.has(r)))}function Zy(t,i){return i.includes(t)?"code":"key"}const ZT=()=>{const t=Fe();return Y.useMemo(()=>({zoomIn:i=>{const{panZoom:l}=t.getState();return l?l.scaleBy(1.2,i):Promise.resolve(!1)},zoomOut:i=>{const{panZoom:l}=t.getState();return l?l.scaleBy(1/1.2,i):Promise.resolve(!1)},zoomTo:(i,l)=>{const{panZoom:o}=t.getState();return o?o.scaleTo(i,l):Promise.resolve(!1)},getZoom:()=>t.getState().transform[2],setViewport:async(i,l)=>{const{transform:[o,r,u],panZoom:d}=t.getState();return d?(await d.setViewport({x:i.x??o,y:i.y??r,zoom:i.zoom??u},l),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{const[i,l,o]=t.getState().transform;return{x:i,y:l,zoom:o}},setCenter:async(i,l,o)=>t.getState().setCenter(i,l,o),fitBounds:async(i,l)=>{const{width:o,height:r,minZoom:u,maxZoom:d,panZoom:g}=t.getState(),p=Tf(i,o,r,u,d,l?.padding??.1);return g?(await g.setViewport(p,{duration:l?.duration,ease:l?.ease,interpolate:l?.interpolate}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(i,l={})=>{const{transform:o,snapGrid:r,snapToGrid:u,domNode:d}=t.getState();if(!d)return i;const{x:g,y:p}=d.getBoundingClientRect(),y={x:i.x-g,y:i.y-p},m=l.snapGrid??r,v=l.snapToGrid??u;return qo(y,o,v,m)},flowToScreenPosition:i=>{const{transform:l,domNode:o}=t.getState();if(!o)return i;const{x:r,y:u}=o.getBoundingClientRect(),d=Xr(i,l);return{x:d.x+r,y:d.y+u}}}),[])};function Pv(t,i){const l=[],o=new Map,r=[];for(const u of t)if(u.type==="add"){r.push(u);continue}else if(u.type==="remove"||u.type==="replace")o.set(u.id,[u]);else{const d=o.get(u.id);d?d.push(u):o.set(u.id,[u])}for(const u of i){const d=o.get(u.id);if(!d){l.push(u);continue}if(d[0].type==="remove")continue;if(d[0].type==="replace"){l.push({...d[0].item});continue}const g={...u};for(const p of d)KT(p,g);l.push(g)}return r.length&&r.forEach(u=>{u.index!==void 0?l.splice(u.index,0,{...u.item}):l.push({...u.item})}),l}function KT(t,i){switch(t.type){case"select":{i.selected=t.selected;break}case"position":{typeof t.position<"u"&&(i.position=t.position),typeof t.dragging<"u"&&(i.dragging=t.dragging);break}case"dimensions":{typeof t.dimensions<"u"&&(i.measured={...t.dimensions},t.setAttributes&&((t.setAttributes===!0||t.setAttributes==="width")&&(i.width=t.dimensions.width),(t.setAttributes===!0||t.setAttributes==="height")&&(i.height=t.dimensions.height))),typeof t.resizing=="boolean"&&(i.resizing=t.resizing);break}}}function Jv(t,i){return Pv(t,i)}function Wv(t,i){return Pv(t,i)}function Wa(t,i){return{id:t,type:"select",selected:i}}function il(t,i=new Set,l=!1){const o=[];for(const[r,u]of t){const d=i.has(r);!(u.selected===void 0&&!d)&&u.selected!==d&&(l&&(u.selected=d),o.push(Wa(u.id,d)))}return o}function Ky({items:t=[],lookup:i}){const l=[],o=new Map(t.map(r=>[r.id,r]));for(const[r,u]of t.entries()){const d=i.get(u.id),g=d?.internals?.userNode??d;g!==void 0&&g!==u&&l.push({id:u.id,item:u,type:"replace"}),g===void 0&&l.push({item:u,type:"add",index:r})}for(const[r]of i)o.get(r)===void 0&&l.push({id:r,type:"remove"});return l}function Qy(t){return{id:t.id,type:"remove"}}const Fy=t=>vC(t),QT=t=>Sv(t);function ex(t){return Y.forwardRef(t)}function Py(t){const[i,l]=Y.useState(BigInt(0)),[o]=Y.useState(()=>FT(()=>l(r=>r+BigInt(1))));return gf(()=>{const r=o.get();r.length&&(t(r),o.reset())},[i]),o}function FT(t){let i=[];return{get:()=>i,reset:()=>{i=[]},push:l=>{i.push(l),t()}}}const tx=Y.createContext(null);function PT({children:t}){const i=Fe(),l=Y.useCallback(g=>{const{nodes:p=[],setNodes:y,hasDefaultNodes:m,onNodesChange:v,nodeLookup:x,fitViewQueued:S,onNodesChangeMiddlewareMap:w}=i.getState();let j=p;for(const A of g)j=typeof A=="function"?A(j):A;let E=Ky({items:j,lookup:x});for(const A of w.values())E=A(E);m&&y(j),E.length>0?v?.(E):S&&window.requestAnimationFrame(()=>{const{fitViewQueued:A,nodes:B,setNodes:C}=i.getState();A&&C(B)})},[]),o=Py(l),r=Y.useCallback(g=>{const{edges:p=[],setEdges:y,hasDefaultEdges:m,onEdgesChange:v,edgeLookup:x}=i.getState();let S=p;for(const w of g)S=typeof w=="function"?w(S):w;m?y(S):v&&v(Ky({items:S,lookup:x}))},[]),u=Py(r),d=Y.useMemo(()=>({nodeQueue:o,edgeQueue:u}),[]);return h.jsx(tx.Provider,{value:d,children:t})}function JT(){const t=Y.useContext(tx);if(!t)throw new Error("useBatchContext must be used within a BatchProvider");return t}const WT=t=>!!t.panZoom;function nc(){const t=ZT(),i=Fe(),l=JT(),o=Oe(WT),r=Y.useMemo(()=>{const u=v=>i.getState().nodeLookup.get(v),d=v=>{l.nodeQueue.push(v)},g=v=>{l.edgeQueue.push(v)},p=v=>{const{nodeLookup:x,nodeOrigin:S}=i.getState(),w=Fy(v)?v:x.get(v.id),j=w.parentId?Tv(w.position,w.measured,w.parentId,x,S):w.position,E={...w,position:j,width:w.measured?.width??w.width,height:w.measured?.height??w.height};return hl(E)},y=(v,x,S={replace:!1})=>{d(w=>w.map(j=>{if(j.id===v){const E=typeof x=="function"?x(j):x;return S.replace&&Fy(E)?E:{...j,...E}}return j}))},m=(v,x,S={replace:!1})=>{g(w=>w.map(j=>{if(j.id===v){const E=typeof x=="function"?x(j):x;return S.replace&&QT(E)?E:{...j,...E}}return j}))};return{getNodes:()=>i.getState().nodes.map(v=>({...v})),getNode:v=>u(v)?.internals.userNode,getInternalNode:u,getEdges:()=>{const{edges:v=[]}=i.getState();return v.map(x=>({...x}))},getEdge:v=>i.getState().edgeLookup.get(v),setNodes:d,setEdges:g,addNodes:v=>{const x=Array.isArray(v)?v:[v];l.nodeQueue.push(S=>[...S,...x])},addEdges:v=>{const x=Array.isArray(v)?v:[v];l.edgeQueue.push(S=>[...S,...x])},toObject:()=>{const{nodes:v=[],edges:x=[],transform:S}=i.getState(),[w,j,E]=S;return{nodes:v.map(A=>({...A})),edges:x.map(A=>({...A})),viewport:{x:w,y:j,zoom:E}}},deleteElements:async({nodes:v=[],edges:x=[]})=>{const{nodes:S,edges:w,onNodesDelete:j,onEdgesDelete:E,triggerNodeChanges:A,triggerEdgeChanges:B,onDelete:C,onBeforeDelete:_}=i.getState(),{nodes:U,edges:R}=await NC({nodesToRemove:v,edgesToRemove:x,nodes:S,edges:w,onBeforeDelete:_}),z=R.length>0,I=U.length>0;if(z){const X=R.map(Qy);E?.(R),B(X)}if(I){const X=U.map(Qy);j?.(U),A(X)}return(I||z)&&C?.({nodes:U,edges:R}),{deletedNodes:U,deletedEdges:R}},getIntersectingNodes:(v,x=!0,S)=>{const w=wy(v),j=w?v:p(v),E=S!==void 0;return j?(S||i.getState().nodes).filter(A=>{const B=i.getState().nodeLookup.get(A.id);if(B&&!w&&(A.id===v.id||!B.internals.positionAbsolute))return!1;const C=hl(E?A:B),_=Ro(C,j);return x&&_>0||_>=C.width*C.height||_>=j.width*j.height}):[]},isNodeIntersecting:(v,x,S=!0)=>{const j=wy(v)?v:p(v);if(!j)return!1;const E=Ro(j,x);return S&&E>0||E>=x.width*x.height||E>=j.width*j.height},updateNode:y,updateNodeData:(v,x,S={replace:!1})=>{y(v,w=>{const j=typeof x=="function"?x(w):x;return S.replace?{...w,data:j}:{...w,data:{...w.data,...j}}},S)},updateEdge:m,updateEdgeData:(v,x,S={replace:!1})=>{m(v,w=>{const j=typeof x=="function"?x(w):x;return S.replace?{...w,data:j}:{...w,data:{...w.data,...j}}},S)},getNodesBounds:v=>{const{nodeLookup:x,nodeOrigin:S}=i.getState();return xC(v,{nodeLookup:x,nodeOrigin:S})},getHandleConnections:({type:v,id:x,nodeId:S})=>Array.from(i.getState().connectionLookup.get(`${S}-${v}${x?`-${x}`:""}`)?.values()??[]),getNodeConnections:({type:v,handleId:x,nodeId:S})=>Array.from(i.getState().connectionLookup.get(`${S}${v?x?`-${v}-${x}`:`-${v}`:""}`)?.values()??[]),fitView:async v=>{const x=i.getState().fitViewResolver??TC();return i.setState({fitViewQueued:!0,fitViewOptions:v,fitViewResolver:x}),l.nodeQueue.push(S=>[...S]),x.promise}}},[]);return Y.useMemo(()=>({...r,...t,viewportInitialized:o}),[o])}const Jy=t=>t.selected,eA=typeof window<"u"?window:void 0;function tA({deleteKeyCode:t,multiSelectionKeyCode:i}){const l=Fe(),{deleteElements:o}=nc(),r=Oo(t,{actInsideInputWithModifier:!1}),u=Oo(i,{target:eA});Y.useEffect(()=>{if(r){const{edges:d,nodes:g}=l.getState();o({nodes:g.filter(Jy),edges:d.filter(Jy)}),l.setState({nodesSelectionActive:!1})}},[r]),Y.useEffect(()=>{l.setState({multiSelectionActive:u})},[u])}function nA(t){const i=Fe();Y.useEffect(()=>{const l=()=>{if(!t.current||!(t.current.checkVisibility?.()??!0))return!1;const o=Af(t.current);(o.height===0||o.width===0)&&i.getState().onError?.("004",pn.error004()),i.setState({width:o.width||500,height:o.height||500})};if(t.current){l(),window.addEventListener("resize",l);const o=new ResizeObserver(()=>l());return o.observe(t.current),()=>{window.removeEventListener("resize",l),o&&t.current&&o.unobserve(t.current)}}},[])}const ac={position:"absolute",width:"100%",height:"100%",top:0,left:0},aA=t=>({userSelectionActive:t.userSelectionActive,lib:t.lib,connectionInProgress:t.connection.inProgress});function iA({onPaneContextMenu:t,zoomOnScroll:i=!0,zoomOnPinch:l=!0,panOnScroll:o=!1,panOnScrollSpeed:r=.5,panOnScrollMode:u=ii.Free,zoomOnDoubleClick:d=!0,panOnDrag:g=!0,defaultViewport:p,translateExtent:y,minZoom:m,maxZoom:v,zoomActivationKeyCode:x,preventScrolling:S=!0,children:w,noWheelClassName:j,noPanClassName:E,onViewportChange:A,isControlledViewport:B,paneClickDistance:C,selectionOnDrag:_}){const U=Fe(),R=Y.useRef(null),{userSelectionActive:z,lib:I,connectionInProgress:X}=Oe(aA,Qe),ce=Oo(x),K=Y.useRef();nA(R);const te=Y.useCallback(ue=>{A?.({x:ue[0],y:ue[1],zoom:ue[2]}),B||U.setState({transform:ue})},[A,B]);return Y.useEffect(()=>{if(R.current){K.current=uT({domNode:R.current,minZoom:m,maxZoom:v,translateExtent:y,viewport:p,onDraggingChange:M=>U.setState(H=>H.paneDragging===M?H:{paneDragging:M}),onPanZoomStart:(M,H)=>{const{onViewportChangeStart:q,onMoveStart:k}=U.getState();k?.(M,H),q?.(H)},onPanZoom:(M,H)=>{const{onViewportChange:q,onMove:k}=U.getState();k?.(M,H),q?.(H)},onPanZoomEnd:(M,H)=>{const{onViewportChangeEnd:q,onMoveEnd:k}=U.getState();k?.(M,H),q?.(H)}});const{x:ue,y:D,zoom:Z}=K.current.getViewport();return U.setState({panZoom:K.current,transform:[ue,D,Z],domNode:R.current.closest(".react-flow")}),()=>{K.current?.destroy()}}},[]),Y.useEffect(()=>{K.current?.update({onPaneContextMenu:t,zoomOnScroll:i,zoomOnPinch:l,panOnScroll:o,panOnScrollSpeed:r,panOnScrollMode:u,zoomOnDoubleClick:d,panOnDrag:g,zoomActivationKeyPressed:ce,preventScrolling:S,noPanClassName:E,userSelectionActive:z,noWheelClassName:j,lib:I,onTransformChange:te,connectionInProgress:X,selectionOnDrag:_,paneClickDistance:C})},[t,i,l,o,r,u,d,g,ce,S,E,z,j,I,te,X,_,C]),h.jsx("div",{className:"react-flow__renderer",ref:R,style:ac,children:w})}const lA=t=>({userSelectionActive:t.userSelectionActive,userSelectionRect:t.userSelectionRect});function oA(){const{userSelectionActive:t,userSelectionRect:i}=Oe(lA,Qe);return t&&i?h.jsx("div",{className:"react-flow__selection react-flow__container",style:{width:i.width,height:i.height,transform:`translate(${i.x}px, ${i.y}px)`}}):null}const Qd=(t,i)=>l=>{l.target===i.current&&t?.(l)},sA=t=>({userSelectionActive:t.userSelectionActive,elementsSelectable:t.elementsSelectable,connectionInProgress:t.connection.inProgress,dragging:t.paneDragging});function rA({isSelecting:t,selectionKeyPressed:i,selectionMode:l=zo.Full,panOnDrag:o,paneClickDistance:r,selectionOnDrag:u,onSelectionStart:d,onSelectionEnd:g,onPaneClick:p,onPaneContextMenu:y,onPaneScroll:m,onPaneMouseEnter:v,onPaneMouseMove:x,onPaneMouseLeave:S,children:w}){const j=Fe(),{userSelectionActive:E,elementsSelectable:A,dragging:B,connectionInProgress:C}=Oe(sA,Qe),_=A&&(t||E),U=Y.useRef(null),R=Y.useRef(),z=Y.useRef(new Set),I=Y.useRef(new Set),X=Y.useRef(!1),ce=q=>{if(X.current||C){X.current=!1;return}p?.(q),j.getState().resetSelectedElements(),j.setState({nodesSelectionActive:!1})},K=q=>{if(Array.isArray(o)&&o?.includes(2)){q.preventDefault();return}y?.(q)},te=m?q=>m(q):void 0,ue=q=>{X.current&&(q.stopPropagation(),X.current=!1)},D=q=>{const{domNode:k}=j.getState();if(R.current=k?.getBoundingClientRect(),!R.current)return;const J=q.target===U.current;if(!J&&!!q.target.closest(".nokey")||!t||!(u&&J||i)||q.button!==0||!q.isPrimary)return;q.target?.setPointerCapture?.(q.pointerId),X.current=!1;const{x:ne,y:ae}=ln(q.nativeEvent,R.current);j.setState({userSelectionRect:{width:0,height:0,startX:ne,startY:ae,x:ne,y:ae}}),J||(q.stopPropagation(),q.preventDefault())},Z=q=>{const{userSelectionRect:k,transform:J,nodeLookup:T,edgeLookup:L,connectionLookup:ne,triggerNodeChanges:ae,triggerEdgeChanges:V,defaultEdgeOptions:se,resetSelectedElements:de}=j.getState();if(!R.current||!k)return;const{x:le,y:fe}=ln(q.nativeEvent,R.current),{startX:be,startY:_e}=k;if(!X.current){const Le=i?0:r;if(Math.hypot(le-be,fe-_e)<=Le)return;de(),d?.(q)}X.current=!0;const ye={startX:be,startY:_e,x:le<be?le:be,y:fe<_e?fe:_e,width:Math.abs(le-be),height:Math.abs(fe-_e)},we=z.current,je=I.current;z.current=new Set(Cf(T,ye,J,l===zo.Partial,!0).map(Le=>Le.id)),I.current=new Set;const qe=se?.selectable??!0;for(const Le of z.current){const ut=ne.get(Le);if(ut)for(const{edgeId:Qt}of ut.values()){const zt=L.get(Qt);zt&&(zt.selectable??qe)&&I.current.add(Qt)}}if(!Ny(we,z.current)){const Le=il(T,z.current,!0);ae(Le)}if(!Ny(je,I.current)){const Le=il(L,I.current);V(Le)}j.setState({userSelectionRect:ye,userSelectionActive:!0,nodesSelectionActive:!1})},M=q=>{q.button===0&&(q.target?.releasePointerCapture?.(q.pointerId),!E&&q.target===U.current&&j.getState().userSelectionRect&&ce?.(q),j.setState({userSelectionActive:!1,userSelectionRect:null}),X.current&&(g?.(q),j.setState({nodesSelectionActive:z.current.size>0})))},H=o===!0||Array.isArray(o)&&o.includes(0);return h.jsxs("div",{className:st(["react-flow__pane",{draggable:H,dragging:B,selection:t}]),onClick:_?void 0:Qd(ce,U),onContextMenu:Qd(K,U),onWheel:Qd(te,U),onPointerEnter:_?void 0:v,onPointerMove:_?Z:x,onPointerUp:_?M:void 0,onPointerDownCapture:_?D:void 0,onClickCapture:_?ue:void 0,onPointerLeave:S,ref:U,style:ac,children:[w,h.jsx(oA,{})]})}function mf({id:t,store:i,unselect:l=!1,nodeRef:o}){const{addSelectedNodes:r,unselectNodesAndEdges:u,multiSelectionActive:d,nodeLookup:g,onError:p}=i.getState(),y=g.get(t);if(!y){p?.("012",pn.error012(t));return}i.setState({nodesSelectionActive:!1}),y.selected?(l||y.selected&&d)&&(u({nodes:[y],edges:[]}),requestAnimationFrame(()=>o?.current?.blur())):r([t])}function nx({nodeRef:t,disabled:i=!1,noDragClassName:l,handleSelector:o,nodeId:r,isSelectable:u,nodeClickDistance:d}){const g=Fe(),[p,y]=Y.useState(!1),m=Y.useRef();return Y.useEffect(()=>{m.current=FC({getStoreItems:()=>g.getState(),onNodeMouseDown:v=>{mf({id:v,store:g,nodeRef:t})},onDragStart:()=>{y(!0)},onDragStop:()=>{y(!1)}})},[]),Y.useEffect(()=>{if(!(i||!t.current||!m.current))return m.current.update({noDragClassName:l,handleSelector:o,domNode:t.current,isSelectable:u,nodeId:r,nodeClickDistance:d}),()=>{m.current?.destroy()}},[l,o,i,u,t,r,d]),p}const cA=t=>i=>i.selected&&(i.draggable||t&&typeof i.draggable>"u");function ax(){const t=Fe();return Y.useCallback(l=>{const{nodeExtent:o,snapToGrid:r,snapGrid:u,nodesDraggable:d,onError:g,updateNodePositions:p,nodeLookup:y,nodeOrigin:m}=t.getState(),v=new Map,x=cA(d),S=r?u[0]:5,w=r?u[1]:5,j=l.direction.x*S*l.factor,E=l.direction.y*w*l.factor;for(const[,A]of y){if(!x(A))continue;let B={x:A.internals.positionAbsolute.x+j,y:A.internals.positionAbsolute.y+E};r&&(B=Uo(B,u));const{position:C,positionAbsolute:_}=wv({nodeId:A.id,nextPosition:B,nodeLookup:y,nodeExtent:o,nodeOrigin:m,onError:g});A.position=C,A.internals.positionAbsolute=_,v.set(A.id,A)}p(v)},[])}const Of=Y.createContext(null),uA=Of.Provider;Of.Consumer;const ix=()=>Y.useContext(Of),dA=t=>({connectOnClick:t.connectOnClick,noPanClassName:t.noPanClassName,rfId:t.rfId}),fA=(t,i,l)=>o=>{const{connectionClickStartHandle:r,connectionMode:u,connection:d}=o,{fromHandle:g,toHandle:p,isValid:y}=d,m=p?.nodeId===t&&p?.id===i&&p?.type===l;return{connectingFrom:g?.nodeId===t&&g?.id===i&&g?.type===l,connectingTo:m,clickConnecting:r?.nodeId===t&&r?.id===i&&r?.type===l,isPossibleEndHandle:u===dl.Strict?g?.type!==l:t!==g?.nodeId||i!==g?.id,connectionInProcess:!!g,clickConnectionInProcess:!!r,valid:m&&y}};function hA({type:t="source",position:i=me.Top,isValidConnection:l,isConnectable:o=!0,isConnectableStart:r=!0,isConnectableEnd:u=!0,id:d,onConnect:g,children:p,className:y,onMouseDown:m,onTouchStart:v,...x},S){const w=d||null,j=t==="target",E=Fe(),A=ix(),{connectOnClick:B,noPanClassName:C,rfId:_}=Oe(dA,Qe),{connectingFrom:U,connectingTo:R,clickConnecting:z,isPossibleEndHandle:I,connectionInProcess:X,clickConnectionInProcess:ce,valid:K}=Oe(fA(A,w,t),Qe);A||E.getState().onError?.("010",pn.error010());const te=Z=>{const{defaultEdgeOptions:M,onConnect:H,hasDefaultEdges:q}=E.getState(),k={...M,...Z};if(q){const{edges:J,setEdges:T}=E.getState();T(OC(k,J))}H?.(k),g?.(k)},ue=Z=>{if(!A)return;const M=jv(Z.nativeEvent);if(r&&(M&&Z.button===0||!M)){const H=E.getState();hf.onPointerDown(Z.nativeEvent,{handleDomNode:Z.currentTarget,autoPanOnConnect:H.autoPanOnConnect,connectionMode:H.connectionMode,connectionRadius:H.connectionRadius,domNode:H.domNode,nodeLookup:H.nodeLookup,lib:H.lib,isTarget:j,handleId:w,nodeId:A,flowId:H.rfId,panBy:H.panBy,cancelConnection:H.cancelConnection,onConnectStart:H.onConnectStart,onConnectEnd:(...q)=>E.getState().onConnectEnd?.(...q),updateConnection:H.updateConnection,onConnect:te,isValidConnection:l||((...q)=>E.getState().isValidConnection?.(...q)??!0),getTransform:()=>E.getState().transform,getFromHandle:()=>E.getState().connection.fromHandle,autoPanSpeed:H.autoPanSpeed,dragThreshold:H.connectionDragThreshold})}M?m?.(Z):v?.(Z)},D=Z=>{const{onClickConnectStart:M,onClickConnectEnd:H,connectionClickStartHandle:q,connectionMode:k,isValidConnection:J,lib:T,rfId:L,nodeLookup:ne,connection:ae}=E.getState();if(!A||!q&&!r)return;if(!q){M?.(Z.nativeEvent,{nodeId:A,handleId:w,handleType:t}),E.setState({connectionClickStartHandle:{nodeId:A,type:t,id:w}});return}const V=Av(Z.target),se=l||J,{connection:de,isValid:le}=hf.isValid(Z.nativeEvent,{handle:{nodeId:A,id:w,type:t},connectionMode:k,fromNodeId:q.nodeId,fromHandleId:q.id||null,fromType:q.type,isValidConnection:se,flowId:L,doc:V,lib:T,nodeLookup:ne});le&&de&&te(de);const fe=structuredClone(ae);delete fe.inProgress,fe.toPosition=fe.toHandle?fe.toHandle.position:null,H?.(Z,fe),E.setState({connectionClickStartHandle:null})};return h.jsx("div",{"data-handleid":w,"data-nodeid":A,"data-handlepos":i,"data-id":`${_}-${A}-${w}-${t}`,className:st(["react-flow__handle",`react-flow__handle-${i}`,"nodrag",C,y,{source:!j,target:j,connectable:o,connectablestart:r,connectableend:u,clickconnecting:z,connectingfrom:U,connectingto:R,valid:K,connectionindicator:o&&(!X||I)&&(X||ce?u:r)}]),onMouseDown:ue,onTouchStart:ue,onClick:B?D:void 0,ref:S,...x,children:p})}const pl=Y.memo(ex(hA));function gA({data:t,isConnectable:i,sourcePosition:l=me.Bottom}){return h.jsxs(h.Fragment,{children:[t?.label,h.jsx(pl,{type:"source",position:l,isConnectable:i})]})}function mA({data:t,isConnectable:i,targetPosition:l=me.Top,sourcePosition:o=me.Bottom}){return h.jsxs(h.Fragment,{children:[h.jsx(pl,{type:"target",position:l,isConnectable:i}),t?.label,h.jsx(pl,{type:"source",position:o,isConnectable:i})]})}function pA(){return null}function yA({data:t,isConnectable:i,targetPosition:l=me.Top}){return h.jsxs(h.Fragment,{children:[h.jsx(pl,{type:"target",position:l,isConnectable:i}),t?.label]})}const $r={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},Wy={input:gA,default:mA,output:yA,group:pA};function vA(t){return t.internals.handleBounds===void 0?{width:t.width??t.initialWidth??t.style?.width,height:t.height??t.initialHeight??t.style?.height}:{width:t.width??t.style?.width,height:t.height??t.style?.height}}const xA=t=>{const{width:i,height:l,x:o,y:r}=ko(t.nodeLookup,{filter:u=>!!u.selected});return{width:an(i)?i:null,height:an(l)?l:null,userSelectionActive:t.userSelectionActive,transformString:`translate(${t.transform[0]}px,${t.transform[1]}px) scale(${t.transform[2]}) translate(${o}px,${r}px)`}};function bA({onSelectionContextMenu:t,noPanClassName:i,disableKeyboardA11y:l}){const o=Fe(),{width:r,height:u,transformString:d,userSelectionActive:g}=Oe(xA,Qe),p=ax(),y=Y.useRef(null);Y.useEffect(()=>{l||y.current?.focus({preventScroll:!0})},[l]);const m=!g&&r!==null&&u!==null;if(nx({nodeRef:y,disabled:!m}),!m)return null;const v=t?S=>{const w=o.getState().nodes.filter(j=>j.selected);t(S,w)}:void 0,x=S=>{Object.prototype.hasOwnProperty.call($r,S.key)&&(S.preventDefault(),p({direction:$r[S.key],factor:S.shiftKey?4:1}))};return h.jsx("div",{className:st(["react-flow__nodesselection","react-flow__container",i]),style:{transform:d},children:h.jsx("div",{ref:y,className:"react-flow__nodesselection-rect",onContextMenu:v,tabIndex:l?void 0:-1,onKeyDown:l?void 0:x,style:{width:r,height:u}})})}const e0=typeof window<"u"?window:void 0,SA=t=>({nodesSelectionActive:t.nodesSelectionActive,userSelectionActive:t.userSelectionActive});function lx({children:t,onPaneClick:i,onPaneMouseEnter:l,onPaneMouseMove:o,onPaneMouseLeave:r,onPaneContextMenu:u,onPaneScroll:d,paneClickDistance:g,deleteKeyCode:p,selectionKeyCode:y,selectionOnDrag:m,selectionMode:v,onSelectionStart:x,onSelectionEnd:S,multiSelectionKeyCode:w,panActivationKeyCode:j,zoomActivationKeyCode:E,elementsSelectable:A,zoomOnScroll:B,zoomOnPinch:C,panOnScroll:_,panOnScrollSpeed:U,panOnScrollMode:R,zoomOnDoubleClick:z,panOnDrag:I,defaultViewport:X,translateExtent:ce,minZoom:K,maxZoom:te,preventScrolling:ue,onSelectionContextMenu:D,noWheelClassName:Z,noPanClassName:M,disableKeyboardA11y:H,onViewportChange:q,isControlledViewport:k}){const{nodesSelectionActive:J,userSelectionActive:T}=Oe(SA,Qe),L=Oo(y,{target:e0}),ne=Oo(j,{target:e0}),ae=ne||I,V=ne||_,se=m&&ae!==!0,de=L||T||se;return tA({deleteKeyCode:p,multiSelectionKeyCode:w}),h.jsx(iA,{onPaneContextMenu:u,elementsSelectable:A,zoomOnScroll:B,zoomOnPinch:C,panOnScroll:V,panOnScrollSpeed:U,panOnScrollMode:R,zoomOnDoubleClick:z,panOnDrag:!L&&ae,defaultViewport:X,translateExtent:ce,minZoom:K,maxZoom:te,zoomActivationKeyCode:E,preventScrolling:ue,noWheelClassName:Z,noPanClassName:M,onViewportChange:q,isControlledViewport:k,paneClickDistance:g,selectionOnDrag:se,children:h.jsxs(rA,{onSelectionStart:x,onSelectionEnd:S,onPaneClick:i,onPaneMouseEnter:l,onPaneMouseMove:o,onPaneMouseLeave:r,onPaneContextMenu:u,onPaneScroll:d,panOnDrag:ae,isSelecting:!!de,selectionMode:v,selectionKeyPressed:L,paneClickDistance:g,selectionOnDrag:se,children:[t,J&&h.jsx(bA,{onSelectionContextMenu:D,noPanClassName:M,disableKeyboardA11y:H})]})})}lx.displayName="FlowRenderer";const wA=Y.memo(lx),NA=t=>i=>t?Cf(i.nodeLookup,{x:0,y:0,width:i.width,height:i.height},i.transform,!0).map(l=>l.id):Array.from(i.nodeLookup.keys());function _A(t){return Oe(Y.useCallback(NA(t),[t]),Qe)}const EA=t=>t.updateNodeInternals;function CA(){const t=Oe(EA),[i]=Y.useState(()=>typeof ResizeObserver>"u"?null:new ResizeObserver(l=>{const o=new Map;l.forEach(r=>{const u=r.target.getAttribute("data-id");o.set(u,{id:u,nodeElement:r.target,force:!0})}),t(o)}));return Y.useEffect(()=>()=>{i?.disconnect()},[i]),i}function TA({node:t,nodeType:i,hasDimensions:l,resizeObserver:o}){const r=Fe(),u=Y.useRef(null),d=Y.useRef(null),g=Y.useRef(t.sourcePosition),p=Y.useRef(t.targetPosition),y=Y.useRef(i),m=l&&!!t.internals.handleBounds;return Y.useEffect(()=>{u.current&&!t.hidden&&(!m||d.current!==u.current)&&(d.current&&o?.unobserve(d.current),o?.observe(u.current),d.current=u.current)},[m,t.hidden]),Y.useEffect(()=>()=>{d.current&&(o?.unobserve(d.current),d.current=null)},[]),Y.useEffect(()=>{if(u.current){const v=y.current!==i,x=g.current!==t.sourcePosition,S=p.current!==t.targetPosition;(v||x||S)&&(y.current=i,g.current=t.sourcePosition,p.current=t.targetPosition,r.getState().updateNodeInternals(new Map([[t.id,{id:t.id,nodeElement:u.current,force:!0}]])))}},[t.id,i,t.sourcePosition,t.targetPosition]),u}function AA({id:t,onClick:i,onMouseEnter:l,onMouseMove:o,onMouseLeave:r,onContextMenu:u,onDoubleClick:d,nodesDraggable:g,elementsSelectable:p,nodesConnectable:y,nodesFocusable:m,resizeObserver:v,noDragClassName:x,noPanClassName:S,disableKeyboardA11y:w,rfId:j,nodeTypes:E,nodeClickDistance:A,onError:B}){const{node:C,internals:_,isParent:U}=Oe(le=>{const fe=le.nodeLookup.get(t),be=le.parentLookup.has(t);return{node:fe,internals:fe.internals,isParent:be}},Qe);let R=C.type||"default",z=E?.[R]||Wy[R];z===void 0&&(B?.("003",pn.error003(R)),R="default",z=E?.default||Wy.default);const I=!!(C.draggable||g&&typeof C.draggable>"u"),X=!!(C.selectable||p&&typeof C.selectable>"u"),ce=!!(C.connectable||y&&typeof C.connectable>"u"),K=!!(C.focusable||m&&typeof C.focusable>"u"),te=Fe(),ue=Cv(C),D=TA({node:C,nodeType:R,hasDimensions:ue,resizeObserver:v}),Z=nx({nodeRef:D,disabled:C.hidden||!I,noDragClassName:x,handleSelector:C.dragHandle,nodeId:t,isSelectable:X,nodeClickDistance:A}),M=ax();if(C.hidden)return null;const H=Xn(C),q=vA(C),k=X||I||i||l||o||r,J=l?le=>l(le,{..._.userNode}):void 0,T=o?le=>o(le,{..._.userNode}):void 0,L=r?le=>r(le,{..._.userNode}):void 0,ne=u?le=>u(le,{..._.userNode}):void 0,ae=d?le=>d(le,{..._.userNode}):void 0,V=le=>{const{selectNodesOnDrag:fe,nodeDragThreshold:be}=te.getState();X&&(!fe||!I||be>0)&&mf({id:t,store:te,nodeRef:D}),i&&i(le,{..._.userNode})},se=le=>{if(!(Mv(le.nativeEvent)||w)){if(yv.includes(le.key)&&X){const fe=le.key==="Escape";mf({id:t,store:te,unselect:fe,nodeRef:D})}else if(I&&C.selected&&Object.prototype.hasOwnProperty.call($r,le.key)){le.preventDefault();const{ariaLabelConfig:fe}=te.getState();te.setState({ariaLiveMessage:fe["node.a11yDescription.ariaLiveMessage"]({direction:le.key.replace("Arrow","").toLowerCase(),x:~~_.positionAbsolute.x,y:~~_.positionAbsolute.y})}),M({direction:$r[le.key],factor:le.shiftKey?4:1})}}},de=()=>{if(w||!D.current?.matches(":focus-visible"))return;const{transform:le,width:fe,height:be,autoPanOnNodeFocus:_e,setCenter:ye}=te.getState();if(!_e)return;Cf(new Map([[t,C]]),{x:0,y:0,width:fe,height:be},le,!0).length>0||ye(C.position.x+H.width/2,C.position.y+H.height/2,{zoom:le[2]})};return h.jsx("div",{className:st(["react-flow__node",`react-flow__node-${R}`,{[S]:I},C.className,{selected:C.selected,selectable:X,parent:U,draggable:I,dragging:Z}]),ref:D,style:{zIndex:_.z,transform:`translate(${_.positionAbsolute.x}px,${_.positionAbsolute.y}px)`,pointerEvents:k?"all":"none",visibility:ue?"visible":"hidden",...C.style,...q},"data-id":t,"data-testid":`rf__node-${t}`,onMouseEnter:J,onMouseMove:T,onMouseLeave:L,onContextMenu:ne,onClick:V,onDoubleClick:ae,onKeyDown:K?se:void 0,tabIndex:K?0:void 0,onFocus:K?de:void 0,role:C.ariaRole??(K?"group":void 0),"aria-roledescription":"node","aria-describedby":w?void 0:`${Kv}-${j}`,"aria-label":C.ariaLabel,...C.domAttributes,children:h.jsx(uA,{value:t,children:h.jsx(z,{id:t,data:C.data,type:R,positionAbsoluteX:_.positionAbsolute.x,positionAbsoluteY:_.positionAbsolute.y,selected:C.selected??!1,selectable:X,draggable:I,deletable:C.deletable??!0,isConnectable:ce,sourcePosition:C.sourcePosition,targetPosition:C.targetPosition,dragging:Z,dragHandle:C.dragHandle,zIndex:_.z,parentId:C.parentId,...H})})})}var MA=Y.memo(AA);const jA=t=>({nodesDraggable:t.nodesDraggable,nodesConnectable:t.nodesConnectable,nodesFocusable:t.nodesFocusable,elementsSelectable:t.elementsSelectable,onError:t.onError});function ox(t){const{nodesDraggable:i,nodesConnectable:l,nodesFocusable:o,elementsSelectable:r,onError:u}=Oe(jA,Qe),d=_A(t.onlyRenderVisibleElements),g=CA();return h.jsx("div",{className:"react-flow__nodes",style:ac,children:d.map(p=>h.jsx(MA,{id:p,nodeTypes:t.nodeTypes,nodeExtent:t.nodeExtent,onClick:t.onNodeClick,onMouseEnter:t.onNodeMouseEnter,onMouseMove:t.onNodeMouseMove,onMouseLeave:t.onNodeMouseLeave,onContextMenu:t.onNodeContextMenu,onDoubleClick:t.onNodeDoubleClick,noDragClassName:t.noDragClassName,noPanClassName:t.noPanClassName,rfId:t.rfId,disableKeyboardA11y:t.disableKeyboardA11y,resizeObserver:g,nodesDraggable:i,nodesConnectable:l,nodesFocusable:o,elementsSelectable:r,nodeClickDistance:t.nodeClickDistance,onError:u},p))})}ox.displayName="NodeRenderer";const zA=Y.memo(ox);function RA(t){return Oe(Y.useCallback(l=>{if(!t)return l.edges.map(r=>r.id);const o=[];if(l.width&&l.height)for(const r of l.edges){const u=l.nodeLookup.get(r.source),d=l.nodeLookup.get(r.target);u&&d&&zC({sourceNode:u,targetNode:d,width:l.width,height:l.height,transform:l.transform})&&o.push(r.id)}return o},[t]),Qe)}const DA=({color:t="none",strokeWidth:i=1})=>{const l={strokeWidth:i,...t&&{stroke:t}};return h.jsx("polyline",{className:"arrow",style:l,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},OA=({color:t="none",strokeWidth:i=1})=>{const l={strokeWidth:i,...t&&{stroke:t,fill:t}};return h.jsx("polyline",{className:"arrowclosed",style:l,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},t0={[Yr.Arrow]:DA,[Yr.ArrowClosed]:OA};function HA(t){const i=Fe();return Y.useMemo(()=>Object.prototype.hasOwnProperty.call(t0,t)?t0[t]:(i.getState().onError?.("009",pn.error009(t)),null),[t])}const IA=({id:t,type:i,color:l,width:o=12.5,height:r=12.5,markerUnits:u="strokeWidth",strokeWidth:d,orient:g="auto-start-reverse"})=>{const p=HA(i);return p?h.jsx("marker",{className:"react-flow__arrowhead",id:t,markerWidth:`${o}`,markerHeight:`${r}`,viewBox:"-10 -10 20 20",markerUnits:u,orient:g,refX:"0",refY:"0",children:h.jsx(p,{color:l,strokeWidth:d})}):null},sx=({defaultColor:t,rfId:i})=>{const l=Oe(u=>u.edges),o=Oe(u=>u.defaultEdgeOptions),r=Y.useMemo(()=>kC(l,{id:i,defaultColor:t,defaultMarkerStart:o?.markerStart,defaultMarkerEnd:o?.markerEnd}),[l,o,i,t]);return r.length?h.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:h.jsx("defs",{children:r.map(u=>h.jsx(IA,{id:u.id,type:u.type,color:u.color,width:u.width,height:u.height,markerUnits:u.markerUnits,strokeWidth:u.strokeWidth,orient:u.orient},u.id))})}):null};sx.displayName="MarkerDefinitions";var BA=Y.memo(sx);function rx({x:t,y:i,label:l,labelStyle:o,labelShowBg:r=!0,labelBgStyle:u,labelBgPadding:d=[2,4],labelBgBorderRadius:g=2,children:p,className:y,...m}){const[v,x]=Y.useState({x:1,y:0,width:0,height:0}),S=st(["react-flow__edge-textwrapper",y]),w=Y.useRef(null);return Y.useEffect(()=>{if(w.current){const j=w.current.getBBox();x({x:j.x,y:j.y,width:j.width,height:j.height})}},[l]),l?h.jsxs("g",{transform:`translate(${t-v.width/2} ${i-v.height/2})`,className:S,visibility:v.width?"visible":"hidden",...m,children:[r&&h.jsx("rect",{width:v.width+2*d[0],x:-d[0],y:-d[1],height:v.height+2*d[1],className:"react-flow__edge-textbg",style:u,rx:g,ry:g}),h.jsx("text",{className:"react-flow__edge-text",y:v.height/2,dy:"0.3em",ref:w,style:o,children:l}),p]}):null}rx.displayName="EdgeText";const LA=Y.memo(rx);function ic({path:t,labelX:i,labelY:l,label:o,labelStyle:r,labelShowBg:u,labelBgStyle:d,labelBgPadding:g,labelBgBorderRadius:p,interactionWidth:y=20,...m}){return h.jsxs(h.Fragment,{children:[h.jsx("path",{...m,d:t,fill:"none",className:st(["react-flow__edge-path",m.className])}),y?h.jsx("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:y,className:"react-flow__edge-interaction"}):null,o&&an(i)&&an(l)?h.jsx(LA,{x:i,y:l,label:o,labelStyle:r,labelShowBg:u,labelBgStyle:d,labelBgPadding:g,labelBgBorderRadius:p}):null]})}function n0({pos:t,x1:i,y1:l,x2:o,y2:r}){return t===me.Left||t===me.Right?[.5*(i+o),l]:[i,.5*(l+r)]}function cx({sourceX:t,sourceY:i,sourcePosition:l=me.Bottom,targetX:o,targetY:r,targetPosition:u=me.Top}){const[d,g]=n0({pos:l,x1:t,y1:i,x2:o,y2:r}),[p,y]=n0({pos:u,x1:o,y1:r,x2:t,y2:i}),[m,v,x,S]=zv({sourceX:t,sourceY:i,targetX:o,targetY:r,sourceControlX:d,sourceControlY:g,targetControlX:p,targetControlY:y});return[`M${t},${i} C${d},${g} ${p},${y} ${o},${r}`,m,v,x,S]}function ux(t){return Y.memo(({id:i,sourceX:l,sourceY:o,targetX:r,targetY:u,sourcePosition:d,targetPosition:g,label:p,labelStyle:y,labelShowBg:m,labelBgStyle:v,labelBgPadding:x,labelBgBorderRadius:S,style:w,markerEnd:j,markerStart:E,interactionWidth:A})=>{const[B,C,_]=cx({sourceX:l,sourceY:o,sourcePosition:d,targetX:r,targetY:u,targetPosition:g}),U=t.isInternal?void 0:i;return h.jsx(ic,{id:U,path:B,labelX:C,labelY:_,label:p,labelStyle:y,labelShowBg:m,labelBgStyle:v,labelBgPadding:x,labelBgBorderRadius:S,style:w,markerEnd:j,markerStart:E,interactionWidth:A})})}const kA=ux({isInternal:!1}),dx=ux({isInternal:!0});kA.displayName="SimpleBezierEdge";dx.displayName="SimpleBezierEdgeInternal";function fx(t){return Y.memo(({id:i,sourceX:l,sourceY:o,targetX:r,targetY:u,label:d,labelStyle:g,labelShowBg:p,labelBgStyle:y,labelBgPadding:m,labelBgBorderRadius:v,style:x,sourcePosition:S=me.Bottom,targetPosition:w=me.Top,markerEnd:j,markerStart:E,pathOptions:A,interactionWidth:B})=>{const[C,_,U]=uf({sourceX:l,sourceY:o,sourcePosition:S,targetX:r,targetY:u,targetPosition:w,borderRadius:A?.borderRadius,offset:A?.offset,stepPosition:A?.stepPosition}),R=t.isInternal?void 0:i;return h.jsx(ic,{id:R,path:C,labelX:_,labelY:U,label:d,labelStyle:g,labelShowBg:p,labelBgStyle:y,labelBgPadding:m,labelBgBorderRadius:v,style:x,markerEnd:j,markerStart:E,interactionWidth:B})})}const hx=fx({isInternal:!1}),gx=fx({isInternal:!0});hx.displayName="SmoothStepEdge";gx.displayName="SmoothStepEdgeInternal";function mx(t){return Y.memo(({id:i,...l})=>{const o=t.isInternal?void 0:i;return h.jsx(hx,{...l,id:o,pathOptions:Y.useMemo(()=>({borderRadius:0,offset:l.pathOptions?.offset}),[l.pathOptions?.offset])})})}const UA=mx({isInternal:!1}),px=mx({isInternal:!0});UA.displayName="StepEdge";px.displayName="StepEdgeInternal";function yx(t){return Y.memo(({id:i,sourceX:l,sourceY:o,targetX:r,targetY:u,label:d,labelStyle:g,labelShowBg:p,labelBgStyle:y,labelBgPadding:m,labelBgBorderRadius:v,style:x,markerEnd:S,markerStart:w,interactionWidth:j})=>{const[E,A,B]=Ov({sourceX:l,sourceY:o,targetX:r,targetY:u}),C=t.isInternal?void 0:i;return h.jsx(ic,{id:C,path:E,labelX:A,labelY:B,label:d,labelStyle:g,labelShowBg:p,labelBgStyle:y,labelBgPadding:m,labelBgBorderRadius:v,style:x,markerEnd:S,markerStart:w,interactionWidth:j})})}const qA=yx({isInternal:!1}),vx=yx({isInternal:!0});qA.displayName="StraightEdge";vx.displayName="StraightEdgeInternal";function xx(t){return Y.memo(({id:i,sourceX:l,sourceY:o,targetX:r,targetY:u,sourcePosition:d=me.Bottom,targetPosition:g=me.Top,label:p,labelStyle:y,labelShowBg:m,labelBgStyle:v,labelBgPadding:x,labelBgBorderRadius:S,style:w,markerEnd:j,markerStart:E,pathOptions:A,interactionWidth:B})=>{const[C,_,U]=Rv({sourceX:l,sourceY:o,sourcePosition:d,targetX:r,targetY:u,targetPosition:g,curvature:A?.curvature}),R=t.isInternal?void 0:i;return h.jsx(ic,{id:R,path:C,labelX:_,labelY:U,label:p,labelStyle:y,labelShowBg:m,labelBgStyle:v,labelBgPadding:x,labelBgBorderRadius:S,style:w,markerEnd:j,markerStart:E,interactionWidth:B})})}const GA=xx({isInternal:!1}),bx=xx({isInternal:!0});GA.displayName="BezierEdge";bx.displayName="BezierEdgeInternal";const a0={default:bx,straight:vx,step:px,smoothstep:gx,simplebezier:dx},i0={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},YA=(t,i,l)=>l===me.Left?t-i:l===me.Right?t+i:t,VA=(t,i,l)=>l===me.Top?t-i:l===me.Bottom?t+i:t,l0="react-flow__edgeupdater";function o0({position:t,centerX:i,centerY:l,radius:o=10,onMouseDown:r,onMouseEnter:u,onMouseOut:d,type:g}){return h.jsx("circle",{onMouseDown:r,onMouseEnter:u,onMouseOut:d,className:st([l0,`${l0}-${g}`]),cx:YA(i,o,t),cy:VA(l,o,t),r:o,stroke:"transparent",fill:"transparent"})}function XA({isReconnectable:t,reconnectRadius:i,edge:l,sourceX:o,sourceY:r,targetX:u,targetY:d,sourcePosition:g,targetPosition:p,onReconnect:y,onReconnectStart:m,onReconnectEnd:v,setReconnecting:x,setUpdateHover:S}){const w=Fe(),j=(_,U)=>{if(_.button!==0)return;const{autoPanOnConnect:R,domNode:z,connectionMode:I,connectionRadius:X,lib:ce,onConnectStart:K,cancelConnection:te,nodeLookup:ue,rfId:D,panBy:Z,updateConnection:M}=w.getState(),H=U.type==="target",q=(T,L)=>{x(!1),v?.(T,l,U.type,L)},k=T=>y?.(l,T),J=(T,L)=>{x(!0),m?.(_,l,U.type),K?.(T,L)};hf.onPointerDown(_.nativeEvent,{autoPanOnConnect:R,connectionMode:I,connectionRadius:X,domNode:z,handleId:U.id,nodeId:U.nodeId,nodeLookup:ue,isTarget:H,edgeUpdaterType:U.type,lib:ce,flowId:D,cancelConnection:te,panBy:Z,isValidConnection:(...T)=>w.getState().isValidConnection?.(...T)??!0,onConnect:k,onConnectStart:J,onConnectEnd:(...T)=>w.getState().onConnectEnd?.(...T),onReconnectEnd:q,updateConnection:M,getTransform:()=>w.getState().transform,getFromHandle:()=>w.getState().connection.fromHandle,dragThreshold:w.getState().connectionDragThreshold,handleDomNode:_.currentTarget})},E=_=>j(_,{nodeId:l.target,id:l.targetHandle??null,type:"target"}),A=_=>j(_,{nodeId:l.source,id:l.sourceHandle??null,type:"source"}),B=()=>S(!0),C=()=>S(!1);return h.jsxs(h.Fragment,{children:[(t===!0||t==="source")&&h.jsx(o0,{position:g,centerX:o,centerY:r,radius:i,onMouseDown:E,onMouseEnter:B,onMouseOut:C,type:"source"}),(t===!0||t==="target")&&h.jsx(o0,{position:p,centerX:u,centerY:d,radius:i,onMouseDown:A,onMouseEnter:B,onMouseOut:C,type:"target"})]})}function $A({id:t,edgesFocusable:i,edgesReconnectable:l,elementsSelectable:o,onClick:r,onDoubleClick:u,onContextMenu:d,onMouseEnter:g,onMouseMove:p,onMouseLeave:y,reconnectRadius:m,onReconnect:v,onReconnectStart:x,onReconnectEnd:S,rfId:w,edgeTypes:j,noPanClassName:E,onError:A,disableKeyboardA11y:B}){let C=Oe(ye=>ye.edgeLookup.get(t));const _=Oe(ye=>ye.defaultEdgeOptions);C=_?{..._,...C}:C;let U=C.type||"default",R=j?.[U]||a0[U];R===void 0&&(A?.("011",pn.error011(U)),U="default",R=j?.default||a0.default);const z=!!(C.focusable||i&&typeof C.focusable>"u"),I=typeof v<"u"&&(C.reconnectable||l&&typeof C.reconnectable>"u"),X=!!(C.selectable||o&&typeof C.selectable>"u"),ce=Y.useRef(null),[K,te]=Y.useState(!1),[ue,D]=Y.useState(!1),Z=Fe(),{zIndex:M,sourceX:H,sourceY:q,targetX:k,targetY:J,sourcePosition:T,targetPosition:L}=Oe(Y.useCallback(ye=>{const we=ye.nodeLookup.get(C.source),je=ye.nodeLookup.get(C.target);if(!we||!je)return{zIndex:C.zIndex,...i0};const qe=LC({id:t,sourceNode:we,targetNode:je,sourceHandle:C.sourceHandle||null,targetHandle:C.targetHandle||null,connectionMode:ye.connectionMode,onError:A});return{zIndex:jC({selected:C.selected,zIndex:C.zIndex,sourceNode:we,targetNode:je,elevateOnSelect:ye.elevateEdgesOnSelect,zIndexMode:ye.zIndexMode}),...qe||i0}},[C.source,C.target,C.sourceHandle,C.targetHandle,C.selected,C.zIndex]),Qe),ne=Y.useMemo(()=>C.markerStart?`url('#${df(C.markerStart,w)}')`:void 0,[C.markerStart,w]),ae=Y.useMemo(()=>C.markerEnd?`url('#${df(C.markerEnd,w)}')`:void 0,[C.markerEnd,w]);if(C.hidden||H===null||q===null||k===null||J===null)return null;const V=ye=>{const{addSelectedEdges:we,unselectNodesAndEdges:je,multiSelectionActive:qe}=Z.getState();X&&(Z.setState({nodesSelectionActive:!1}),C.selected&&qe?(je({nodes:[],edges:[C]}),ce.current?.blur()):we([t])),r&&r(ye,C)},se=u?ye=>{u(ye,{...C})}:void 0,de=d?ye=>{d(ye,{...C})}:void 0,le=g?ye=>{g(ye,{...C})}:void 0,fe=p?ye=>{p(ye,{...C})}:void 0,be=y?ye=>{y(ye,{...C})}:void 0,_e=ye=>{if(!B&&yv.includes(ye.key)&&X){const{unselectNodesAndEdges:we,addSelectedEdges:je}=Z.getState();ye.key==="Escape"?(ce.current?.blur(),we({edges:[C]})):je([t])}};return h.jsx("svg",{style:{zIndex:M},children:h.jsxs("g",{className:st(["react-flow__edge",`react-flow__edge-${U}`,C.className,E,{selected:C.selected,animated:C.animated,inactive:!X&&!r,updating:K,selectable:X}]),onClick:V,onDoubleClick:se,onContextMenu:de,onMouseEnter:le,onMouseMove:fe,onMouseLeave:be,onKeyDown:z?_e:void 0,tabIndex:z?0:void 0,role:C.ariaRole??(z?"group":"img"),"aria-roledescription":"edge","data-id":t,"data-testid":`rf__edge-${t}`,"aria-label":C.ariaLabel===null?void 0:C.ariaLabel||`Edge from ${C.source} to ${C.target}`,"aria-describedby":z?`${Qv}-${w}`:void 0,ref:ce,...C.domAttributes,children:[!ue&&h.jsx(R,{id:t,source:C.source,target:C.target,type:C.type,selected:C.selected,animated:C.animated,selectable:X,deletable:C.deletable??!0,label:C.label,labelStyle:C.labelStyle,labelShowBg:C.labelShowBg,labelBgStyle:C.labelBgStyle,labelBgPadding:C.labelBgPadding,labelBgBorderRadius:C.labelBgBorderRadius,sourceX:H,sourceY:q,targetX:k,targetY:J,sourcePosition:T,targetPosition:L,data:C.data,style:C.style,sourceHandleId:C.sourceHandle,targetHandleId:C.targetHandle,markerStart:ne,markerEnd:ae,pathOptions:"pathOptions"in C?C.pathOptions:void 0,interactionWidth:C.interactionWidth}),I&&h.jsx(XA,{edge:C,isReconnectable:I,reconnectRadius:m,onReconnect:v,onReconnectStart:x,onReconnectEnd:S,sourceX:H,sourceY:q,targetX:k,targetY:J,sourcePosition:T,targetPosition:L,setUpdateHover:te,setReconnecting:D})]})})}var ZA=Y.memo($A);const KA=t=>({edgesFocusable:t.edgesFocusable,edgesReconnectable:t.edgesReconnectable,elementsSelectable:t.elementsSelectable,connectionMode:t.connectionMode,onError:t.onError});function Sx({defaultMarkerColor:t,onlyRenderVisibleElements:i,rfId:l,edgeTypes:o,noPanClassName:r,onReconnect:u,onEdgeContextMenu:d,onEdgeMouseEnter:g,onEdgeMouseMove:p,onEdgeMouseLeave:y,onEdgeClick:m,reconnectRadius:v,onEdgeDoubleClick:x,onReconnectStart:S,onReconnectEnd:w,disableKeyboardA11y:j}){const{edgesFocusable:E,edgesReconnectable:A,elementsSelectable:B,onError:C}=Oe(KA,Qe),_=RA(i);return h.jsxs("div",{className:"react-flow__edges",children:[h.jsx(BA,{defaultColor:t,rfId:l}),_.map(U=>h.jsx(ZA,{id:U,edgesFocusable:E,edgesReconnectable:A,elementsSelectable:B,noPanClassName:r,onReconnect:u,onContextMenu:d,onMouseEnter:g,onMouseMove:p,onMouseLeave:y,onClick:m,reconnectRadius:v,onDoubleClick:x,onReconnectStart:S,onReconnectEnd:w,rfId:l,onError:C,edgeTypes:o,disableKeyboardA11y:j},U))]})}Sx.displayName="EdgeRenderer";const QA=Y.memo(Sx),FA=t=>`translate(${t.transform[0]}px,${t.transform[1]}px) scale(${t.transform[2]})`;function PA({children:t}){const i=Oe(FA);return h.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:i},children:t})}function JA(t){const i=nc(),l=Y.useRef(!1);Y.useEffect(()=>{!l.current&&i.viewportInitialized&&t&&(setTimeout(()=>t(i),1),l.current=!0)},[t,i.viewportInitialized])}const WA=t=>t.panZoom?.syncViewport;function eM(t){const i=Oe(WA),l=Fe();return Y.useEffect(()=>{t&&(i?.(t),l.setState({transform:[t.x,t.y,t.zoom]}))},[t,i]),null}function tM(t){return t.connection.inProgress?{...t.connection,to:qo(t.connection.to,t.transform)}:{...t.connection}}function nM(t){return tM}function aM(t){const i=nM();return Oe(i,Qe)}const iM=t=>({nodesConnectable:t.nodesConnectable,isValid:t.connection.isValid,inProgress:t.connection.inProgress,width:t.width,height:t.height});function lM({containerStyle:t,style:i,type:l,component:o}){const{nodesConnectable:r,width:u,height:d,isValid:g,inProgress:p}=Oe(iM,Qe);return!(u&&r&&p)?null:h.jsx("svg",{style:t,width:u,height:d,className:"react-flow__connectionline react-flow__container",children:h.jsx("g",{className:st(["react-flow__connection",bv(g)]),children:h.jsx(wx,{style:i,type:l,CustomComponent:o,isValid:g})})})}const wx=({style:t,type:i=Ea.Bezier,CustomComponent:l,isValid:o})=>{const{inProgress:r,from:u,fromNode:d,fromHandle:g,fromPosition:p,to:y,toNode:m,toHandle:v,toPosition:x,pointer:S}=aM();if(!r)return;if(l)return h.jsx(l,{connectionLineType:i,connectionLineStyle:t,fromNode:d,fromHandle:g,fromX:u.x,fromY:u.y,toX:y.x,toY:y.y,fromPosition:p,toPosition:x,connectionStatus:bv(o),toNode:m,toHandle:v,pointer:S});let w="";const j={sourceX:u.x,sourceY:u.y,sourcePosition:p,targetX:y.x,targetY:y.y,targetPosition:x};switch(i){case Ea.Bezier:[w]=Rv(j);break;case Ea.SimpleBezier:[w]=cx(j);break;case Ea.Step:[w]=uf({...j,borderRadius:0});break;case Ea.SmoothStep:[w]=uf(j);break;default:[w]=Ov(j)}return h.jsx("path",{d:w,fill:"none",className:"react-flow__connection-path",style:t})};wx.displayName="ConnectionLine";const oM={};function s0(t=oM){Y.useRef(t),Fe(),Y.useEffect(()=>{},[t])}function sM(){Fe(),Y.useRef(!1),Y.useEffect(()=>{},[])}function Nx({nodeTypes:t,edgeTypes:i,onInit:l,onNodeClick:o,onEdgeClick:r,onNodeDoubleClick:u,onEdgeDoubleClick:d,onNodeMouseEnter:g,onNodeMouseMove:p,onNodeMouseLeave:y,onNodeContextMenu:m,onSelectionContextMenu:v,onSelectionStart:x,onSelectionEnd:S,connectionLineType:w,connectionLineStyle:j,connectionLineComponent:E,connectionLineContainerStyle:A,selectionKeyCode:B,selectionOnDrag:C,selectionMode:_,multiSelectionKeyCode:U,panActivationKeyCode:R,zoomActivationKeyCode:z,deleteKeyCode:I,onlyRenderVisibleElements:X,elementsSelectable:ce,defaultViewport:K,translateExtent:te,minZoom:ue,maxZoom:D,preventScrolling:Z,defaultMarkerColor:M,zoomOnScroll:H,zoomOnPinch:q,panOnScroll:k,panOnScrollSpeed:J,panOnScrollMode:T,zoomOnDoubleClick:L,panOnDrag:ne,onPaneClick:ae,onPaneMouseEnter:V,onPaneMouseMove:se,onPaneMouseLeave:de,onPaneScroll:le,onPaneContextMenu:fe,paneClickDistance:be,nodeClickDistance:_e,onEdgeContextMenu:ye,onEdgeMouseEnter:we,onEdgeMouseMove:je,onEdgeMouseLeave:qe,reconnectRadius:Le,onReconnect:ut,onReconnectStart:Qt,onReconnectEnd:zt,noDragClassName:Ft,noWheelClassName:vn,noPanClassName:Ta,disableKeyboardA11y:Aa,nodeExtent:ft,rfId:ui,viewport:xn,onViewportChange:$n}){return s0(t),s0(i),sM(),JA(l),eM(xn),h.jsx(wA,{onPaneClick:ae,onPaneMouseEnter:V,onPaneMouseMove:se,onPaneMouseLeave:de,onPaneContextMenu:fe,onPaneScroll:le,paneClickDistance:be,deleteKeyCode:I,selectionKeyCode:B,selectionOnDrag:C,selectionMode:_,onSelectionStart:x,onSelectionEnd:S,multiSelectionKeyCode:U,panActivationKeyCode:R,zoomActivationKeyCode:z,elementsSelectable:ce,zoomOnScroll:H,zoomOnPinch:q,zoomOnDoubleClick:L,panOnScroll:k,panOnScrollSpeed:J,panOnScrollMode:T,panOnDrag:ne,defaultViewport:K,translateExtent:te,minZoom:ue,maxZoom:D,onSelectionContextMenu:v,preventScrolling:Z,noDragClassName:Ft,noWheelClassName:vn,noPanClassName:Ta,disableKeyboardA11y:Aa,onViewportChange:$n,isControlledViewport:!!xn,children:h.jsxs(PA,{children:[h.jsx(QA,{edgeTypes:i,onEdgeClick:r,onEdgeDoubleClick:d,onReconnect:ut,onReconnectStart:Qt,onReconnectEnd:zt,onlyRenderVisibleElements:X,onEdgeContextMenu:ye,onEdgeMouseEnter:we,onEdgeMouseMove:je,onEdgeMouseLeave:qe,reconnectRadius:Le,defaultMarkerColor:M,noPanClassName:Ta,disableKeyboardA11y:Aa,rfId:ui}),h.jsx(lM,{style:j,type:w,component:E,containerStyle:A}),h.jsx("div",{className:"react-flow__edgelabel-renderer"}),h.jsx(zA,{nodeTypes:t,onNodeClick:o,onNodeDoubleClick:u,onNodeMouseEnter:g,onNodeMouseMove:p,onNodeMouseLeave:y,onNodeContextMenu:m,nodeClickDistance:_e,onlyRenderVisibleElements:X,noPanClassName:Ta,noDragClassName:Ft,disableKeyboardA11y:Aa,nodeExtent:ft,rfId:ui}),h.jsx("div",{className:"react-flow__viewport-portal"})]})})}Nx.displayName="GraphView";const rM=Y.memo(Nx),r0=({nodes:t,edges:i,defaultNodes:l,defaultEdges:o,width:r,height:u,fitView:d,fitViewOptions:g,minZoom:p=.5,maxZoom:y=2,nodeOrigin:m,nodeExtent:v,zIndexMode:x="basic"}={})=>{const S=new Map,w=new Map,j=new Map,E=new Map,A=o??i??[],B=l??t??[],C=m??[0,0],_=v??jo;Bv(j,E,A);const{nodesInitialized:U}=ff(B,S,w,{nodeOrigin:C,nodeExtent:_,zIndexMode:x});let R=[0,0,1];if(d&&r&&u){const z=ko(S,{filter:K=>!!((K.width||K.initialWidth)&&(K.height||K.initialHeight))}),{x:I,y:X,zoom:ce}=Tf(z,r,u,p,y,g?.padding??.1);R=[I,X,ce]}return{rfId:"1",width:r??0,height:u??0,transform:R,nodes:B,nodesInitialized:U,nodeLookup:S,parentLookup:w,edges:A,edgeLookup:E,connectionLookup:j,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:l!==void 0,hasDefaultEdges:o!==void 0,panZoom:null,minZoom:p,maxZoom:y,translateExtent:jo,nodeExtent:_,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:dl.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:C,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:d??!1,fitViewOptions:g,fitViewResolver:null,connection:{...xv},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:_C,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:vv,zIndexMode:x,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},cM=({nodes:t,edges:i,defaultNodes:l,defaultEdges:o,width:r,height:u,fitView:d,fitViewOptions:g,minZoom:p,maxZoom:y,nodeOrigin:m,nodeExtent:v,zIndexMode:x})=>AT((S,w)=>{async function j(){const{nodeLookup:E,panZoom:A,fitViewOptions:B,fitViewResolver:C,width:_,height:U,minZoom:R,maxZoom:z}=w();A&&(await wC({nodes:E,width:_,height:U,panZoom:A,minZoom:R,maxZoom:z},B),C?.resolve(!0),S({fitViewResolver:null}))}return{...r0({nodes:t,edges:i,width:r,height:u,fitView:d,fitViewOptions:g,minZoom:p,maxZoom:y,nodeOrigin:m,nodeExtent:v,defaultNodes:l,defaultEdges:o,zIndexMode:x}),setNodes:E=>{const{nodeLookup:A,parentLookup:B,nodeOrigin:C,elevateNodesOnSelect:_,fitViewQueued:U,zIndexMode:R,nodesSelectionActive:z}=w(),{nodesInitialized:I,hasSelectedNodes:X}=ff(E,A,B,{nodeOrigin:C,nodeExtent:v,elevateNodesOnSelect:_,checkEquality:!0,zIndexMode:R}),ce=z&&X;U&&I?(j(),S({nodes:E,nodesInitialized:I,fitViewQueued:!1,fitViewOptions:void 0,nodesSelectionActive:ce})):S({nodes:E,nodesInitialized:I,nodesSelectionActive:ce})},setEdges:E=>{const{connectionLookup:A,edgeLookup:B}=w();Bv(A,B,E),S({edges:E})},setDefaultNodesAndEdges:(E,A)=>{if(E){const{setNodes:B}=w();B(E),S({hasDefaultNodes:!0})}if(A){const{setEdges:B}=w();B(A),S({hasDefaultEdges:!0})}},updateNodeInternals:E=>{const{triggerNodeChanges:A,nodeLookup:B,parentLookup:C,domNode:_,nodeOrigin:U,nodeExtent:R,debug:z,fitViewQueued:I,zIndexMode:X}=w(),{changes:ce,updatedInternals:K}=$C(E,B,C,_,U,R,X);K&&(GC(B,C,{nodeOrigin:U,nodeExtent:R,zIndexMode:X}),I?(j(),S({fitViewQueued:!1,fitViewOptions:void 0})):S({}),ce?.length>0&&(z&&console.log("React Flow: trigger node changes",ce),A?.(ce)))},updateNodePositions:(E,A=!1)=>{const B=[];let C=[];const{nodeLookup:_,triggerNodeChanges:U,connection:R,updateConnection:z,onNodesChangeMiddlewareMap:I}=w();for(const[X,ce]of E){const K=_.get(X),te=!!(K?.expandParent&&K?.parentId&&ce?.position),ue={id:X,type:"position",position:te?{x:Math.max(0,ce.position.x),y:Math.max(0,ce.position.y)}:ce.position,dragging:A};if(K&&R.inProgress&&R.fromNode.id===K.id){const D=ri(K,R.fromHandle,me.Left,!0);z({...R,from:D})}te&&K.parentId&&B.push({id:X,parentId:K.parentId,rect:{...ce.internals.positionAbsolute,width:ce.measured.width??0,height:ce.measured.height??0}}),C.push(ue)}if(B.length>0){const{parentLookup:X,nodeOrigin:ce}=w(),K=Df(B,_,X,ce);C.push(...K)}for(const X of I.values())C=X(C);U(C)},triggerNodeChanges:E=>{const{onNodesChange:A,setNodes:B,nodes:C,hasDefaultNodes:_,debug:U}=w();if(E?.length){if(_){const R=Jv(E,C);B(R)}U&&console.log("React Flow: trigger node changes",E),A?.(E)}},triggerEdgeChanges:E=>{const{onEdgesChange:A,setEdges:B,edges:C,hasDefaultEdges:_,debug:U}=w();if(E?.length){if(_){const R=Wv(E,C);B(R)}U&&console.log("React Flow: trigger edge changes",E),A?.(E)}},addSelectedNodes:E=>{const{multiSelectionActive:A,edgeLookup:B,nodeLookup:C,triggerNodeChanges:_,triggerEdgeChanges:U}=w();if(A){const R=E.map(z=>Wa(z,!0));_(R);return}_(il(C,new Set([...E]),!0)),U(il(B))},addSelectedEdges:E=>{const{multiSelectionActive:A,edgeLookup:B,nodeLookup:C,triggerNodeChanges:_,triggerEdgeChanges:U}=w();if(A){const R=E.map(z=>Wa(z,!0));U(R);return}U(il(B,new Set([...E]))),_(il(C,new Set,!0))},unselectNodesAndEdges:({nodes:E,edges:A}={})=>{const{edges:B,nodes:C,nodeLookup:_,triggerNodeChanges:U,triggerEdgeChanges:R}=w(),z=E||C,I=A||B,X=[];for(const K of z){if(!K.selected)continue;const te=_.get(K.id);te&&(te.selected=!1),X.push(Wa(K.id,!1))}const ce=[];for(const K of I)K.selected&&ce.push(Wa(K.id,!1));U(X),R(ce)},setMinZoom:E=>{const{panZoom:A,maxZoom:B}=w();A?.setScaleExtent([E,B]),S({minZoom:E})},setMaxZoom:E=>{const{panZoom:A,minZoom:B}=w();A?.setScaleExtent([B,E]),S({maxZoom:E})},setTranslateExtent:E=>{w().panZoom?.setTranslateExtent(E),S({translateExtent:E})},resetSelectedElements:()=>{const{edges:E,nodes:A,triggerNodeChanges:B,triggerEdgeChanges:C,elementsSelectable:_}=w();if(!_)return;const U=A.reduce((z,I)=>I.selected?[...z,Wa(I.id,!1)]:z,[]),R=E.reduce((z,I)=>I.selected?[...z,Wa(I.id,!1)]:z,[]);B(U),C(R)},setNodeExtent:E=>{const{nodes:A,nodeLookup:B,parentLookup:C,nodeOrigin:_,elevateNodesOnSelect:U,nodeExtent:R,zIndexMode:z}=w();E[0][0]===R[0][0]&&E[0][1]===R[0][1]&&E[1][0]===R[1][0]&&E[1][1]===R[1][1]||(ff(A,B,C,{nodeOrigin:_,nodeExtent:E,elevateNodesOnSelect:U,checkEquality:!1,zIndexMode:z}),S({nodeExtent:E}))},panBy:E=>{const{transform:A,width:B,height:C,panZoom:_,translateExtent:U}=w();return ZC({delta:E,panZoom:_,transform:A,translateExtent:U,width:B,height:C})},setCenter:async(E,A,B)=>{const{width:C,height:_,maxZoom:U,panZoom:R}=w();if(!R)return Promise.resolve(!1);const z=typeof B?.zoom<"u"?B.zoom:U;return await R.setViewport({x:C/2-E*z,y:_/2-A*z,zoom:z},{duration:B?.duration,ease:B?.ease,interpolate:B?.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{S({connection:{...xv}})},updateConnection:E=>{S({connection:E})},reset:()=>S({...r0()})}},Object.is);function _x({initialNodes:t,initialEdges:i,defaultNodes:l,defaultEdges:o,initialWidth:r,initialHeight:u,initialMinZoom:d,initialMaxZoom:g,initialFitViewOptions:p,fitView:y,nodeOrigin:m,nodeExtent:v,zIndexMode:x,children:S}){const[w]=Y.useState(()=>cM({nodes:t,edges:i,defaultNodes:l,defaultEdges:o,width:r,height:u,fitView:y,minZoom:d,maxZoom:g,fitViewOptions:p,nodeOrigin:m,nodeExtent:v,zIndexMode:x}));return h.jsx(MT,{value:w,children:h.jsx(PT,{children:S})})}function uM({children:t,nodes:i,edges:l,defaultNodes:o,defaultEdges:r,width:u,height:d,fitView:g,fitViewOptions:p,minZoom:y,maxZoom:m,nodeOrigin:v,nodeExtent:x,zIndexMode:S}){return Y.useContext(tc)?h.jsx(h.Fragment,{children:t}):h.jsx(_x,{initialNodes:i,initialEdges:l,defaultNodes:o,defaultEdges:r,initialWidth:u,initialHeight:d,fitView:g,initialFitViewOptions:p,initialMinZoom:y,initialMaxZoom:m,nodeOrigin:v,nodeExtent:x,zIndexMode:S,children:t})}const dM={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function fM({nodes:t,edges:i,defaultNodes:l,defaultEdges:o,className:r,nodeTypes:u,edgeTypes:d,onNodeClick:g,onEdgeClick:p,onInit:y,onMove:m,onMoveStart:v,onMoveEnd:x,onConnect:S,onConnectStart:w,onConnectEnd:j,onClickConnectStart:E,onClickConnectEnd:A,onNodeMouseEnter:B,onNodeMouseMove:C,onNodeMouseLeave:_,onNodeContextMenu:U,onNodeDoubleClick:R,onNodeDragStart:z,onNodeDrag:I,onNodeDragStop:X,onNodesDelete:ce,onEdgesDelete:K,onDelete:te,onSelectionChange:ue,onSelectionDragStart:D,onSelectionDrag:Z,onSelectionDragStop:M,onSelectionContextMenu:H,onSelectionStart:q,onSelectionEnd:k,onBeforeDelete:J,connectionMode:T,connectionLineType:L=Ea.Bezier,connectionLineStyle:ne,connectionLineComponent:ae,connectionLineContainerStyle:V,deleteKeyCode:se="Backspace",selectionKeyCode:de="Shift",selectionOnDrag:le=!1,selectionMode:fe=zo.Full,panActivationKeyCode:be="Space",multiSelectionKeyCode:_e=Do()?"Meta":"Control",zoomActivationKeyCode:ye=Do()?"Meta":"Control",snapToGrid:we,snapGrid:je,onlyRenderVisibleElements:qe=!1,selectNodesOnDrag:Le,nodesDraggable:ut,autoPanOnNodeFocus:Qt,nodesConnectable:zt,nodesFocusable:Ft,nodeOrigin:vn=Fv,edgesFocusable:Ta,edgesReconnectable:Aa,elementsSelectable:ft=!0,defaultViewport:ui=GT,minZoom:xn=.5,maxZoom:$n=2,translateExtent:Ma=jo,preventScrolling:lc=!0,nodeExtent:di,defaultMarkerColor:oc="#b1b1b7",zoomOnScroll:sc=!0,zoomOnPinch:ja=!0,panOnScroll:xt=!1,panOnScrollSpeed:sn=.5,panOnScrollMode:bt=ii.Free,zoomOnDoubleClick:rc=!0,panOnDrag:cc=!0,onPaneClick:uc,onPaneMouseEnter:fi,onPaneMouseMove:hi,onPaneMouseLeave:gi,onPaneScroll:bn,onPaneContextMenu:mi,paneClickDistance:za=1,nodeClickDistance:dc=0,children:Yo,onReconnect:yl,onReconnectStart:Ra,onReconnectEnd:fc,onEdgeContextMenu:Vo,onEdgeDoubleClick:Xo,onEdgeMouseEnter:$o,onEdgeMouseMove:vl,onEdgeMouseLeave:xl,reconnectRadius:Zo=10,onNodesChange:Ko,onEdgesChange:rn,noDragClassName:rt="nodrag",noWheelClassName:yt="nowheel",noPanClassName:Sn="nopan",fitView:pi,fitViewOptions:Qo,connectOnClick:hc,attributionPosition:Fo,proOptions:Da,defaultEdgeOptions:bl,elevateNodesOnSelect:Zn=!0,elevateEdgesOnSelect:Kn=!1,disableKeyboardA11y:Qn=!1,autoPanOnConnect:Fn,autoPanOnNodeDrag:tt,autoPanSpeed:Po,connectionRadius:Jo,isValidConnection:wn,onError:Pn,style:gc,id:Sl,nodeDragThreshold:Wo,connectionDragThreshold:mc,viewport:yi,onViewportChange:vi,width:Pt,height:wt,colorMode:es="light",debug:pc,onScroll:xi,ariaLabelConfig:ts,zIndexMode:Oa="basic",...yc},Nt){const Ha=Sl||"1",ns=$T(es),wl=Y.useCallback(Nn=>{Nn.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),xi?.(Nn)},[xi]);return h.jsx("div",{"data-testid":"rf__wrapper",...yc,onScroll:wl,style:{...gc,...dM},ref:Nt,className:st(["react-flow",r,ns]),id:Sl,role:"application",children:h.jsxs(uM,{nodes:t,edges:i,width:Pt,height:wt,fitView:pi,fitViewOptions:Qo,minZoom:xn,maxZoom:$n,nodeOrigin:vn,nodeExtent:di,zIndexMode:Oa,children:[h.jsx(XT,{nodes:t,edges:i,defaultNodes:l,defaultEdges:o,onConnect:S,onConnectStart:w,onConnectEnd:j,onClickConnectStart:E,onClickConnectEnd:A,nodesDraggable:ut,autoPanOnNodeFocus:Qt,nodesConnectable:zt,nodesFocusable:Ft,edgesFocusable:Ta,edgesReconnectable:Aa,elementsSelectable:ft,elevateNodesOnSelect:Zn,elevateEdgesOnSelect:Kn,minZoom:xn,maxZoom:$n,nodeExtent:di,onNodesChange:Ko,onEdgesChange:rn,snapToGrid:we,snapGrid:je,connectionMode:T,translateExtent:Ma,connectOnClick:hc,defaultEdgeOptions:bl,fitView:pi,fitViewOptions:Qo,onNodesDelete:ce,onEdgesDelete:K,onDelete:te,onNodeDragStart:z,onNodeDrag:I,onNodeDragStop:X,onSelectionDrag:Z,onSelectionDragStart:D,onSelectionDragStop:M,onMove:m,onMoveStart:v,onMoveEnd:x,noPanClassName:Sn,nodeOrigin:vn,rfId:Ha,autoPanOnConnect:Fn,autoPanOnNodeDrag:tt,autoPanSpeed:Po,onError:Pn,connectionRadius:Jo,isValidConnection:wn,selectNodesOnDrag:Le,nodeDragThreshold:Wo,connectionDragThreshold:mc,onBeforeDelete:J,debug:pc,ariaLabelConfig:ts,zIndexMode:Oa}),h.jsx(rM,{onInit:y,onNodeClick:g,onEdgeClick:p,onNodeMouseEnter:B,onNodeMouseMove:C,onNodeMouseLeave:_,onNodeContextMenu:U,onNodeDoubleClick:R,nodeTypes:u,edgeTypes:d,connectionLineType:L,connectionLineStyle:ne,connectionLineComponent:ae,connectionLineContainerStyle:V,selectionKeyCode:de,selectionOnDrag:le,selectionMode:fe,deleteKeyCode:se,multiSelectionKeyCode:_e,panActivationKeyCode:be,zoomActivationKeyCode:ye,onlyRenderVisibleElements:qe,defaultViewport:ui,translateExtent:Ma,minZoom:xn,maxZoom:$n,preventScrolling:lc,zoomOnScroll:sc,zoomOnPinch:ja,zoomOnDoubleClick:rc,panOnScroll:xt,panOnScrollSpeed:sn,panOnScrollMode:bt,panOnDrag:cc,onPaneClick:uc,onPaneMouseEnter:fi,onPaneMouseMove:hi,onPaneMouseLeave:gi,onPaneScroll:bn,onPaneContextMenu:mi,paneClickDistance:za,nodeClickDistance:dc,onSelectionContextMenu:H,onSelectionStart:q,onSelectionEnd:k,onReconnect:yl,onReconnectStart:Ra,onReconnectEnd:fc,onEdgeContextMenu:Vo,onEdgeDoubleClick:Xo,onEdgeMouseEnter:$o,onEdgeMouseMove:vl,onEdgeMouseLeave:xl,reconnectRadius:Zo,defaultMarkerColor:oc,noDragClassName:rt,noWheelClassName:yt,noPanClassName:Sn,rfId:Ha,disableKeyboardA11y:Qn,nodeExtent:di,viewport:yi,onViewportChange:vi}),h.jsx(qT,{onSelectionChange:ue}),Yo,h.jsx(IT,{proOptions:Da,position:Fo}),h.jsx(HT,{rfId:Ha,disableKeyboardA11y:Qn})]})})}var hM=ex(fM);function gM({dimensions:t,lineWidth:i,variant:l,className:o}){return h.jsx("path",{strokeWidth:i,d:`M${t[0]/2} 0 V${t[1]} M0 ${t[1]/2} H${t[0]}`,className:st(["react-flow__background-pattern",l,o])})}function mM({radius:t,className:i}){return h.jsx("circle",{cx:t,cy:t,r:t,className:st(["react-flow__background-pattern","dots",i])})}var Ca;(function(t){t.Lines="lines",t.Dots="dots",t.Cross="cross"})(Ca||(Ca={}));const pM={[Ca.Dots]:1,[Ca.Lines]:1,[Ca.Cross]:6},yM=t=>({transform:t.transform,patternId:`pattern-${t.rfId}`});function Ex({id:t,variant:i=Ca.Dots,gap:l=20,size:o,lineWidth:r=1,offset:u=0,color:d,bgColor:g,style:p,className:y,patternClassName:m}){const v=Y.useRef(null),{transform:x,patternId:S}=Oe(yM,Qe),w=o||pM[i],j=i===Ca.Dots,E=i===Ca.Cross,A=Array.isArray(l)?l:[l,l],B=[A[0]*x[2]||1,A[1]*x[2]||1],C=w*x[2],_=Array.isArray(u)?u:[u,u],U=E?[C,C]:B,R=[_[0]*x[2]||1+U[0]/2,_[1]*x[2]||1+U[1]/2],z=`${S}${t||""}`;return h.jsxs("svg",{className:st(["react-flow__background",y]),style:{...p,...ac,"--xy-background-color-props":g,"--xy-background-pattern-color-props":d},ref:v,"data-testid":"rf__background",children:[h.jsx("pattern",{id:z,x:x[0]%B[0],y:x[1]%B[1],width:B[0],height:B[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${R[0]},-${R[1]})`,children:j?h.jsx(mM,{radius:C/2,className:m}):h.jsx(gM,{dimensions:U,lineWidth:r,variant:i,className:m})}),h.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${z})`})]})}Ex.displayName="Background";const vM=Y.memo(Ex);function xM(){return h.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:h.jsx("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function bM(){return h.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:h.jsx("path",{d:"M0 0h32v4.2H0z"})})}function SM(){return h.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:h.jsx("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"})})}function wM(){return h.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:h.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"})})}function NM(){return h.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:h.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"})})}function _r({children:t,className:i,...l}){return h.jsx("button",{type:"button",className:st(["react-flow__controls-button",i]),...l,children:t})}const _M=t=>({isInteractive:t.nodesDraggable||t.nodesConnectable||t.elementsSelectable,minZoomReached:t.transform[2]<=t.minZoom,maxZoomReached:t.transform[2]>=t.maxZoom,ariaLabelConfig:t.ariaLabelConfig});function Cx({style:t,showZoom:i=!0,showFitView:l=!0,showInteractive:o=!0,fitViewOptions:r,onZoomIn:u,onZoomOut:d,onFitView:g,onInteractiveChange:p,className:y,children:m,position:v="bottom-left",orientation:x="vertical","aria-label":S}){const w=Fe(),{isInteractive:j,minZoomReached:E,maxZoomReached:A,ariaLabelConfig:B}=Oe(_M,Qe),{zoomIn:C,zoomOut:_,fitView:U}=nc(),R=()=>{C(),u?.()},z=()=>{_(),d?.()},I=()=>{U(r),g?.()},X=()=>{w.setState({nodesDraggable:!j,nodesConnectable:!j,elementsSelectable:!j}),p?.(!j)},ce=x==="horizontal"?"horizontal":"vertical";return h.jsxs(Go,{className:st(["react-flow__controls",ce,y]),position:v,style:t,"data-testid":"rf__controls","aria-label":S??B["controls.ariaLabel"],children:[i&&h.jsxs(h.Fragment,{children:[h.jsx(_r,{onClick:R,className:"react-flow__controls-zoomin",title:B["controls.zoomIn.ariaLabel"],"aria-label":B["controls.zoomIn.ariaLabel"],disabled:A,children:h.jsx(xM,{})}),h.jsx(_r,{onClick:z,className:"react-flow__controls-zoomout",title:B["controls.zoomOut.ariaLabel"],"aria-label":B["controls.zoomOut.ariaLabel"],disabled:E,children:h.jsx(bM,{})})]}),l&&h.jsx(_r,{className:"react-flow__controls-fitview",onClick:I,title:B["controls.fitView.ariaLabel"],"aria-label":B["controls.fitView.ariaLabel"],children:h.jsx(SM,{})}),o&&h.jsx(_r,{className:"react-flow__controls-interactive",onClick:X,title:B["controls.interactive.ariaLabel"],"aria-label":B["controls.interactive.ariaLabel"],children:j?h.jsx(NM,{}):h.jsx(wM,{})}),m]})}Cx.displayName="Controls";const EM=Y.memo(Cx);function CM({id:t,x:i,y:l,width:o,height:r,style:u,color:d,strokeColor:g,strokeWidth:p,className:y,borderRadius:m,shapeRendering:v,selected:x,onClick:S}){const{background:w,backgroundColor:j}=u||{},E=d||w||j;return h.jsx("rect",{className:st(["react-flow__minimap-node",{selected:x},y]),x:i,y:l,rx:m,ry:m,width:o,height:r,style:{fill:E,stroke:g,strokeWidth:p},shapeRendering:v,onClick:S?A=>S(A,t):void 0})}const TM=Y.memo(CM),AM=t=>t.nodes.map(i=>i.id),Fd=t=>t instanceof Function?t:()=>t;function MM({nodeStrokeColor:t,nodeColor:i,nodeClassName:l="",nodeBorderRadius:o=5,nodeStrokeWidth:r,nodeComponent:u=TM,onClick:d}){const g=Oe(AM,Qe),p=Fd(i),y=Fd(t),m=Fd(l),v=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return h.jsx(h.Fragment,{children:g.map(x=>h.jsx(zM,{id:x,nodeColorFunc:p,nodeStrokeColorFunc:y,nodeClassNameFunc:m,nodeBorderRadius:o,nodeStrokeWidth:r,NodeComponent:u,onClick:d,shapeRendering:v},x))})}function jM({id:t,nodeColorFunc:i,nodeStrokeColorFunc:l,nodeClassNameFunc:o,nodeBorderRadius:r,nodeStrokeWidth:u,shapeRendering:d,NodeComponent:g,onClick:p}){const{node:y,x:m,y:v,width:x,height:S}=Oe(w=>{const j=w.nodeLookup.get(t);if(!j)return{node:void 0,x:0,y:0,width:0,height:0};const E=j.internals.userNode,{x:A,y:B}=j.internals.positionAbsolute,{width:C,height:_}=Xn(E);return{node:E,x:A,y:B,width:C,height:_}},Qe);return!y||y.hidden||!Cv(y)?null:h.jsx(g,{x:m,y:v,width:x,height:S,style:y.style,selected:!!y.selected,className:o(y),color:i(y),borderRadius:r,strokeColor:l(y),strokeWidth:u,shapeRendering:d,onClick:p,id:y.id})}const zM=Y.memo(jM);var RM=Y.memo(MM);const DM=200,OM=150,HM=t=>!t.hidden,IM=t=>{const i={x:-t.transform[0]/t.transform[2],y:-t.transform[1]/t.transform[2],width:t.width/t.transform[2],height:t.height/t.transform[2]};return{viewBB:i,boundingRect:t.nodeLookup.size>0?Ev(ko(t.nodeLookup,{filter:HM}),i):i,rfId:t.rfId,panZoom:t.panZoom,translateExtent:t.translateExtent,flowWidth:t.width,flowHeight:t.height,ariaLabelConfig:t.ariaLabelConfig}},BM="react-flow__minimap-desc";function Tx({style:t,className:i,nodeStrokeColor:l,nodeColor:o,nodeClassName:r="",nodeBorderRadius:u=5,nodeStrokeWidth:d,nodeComponent:g,bgColor:p,maskColor:y,maskStrokeColor:m,maskStrokeWidth:v,position:x="bottom-right",onClick:S,onNodeClick:w,pannable:j=!1,zoomable:E=!1,ariaLabel:A,inversePan:B,zoomStep:C=1,offsetScale:_=5}){const U=Fe(),R=Y.useRef(null),{boundingRect:z,viewBB:I,rfId:X,panZoom:ce,translateExtent:K,flowWidth:te,flowHeight:ue,ariaLabelConfig:D}=Oe(IM,Qe),Z=t?.width??DM,M=t?.height??OM,H=z.width/Z,q=z.height/M,k=Math.max(H,q),J=k*Z,T=k*M,L=_*k,ne=z.x-(J-z.width)/2-L,ae=z.y-(T-z.height)/2-L,V=J+L*2,se=T+L*2,de=`${BM}-${X}`,le=Y.useRef(0),fe=Y.useRef();le.current=k,Y.useEffect(()=>{if(R.current&&ce)return fe.current=nT({domNode:R.current,panZoom:ce,getTransform:()=>U.getState().transform,getViewScale:()=>le.current}),()=>{fe.current?.destroy()}},[ce]),Y.useEffect(()=>{fe.current?.update({translateExtent:K,width:te,height:ue,inversePan:B,pannable:j,zoomStep:C,zoomable:E})},[j,E,B,C,K,te,ue]);const be=S?we=>{const[je,qe]=fe.current?.pointer(we)||[0,0];S(we,{x:je,y:qe})}:void 0,_e=w?Y.useCallback((we,je)=>{const qe=U.getState().nodeLookup.get(je).internals.userNode;w(we,qe)},[]):void 0,ye=A??D["minimap.ariaLabel"];return h.jsx(Go,{position:x,style:{...t,"--xy-minimap-background-color-props":typeof p=="string"?p:void 0,"--xy-minimap-mask-background-color-props":typeof y=="string"?y:void 0,"--xy-minimap-mask-stroke-color-props":typeof m=="string"?m:void 0,"--xy-minimap-mask-stroke-width-props":typeof v=="number"?v*k:void 0,"--xy-minimap-node-background-color-props":typeof o=="string"?o:void 0,"--xy-minimap-node-stroke-color-props":typeof l=="string"?l:void 0,"--xy-minimap-node-stroke-width-props":typeof d=="number"?d:void 0},className:st(["react-flow__minimap",i]),"data-testid":"rf__minimap",children:h.jsxs("svg",{width:Z,height:M,viewBox:`${ne} ${ae} ${V} ${se}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":de,ref:R,onClick:be,children:[ye&&h.jsx("title",{id:de,children:ye}),h.jsx(RM,{onClick:_e,nodeColor:o,nodeStrokeColor:l,nodeBorderRadius:u,nodeClassName:r,nodeStrokeWidth:d,nodeComponent:g}),h.jsx("path",{className:"react-flow__minimap-mask",d:`M${ne-L},${ae-L}h${V+L*2}v${se+L*2}h${-V-L*2}z
|
|
21
|
-
M${I.x},${I.y}h${I.width}v${I.height}h${-I.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}Tx.displayName="MiniMap";const LM=Y.memo(Tx),kM=t=>i=>t?`${Math.max(1/i.transform[2],1)}`:void 0,UM={[ml.Line]:"right",[ml.Handle]:"bottom-right"};function qM({nodeId:t,position:i,variant:l=ml.Handle,className:o,style:r=void 0,children:u,color:d,minWidth:g=10,minHeight:p=10,maxWidth:y=Number.MAX_VALUE,maxHeight:m=Number.MAX_VALUE,keepAspectRatio:v=!1,resizeDirection:x,autoScale:S=!0,shouldResize:w,onResizeStart:j,onResize:E,onResizeEnd:A}){const B=ix(),C=typeof t=="string"?t:B,_=Fe(),U=Y.useRef(null),R=l===ml.Handle,z=Oe(Y.useCallback(kM(R&&S),[R,S]),Qe),I=Y.useRef(null),X=i??UM[l];Y.useEffect(()=>{if(!(!U.current||!C))return I.current||(I.current=pT({domNode:U.current,nodeId:C,getStoreItems:()=>{const{nodeLookup:K,transform:te,snapGrid:ue,snapToGrid:D,nodeOrigin:Z,domNode:M}=_.getState();return{nodeLookup:K,transform:te,snapGrid:ue,snapToGrid:D,nodeOrigin:Z,paneDomNode:M}},onChange:(K,te)=>{const{triggerNodeChanges:ue,nodeLookup:D,parentLookup:Z,nodeOrigin:M}=_.getState(),H=[],q={x:K.x,y:K.y},k=D.get(C);if(k&&k.expandParent&&k.parentId){const J=k.origin??M,T=K.width??k.measured.width??0,L=K.height??k.measured.height??0,ne={id:k.id,parentId:k.parentId,rect:{width:T,height:L,...Tv({x:K.x??k.position.x,y:K.y??k.position.y},{width:T,height:L},k.parentId,D,J)}},ae=Df([ne],D,Z,M);H.push(...ae),q.x=K.x?Math.max(J[0]*T,K.x):void 0,q.y=K.y?Math.max(J[1]*L,K.y):void 0}if(q.x!==void 0&&q.y!==void 0){const J={id:C,type:"position",position:{...q}};H.push(J)}if(K.width!==void 0&&K.height!==void 0){const T={id:C,type:"dimensions",resizing:!0,setAttributes:x?x==="horizontal"?"width":"height":!0,dimensions:{width:K.width,height:K.height}};H.push(T)}for(const J of te){const T={...J,type:"position"};H.push(T)}ue(H)},onEnd:({width:K,height:te})=>{const ue={id:C,type:"dimensions",resizing:!1,dimensions:{width:K,height:te}};_.getState().triggerNodeChanges([ue])}})),I.current.update({controlPosition:X,boundaries:{minWidth:g,minHeight:p,maxWidth:y,maxHeight:m},keepAspectRatio:v,resizeDirection:x,onResizeStart:j,onResize:E,onResizeEnd:A,shouldResize:w}),()=>{I.current?.destroy()}},[X,g,p,y,m,v,j,E,A,w]);const ce=X.split("-");return h.jsx("div",{className:st(["react-flow__resize-control","nodrag",...ce,l,o]),ref:U,style:{...r,scale:z,...d&&{[R?"backgroundColor":"borderColor"]:d}},children:u})}Y.memo(qM);const Pd=5,Or=240,GM=180,YM=420;function VM(t){const i=/^(\d+)x(\d+)$/.exec(t??"");if(!i)return Or;const l=Number(i[1]),o=Number(i[2]);if(!Number.isFinite(l)||!Number.isFinite(o)||l<=0||o<=0)return Or;const r=Or*(l/o);return Math.round(Math.min(YM,Math.max(GM,r)))}function XM({id:t,data:i,selected:l}){const{t:o}=Te(),r=i,u=W(k=>k.updateNodePrompt),d=W(k=>k.addNodeReferences),g=W(k=>k.removeNodeReference),p=W(k=>k.generateNode),y=W(k=>k.generateNodeInPlace),m=W(k=>k.generateNodeVariation),v=W(k=>k.addChildNode),x=W(k=>k.duplicateBranchRoot),S=W(k=>k.deleteNode),w=Y.useRef(null),[j,E]=Y.useState(!1),A=r.referenceImages??[],B=r.status==="pending"||r.status==="reconciling",C=!B&&A.length<Pd,_={"--node-preview-w":`${VM(r.size)}px`,"--node-preview-h":`${Or}px`},U=Y.useCallback(k=>u(t,k.target.value),[t,u]),R=Y.useCallback(()=>{p(t)},[t,p]),z=Y.useCallback(()=>{y(t)},[t,y]),I=Y.useCallback(()=>{m(t)},[t,m]),X=Y.useCallback(()=>{r.status==="ready"&&v(t)},[t,r.status,v]),ce=Y.useCallback(()=>{x(t)},[t,x]),K=Y.useCallback(()=>S(t),[t,S]),te=k=>{if(!k)return[];const J=[];for(const T of Array.from(k)){if(T.kind!=="file"||!T.type.startsWith("image/"))continue;const L=T.getAsFile();L&&J.push(L)}return J},ue=k=>{if(k.preventDefault(),k.stopPropagation(),E(!1),!C)return;const J=Array.from(k.dataTransfer.files).filter(T=>T.type.startsWith("image/"));J.length>0&&d(t,J)},D=k=>{k.preventDefault(),k.stopPropagation(),C&&!j&&E(!0)},Z=k=>{k.currentTarget.contains(k.relatedTarget)||E(!1)},M=k=>{const J=te(k.clipboardData?.items??null);if(J.length===0||(k.preventDefault(),k.stopPropagation(),!C))return;const T=Pd-A.length;d(t,J.slice(0,T))},q=(()=>{switch(r.status){case"empty":return o("node.empty");case"pending":return o("node.pending");case"reconciling":return r.pendingPhase?o("node.reconcilingPhase",{phase:r.pendingPhase}):o("node.reconciling");case"ready":return[r.webSearchCalls?o("node.readyWithSearch",{elapsed:r.elapsed??"?",searches:r.webSearchCalls}):o("node.ready",{elapsed:r.elapsed??"?"}),b0(r.model)].filter(Boolean).join(" · ");case"stale":return r.error?o("node.staleWithError",{error:r.error}):o("node.stale");case"asset-missing":return r.error?o("node.assetMissingWithError",{error:r.error}):o("node.assetMissing");case"error":return o("node.error",{error:r.error??o("node.errorUnknown")});default:return""}})();return h.jsxs("div",{className:`image-node image-node--${r.status}${l?" image-node--selected":""}`,style:_,children:[r.parentServerNodeId?h.jsx(pl,{type:"target",position:me.Left,className:"image-node__handle"}):null,h.jsx("div",{className:"image-node__preview",children:r.imageUrl&&r.status!=="asset-missing"?h.jsx("img",{src:r.imageUrl,alt:o("node.nodeImageAlt")}):B&&r.partialImageUrl?h.jsx("img",{className:"image-node__partial",src:r.partialImageUrl,alt:o("node.partialImageAlt")}):B?h.jsx("div",{className:"image-node__skeleton"}):r.status==="asset-missing"?h.jsx("div",{className:"image-node__placeholder",children:o("node.noAsset")}):r.status==="stale"?h.jsx("div",{className:"image-node__placeholder",children:o("node.stateStale")}):h.jsx("div",{className:"image-node__placeholder",children:o("node.noImage")})}),h.jsxs("div",{className:`image-node__composer nodrag${j?" is-dragging":""}`,onDrop:ue,onDragOver:D,onDragLeave:Z,onPaste:M,children:[A.length>0?h.jsx("div",{className:"image-node__refs",children:A.map((k,J)=>h.jsxs("div",{className:"image-node__ref-chip",title:o("node.refAlt",{n:J+1}),children:[h.jsx("img",{src:k,alt:o("node.refAlt",{n:J+1})}),h.jsx("button",{type:"button",className:"image-node__ref-remove",onClick:()=>g(t,J),disabled:B,"aria-label":o("node.removeRef",{n:J+1}),children:"×"})]},J))}):null,h.jsx("textarea",{className:"image-node__prompt",value:r.prompt,onChange:U,onKeyDown:k=>k.stopPropagation(),placeholder:r.parentServerNodeId?o("node.editPromptPlaceholder"):o("node.promptPlaceholder"),rows:2,disabled:B}),h.jsxs("div",{className:"image-node__composer-bar",children:[h.jsx("button",{type:"button",className:"image-node__attach",onClick:()=>C&&w.current?.click(),disabled:!C,title:r.parentServerNodeId?o("node.nodeRefsUsedWithParent"):o("node.attachRefTitle"),children:o("node.attachRef")}),j?h.jsx("span",{className:"image-node__drop-hint",children:o("node.dropRefs")}):A.length>0?h.jsxs("span",{className:"image-node__ref-count",children:[A.length,"/",Pd]}):null]}),h.jsx("input",{ref:w,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:k=>{const J=Array.from(k.target.files??[]);J.length>0&&d(t,J),k.target.value=""}})]}),h.jsxs("div",{className:"image-node__footer nodrag",children:[h.jsx("span",{className:"image-node__status",title:q,children:q}),h.jsxs("div",{className:"image-node__actions",children:[r.status==="ready"?h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",onClick:z,disabled:B,title:o("node.regenerateTitle"),"aria-label":o("node.regenerateTitle"),children:"↻"}),h.jsx("button",{type:"button",onClick:I,disabled:B,title:o("node.newVariationTitle"),"aria-label":o("node.newVariationTitle"),children:o("node.newVariation")})]}):h.jsx("button",{type:"button",onClick:R,disabled:B,children:o("node.generate")}),r.status==="ready"?h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",onClick:X,title:o("node.addChildTitle"),"aria-label":o("node.addChildTitle"),children:o("node.addChild")}),h.jsx("button",{type:"button",onClick:ce,title:o("node.duplicateBranchTitle"),"aria-label":o("node.duplicateBranchTitle"),children:o("node.duplicateBranch")})]}):null,h.jsx("button",{type:"button",onClick:K,className:"image-node__del",title:o("node.deleteTitle"),"aria-label":o("node.deleteTitle"),children:"×"})]})]}),h.jsx(pl,{type:"source",position:me.Right,className:"image-node__handle image-node__handle--source"})]})}const $M=Y.memo(XM);function ZM(){const{t}=Te(),i=W(E=>E.graphNodes),l=W(E=>E.graphEdges),o=W(E=>E.nodeSelectionMode),r=W(E=>E.nodeBatchRunning),u=W(E=>E.nodeBatchStopping),d=W(E=>E.toggleNodeSelectionMode),g=W(E=>E.selectAllGraphNodes),p=W(E=>E.clearNodeSelection),y=W(E=>E.runNodeBatch),m=W(E=>E.cancelNodeBatch),v=i.filter(E=>E.selected).map(E=>E.id),x=new Set(v),S=i.filter(E=>x.has(E.id)&&!E0(E)).length,w=C0(l,v).length,j=E=>{y(E)};return h.jsxs(Go,{position:"top-center",className:"node-batch-bar nodrag",children:[h.jsx("button",{type:"button",onClick:d,"aria-pressed":o,children:t(o?"nodeBatch.selectionOn":"nodeBatch.selectionOff")}),h.jsx("button",{type:"button",onClick:g,disabled:i.length===0,children:t("nodeBatch.selectAll")}),v.length>0?h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"node-batch-bar__meta",children:t("nodeBatch.summary",{selected:v.length,missing:S,stale:w})}),h.jsx("button",{type:"button",onClick:()=>j("missing-only"),disabled:r,children:t("nodeBatch.generateMissing")}),h.jsx("button",{type:"button",onClick:()=>j("regenerate-all"),disabled:r,children:t("nodeBatch.regenerateSelected")}),r?h.jsx("button",{type:"button",onClick:m,disabled:u,children:t(u?"nodeBatch.stopping":"nodeBatch.stopRemaining")}):null,h.jsx("button",{type:"button",onClick:p,disabled:r,children:t("nodeBatch.clear")})]}):null]})}function KM(){const{t}=Te(),i=W(z=>z.graphNodes),l=W(z=>z.graphEdges),o=W(z=>z.setGraphNodes),r=W(z=>z.setGraphEdges),u=W(z=>z.disconnectEdges),d=W(z=>z.addRootNode),g=W(z=>z.addChildNodeAt),p=W(z=>z.connectNodes),y=W(z=>z.deleteNodes),m=W(z=>z.nodeSelectionMode),v=W(z=>z.selectNodeGraph),x=W(z=>z.sessionLoading),S=W(z=>z.resolvedTheme),{screenToFlowPosition:w}=nc(),j=Y.useRef(null),E=Y.useMemo(()=>({imageNode:$M}),[]),A=Y.useCallback(z=>o(Jv(z,i)),[i,o]),B=Y.useCallback(z=>{const I=z.filter(X=>X.type==="remove").map(X=>X.id);if(I.length>0){if(m)return;u(I);return}r(Wv(z,l))},[u,l,m,r]),C=Y.useCallback(z=>{z.source&&z.target&&p(z.source,z.target)},[p]),_=Y.useCallback((z,I)=>{if(I.isValid)return;const X=I.fromNode?.id;if(!X)return;const ce="touches"in z?z.changedTouches[0].clientX:z.clientX,K="touches"in z?z.changedTouches[0].clientY:z.clientY,te=w({x:ce,y:K});g(X,te)},[g,w]),U=Y.useCallback(z=>y(z.map(I=>I.id)),[y]),R=Y.useCallback((z,I)=>{m&&(z.preventDefault(),v(I.id,z.metaKey||z.ctrlKey))},[m,v]);return h.jsxs("main",{className:"node-canvas",ref:j,children:[x&&h.jsx("div",{className:"node-canvas__loading",children:t("nodeCanvas.loading")}),i.length===0?h.jsx("button",{type:"button",className:"node-canvas__plus",onClick:()=>d(),children:t("nodeCanvas.addFirst")}):h.jsxs(h.Fragment,{children:[h.jsxs(hM,{nodes:i,edges:l,onNodesChange:A,onEdgesChange:B,onConnect:C,onConnectEnd:_,onNodesDelete:U,onNodeClick:R,nodeTypes:E,connectionRadius:32,selectionOnDrag:m,multiSelectionKeyCode:m?null:void 0,panOnDrag:m?[2]:!0,fitView:!0,deleteKeyCode:m?null:["Delete","Backspace"],proOptions:{hideAttribution:!0},children:[h.jsx(ZM,{}),h.jsx(vM,{gap:24,color:S==="light"?"#d9dee6":"#2a2a2a"}),h.jsx(EM,{className:"node-canvas__controls"}),h.jsx(LM,{pannable:!0,zoomable:!0,maskColor:S==="light"?"rgba(246, 247, 251, 0.72)":"rgba(10, 10, 10, 0.7)",nodeColor:S==="light"?"#1f2430":"#f0f0f0",nodeStrokeColor:S==="light"?"#ffffff":"#1a1a1a",style:{background:S==="light"?"#ffffff":"#141414",border:`1px solid ${S==="light"?"#d9dee6":"#2a2a2a"}`}})]}),h.jsx("button",{type:"button",className:"node-canvas__add-root",onClick:()=>d(),title:t("nodeCanvas.addRootTitle"),children:"+"}),h.jsx("div",{className:"node-canvas__hint",children:t("nodeCanvas.hint")})]})]})}function QM(){return h.jsx(_x,{children:h.jsx(KM,{})})}function Gn({title:t,help:i,items:l,value:o,onChange:r}){return h.jsxs("div",{className:"option-group",children:[t?h.jsx("div",{className:"section-title",children:t}):null,h.jsx("div",{className:"option-row",children:l.map(u=>h.jsxs("button",{className:`option-btn${u.value===o?" active":""}`,style:u.color?{color:u.color}:void 0,disabled:u.disabled,onClick:()=>r(u.value),type:"button",children:[u.label,u.sub?h.jsxs(h.Fragment,{children:[h.jsx("br",{}),h.jsx("span",{className:"option-sub",children:u.sub})]}):null]},u.value))}),i?h.jsx("p",{className:"option-help",children:i}):null]})}function mo(t){return t.map(i=>({value:i.value,label:i.label,sub:i.sub}))}function FM(){const t=W(S=>S.sizePreset),i=W(S=>S.setSizePreset),l=W(S=>S.customW),o=W(S=>S.customH),r=W(S=>S.setCustomSize),{t:u}=Te(),[d,g]=Y.useState(String(l)),[p,y]=Y.useState(String(o)),m=t==="custom";Y.useEffect(()=>{g(String(l)),y(String(o))},[l,o]);function v(){const S=sl(d,l),w=sl(p,o);r(S,w),g(String(S)),y(String(w))}function x(S){S.key==="Enter"&&(S.preventDefault(),v())}return h.jsxs("div",{className:"option-group",children:[h.jsx("div",{className:"section-title",children:u("size.title")}),h.jsx(Gn,{title:"",items:mo(Hw),value:t,onChange:i}),h.jsx(Gn,{title:"",items:mo(Iw),value:t,onChange:i}),h.jsx(Gn,{title:"",items:mo(Bw),value:t,onChange:i}),h.jsx(Gn,{title:"",items:mo(Lw),value:t,onChange:i}),h.jsx(Gn,{title:"",items:mo(kw()),value:t,onChange:i}),m?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"option-row",children:[h.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:d,onChange:S=>g(S.target.value.replace(/\D/g,"")),onBlur:v,onKeyDown:x,placeholder:u("size.width")}),h.jsx("span",{style:{color:"var(--text-dim)",alignSelf:"center",fontFamily:"var(--mono)",fontSize:12},children:"x"}),h.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:p,onChange:S=>y(S.target.value.replace(/\D/g,"")),onBlur:v,onKeyDown:x,placeholder:u("size.height")})]}),h.jsx("div",{className:"size-hint",children:u("size.hint")})]}):null]})}const PM={low:{"1024x1024":.006,"1024x1536":.005,"1536x1024":.005,"1024x1360":.005,"1360x1024":.005,"1024x1824":.006,"1824x1024":.006,"2048x2048":.012,"2048x1152":.009,"1152x2048":.009,"3824x2160":.023,"2160x3824":.023,auto:.006},medium:{"1024x1024":.053,"1024x1536":.041,"1536x1024":.041,"1024x1360":.041,"1360x1024":.041,"1024x1824":.05,"1824x1024":.05,"2048x2048":.106,"2048x1152":.08,"1152x2048":.08,"3824x2160":.2,"2160x3824":.2,auto:.053},high:{"1024x1024":.211,"1024x1536":.165,"1536x1024":.165,"1024x1360":.165,"1360x1024":.165,"1024x1824":.2,"1824x1024":.2,"2048x2048":.422,"2048x1152":.32,"1152x2048":.32,"3824x2160":.8,"2160x3824":.8,auto:.211}};function JM(t,i){return PM[t]?.[i]??0}function WM(){const{t}=Te(),i=W(y=>y.provider),l=W(y=>y.quality),r=W(y=>y.getResolvedSize)(),u=i==="oauth",d=JM(l,r),g=u?t("cost.free"):t("cost.approx",{amount:d.toFixed(3)}),p=u?"var(--green)":void 0;return h.jsxs("div",{className:"cost-estimate",children:[h.jsx("span",{children:t("cost.label")}),h.jsx("span",{className:"price",style:p?{color:p}:void 0,children:g})]})}const ej=[{value:"png",label:"PNG"},{value:"jpeg",label:"JPEG"},{value:"webp",label:"WebP"}],tj=[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"}];function nj(){const t=W(E=>E.rightPanelOpen),i=W(E=>E.toggleRightPanel),{t:l}=Te(),[o,r]=Y.useState(typeof window<"u"?window.matchMedia("(max-width: 800px)").matches:!1);Y.useEffect(()=>{if(typeof window>"u")return;const E=window.matchMedia("(max-width: 800px)"),A=()=>r(E.matches);return E.addEventListener("change",A),()=>E.removeEventListener("change",A)},[]);const u=o?t:!0,d=W(E=>E.quality),g=W(E=>E.setQuality),p=W(E=>E.format),y=W(E=>E.setFormat),m=W(E=>E.moderation),v=W(E=>E.setModeration),x=W(E=>E.count),S=W(E=>E.setCount),w=[{value:"low",label:l("quality.lowLabel"),sub:l("quality.lowSub")},{value:"medium",label:l("quality.mediumLabel"),sub:l("quality.mediumSub")},{value:"high",label:l("quality.highLabel"),sub:l("quality.highSub")}],j=[{value:"auto",label:l("moderation.autoLabel"),sub:l("moderation.autoSub")},{value:"low",label:l("moderation.lowLabel"),sub:l("moderation.lowSub"),color:"var(--amber)"}];return h.jsxs(h.Fragment,{children:[o&&t?h.jsx("div",{className:"right-panel-backdrop",role:"button","aria-label":l("panel.closeSettings"),onClick:i}):null,h.jsxs("aside",{className:`right-panel${t?"":" collapsed"}${o&&u?" drawer-open":""}`,"aria-label":l("panel.detailSettings"),children:[h.jsx("button",{type:"button",className:"right-panel-toggle","aria-expanded":t,"aria-controls":"right-panel-body",onClick:i,title:l(t?"panel.toggleHide":"panel.toggleShow"),children:o?l(t?"panel.close":"panel.open"):t?">":"<"}),h.jsxs("div",{id:"right-panel-body",className:"right-panel-body",hidden:!t,children:[h.jsx("div",{className:"section-title",children:l("panel.detailSettings")}),h.jsx(Gn,{title:l("quality.title"),items:w,value:d,onChange:g}),h.jsx(FM,{}),h.jsx(Gn,{title:l("format.title"),items:ej,value:p,onChange:y}),h.jsx(Gn,{title:l("moderation.title"),items:j,value:m,onChange:v}),h.jsx("p",{className:"option-help",children:l("moderation.explain")}),h.jsx(Gn,{title:l("count.title"),items:tj,value:String(x),onChange:E=>S(Number(E))}),h.jsx(WM,{})]})]})]})}function aj(){const[t,i]=Y.useState(null),[l,o]=Y.useState(!1);return Y.useEffect(()=>{let r=!1;return ZS().then(u=>{r||i(u)}).catch(()=>{r||o(!0)}),()=>{r=!0}},[]),{data:t,error:l}}function ij(){const[t,i]=Y.useState(null);return Y.useEffect(()=>{let l=!1,o=null;const r=async()=>{try{const u=await $S();if(l)return;i(u),u.status==="starting"&&(o=setTimeout(r,3e3))}catch{l||i(null)}};return r(),()=>{l=!0,o&&clearTimeout(o)}},[]),t}function lj(t){return t==="ready"?"Ready":t==="auth_required"?"Login required":t==="starting"?"Starting":t==="offline"?"Offline":"Checking"}function oj(){const{t}=Te(),i=ij(),{data:l,error:o}=aj(),r=l?.apiKeySource==="env"||l?.apiKeySource==="config"||l?.apiKeyValid===!0,u=i?.status==="ready",d=l?.apiKeySource==="config"?t("settings.account.apiSourceConfig"):t("settings.account.apiSourceEnv");return h.jsxs(h.Fragment,{children:[h.jsxs("article",{className:"settings-row",children:[h.jsxs("div",{className:"settings-row__copy",children:[h.jsx("p",{className:"settings-eyebrow",children:t("settings.account.primaryEyebrow")}),h.jsx("h4",{children:t("settings.account.oauthTitle")}),h.jsx("p",{children:t("settings.account.oauthBody")})]}),h.jsxs("div",{className:`settings-status${u?" is-ok":""}`,children:[h.jsx("span",{"aria-hidden":"true"}),lj(i?.status)]})]}),r?h.jsxs("article",{className:"settings-row",children:[h.jsxs("div",{className:"settings-row__copy",children:[h.jsx("p",{className:"settings-eyebrow",children:d}),h.jsx("h4",{children:t("settings.account.apiTitle")}),h.jsx("p",{children:t("settings.account.apiBody")})]}),h.jsxs("div",{className:"settings-status is-muted",children:[h.jsx("span",{"aria-hidden":"true"}),t(o?"settings.account.apiUnknown":"settings.account.apiDisabled")]})]}):null]})}const sj={ko:"KO",en:"EN"};function rj(){const{t,locale:i}=Te(),l=W(o=>o.setLocale);return h.jsx("div",{className:"lang-toggle",role:"group","aria-label":t("language.label"),children:Mw.map(o=>h.jsx("button",{type:"button",className:`lang-toggle__btn ${i===o?"is-active":""}`,onClick:()=>l(o),"aria-pressed":i===o,title:t(`language.${o}`),children:h.jsx("span",{className:"lang-toggle__label",children:sj[o]})},o))})}const cj=["system","dark","light"];function uj(){const{t}=Te(),i=W(o=>o.theme),l=W(o=>o.setTheme);return h.jsx("div",{className:"theme-toggle",role:"group","aria-label":t("theme.label"),children:cj.map(o=>h.jsx("button",{type:"button",className:`theme-toggle__btn ${i===o?"is-active":""}`,onClick:()=>l(o),"aria-pressed":i===o,title:t(`theme.${o}`),children:t(`theme.${o}`)},o))})}const Jd=["account","generation","appearance","language","future"];function po({id:t,setRef:i,children:l}){const{t:o}=Te();return h.jsxs("section",{id:t,ref:r=>i(t,r),className:"settings-section","aria-labelledby":`settings-section-${t}`,children:[h.jsx("header",{className:"settings-section__header",children:h.jsxs("div",{children:[h.jsx("h3",{id:`settings-section-${t}`,children:o(`settings.sections.${t}.title`)}),h.jsx("p",{children:o(`settings.sections.${t}.hint`)})]})}),h.jsx("div",{className:"settings-section__body",children:l})]})}function dj(){const{t}=Te(),i=W(m=>m.activeSettingsSection),l=W(m=>m.setActiveSettingsSection),o=W(m=>m.closeSettings),r=Y.useRef(null),u=Y.useRef(null),d=Y.useRef(!1),g=Y.useRef({account:null,generation:null,appearance:null,language:null,future:null}),p=(m,v)=>{g.current[m]=v},y=m=>{l(m),d.current=!0,g.current[m]?.scrollIntoView({behavior:"auto",block:"start"}),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>{d.current=!1,u.current=null},120)};return Y.useEffect(()=>{const m=v=>{v.key==="Escape"&&o()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[o]),Y.useEffect(()=>{const m=r.current;if(!m||typeof IntersectionObserver!="function")return;const v=new IntersectionObserver(x=>{if(d.current)return;const w=x.filter(j=>j.isIntersecting).sort((j,E)=>E.intersectionRatio-j.intersectionRatio)[0]?.target.id;w&&Jd.includes(w)&&l(w)},{root:m,threshold:[.35,.6]});for(const x of Jd){const S=g.current[x];S&&v.observe(S)}return()=>v.disconnect()},[l]),Y.useEffect(()=>()=>{u.current!==null&&window.clearTimeout(u.current)},[]),h.jsx("main",{ref:r,className:"settings-workspace","aria-labelledby":"settings-title",children:h.jsxs("div",{className:"settings-shell",children:[h.jsxs("header",{className:"settings-header",children:[h.jsxs("div",{children:[h.jsx("p",{className:"settings-eyebrow",children:t("settings.eyebrow")}),h.jsx("h2",{id:"settings-title",children:t("settings.title")}),h.jsx("p",{children:t("settings.subtitle")})]}),h.jsx("button",{type:"button",className:"settings-close",onClick:o,"aria-label":t("settings.closeAria"),title:t("settings.closeTitle"),children:"X"})]}),h.jsxs("div",{className:"settings-layout",children:[h.jsx("nav",{className:"settings-nav","aria-label":t("settings.navAria"),children:Jd.map(m=>h.jsxs("button",{type:"button",className:`settings-nav__item${i===m?" is-active":""}`,onClick:()=>y(m),"aria-label":t("settings.jumpTo",{section:t(`settings.sections.${m}.title`)}),children:[h.jsx("span",{children:t(`settings.sections.${m}.title`)}),h.jsx("small",{children:t(`settings.sections.${m}.hint`)})]},m))}),h.jsxs("section",{className:"settings-content","aria-label":t("settings.contentAria"),children:[h.jsx(po,{id:"account",setRef:p,children:h.jsx(oj,{})}),h.jsx(po,{id:"generation",setRef:p,children:h.jsxs("article",{className:"settings-row",children:[h.jsxs("div",{className:"settings-row__copy",children:[h.jsx("h4",{children:t("settings.imageModel.title")}),h.jsx("p",{children:t("settings.imageModel.body")}),h.jsx("p",{className:"settings-row__microcopy",children:t("settings.imageModel.unsupportedHelp")})]}),h.jsx("div",{className:"settings-row__control",children:h.jsx(L0,{variant:"settings"})})]})}),h.jsx(po,{id:"appearance",setRef:p,children:h.jsxs("article",{className:"settings-row",children:[h.jsxs("div",{className:"settings-row__copy",children:[h.jsx("h4",{children:t("settings.appearance.themeTitle")}),h.jsx("p",{children:t("settings.appearance.themeBody")})]}),h.jsx("div",{className:"settings-row__control",children:h.jsx(uj,{})})]})}),h.jsx(po,{id:"language",setRef:p,children:h.jsxs("article",{className:"settings-row",children:[h.jsxs("div",{className:"settings-row__copy",children:[h.jsx("h4",{children:t("settings.language.title")}),h.jsx("p",{children:t("settings.language.body")})]}),h.jsx("div",{className:"settings-row__control",children:h.jsx(rj,{})})]})}),h.jsx(po,{id:"future",setRef:p,children:h.jsxs("article",{className:"settings-note",children:[h.jsx("h4",{children:t("settings.future.title")}),h.jsx("p",{children:t("settings.future.body")})]})})]})]})]})})}function fj(){const t=W(r=>r.toast),[i,l]=Y.useState(!1);if(Y.useEffect(()=>{if(!t)return;l(!0);const r=setTimeout(()=>l(!1),3e3);return()=>clearTimeout(r)},[t]),!t)return null;const o=["toast",i?"visible":"",t.error?"error":""].filter(Boolean).join(" ");return h.jsx("div",{className:o,children:t.message})}function hj(){const{t}=Te(),i=W(v=>v.errorCard),l=W(v=>v.dismissErrorCard);if(!i)return null;const o=wo[i.code]??wo.UNKNOWN,r=`${o.cardKey??"errorCard.unknown"}.title`,u=`${o.cardKey??"errorCard.unknown"}.body`,d=o.cta?`${o.cardKey??"errorCard.unknown"}.cta`:null,g=t(r),p=t(u),y=d?t(d):null,m=()=>{if(o.cta==="reload"){window.location.reload();return}else l()};return h.jsx("div",{className:"error-card-backdrop",role:"alertdialog","aria-labelledby":"error-card-title",children:h.jsxs("div",{className:"error-card",children:[h.jsx("div",{className:"error-card__icon","aria-hidden":"true",children:h.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"12",cy:"12",r:"10"}),h.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),h.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),h.jsxs("div",{className:"error-card__content",children:[h.jsx("h3",{id:"error-card-title",className:"error-card__title",children:g}),h.jsx("p",{className:"error-card__body",children:p}),i.fallbackMessage&&h.jsxs("details",{className:"error-card__details",children:[h.jsx("summary",{children:t("errorCard.details")}),h.jsx("pre",{children:i.fallbackMessage})]}),h.jsxs("div",{className:"error-card__actions",children:[h.jsx("button",{type:"button",className:"btn btn--ghost",onClick:l,children:t("errorCard.close")}),y&&h.jsx("button",{type:"button",className:"btn btn--primary",onClick:m,children:y})]})]})]})})}function gj(t){if(!t)return"earlier";const i=new Date(t);if(Number.isNaN(i.getTime()))return"earlier";const o=Math.floor((new Date().getTime()-i.getTime())/864e5);return o===0?"today":o===1?"yesterday":o<7?"thisWeek":i.toLocaleDateString("ko-KR",{year:"numeric",month:"short",day:"numeric"})}function c0(t){return t.filename||t.image}function mj({item:t,onOpen:i,onCopyPath:l,onDownloadManifest:o}){const{t:r}=Te(),d=t.cards?.find(g=>g.headline)?.headline||t.headline||r("gallery.cardNewsSet");return h.jsxs(h.Fragment,{children:[h.jsxs("button",{type:"button",className:"gallery__tile",onClick:()=>i(t),title:d,children:[t.image?h.jsx("img",{src:t.image,alt:d,loading:"lazy"}):null,h.jsxs("div",{className:"gallery__caption",children:[h.jsx("small",{children:r("gallery.cardNewsSet")}),h.jsx("span",{className:"gallery__caption-text",children:d})]}),h.jsx("div",{className:"gallery-card-news-strip",children:(t.cards||[]).slice(0,5).map((g,p)=>h.jsxs("span",{children:[g.url?h.jsx("img",{src:g.url,alt:g.headline??"",loading:"lazy"}):null,h.jsx("em",{children:g.cardOrder??p+1})]},`${g.url}-${p}`))})]}),h.jsxs("div",{className:"gallery-card-news-actions",children:[h.jsx("span",{children:r("gallery.cardNewsCount",{n:t.cards?.length??0})}),h.jsx("button",{type:"button",onClick:()=>i(t),children:r("gallery.openCardNewsSet")}),h.jsx("button",{type:"button",onClick:g=>l(t,g),children:r("gallery.copyCardNewsSetPath")}),h.jsx("button",{type:"button",onClick:g=>o(t,g),children:r("gallery.downloadCardNewsManifest")})]})]})}function pj({item:t,active:i,itemRef:l,onSelect:o,onDelete:r,t:u}){return h.jsxs("div",{ref:l,className:`gallery__tile-wrap${i?" gallery__tile-wrap--active":""}`,children:[h.jsxs("button",{type:"button",className:`gallery__tile${i?" gallery__tile--active":""}`,onClick:()=>o(t),title:t.prompt??"",children:[h.jsx("img",{src:t.thumb||t.image,alt:t.prompt??u("gallery.imageAltFallback"),loading:"lazy",decoding:"async"}),t.prompt&&h.jsx("div",{className:"gallery__caption",children:h.jsx("span",{className:"gallery__caption-text",children:t.prompt})})]}),t.filename&&h.jsx("button",{type:"button",className:"gallery__delete",onClick:d=>r(t,d),title:u("gallery.deleteTitle"),"aria-label":u("gallery.deleteAria"),children:"×"})]})}const u0="ima2.storageNoticeDismissed.0.09.23";function yj(){const{t}=Te(),i=W(V=>V.galleryOpen),l=W(V=>V.closeGallery),o=W(V=>V.history),r=W(V=>V.selectHistory),u=W(V=>V.currentImage),d=W(V=>V.removeFromHistory),g=W(V=>V.addHistoryItem),p=W(V=>V.showToast),[y,m]=Y.useState(""),[v,x]=Y.useState("date"),[S,w]=Y.useState([]),[j,E]=Y.useState([]),[A,B]=Y.useState(null),[C,_]=Y.useState(null),[U,R]=Y.useState(()=>{try{return localStorage.getItem(u0)==="1"}catch{return!1}}),z=Y.useRef(null),I=Y.useRef({}),X=Y.useRef(0);Y.useEffect(()=>{if(!i)return;const V=se=>{se.key==="Escape"&&l()};return window.addEventListener("keydown",V),()=>window.removeEventListener("keydown",V)},[i,l]),Y.useEffect(()=>{i||(m(""),B(null))},[i]),Y.useEffect(()=>{if(!i)return;let V=!1;return(async()=>{try{const se=await FS();V||_(se)}catch{V||_({generatedDirLabel:"~/.ima2/generated",generatedCount:0,legacyCandidatesScanned:0,legacySourcesFound:0,legacyFilesFound:0,state:"unknown",messageKind:"unknown",recoveryDocsPath:"docs/RECOVER_OLD_IMAGES.md",doctorCommand:"ima2 doctor",overrides:{generatedDir:!1,configDir:!1}})}})(),()=>{V=!0}},[i]),Y.useEffect(()=>{if(!i||v!=="session")return;let V=!1;return(async()=>{try{const se=await QS({limit:500});if(V)return;const de=le=>{const fe=le.kind,be=fe==="classic"||fe==="edit"||fe==="generate"||fe==="card-news-card"||fe==="card-news-set"?fe:null;return{image:le.url,url:le.url,filename:le.filename,prompt:le.prompt??void 0,size:le.size??void 0,quality:le.quality??void 0,model:le.model??void 0,provider:le.provider,createdAt:le.createdAt,sessionId:le.sessionId??null,nodeId:le.nodeId??null,clientNodeId:le.clientNodeId??null,kind:be,setId:le.setId??null,cardId:le.cardId??null,cardOrder:le.cardOrder??null,headline:le.headline??null,body:le.body??null,cards:le.cards}};w(se.sessions.map(le=>({sessionId:le.sessionId,title:le.title??null,label:le.label??null,displayLabel:le.title||le.label||le.sessionId.slice(0,8),items:le.items.map(de)}))),E(se.loose.map(de))}catch{}})(),()=>{V=!0}},[i,v]);const ce=Y.useMemo(()=>{const V=y.trim().toLowerCase().normalize("NFC");return V?o.filter(se=>(se.prompt??"").toLowerCase().normalize("NFC").includes(V)||(se.filename??"").toLowerCase().normalize("NFC").includes(V)):o},[o,y]),K=Y.useMemo(()=>{const V=new Map;for(const se of ce){const de=gj(se.createdAt);V.has(de)||V.set(de,[]),V.get(de).push(se)}return Array.from(V.entries())},[ce]),te=v==="session"?S.reduce((V,se)=>V+se.items.length,0)+j.length:ce.length;Y.useLayoutEffect(()=>{if(!i)return;const V=u?c0(u):null,se=V?I.current[V]:null;if(se){se.scrollIntoView({block:"center"});return}z.current&&(z.current.scrollTop=X.current)},[i,u?.filename,u?.image,v,te,K.length,S.length,j.length]),Y.useEffect(()=>{if(!A)return;const V=setInterval(()=>{B(se=>!se||Date.now()>=se.expiresAt?null:{...se})},500);return()=>clearInterval(V)},[A]);async function ue(V,se){if(se.stopPropagation(),!!V.filename)try{const de=await JS(V.filename);d(V.filename),B({filename:V.filename,trashId:de.trashId,item:V,expiresAt:Date.now()+9500})}catch(de){console.error("[gallery] delete failed",de)}}async function D(){if(A)try{await WS(A.filename,A.trashId),g(A.item)}catch(V){console.error("[gallery] restore failed",V)}finally{B(null)}}async function Z(){try{await PS()}catch{p(t("toast.openGeneratedDirFailed"),!0)}}async function M(V){if(V.setId)try{await Se.getState().loadSet(V.setId),W.getState().setUIMode("card-news"),l()}catch{p(t("gallery.openCardNewsSetFailed"),!0)}}async function H(V,se){if(se.stopPropagation(),!V.setId)return;const de=`generated/cardnews/${V.setId}`;try{await navigator.clipboard?.writeText(de),p(t("gallery.cardNewsPathCopied"))}catch{p(t("toast.copyFailed"),!0)}}function q(V,se){se.stopPropagation(),V.setId&&window.open(TN(V.setId),"_blank","noopener,noreferrer")}function k(){R(!0);try{localStorage.setItem(u0,"1")}catch{}}if(!i)return null;const J=V=>V==="earlier"||V==="today"||V==="yesterday"||V==="thisWeek"?t(`gallery.${V}`):V,T=(V,se,de)=>{const le=u?.image===V.image,fe=be=>{I.current[c0(V)]=be};return V.kind==="card-news-set"?h.jsx("div",{ref:fe,className:"gallery__tile-wrap gallery-card-news-set",children:h.jsx(mj,{item:V,onOpen:be=>{M(be)},onCopyPath:H,onDownloadManifest:q})},`${se}-${de}-${V.filename??de}`):h.jsx(pj,{item:V,active:le,itemRef:fe,onSelect:be=>{r(be),l()},onDelete:ue,t},`${se}-${de}-${V.filename??de}`)},L=v==="session",ne=C!=null&&C.state!=="ok"&&!U,ae=C?.state==="recoverable"?"gallery.storageNoticeRecoverable":C?.state==="not_found"?"gallery.storageNoticeNotFound":"gallery.storageNoticeUnknown";return h.jsx("div",{className:"gallery-backdrop",onClick:l,role:"presentation",children:h.jsxs("div",{className:"gallery",role:"dialog","aria-modal":"true","aria-label":t("gallery.ariaLabel"),onClick:V=>V.stopPropagation(),children:[h.jsxs("div",{className:"gallery__header",children:[h.jsxs("div",{className:"gallery__title-row",children:[h.jsx("div",{className:"gallery__title",children:t("gallery.title")}),h.jsxs("div",{className:"gallery__meta",children:[t("gallery.total",{n:te}),y?t("gallery.totalFiltered",{n:o.length}):""]}),h.jsxs("div",{className:"gallery__group-toggle",role:"tablist","aria-label":t("gallery.sortByAria"),children:[h.jsx("button",{type:"button",role:"tab","aria-selected":v==="date",className:v==="date"?"active":"",onClick:()=>x("date"),children:t("gallery.sortByDate")}),h.jsx("button",{type:"button",role:"tab","aria-selected":v==="session",className:v==="session"?"active":"",onClick:()=>x("session"),children:t("gallery.sortBySession")})]})]}),h.jsx("input",{type:"text",className:"gallery__search",placeholder:t(L?"gallery.searchDisabledPlaceholder":"gallery.searchPlaceholder"),value:y,onChange:V=>m(V.target.value),autoFocus:!0,disabled:L}),h.jsx("button",{type:"button",className:"gallery__close",onClick:l,"aria-label":t("gallery.closeAria"),title:t("gallery.closeTitle"),children:"×"})]}),h.jsxs("div",{className:`gallery__storage-bar${ne?" gallery__storage-bar--notice":""}`,children:[ne?h.jsxs("div",{className:"gallery__storage-copy",children:[h.jsx("div",{className:"gallery__storage-title",children:t("gallery.storageNoticeTitle")}),h.jsx("div",{className:"gallery__storage-text",children:t(ae)})]}):h.jsx("div",{className:"gallery__storage-copy gallery__storage-copy--quiet",children:C?.generatedDirLabel??"~/.ima2/generated"}),h.jsxs("div",{className:"gallery__storage-actions",children:[h.jsx("button",{type:"button",className:"gallery__storage-button",onClick:Z,title:t("gallery.openGeneratedDirTitle"),children:t("gallery.openGeneratedDir")}),ne&&h.jsx("button",{type:"button",className:"gallery__storage-button gallery__storage-button--ghost",onClick:k,children:t("common.close")})]})]}),h.jsx("div",{className:"gallery__scroll",ref:z,onScroll:()=>{X.current=z.current?.scrollTop??0},children:L?h.jsxs(h.Fragment,{children:[S.map(V=>h.jsxs("section",{className:"gallery__group",children:[h.jsxs("header",{className:"gallery__group-header",children:[h.jsx("span",{className:"gallery__group-label",title:V.sessionId,children:V.title?V.displayLabel:t("gallery.sessionLabel",{name:V.displayLabel})}),h.jsx("span",{className:"gallery__group-count",children:V.items.length})]}),h.jsx("div",{className:"gallery__grid",children:V.items.map((se,de)=>T(se,V.sessionId,de))})]},V.sessionId)),j.length>0&&h.jsxs("section",{className:"gallery__group",children:[h.jsxs("header",{className:"gallery__group-header",children:[h.jsx("span",{className:"gallery__group-label",children:t("gallery.standalone")}),h.jsx("span",{className:"gallery__group-count",children:j.length})]}),h.jsx("div",{className:"gallery__grid",children:j.map((V,se)=>T(V,"loose",se))})]}),S.length===0&&j.length===0&&h.jsx("div",{className:"gallery__empty",children:t("gallery.emptySessions")})]}):ce.length===0?h.jsx("div",{className:"gallery__empty",children:o.length===0?t("gallery.emptyAll"):t("gallery.noResults")}):K.map(([V,se])=>h.jsxs("section",{className:"gallery__group",children:[h.jsxs("header",{className:"gallery__group-header",children:[h.jsx("span",{className:"gallery__group-label",children:J(V)}),h.jsx("span",{className:"gallery__group-count",children:se.length})]}),h.jsx("div",{className:"gallery__grid",children:se.map((de,le)=>T(de,V,le))})]},V))}),A&&h.jsxs("div",{className:"gallery__undo",children:[h.jsx("span",{children:t("gallery.deleted",{filename:A.filename})}),h.jsx("button",{type:"button",onClick:D,children:t("gallery.undo")}),h.jsx("span",{className:"gallery__undo-timer",children:t("gallery.secondsSuffix",{n:Math.max(0,Math.ceil((A.expiresAt-Date.now())/1e3))})})]})]})})}function vj(t){return t.includes("ratio")?"sizeConfirm.reasonRatio":t.includes("pixels")?"sizeConfirm.reasonPixels":t.includes("min")?"sizeConfirm.reasonMin":t.includes("max")?"sizeConfirm.reasonMax":"sizeConfirm.reasonSnap"}function xj(){const t=W(g=>g.customSizeConfirm),i=W(g=>g.confirmCustomSizeAdjustment),l=W(g=>g.cancelCustomSizeAdjustment),o=Y.useRef(null),{t:r}=Te();if(Y.useEffect(()=>{if(!t)return;o.current?.focus();const g=p=>{p.key==="Escape"&&l()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[l,t]),!t)return null;const u=`${t.requestedW}x${t.requestedH}`,d=`${t.adjustedW}x${t.adjustedH}`;return h.jsx("div",{className:"modal-backdrop custom-size-confirm-backdrop",role:"presentation",children:h.jsxs("div",{className:"modal custom-size-confirm",role:"dialog","aria-modal":"true","aria-labelledby":"custom-size-confirm-title","aria-describedby":"custom-size-confirm-body",children:[h.jsx("div",{id:"custom-size-confirm-title",className:"modal__title",children:r("sizeConfirm.title")}),h.jsxs("div",{id:"custom-size-confirm-body",className:"modal__body",children:[h.jsx("p",{children:r("sizeConfirm.body")}),h.jsxs("dl",{className:"size-confirm__pairs",children:[h.jsxs("div",{className:"size-confirm__pair",children:[h.jsx("dt",{children:r("sizeConfirm.requested")}),h.jsx("dd",{children:u})]}),h.jsxs("div",{className:"size-confirm__pair",children:[h.jsx("dt",{children:r("sizeConfirm.adjusted")}),h.jsx("dd",{children:d})]})]}),h.jsx("p",{className:"size-confirm__reason",children:r(vj(t.reasons))})]}),h.jsxs("div",{className:"modal__actions",children:[h.jsx("button",{ref:o,type:"button",className:"modal__btn modal__btn--secondary",onClick:l,children:r("sizeConfirm.cancel")}),h.jsx("button",{type:"button",className:"modal__btn",onClick:()=>{i()},children:r("sizeConfirm.approve")})]})]})})}function bj(t){const i=t.slots.filter(o=>o.kind==="text"||o.textKind).length,l=t.slots.filter(o=>o.kind==="image").length;return`${i} text / ${l} image`}function Sj(){const{t}=Te(),i=Se(r=>r.templates),l=Se(r=>r.imageTemplateId),o=Se(r=>r.setImageTemplate);return h.jsxs("section",{className:"card-news-panel",children:[h.jsxs("div",{className:"card-news-panel__head",children:[h.jsx("span",{children:t("cardNews.imageTemplate")}),h.jsx("button",{type:"button",disabled:!0,title:t("cardNews.newTemplateLater"),children:"+"})]}),h.jsx("div",{className:"card-news-template-grid",children:i.map(r=>h.jsxs("button",{type:"button",className:`card-news-template${l===r.id?" selected":""}`,onClick:()=>o(r.id),children:[h.jsx("img",{src:r.previewUrl,alt:""}),h.jsxs("span",{className:"card-news-template__body",children:[h.jsx("span",{className:"card-news-template__name",children:r.name}),h.jsx("span",{className:"card-news-template__meta",children:bj(r)}),h.jsx("span",{className:"card-news-template__sizes",children:r.recommendedOutputSizes.join(" · ")})]})]},r.id))})]})}function wj(){const{t}=Te(),i=Se(r=>r.roleTemplates),l=Se(r=>r.roleTemplateId),o=Se(r=>r.setRoleTemplate);return h.jsxs("section",{className:"card-news-panel",children:[h.jsx("div",{className:"card-news-panel__head",children:h.jsx("span",{children:t("cardNews.roleTemplate")})}),h.jsx("div",{className:"card-news-role-row",children:i.map(r=>h.jsx("button",{type:"button",className:l===r.id?"selected":"",onClick:()=>o(r.id),children:r.name},r.id))})]})}function Nj({status:t,locked:i}){const{t:l}=Te(),o=i?"locked":t,r=o==="queued"||o==="generating";return h.jsxs("span",{className:`card-news-status-badge card-news-status-badge--${o}`,children:[r?h.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,l(`cardNews.status.${o}`)]})}function _j(t,i){const l=`cardNews.roles.${t}`,o=i(l);return o===l?t:o}function Ej(){const{t}=Te(),i=Se(r=>r.activePlan),l=Se(r=>r.selectedCardId),o=Se(r=>r.selectCard);return i?h.jsx("div",{className:"card-news-deck","aria-label":"Card deck",onWheel:B0,children:i.cards.map(r=>h.jsxs("button",{type:"button",className:`card-news-deck-card${l===r.id?" selected":""}`,onClick:()=>o(r.id),children:[h.jsx("span",{children:String(r.order).padStart(2,"0")}),r.url?h.jsx("img",{src:r.url,alt:"",className:"card-news-deck-card__thumb"}):null,h.jsx("strong",{children:_j(r.role,t)}),h.jsx("small",{children:r.headline||r.textFields.find(u=>u.renderMode==="in-image")?.text}),h.jsx(Nj,{status:r.status,locked:r.locked})]},r.id))}):null}const Cj=[];function Tj(){const{t}=Te(),i=Se(r=>r.activePlan?.cards??Cj),l=Se(r=>r.generating),o={total:i.length,done:i.filter(r=>r.status==="generated").length,queued:i.filter(r=>r.status==="queued").length,errors:i.filter(r=>r.status==="error").length,skipped:i.filter(r=>r.locked||r.status==="skipped").length};return o.total?h.jsxs("div",{className:"card-news-batch-bar","aria-live":"polite",children:[h.jsx("span",{children:l?t("cardNews.progress.generating",{done:o.done,total:o.total}):t("cardNews.progress.summary",{done:o.done,total:o.total})}),h.jsx("span",{children:t("cardNews.progress.detail",{queued:o.queued,errors:o.errors,skipped:o.skipped})})]}):null}function Aj({meta:t}){const{t:i}=Te();if(!t)return null;const l=t.mode==="structured-output"?i("cardNews.planner.structured"):t.mode==="json-mode"?i("cardNews.planner.jsonMode"):i("cardNews.planner.fallback");return h.jsxs("span",{className:"card-news-planner-badge",children:[l," · ",t.model,t.repaired?` · ${i("cardNews.planner.repaired")}`:""]})}function Mj(t){const i=t.textFields.filter(l=>l.renderMode==="in-image"&&l.text).map(l=>`[${l.placement}] ${l.text}`);return[t.headline,...i].filter(Boolean).join(`
|
|
21
|
+
M${I.x},${I.y}h${I.width}v${I.height}h${-I.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}Tx.displayName="MiniMap";const LM=Y.memo(Tx),kM=t=>i=>t?`${Math.max(1/i.transform[2],1)}`:void 0,UM={[ml.Line]:"right",[ml.Handle]:"bottom-right"};function qM({nodeId:t,position:i,variant:l=ml.Handle,className:o,style:r=void 0,children:u,color:d,minWidth:g=10,minHeight:p=10,maxWidth:y=Number.MAX_VALUE,maxHeight:m=Number.MAX_VALUE,keepAspectRatio:v=!1,resizeDirection:x,autoScale:S=!0,shouldResize:w,onResizeStart:j,onResize:E,onResizeEnd:A}){const B=ix(),C=typeof t=="string"?t:B,_=Fe(),U=Y.useRef(null),R=l===ml.Handle,z=Oe(Y.useCallback(kM(R&&S),[R,S]),Qe),I=Y.useRef(null),X=i??UM[l];Y.useEffect(()=>{if(!(!U.current||!C))return I.current||(I.current=pT({domNode:U.current,nodeId:C,getStoreItems:()=>{const{nodeLookup:K,transform:te,snapGrid:ue,snapToGrid:D,nodeOrigin:Z,domNode:M}=_.getState();return{nodeLookup:K,transform:te,snapGrid:ue,snapToGrid:D,nodeOrigin:Z,paneDomNode:M}},onChange:(K,te)=>{const{triggerNodeChanges:ue,nodeLookup:D,parentLookup:Z,nodeOrigin:M}=_.getState(),H=[],q={x:K.x,y:K.y},k=D.get(C);if(k&&k.expandParent&&k.parentId){const J=k.origin??M,T=K.width??k.measured.width??0,L=K.height??k.measured.height??0,ne={id:k.id,parentId:k.parentId,rect:{width:T,height:L,...Tv({x:K.x??k.position.x,y:K.y??k.position.y},{width:T,height:L},k.parentId,D,J)}},ae=Df([ne],D,Z,M);H.push(...ae),q.x=K.x?Math.max(J[0]*T,K.x):void 0,q.y=K.y?Math.max(J[1]*L,K.y):void 0}if(q.x!==void 0&&q.y!==void 0){const J={id:C,type:"position",position:{...q}};H.push(J)}if(K.width!==void 0&&K.height!==void 0){const T={id:C,type:"dimensions",resizing:!0,setAttributes:x?x==="horizontal"?"width":"height":!0,dimensions:{width:K.width,height:K.height}};H.push(T)}for(const J of te){const T={...J,type:"position"};H.push(T)}ue(H)},onEnd:({width:K,height:te})=>{const ue={id:C,type:"dimensions",resizing:!1,dimensions:{width:K,height:te}};_.getState().triggerNodeChanges([ue])}})),I.current.update({controlPosition:X,boundaries:{minWidth:g,minHeight:p,maxWidth:y,maxHeight:m},keepAspectRatio:v,resizeDirection:x,onResizeStart:j,onResize:E,onResizeEnd:A,shouldResize:w}),()=>{I.current?.destroy()}},[X,g,p,y,m,v,j,E,A,w]);const ce=X.split("-");return h.jsx("div",{className:st(["react-flow__resize-control","nodrag",...ce,l,o]),ref:U,style:{...r,scale:z,...d&&{[R?"backgroundColor":"borderColor"]:d}},children:u})}Y.memo(qM);const Pd=5,Or=240,GM=180,YM=420;function VM(t){const i=/^(\d+)x(\d+)$/.exec(t??"");if(!i)return Or;const l=Number(i[1]),o=Number(i[2]);if(!Number.isFinite(l)||!Number.isFinite(o)||l<=0||o<=0)return Or;const r=Or*(l/o);return Math.round(Math.min(YM,Math.max(GM,r)))}function XM({id:t,data:i,selected:l}){const{t:o}=Te(),r=i,u=W(k=>k.updateNodePrompt),d=W(k=>k.addNodeReferences),g=W(k=>k.removeNodeReference),p=W(k=>k.generateNode),y=W(k=>k.generateNodeInPlace),m=W(k=>k.generateNodeVariation),v=W(k=>k.addChildNode),x=W(k=>k.duplicateBranchRoot),S=W(k=>k.deleteNode),w=Y.useRef(null),[j,E]=Y.useState(!1),A=r.referenceImages??[],B=r.status==="pending"||r.status==="reconciling",C=!B&&A.length<Pd,_={"--node-preview-w":`${VM(r.size)}px`,"--node-preview-h":`${Or}px`},U=Y.useCallback(k=>u(t,k.target.value),[t,u]),R=Y.useCallback(()=>{p(t)},[t,p]),z=Y.useCallback(()=>{y(t)},[t,y]),I=Y.useCallback(()=>{m(t)},[t,m]),X=Y.useCallback(()=>{r.status==="ready"&&v(t)},[t,r.status,v]),ce=Y.useCallback(()=>{x(t)},[t,x]),K=Y.useCallback(()=>S(t),[t,S]),te=k=>{if(!k)return[];const J=[];for(const T of Array.from(k)){if(T.kind!=="file"||!T.type.startsWith("image/"))continue;const L=T.getAsFile();L&&J.push(L)}return J},ue=k=>{if(k.preventDefault(),k.stopPropagation(),E(!1),!C)return;const J=Array.from(k.dataTransfer.files).filter(T=>T.type.startsWith("image/"));J.length>0&&d(t,J)},D=k=>{k.preventDefault(),k.stopPropagation(),C&&!j&&E(!0)},Z=k=>{k.currentTarget.contains(k.relatedTarget)||E(!1)},M=k=>{const J=te(k.clipboardData?.items??null);if(J.length===0||(k.preventDefault(),k.stopPropagation(),!C))return;const T=Pd-A.length;d(t,J.slice(0,T))},q=(()=>{switch(r.status){case"empty":return o("node.empty");case"pending":return o("node.pending");case"reconciling":return r.pendingPhase?o("node.reconcilingPhase",{phase:r.pendingPhase}):o("node.reconciling");case"ready":return[r.webSearchCalls?o("node.readyWithSearch",{elapsed:r.elapsed??"?",searches:r.webSearchCalls}):o("node.ready",{elapsed:r.elapsed??"?"}),b0(r.model)].filter(Boolean).join(" · ");case"stale":return r.error?o("node.staleWithError",{error:r.error}):o("node.stale");case"asset-missing":return r.error?o("node.assetMissingWithError",{error:r.error}):o("node.assetMissing");case"error":return o("node.error",{error:r.error??o("node.errorUnknown")});default:return""}})();return h.jsxs("div",{className:`image-node image-node--${r.status}${l?" image-node--selected":""}`,style:_,children:[r.parentServerNodeId?h.jsx(pl,{type:"target",position:me.Left,className:"image-node__handle"}):null,h.jsx("div",{className:"image-node__preview",children:r.imageUrl&&r.status!=="asset-missing"?h.jsx("img",{src:r.imageUrl,alt:o("node.nodeImageAlt")}):B&&r.partialImageUrl?h.jsx("img",{className:"image-node__partial",src:r.partialImageUrl,alt:o("node.partialImageAlt")}):B?h.jsx("div",{className:"image-node__skeleton"}):r.status==="asset-missing"?h.jsx("div",{className:"image-node__placeholder",children:o("node.noAsset")}):r.status==="stale"?h.jsx("div",{className:"image-node__placeholder",children:o("node.stateStale")}):h.jsx("div",{className:"image-node__placeholder",children:o("node.noImage")})}),h.jsxs("div",{className:`image-node__composer nodrag${j?" is-dragging":""}`,onDrop:ue,onDragOver:D,onDragLeave:Z,onPaste:M,children:[A.length>0?h.jsx("div",{className:"image-node__refs",children:A.map((k,J)=>h.jsxs("div",{className:"image-node__ref-chip",title:o("node.refAlt",{n:J+1}),children:[h.jsx("img",{src:k,alt:o("node.refAlt",{n:J+1})}),h.jsx("button",{type:"button",className:"image-node__ref-remove",onClick:()=>g(t,J),disabled:B,"aria-label":o("node.removeRef",{n:J+1}),children:"×"})]},J))}):null,h.jsx("textarea",{className:"image-node__prompt",value:r.prompt,onChange:U,onKeyDown:k=>k.stopPropagation(),placeholder:r.parentServerNodeId?o("node.editPromptPlaceholder"):o("node.promptPlaceholder"),rows:2,disabled:B}),h.jsxs("div",{className:"image-node__composer-bar",children:[h.jsx("button",{type:"button",className:"image-node__attach",onClick:()=>C&&w.current?.click(),disabled:!C,title:r.parentServerNodeId?o("node.nodeRefsUsedWithParent"):o("node.attachRefTitle"),children:o("node.attachRef")}),j?h.jsx("span",{className:"image-node__drop-hint",children:o("node.dropRefs")}):A.length>0?h.jsxs("span",{className:"image-node__ref-count",children:[A.length,"/",Pd]}):null]}),h.jsx("input",{ref:w,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:k=>{const J=Array.from(k.target.files??[]);J.length>0&&d(t,J),k.target.value=""}})]}),h.jsxs("div",{className:"image-node__footer nodrag",children:[h.jsx("span",{className:"image-node__status",title:q,children:q}),h.jsxs("div",{className:"image-node__actions",children:[r.status==="ready"?h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",onClick:z,disabled:B,title:o("node.regenerateTitle"),"aria-label":o("node.regenerateTitle"),children:"↻"}),h.jsx("button",{type:"button",onClick:I,disabled:B,title:o("node.newVariationTitle"),"aria-label":o("node.newVariationTitle"),children:o("node.newVariation")})]}):h.jsx("button",{type:"button",className:"image-node__generate",onClick:R,disabled:B,title:o("node.generateTitle"),"aria-label":o("node.generateTitle"),children:o("node.generate")}),r.status==="ready"?h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",onClick:X,title:o("node.addChildTitle"),"aria-label":o("node.addChildTitle"),children:o("node.addChild")}),h.jsx("button",{type:"button",onClick:ce,title:o("node.duplicateBranchTitle"),"aria-label":o("node.duplicateBranchTitle"),children:o("node.duplicateBranch")})]}):null,h.jsx("button",{type:"button",onClick:K,className:"image-node__del",title:o("node.deleteTitle"),"aria-label":o("node.deleteTitle"),children:"×"})]})]}),h.jsx(pl,{type:"source",position:me.Right,className:"image-node__handle image-node__handle--source"})]})}const $M=Y.memo(XM);function ZM(){const{t}=Te(),i=W(E=>E.graphNodes),l=W(E=>E.graphEdges),o=W(E=>E.nodeSelectionMode),r=W(E=>E.nodeBatchRunning),u=W(E=>E.nodeBatchStopping),d=W(E=>E.toggleNodeSelectionMode),g=W(E=>E.selectAllGraphNodes),p=W(E=>E.clearNodeSelection),y=W(E=>E.runNodeBatch),m=W(E=>E.cancelNodeBatch),v=i.filter(E=>E.selected).map(E=>E.id),x=new Set(v),S=i.filter(E=>x.has(E.id)&&!E0(E)).length,w=C0(l,v).length,j=E=>{y(E)};return h.jsxs(Go,{position:"top-center",className:"node-batch-bar nodrag",children:[h.jsx("button",{type:"button",onClick:d,"aria-pressed":o,children:t(o?"nodeBatch.selectionOn":"nodeBatch.selectionOff")}),h.jsx("button",{type:"button",onClick:g,disabled:i.length===0,children:t("nodeBatch.selectAll")}),v.length>0?h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"node-batch-bar__meta",children:t("nodeBatch.summary",{selected:v.length,missing:S,stale:w})}),h.jsx("button",{type:"button",onClick:()=>j("missing-only"),disabled:r,children:t("nodeBatch.generateMissing")}),h.jsx("button",{type:"button",onClick:()=>j("regenerate-all"),disabled:r,children:t("nodeBatch.regenerateSelected")}),r?h.jsx("button",{type:"button",onClick:m,disabled:u,children:t(u?"nodeBatch.stopping":"nodeBatch.stopRemaining")}):null,h.jsx("button",{type:"button",onClick:p,disabled:r,children:t("nodeBatch.clear")})]}):null]})}function KM(){const{t}=Te(),i=W(z=>z.graphNodes),l=W(z=>z.graphEdges),o=W(z=>z.setGraphNodes),r=W(z=>z.setGraphEdges),u=W(z=>z.disconnectEdges),d=W(z=>z.addRootNode),g=W(z=>z.addChildNodeAt),p=W(z=>z.connectNodes),y=W(z=>z.deleteNodes),m=W(z=>z.nodeSelectionMode),v=W(z=>z.selectNodeGraph),x=W(z=>z.sessionLoading),S=W(z=>z.resolvedTheme),{screenToFlowPosition:w}=nc(),j=Y.useRef(null),E=Y.useMemo(()=>({imageNode:$M}),[]),A=Y.useCallback(z=>o(Jv(z,i)),[i,o]),B=Y.useCallback(z=>{const I=z.filter(X=>X.type==="remove").map(X=>X.id);if(I.length>0){if(m)return;u(I);return}r(Wv(z,l))},[u,l,m,r]),C=Y.useCallback(z=>{z.source&&z.target&&p(z.source,z.target)},[p]),_=Y.useCallback((z,I)=>{if(I.isValid)return;const X=I.fromNode?.id;if(!X)return;const ce="touches"in z?z.changedTouches[0].clientX:z.clientX,K="touches"in z?z.changedTouches[0].clientY:z.clientY,te=w({x:ce,y:K});g(X,te)},[g,w]),U=Y.useCallback(z=>y(z.map(I=>I.id)),[y]),R=Y.useCallback((z,I)=>{m&&(z.preventDefault(),v(I.id,z.metaKey||z.ctrlKey))},[m,v]);return h.jsxs("main",{className:"node-canvas",ref:j,children:[x&&h.jsx("div",{className:"node-canvas__loading",children:t("nodeCanvas.loading")}),i.length===0?h.jsx("button",{type:"button",className:"node-canvas__plus",onClick:()=>d(),children:t("nodeCanvas.addFirst")}):h.jsxs(h.Fragment,{children:[h.jsxs(hM,{nodes:i,edges:l,onNodesChange:A,onEdgesChange:B,onConnect:C,onConnectEnd:_,onNodesDelete:U,onNodeClick:R,nodeTypes:E,connectionRadius:32,selectionOnDrag:m,multiSelectionKeyCode:m?null:void 0,panOnDrag:m?[2]:!0,fitView:!0,deleteKeyCode:m?null:["Delete","Backspace"],proOptions:{hideAttribution:!0},children:[h.jsx(ZM,{}),h.jsx(vM,{gap:24,color:S==="light"?"#d9dee6":"#2a2a2a"}),h.jsx(EM,{className:"node-canvas__controls"}),h.jsx(LM,{pannable:!0,zoomable:!0,maskColor:S==="light"?"rgba(246, 247, 251, 0.72)":"rgba(10, 10, 10, 0.7)",nodeColor:S==="light"?"#1f2430":"#f0f0f0",nodeStrokeColor:S==="light"?"#ffffff":"#1a1a1a",style:{background:S==="light"?"#ffffff":"#141414",border:`1px solid ${S==="light"?"#d9dee6":"#2a2a2a"}`}})]}),h.jsx("button",{type:"button",className:"node-canvas__add-root",onClick:()=>d(),title:t("nodeCanvas.addRootTitle"),children:"+"}),h.jsx("div",{className:"node-canvas__hint",children:t("nodeCanvas.hint")})]})]})}function QM(){return h.jsx(_x,{children:h.jsx(KM,{})})}function Gn({title:t,help:i,items:l,value:o,onChange:r}){return h.jsxs("div",{className:"option-group",children:[t?h.jsx("div",{className:"section-title",children:t}):null,h.jsx("div",{className:"option-row",children:l.map(u=>h.jsxs("button",{className:`option-btn${u.value===o?" active":""}`,style:u.color?{color:u.color}:void 0,disabled:u.disabled,onClick:()=>r(u.value),type:"button",children:[u.label,u.sub?h.jsxs(h.Fragment,{children:[h.jsx("br",{}),h.jsx("span",{className:"option-sub",children:u.sub})]}):null]},u.value))}),i?h.jsx("p",{className:"option-help",children:i}):null]})}function mo(t){return t.map(i=>({value:i.value,label:i.label,sub:i.sub}))}function FM(){const t=W(S=>S.sizePreset),i=W(S=>S.setSizePreset),l=W(S=>S.customW),o=W(S=>S.customH),r=W(S=>S.setCustomSize),{t:u}=Te(),[d,g]=Y.useState(String(l)),[p,y]=Y.useState(String(o)),m=t==="custom";Y.useEffect(()=>{g(String(l)),y(String(o))},[l,o]);function v(){const S=sl(d,l),w=sl(p,o);r(S,w),g(String(S)),y(String(w))}function x(S){S.key==="Enter"&&(S.preventDefault(),v())}return h.jsxs("div",{className:"option-group",children:[h.jsx("div",{className:"section-title",children:u("size.title")}),h.jsx(Gn,{title:"",items:mo(Hw),value:t,onChange:i}),h.jsx(Gn,{title:"",items:mo(Iw),value:t,onChange:i}),h.jsx(Gn,{title:"",items:mo(Bw),value:t,onChange:i}),h.jsx(Gn,{title:"",items:mo(Lw),value:t,onChange:i}),h.jsx(Gn,{title:"",items:mo(kw()),value:t,onChange:i}),m?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"option-row",children:[h.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:d,onChange:S=>g(S.target.value.replace(/\D/g,"")),onBlur:v,onKeyDown:x,placeholder:u("size.width")}),h.jsx("span",{style:{color:"var(--text-dim)",alignSelf:"center",fontFamily:"var(--mono)",fontSize:12},children:"x"}),h.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:p,onChange:S=>y(S.target.value.replace(/\D/g,"")),onBlur:v,onKeyDown:x,placeholder:u("size.height")})]}),h.jsx("div",{className:"size-hint",children:u("size.hint")})]}):null]})}const PM={low:{"1024x1024":.006,"1024x1536":.005,"1536x1024":.005,"1024x1360":.005,"1360x1024":.005,"1024x1824":.006,"1824x1024":.006,"2048x2048":.012,"2048x1152":.009,"1152x2048":.009,"3824x2160":.023,"2160x3824":.023,auto:.006},medium:{"1024x1024":.053,"1024x1536":.041,"1536x1024":.041,"1024x1360":.041,"1360x1024":.041,"1024x1824":.05,"1824x1024":.05,"2048x2048":.106,"2048x1152":.08,"1152x2048":.08,"3824x2160":.2,"2160x3824":.2,auto:.053},high:{"1024x1024":.211,"1024x1536":.165,"1536x1024":.165,"1024x1360":.165,"1360x1024":.165,"1024x1824":.2,"1824x1024":.2,"2048x2048":.422,"2048x1152":.32,"1152x2048":.32,"3824x2160":.8,"2160x3824":.8,auto:.211}};function JM(t,i){return PM[t]?.[i]??0}function WM(){const{t}=Te(),i=W(y=>y.provider),l=W(y=>y.quality),r=W(y=>y.getResolvedSize)(),u=i==="oauth",d=JM(l,r),g=u?t("cost.free"):t("cost.approx",{amount:d.toFixed(3)}),p=u?"var(--green)":void 0;return h.jsxs("div",{className:"cost-estimate",children:[h.jsx("span",{children:t("cost.label")}),h.jsx("span",{className:"price",style:p?{color:p}:void 0,children:g})]})}const ej=[{value:"png",label:"PNG"},{value:"jpeg",label:"JPEG"},{value:"webp",label:"WebP"}],tj=[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"}];function nj(){const t=W(E=>E.rightPanelOpen),i=W(E=>E.toggleRightPanel),{t:l}=Te(),[o,r]=Y.useState(typeof window<"u"?window.matchMedia("(max-width: 800px)").matches:!1);Y.useEffect(()=>{if(typeof window>"u")return;const E=window.matchMedia("(max-width: 800px)"),A=()=>r(E.matches);return E.addEventListener("change",A),()=>E.removeEventListener("change",A)},[]);const u=o?t:!0,d=W(E=>E.quality),g=W(E=>E.setQuality),p=W(E=>E.format),y=W(E=>E.setFormat),m=W(E=>E.moderation),v=W(E=>E.setModeration),x=W(E=>E.count),S=W(E=>E.setCount),w=[{value:"low",label:l("quality.lowLabel"),sub:l("quality.lowSub")},{value:"medium",label:l("quality.mediumLabel"),sub:l("quality.mediumSub")},{value:"high",label:l("quality.highLabel"),sub:l("quality.highSub")}],j=[{value:"auto",label:l("moderation.autoLabel"),sub:l("moderation.autoSub")},{value:"low",label:l("moderation.lowLabel"),sub:l("moderation.lowSub"),color:"var(--amber)"}];return h.jsxs(h.Fragment,{children:[o&&t?h.jsx("div",{className:"right-panel-backdrop",role:"button","aria-label":l("panel.closeSettings"),onClick:i}):null,h.jsxs("aside",{className:`right-panel${t?"":" collapsed"}${o&&u?" drawer-open":""}`,"aria-label":l("panel.detailSettings"),children:[h.jsx("button",{type:"button",className:"right-panel-toggle","aria-expanded":t,"aria-controls":"right-panel-body",onClick:i,title:l(t?"panel.toggleHide":"panel.toggleShow"),children:o?l(t?"panel.close":"panel.open"):t?">":"<"}),h.jsxs("div",{id:"right-panel-body",className:"right-panel-body",hidden:!t,children:[h.jsx("div",{className:"section-title",children:l("panel.detailSettings")}),h.jsx(Gn,{title:l("quality.title"),items:w,value:d,onChange:g}),h.jsx(FM,{}),h.jsx(Gn,{title:l("format.title"),items:ej,value:p,onChange:y}),h.jsx(Gn,{title:l("moderation.title"),items:j,value:m,onChange:v}),h.jsx("p",{className:"option-help",children:l("moderation.explain")}),h.jsx(Gn,{title:l("count.title"),items:tj,value:String(x),onChange:E=>S(Number(E))}),h.jsx(WM,{})]})]})]})}function aj(){const[t,i]=Y.useState(null),[l,o]=Y.useState(!1);return Y.useEffect(()=>{let r=!1;return ZS().then(u=>{r||i(u)}).catch(()=>{r||o(!0)}),()=>{r=!0}},[]),{data:t,error:l}}function ij(){const[t,i]=Y.useState(null);return Y.useEffect(()=>{let l=!1,o=null;const r=async()=>{try{const u=await $S();if(l)return;i(u),u.status==="starting"&&(o=setTimeout(r,3e3))}catch{l||i(null)}};return r(),()=>{l=!0,o&&clearTimeout(o)}},[]),t}function lj(t){return t==="ready"?"Ready":t==="auth_required"?"Login required":t==="starting"?"Starting":t==="offline"?"Offline":"Checking"}function oj(){const{t}=Te(),i=ij(),{data:l,error:o}=aj(),r=l?.apiKeySource==="env"||l?.apiKeySource==="config"||l?.apiKeyValid===!0,u=i?.status==="ready",d=l?.apiKeySource==="config"?t("settings.account.apiSourceConfig"):t("settings.account.apiSourceEnv");return h.jsxs(h.Fragment,{children:[h.jsxs("article",{className:"settings-row",children:[h.jsxs("div",{className:"settings-row__copy",children:[h.jsx("p",{className:"settings-eyebrow",children:t("settings.account.primaryEyebrow")}),h.jsx("h4",{children:t("settings.account.oauthTitle")}),h.jsx("p",{children:t("settings.account.oauthBody")})]}),h.jsxs("div",{className:`settings-status${u?" is-ok":""}`,children:[h.jsx("span",{"aria-hidden":"true"}),lj(i?.status)]})]}),r?h.jsxs("article",{className:"settings-row",children:[h.jsxs("div",{className:"settings-row__copy",children:[h.jsx("p",{className:"settings-eyebrow",children:d}),h.jsx("h4",{children:t("settings.account.apiTitle")}),h.jsx("p",{children:t("settings.account.apiBody")})]}),h.jsxs("div",{className:"settings-status is-muted",children:[h.jsx("span",{"aria-hidden":"true"}),t(o?"settings.account.apiUnknown":"settings.account.apiDisabled")]})]}):null]})}const sj={ko:"KO",en:"EN"};function rj(){const{t,locale:i}=Te(),l=W(o=>o.setLocale);return h.jsx("div",{className:"lang-toggle",role:"group","aria-label":t("language.label"),children:Mw.map(o=>h.jsx("button",{type:"button",className:`lang-toggle__btn ${i===o?"is-active":""}`,onClick:()=>l(o),"aria-pressed":i===o,title:t(`language.${o}`),children:h.jsx("span",{className:"lang-toggle__label",children:sj[o]})},o))})}const cj=["system","dark","light"];function uj(){const{t}=Te(),i=W(o=>o.theme),l=W(o=>o.setTheme);return h.jsx("div",{className:"theme-toggle",role:"group","aria-label":t("theme.label"),children:cj.map(o=>h.jsx("button",{type:"button",className:`theme-toggle__btn ${i===o?"is-active":""}`,onClick:()=>l(o),"aria-pressed":i===o,title:t(`theme.${o}`),children:t(`theme.${o}`)},o))})}const Jd=["account","generation","appearance","language","future"];function po({id:t,setRef:i,children:l}){const{t:o}=Te();return h.jsxs("section",{id:t,ref:r=>i(t,r),className:"settings-section","aria-labelledby":`settings-section-${t}`,children:[h.jsx("header",{className:"settings-section__header",children:h.jsxs("div",{children:[h.jsx("h3",{id:`settings-section-${t}`,children:o(`settings.sections.${t}.title`)}),h.jsx("p",{children:o(`settings.sections.${t}.hint`)})]})}),h.jsx("div",{className:"settings-section__body",children:l})]})}function dj(){const{t}=Te(),i=W(m=>m.activeSettingsSection),l=W(m=>m.setActiveSettingsSection),o=W(m=>m.closeSettings),r=Y.useRef(null),u=Y.useRef(null),d=Y.useRef(!1),g=Y.useRef({account:null,generation:null,appearance:null,language:null,future:null}),p=(m,v)=>{g.current[m]=v},y=m=>{l(m),d.current=!0,g.current[m]?.scrollIntoView({behavior:"auto",block:"start"}),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>{d.current=!1,u.current=null},120)};return Y.useEffect(()=>{const m=v=>{v.key==="Escape"&&o()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[o]),Y.useEffect(()=>{const m=r.current;if(!m||typeof IntersectionObserver!="function")return;const v=new IntersectionObserver(x=>{if(d.current)return;const w=x.filter(j=>j.isIntersecting).sort((j,E)=>E.intersectionRatio-j.intersectionRatio)[0]?.target.id;w&&Jd.includes(w)&&l(w)},{root:m,threshold:[.35,.6]});for(const x of Jd){const S=g.current[x];S&&v.observe(S)}return()=>v.disconnect()},[l]),Y.useEffect(()=>()=>{u.current!==null&&window.clearTimeout(u.current)},[]),h.jsx("main",{ref:r,className:"settings-workspace","aria-labelledby":"settings-title",children:h.jsxs("div",{className:"settings-shell",children:[h.jsxs("header",{className:"settings-header",children:[h.jsxs("div",{children:[h.jsx("p",{className:"settings-eyebrow",children:t("settings.eyebrow")}),h.jsx("h2",{id:"settings-title",children:t("settings.title")}),h.jsx("p",{children:t("settings.subtitle")})]}),h.jsx("button",{type:"button",className:"settings-close",onClick:o,"aria-label":t("settings.closeAria"),title:t("settings.closeTitle"),children:"X"})]}),h.jsxs("div",{className:"settings-layout",children:[h.jsx("nav",{className:"settings-nav","aria-label":t("settings.navAria"),children:Jd.map(m=>h.jsxs("button",{type:"button",className:`settings-nav__item${i===m?" is-active":""}`,onClick:()=>y(m),"aria-label":t("settings.jumpTo",{section:t(`settings.sections.${m}.title`)}),children:[h.jsx("span",{children:t(`settings.sections.${m}.title`)}),h.jsx("small",{children:t(`settings.sections.${m}.hint`)})]},m))}),h.jsxs("section",{className:"settings-content","aria-label":t("settings.contentAria"),children:[h.jsx(po,{id:"account",setRef:p,children:h.jsx(oj,{})}),h.jsx(po,{id:"generation",setRef:p,children:h.jsxs("article",{className:"settings-row",children:[h.jsxs("div",{className:"settings-row__copy",children:[h.jsx("h4",{children:t("settings.imageModel.title")}),h.jsx("p",{children:t("settings.imageModel.body")}),h.jsx("p",{className:"settings-row__microcopy",children:t("settings.imageModel.unsupportedHelp")})]}),h.jsx("div",{className:"settings-row__control",children:h.jsx(L0,{variant:"settings"})})]})}),h.jsx(po,{id:"appearance",setRef:p,children:h.jsxs("article",{className:"settings-row",children:[h.jsxs("div",{className:"settings-row__copy",children:[h.jsx("h4",{children:t("settings.appearance.themeTitle")}),h.jsx("p",{children:t("settings.appearance.themeBody")})]}),h.jsx("div",{className:"settings-row__control",children:h.jsx(uj,{})})]})}),h.jsx(po,{id:"language",setRef:p,children:h.jsxs("article",{className:"settings-row",children:[h.jsxs("div",{className:"settings-row__copy",children:[h.jsx("h4",{children:t("settings.language.title")}),h.jsx("p",{children:t("settings.language.body")})]}),h.jsx("div",{className:"settings-row__control",children:h.jsx(rj,{})})]})}),h.jsx(po,{id:"future",setRef:p,children:h.jsxs("article",{className:"settings-note",children:[h.jsx("h4",{children:t("settings.future.title")}),h.jsx("p",{children:t("settings.future.body")})]})})]})]})]})})}function fj(){const t=W(r=>r.toast),[i,l]=Y.useState(!1);if(Y.useEffect(()=>{if(!t)return;l(!0);const r=setTimeout(()=>l(!1),3e3);return()=>clearTimeout(r)},[t]),!t)return null;const o=["toast",i?"visible":"",t.error?"error":""].filter(Boolean).join(" ");return h.jsx("div",{className:o,children:t.message})}function hj(){const{t}=Te(),i=W(v=>v.errorCard),l=W(v=>v.dismissErrorCard);if(!i)return null;const o=wo[i.code]??wo.UNKNOWN,r=`${o.cardKey??"errorCard.unknown"}.title`,u=`${o.cardKey??"errorCard.unknown"}.body`,d=o.cta?`${o.cardKey??"errorCard.unknown"}.cta`:null,g=t(r),p=t(u),y=d?t(d):null,m=()=>{if(o.cta==="reload"){window.location.reload();return}else l()};return h.jsx("div",{className:"error-card-backdrop",role:"alertdialog","aria-labelledby":"error-card-title",children:h.jsxs("div",{className:"error-card",children:[h.jsx("div",{className:"error-card__icon","aria-hidden":"true",children:h.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("circle",{cx:"12",cy:"12",r:"10"}),h.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),h.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),h.jsxs("div",{className:"error-card__content",children:[h.jsx("h3",{id:"error-card-title",className:"error-card__title",children:g}),h.jsx("p",{className:"error-card__body",children:p}),i.fallbackMessage&&h.jsxs("details",{className:"error-card__details",children:[h.jsx("summary",{children:t("errorCard.details")}),h.jsx("pre",{children:i.fallbackMessage})]}),h.jsxs("div",{className:"error-card__actions",children:[h.jsx("button",{type:"button",className:"btn btn--ghost",onClick:l,children:t("errorCard.close")}),y&&h.jsx("button",{type:"button",className:"btn btn--primary",onClick:m,children:y})]})]})]})})}function gj(t){if(!t)return"earlier";const i=new Date(t);if(Number.isNaN(i.getTime()))return"earlier";const o=Math.floor((new Date().getTime()-i.getTime())/864e5);return o===0?"today":o===1?"yesterday":o<7?"thisWeek":i.toLocaleDateString("ko-KR",{year:"numeric",month:"short",day:"numeric"})}function c0(t){return t.filename||t.image}function mj({item:t,onOpen:i,onCopyPath:l,onDownloadManifest:o}){const{t:r}=Te(),d=t.cards?.find(g=>g.headline)?.headline||t.headline||r("gallery.cardNewsSet");return h.jsxs(h.Fragment,{children:[h.jsxs("button",{type:"button",className:"gallery__tile",onClick:()=>i(t),title:d,children:[t.image?h.jsx("img",{src:t.image,alt:d,loading:"lazy"}):null,h.jsxs("div",{className:"gallery__caption",children:[h.jsx("small",{children:r("gallery.cardNewsSet")}),h.jsx("span",{className:"gallery__caption-text",children:d})]}),h.jsx("div",{className:"gallery-card-news-strip",children:(t.cards||[]).slice(0,5).map((g,p)=>h.jsxs("span",{children:[g.url?h.jsx("img",{src:g.url,alt:g.headline??"",loading:"lazy"}):null,h.jsx("em",{children:g.cardOrder??p+1})]},`${g.url}-${p}`))})]}),h.jsxs("div",{className:"gallery-card-news-actions",children:[h.jsx("span",{children:r("gallery.cardNewsCount",{n:t.cards?.length??0})}),h.jsx("button",{type:"button",onClick:()=>i(t),children:r("gallery.openCardNewsSet")}),h.jsx("button",{type:"button",onClick:g=>l(t,g),children:r("gallery.copyCardNewsSetPath")}),h.jsx("button",{type:"button",onClick:g=>o(t,g),children:r("gallery.downloadCardNewsManifest")})]})]})}function pj({item:t,active:i,itemRef:l,onSelect:o,onDelete:r,t:u}){return h.jsxs("div",{ref:l,className:`gallery__tile-wrap${i?" gallery__tile-wrap--active":""}`,children:[h.jsxs("button",{type:"button",className:`gallery__tile${i?" gallery__tile--active":""}`,onClick:()=>o(t),title:t.prompt??"",children:[h.jsx("img",{src:t.thumb||t.image,alt:t.prompt??u("gallery.imageAltFallback"),loading:"lazy",decoding:"async"}),t.prompt&&h.jsx("div",{className:"gallery__caption",children:h.jsx("span",{className:"gallery__caption-text",children:t.prompt})})]}),t.filename&&h.jsx("button",{type:"button",className:"gallery__delete",onClick:d=>r(t,d),title:u("gallery.deleteTitle"),"aria-label":u("gallery.deleteAria"),children:"×"})]})}const u0="ima2.storageNoticeDismissed.0.09.23";function yj(){const{t}=Te(),i=W(V=>V.galleryOpen),l=W(V=>V.closeGallery),o=W(V=>V.history),r=W(V=>V.selectHistory),u=W(V=>V.currentImage),d=W(V=>V.removeFromHistory),g=W(V=>V.addHistoryItem),p=W(V=>V.showToast),[y,m]=Y.useState(""),[v,x]=Y.useState("date"),[S,w]=Y.useState([]),[j,E]=Y.useState([]),[A,B]=Y.useState(null),[C,_]=Y.useState(null),[U,R]=Y.useState(()=>{try{return localStorage.getItem(u0)==="1"}catch{return!1}}),z=Y.useRef(null),I=Y.useRef({}),X=Y.useRef(0);Y.useEffect(()=>{if(!i)return;const V=se=>{se.key==="Escape"&&l()};return window.addEventListener("keydown",V),()=>window.removeEventListener("keydown",V)},[i,l]),Y.useEffect(()=>{i||(m(""),B(null))},[i]),Y.useEffect(()=>{if(!i)return;let V=!1;return(async()=>{try{const se=await FS();V||_(se)}catch{V||_({generatedDirLabel:"~/.ima2/generated",generatedCount:0,legacyCandidatesScanned:0,legacySourcesFound:0,legacyFilesFound:0,state:"unknown",messageKind:"unknown",recoveryDocsPath:"docs/RECOVER_OLD_IMAGES.md",doctorCommand:"ima2 doctor",overrides:{generatedDir:!1,configDir:!1}})}})(),()=>{V=!0}},[i]),Y.useEffect(()=>{if(!i||v!=="session")return;let V=!1;return(async()=>{try{const se=await QS({limit:500});if(V)return;const de=le=>{const fe=le.kind,be=fe==="classic"||fe==="edit"||fe==="generate"||fe==="card-news-card"||fe==="card-news-set"?fe:null;return{image:le.url,url:le.url,filename:le.filename,prompt:le.prompt??void 0,size:le.size??void 0,quality:le.quality??void 0,model:le.model??void 0,provider:le.provider,createdAt:le.createdAt,sessionId:le.sessionId??null,nodeId:le.nodeId??null,clientNodeId:le.clientNodeId??null,kind:be,setId:le.setId??null,cardId:le.cardId??null,cardOrder:le.cardOrder??null,headline:le.headline??null,body:le.body??null,cards:le.cards}};w(se.sessions.map(le=>({sessionId:le.sessionId,title:le.title??null,label:le.label??null,displayLabel:le.title||le.label||le.sessionId.slice(0,8),items:le.items.map(de)}))),E(se.loose.map(de))}catch{}})(),()=>{V=!0}},[i,v]);const ce=Y.useMemo(()=>{const V=y.trim().toLowerCase().normalize("NFC");return V?o.filter(se=>(se.prompt??"").toLowerCase().normalize("NFC").includes(V)||(se.filename??"").toLowerCase().normalize("NFC").includes(V)):o},[o,y]),K=Y.useMemo(()=>{const V=new Map;for(const se of ce){const de=gj(se.createdAt);V.has(de)||V.set(de,[]),V.get(de).push(se)}return Array.from(V.entries())},[ce]),te=v==="session"?S.reduce((V,se)=>V+se.items.length,0)+j.length:ce.length;Y.useLayoutEffect(()=>{if(!i)return;const V=u?c0(u):null,se=V?I.current[V]:null;if(se){se.scrollIntoView({block:"center"});return}z.current&&(z.current.scrollTop=X.current)},[i,u?.filename,u?.image,v,te,K.length,S.length,j.length]),Y.useEffect(()=>{if(!A)return;const V=setInterval(()=>{B(se=>!se||Date.now()>=se.expiresAt?null:{...se})},500);return()=>clearInterval(V)},[A]);async function ue(V,se){if(se.stopPropagation(),!!V.filename)try{const de=await JS(V.filename);d(V.filename),B({filename:V.filename,trashId:de.trashId,item:V,expiresAt:Date.now()+9500})}catch(de){console.error("[gallery] delete failed",de)}}async function D(){if(A)try{await WS(A.filename,A.trashId),g(A.item)}catch(V){console.error("[gallery] restore failed",V)}finally{B(null)}}async function Z(){try{await PS()}catch{p(t("toast.openGeneratedDirFailed"),!0)}}async function M(V){if(V.setId)try{await Se.getState().loadSet(V.setId),W.getState().setUIMode("card-news"),l()}catch{p(t("gallery.openCardNewsSetFailed"),!0)}}async function H(V,se){if(se.stopPropagation(),!V.setId)return;const de=`generated/cardnews/${V.setId}`;try{await navigator.clipboard?.writeText(de),p(t("gallery.cardNewsPathCopied"))}catch{p(t("toast.copyFailed"),!0)}}function q(V,se){se.stopPropagation(),V.setId&&window.open(TN(V.setId),"_blank","noopener,noreferrer")}function k(){R(!0);try{localStorage.setItem(u0,"1")}catch{}}if(!i)return null;const J=V=>V==="earlier"||V==="today"||V==="yesterday"||V==="thisWeek"?t(`gallery.${V}`):V,T=(V,se,de)=>{const le=u?.image===V.image,fe=be=>{I.current[c0(V)]=be};return V.kind==="card-news-set"?h.jsx("div",{ref:fe,className:"gallery__tile-wrap gallery-card-news-set",children:h.jsx(mj,{item:V,onOpen:be=>{M(be)},onCopyPath:H,onDownloadManifest:q})},`${se}-${de}-${V.filename??de}`):h.jsx(pj,{item:V,active:le,itemRef:fe,onSelect:be=>{r(be),l()},onDelete:ue,t},`${se}-${de}-${V.filename??de}`)},L=v==="session",ne=C!=null&&C.state!=="ok"&&!U,ae=C?.state==="recoverable"?"gallery.storageNoticeRecoverable":C?.state==="not_found"?"gallery.storageNoticeNotFound":"gallery.storageNoticeUnknown";return h.jsx("div",{className:"gallery-backdrop",onClick:l,role:"presentation",children:h.jsxs("div",{className:"gallery",role:"dialog","aria-modal":"true","aria-label":t("gallery.ariaLabel"),onClick:V=>V.stopPropagation(),children:[h.jsxs("div",{className:"gallery__header",children:[h.jsxs("div",{className:"gallery__title-row",children:[h.jsx("div",{className:"gallery__title",children:t("gallery.title")}),h.jsxs("div",{className:"gallery__meta",children:[t("gallery.total",{n:te}),y?t("gallery.totalFiltered",{n:o.length}):""]}),h.jsxs("div",{className:"gallery__group-toggle",role:"tablist","aria-label":t("gallery.sortByAria"),children:[h.jsx("button",{type:"button",role:"tab","aria-selected":v==="date",className:v==="date"?"active":"",onClick:()=>x("date"),children:t("gallery.sortByDate")}),h.jsx("button",{type:"button",role:"tab","aria-selected":v==="session",className:v==="session"?"active":"",onClick:()=>x("session"),children:t("gallery.sortBySession")})]})]}),h.jsx("input",{type:"text",className:"gallery__search",placeholder:t(L?"gallery.searchDisabledPlaceholder":"gallery.searchPlaceholder"),value:y,onChange:V=>m(V.target.value),autoFocus:!0,disabled:L}),h.jsx("button",{type:"button",className:"gallery__close",onClick:l,"aria-label":t("gallery.closeAria"),title:t("gallery.closeTitle"),children:"×"})]}),h.jsxs("div",{className:`gallery__storage-bar${ne?" gallery__storage-bar--notice":""}`,children:[ne?h.jsxs("div",{className:"gallery__storage-copy",children:[h.jsx("div",{className:"gallery__storage-title",children:t("gallery.storageNoticeTitle")}),h.jsx("div",{className:"gallery__storage-text",children:t(ae)})]}):h.jsx("div",{className:"gallery__storage-copy gallery__storage-copy--quiet",children:C?.generatedDirLabel??"~/.ima2/generated"}),h.jsxs("div",{className:"gallery__storage-actions",children:[h.jsx("button",{type:"button",className:"gallery__storage-button",onClick:Z,title:t("gallery.openGeneratedDirTitle"),children:t("gallery.openGeneratedDir")}),ne&&h.jsx("button",{type:"button",className:"gallery__storage-button gallery__storage-button--ghost",onClick:k,children:t("common.close")})]})]}),h.jsx("div",{className:"gallery__scroll",ref:z,onScroll:()=>{X.current=z.current?.scrollTop??0},children:L?h.jsxs(h.Fragment,{children:[S.map(V=>h.jsxs("section",{className:"gallery__group",children:[h.jsxs("header",{className:"gallery__group-header",children:[h.jsx("span",{className:"gallery__group-label",title:V.sessionId,children:V.title?V.displayLabel:t("gallery.sessionLabel",{name:V.displayLabel})}),h.jsx("span",{className:"gallery__group-count",children:V.items.length})]}),h.jsx("div",{className:"gallery__grid",children:V.items.map((se,de)=>T(se,V.sessionId,de))})]},V.sessionId)),j.length>0&&h.jsxs("section",{className:"gallery__group",children:[h.jsxs("header",{className:"gallery__group-header",children:[h.jsx("span",{className:"gallery__group-label",children:t("gallery.standalone")}),h.jsx("span",{className:"gallery__group-count",children:j.length})]}),h.jsx("div",{className:"gallery__grid",children:j.map((V,se)=>T(V,"loose",se))})]}),S.length===0&&j.length===0&&h.jsx("div",{className:"gallery__empty",children:t("gallery.emptySessions")})]}):ce.length===0?h.jsx("div",{className:"gallery__empty",children:o.length===0?t("gallery.emptyAll"):t("gallery.noResults")}):K.map(([V,se])=>h.jsxs("section",{className:"gallery__group",children:[h.jsxs("header",{className:"gallery__group-header",children:[h.jsx("span",{className:"gallery__group-label",children:J(V)}),h.jsx("span",{className:"gallery__group-count",children:se.length})]}),h.jsx("div",{className:"gallery__grid",children:se.map((de,le)=>T(de,V,le))})]},V))}),A&&h.jsxs("div",{className:"gallery__undo",children:[h.jsx("span",{children:t("gallery.deleted",{filename:A.filename})}),h.jsx("button",{type:"button",onClick:D,children:t("gallery.undo")}),h.jsx("span",{className:"gallery__undo-timer",children:t("gallery.secondsSuffix",{n:Math.max(0,Math.ceil((A.expiresAt-Date.now())/1e3))})})]})]})})}function vj(t){return t.includes("ratio")?"sizeConfirm.reasonRatio":t.includes("pixels")?"sizeConfirm.reasonPixels":t.includes("min")?"sizeConfirm.reasonMin":t.includes("max")?"sizeConfirm.reasonMax":"sizeConfirm.reasonSnap"}function xj(){const t=W(g=>g.customSizeConfirm),i=W(g=>g.confirmCustomSizeAdjustment),l=W(g=>g.cancelCustomSizeAdjustment),o=Y.useRef(null),{t:r}=Te();if(Y.useEffect(()=>{if(!t)return;o.current?.focus();const g=p=>{p.key==="Escape"&&l()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[l,t]),!t)return null;const u=`${t.requestedW}x${t.requestedH}`,d=`${t.adjustedW}x${t.adjustedH}`;return h.jsx("div",{className:"modal-backdrop custom-size-confirm-backdrop",role:"presentation",children:h.jsxs("div",{className:"modal custom-size-confirm",role:"dialog","aria-modal":"true","aria-labelledby":"custom-size-confirm-title","aria-describedby":"custom-size-confirm-body",children:[h.jsx("div",{id:"custom-size-confirm-title",className:"modal__title",children:r("sizeConfirm.title")}),h.jsxs("div",{id:"custom-size-confirm-body",className:"modal__body",children:[h.jsx("p",{children:r("sizeConfirm.body")}),h.jsxs("dl",{className:"size-confirm__pairs",children:[h.jsxs("div",{className:"size-confirm__pair",children:[h.jsx("dt",{children:r("sizeConfirm.requested")}),h.jsx("dd",{children:u})]}),h.jsxs("div",{className:"size-confirm__pair",children:[h.jsx("dt",{children:r("sizeConfirm.adjusted")}),h.jsx("dd",{children:d})]})]}),h.jsx("p",{className:"size-confirm__reason",children:r(vj(t.reasons))})]}),h.jsxs("div",{className:"modal__actions",children:[h.jsx("button",{ref:o,type:"button",className:"modal__btn modal__btn--secondary",onClick:l,children:r("sizeConfirm.cancel")}),h.jsx("button",{type:"button",className:"modal__btn",onClick:()=>{i()},children:r("sizeConfirm.approve")})]})]})})}function bj(t){const i=t.slots.filter(o=>o.kind==="text"||o.textKind).length,l=t.slots.filter(o=>o.kind==="image").length;return`${i} text / ${l} image`}function Sj(){const{t}=Te(),i=Se(r=>r.templates),l=Se(r=>r.imageTemplateId),o=Se(r=>r.setImageTemplate);return h.jsxs("section",{className:"card-news-panel",children:[h.jsxs("div",{className:"card-news-panel__head",children:[h.jsx("span",{children:t("cardNews.imageTemplate")}),h.jsx("button",{type:"button",disabled:!0,title:t("cardNews.newTemplateLater"),children:"+"})]}),h.jsx("div",{className:"card-news-template-grid",children:i.map(r=>h.jsxs("button",{type:"button",className:`card-news-template${l===r.id?" selected":""}`,onClick:()=>o(r.id),children:[h.jsx("img",{src:r.previewUrl,alt:""}),h.jsxs("span",{className:"card-news-template__body",children:[h.jsx("span",{className:"card-news-template__name",children:r.name}),h.jsx("span",{className:"card-news-template__meta",children:bj(r)}),h.jsx("span",{className:"card-news-template__sizes",children:r.recommendedOutputSizes.join(" · ")})]})]},r.id))})]})}function wj(){const{t}=Te(),i=Se(r=>r.roleTemplates),l=Se(r=>r.roleTemplateId),o=Se(r=>r.setRoleTemplate);return h.jsxs("section",{className:"card-news-panel",children:[h.jsx("div",{className:"card-news-panel__head",children:h.jsx("span",{children:t("cardNews.roleTemplate")})}),h.jsx("div",{className:"card-news-role-row",children:i.map(r=>h.jsx("button",{type:"button",className:l===r.id?"selected":"",onClick:()=>o(r.id),children:r.name},r.id))})]})}function Nj({status:t,locked:i}){const{t:l}=Te(),o=i?"locked":t,r=o==="queued"||o==="generating";return h.jsxs("span",{className:`card-news-status-badge card-news-status-badge--${o}`,children:[r?h.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,l(`cardNews.status.${o}`)]})}function _j(t,i){const l=`cardNews.roles.${t}`,o=i(l);return o===l?t:o}function Ej(){const{t}=Te(),i=Se(r=>r.activePlan),l=Se(r=>r.selectedCardId),o=Se(r=>r.selectCard);return i?h.jsx("div",{className:"card-news-deck","aria-label":"Card deck",onWheel:B0,children:i.cards.map(r=>h.jsxs("button",{type:"button",className:`card-news-deck-card${l===r.id?" selected":""}`,onClick:()=>o(r.id),children:[h.jsx("span",{children:String(r.order).padStart(2,"0")}),r.url?h.jsx("img",{src:r.url,alt:"",className:"card-news-deck-card__thumb"}):null,h.jsx("strong",{children:_j(r.role,t)}),h.jsx("small",{children:r.headline||r.textFields.find(u=>u.renderMode==="in-image")?.text}),h.jsx(Nj,{status:r.status,locked:r.locked})]},r.id))}):null}const Cj=[];function Tj(){const{t}=Te(),i=Se(r=>r.activePlan?.cards??Cj),l=Se(r=>r.generating),o={total:i.length,done:i.filter(r=>r.status==="generated").length,queued:i.filter(r=>r.status==="queued").length,errors:i.filter(r=>r.status==="error").length,skipped:i.filter(r=>r.locked||r.status==="skipped").length};return o.total?h.jsxs("div",{className:"card-news-batch-bar","aria-live":"polite",children:[h.jsx("span",{children:l?t("cardNews.progress.generating",{done:o.done,total:o.total}):t("cardNews.progress.summary",{done:o.done,total:o.total})}),h.jsx("span",{children:t("cardNews.progress.detail",{queued:o.queued,errors:o.errors,skipped:o.skipped})})]}):null}function Aj({meta:t}){const{t:i}=Te();if(!t)return null;const l=t.mode==="structured-output"?i("cardNews.planner.structured"):t.mode==="json-mode"?i("cardNews.planner.jsonMode"):i("cardNews.planner.fallback");return h.jsxs("span",{className:"card-news-planner-badge",children:[l," · ",t.model,t.repaired?` · ${i("cardNews.planner.repaired")}`:""]})}function Mj(t){const i=t.textFields.filter(l=>l.renderMode==="in-image"&&l.text).map(l=>`[${l.placement}] ${l.text}`);return[t.headline,...i].filter(Boolean).join(`
|
|
22
22
|
`)}function jj(t,i){const l=t.slotId?i?.slots.find(o=>o.id===t.slotId):null;return l?{left:`${l.x/20.48}%`,top:`${l.y/20.48}%`,width:`${l.w/20.48}%`,minHeight:`${l.h/20.48}%`}:zj(t)}const d0={"top-left":{left:"10%",top:"10%",width:"34%"},"top-center":{left:"50%",top:"10%",width:"42%",transform:"translateX(-50%)"},"top-right":{right:"10%",top:"10%",width:"34%"},"center-left":{left:"10%",top:"50%",width:"34%",transform:"translateY(-50%)"},center:{left:"50%",top:"50%",width:"44%",transform:"translate(-50%, -50%)"},"center-right":{right:"10%",top:"50%",width:"34%",transform:"translateY(-50%)"},"bottom-left":{left:"10%",bottom:"10%",width:"34%"},"bottom-center":{left:"50%",bottom:"10%",width:"42%",transform:"translateX(-50%)"},"bottom-right":{right:"10%",bottom:"10%",width:"34%"},free:{left:"50%",top:"50%",width:"44%",transform:"translate(-50%, -50%)"}};function zj(t){return d0[t.placement]||d0.center}function Rj(){const{t}=Te(),i=Se(v=>v.activePlan),l=Se(v=>v.selectedCardId),o=Se(v=>v.selectedTextFieldId),r=Se(v=>v.templates),u=Se(v=>v.plannerMeta),d=Se(v=>v.retryCard),g=Se(v=>v.selectTextField),p=i?.cards.find(v=>v.id===l)||i?.cards[0],y=i?r.find(v=>v.id===i.imageTemplateId):void 0,m=p?.textFields.filter(v=>v.renderMode==="in-image")||[];return!i||!p?h.jsxs("section",{className:"card-news-empty",children:[h.jsxs("div",{className:"card-news-empty__deck","aria-hidden":"true",children:[h.jsx("div",{className:"card-news-empty__card card-news-empty__card--back"}),h.jsx("div",{className:"card-news-empty__card card-news-empty__card--mid"}),h.jsxs("div",{className:"card-news-empty__card",children:[h.jsx("span",{}),h.jsx("strong",{}),h.jsx("em",{})]})]}),h.jsxs("div",{className:"card-news-empty__copy",children:[h.jsx("span",{children:t("uiMode.cardNews")}),h.jsx("h2",{children:t("cardNews.emptyTitle")}),h.jsx("p",{children:t("cardNews.emptyBody")})]})]}):h.jsxs("section",{className:"card-news-stage",children:[h.jsxs("div",{className:"card-news-stage__header",children:[h.jsxs("div",{children:[h.jsx("h2",{children:i.title}),h.jsx("p",{children:i.generationStrategy}),h.jsx(Aj,{meta:u})]}),h.jsxs("span",{children:[p.order," / ",i.cards.length]})]}),h.jsx(Tj,{}),h.jsxs("div",{className:"card-news-preview",children:[p.status==="queued"||p.status==="generating"?h.jsx("div",{className:"card-news-preview__loading",children:t("cardNews.progress.cardGenerating")}):p.status==="error"?h.jsxs("div",{className:"card-news-preview__error",children:[h.jsx("span",{children:p.error||t("cardNews.error")}),p.locked?null:h.jsx("button",{type:"button",onClick:()=>{d(p.id)},children:t("cardNews.retryCard")})]}):p.url?h.jsx("img",{src:p.url,alt:p.headline}):h.jsx("div",{className:"card-news-preview__slot"}),m.length?h.jsx("div",{className:"card-news-stage-overlay",children:m.map(v=>h.jsx("button",{type:"button",className:`card-news-stage-overlay__field card-news-stage-overlay__field--${v.placement}${o===v.id?" selected":""}`,style:jj(v,y),onClick:()=>g(v.id),"aria-label":t("cardNews.selectTextField",{text:v.text||v.kind}),children:h.jsx("span",{children:v.text||v.kind})},v.id))}):null]}),p.url?h.jsxs("div",{className:"card-news-result-actions",children:[h.jsx("button",{type:"button",onClick:()=>navigator.clipboard?.writeText(p.visualPrompt),children:t("cardNews.actions.copyPrompt")}),h.jsx("button",{type:"button",onClick:()=>navigator.clipboard?.writeText(Mj(p)),children:t("cardNews.actions.copyCopy")}),h.jsx("a",{href:p.url,target:"_blank",rel:"noreferrer",children:t("cardNews.actions.openImage")}),h.jsx("a",{href:p.url,download:!0,children:t("cardNews.actions.downloadCard")})]}):null]})}function Ax(t,i){const l=`cardNews.placements.${t}`,o=i(l);return o===l?t:o}function Dj({placement:t}){const{t:i}=Te();return h.jsx("span",{className:"card-news-placement-chip",children:Ax(t,i)})}const Oj=["headline","body","caption","cta","badge","number"],Hj=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right","free"],Ij=["in-image","ui-only"],Bj=["primary","secondary","supporting"];function Er(t,i,l){const o=`cardNews.${t}.${i}`,r=l(o);return r===o?i:r}function Lj({field:t,locked:i,selected:l=!1,onSelect:o,onChange:r,onRemove:u}){const{t:d}=Te(),g=t.text.length,p=typeof t.maxChars=="number"&&g>t.maxChars,y=t.maxChars===null||t.maxChars>80;return h.jsxs("div",{className:`card-news-text-field-card${l?" selected":""}`,onClick:o,children:[h.jsxs("div",{className:"card-news-text-field-card__header",children:[h.jsx("span",{children:Er("textKinds",t.kind,d)}),h.jsx(Dj,{placement:t.placement})]}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:d("cardNews.textFieldText")}),y?h.jsx("textarea",{value:t.text,disabled:i,onChange:m=>r({text:m.target.value,source:"user"})}):h.jsx("input",{value:t.text,disabled:i,onChange:m=>r({text:m.target.value,source:"user"})})]}),h.jsxs("div",{className:"card-news-text-field-card__grid",children:[h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:d("cardNews.textKind")}),h.jsx("select",{value:t.kind,disabled:i,onChange:m=>r({kind:m.target.value,source:"user"}),children:Oj.map(m=>h.jsx("option",{value:m,children:Er("textKinds",m,d)},m))})]}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:d("cardNews.placement")}),h.jsx("select",{value:t.placement,disabled:i,onChange:m=>r({placement:m.target.value,source:"user"}),children:Hj.map(m=>h.jsx("option",{value:m,children:Ax(m,d)},m))})]}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:d("cardNews.renderMode")}),h.jsx("select",{value:t.renderMode,disabled:i,onChange:m=>r({renderMode:m.target.value,source:"user"}),children:Ij.map(m=>h.jsx("option",{value:m,children:Er("renderModes",m,d)},m))})]}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:d("cardNews.hierarchyLabel")}),h.jsx("select",{value:t.hierarchy,disabled:i,onChange:m=>r({hierarchy:m.target.value,source:"user"}),children:Bj.map(m=>h.jsx("option",{value:m,children:Er("hierarchy",m,d)},m))})]})]}),h.jsxs("div",{className:`card-news-text-field-card__meta${p?" over":""}`,children:[h.jsx("span",{children:t.maxChars===null?g:`${g}/${t.maxChars}`}),p?h.jsx("span",{children:d("cardNews.textTooLong")}):null,u?h.jsx("button",{type:"button",disabled:i,onClick:u,children:d("cardNews.removeTextField")}):null]})]})}function kj(){return{id:`tf_${Date.now().toString(36)}`,kind:"body",text:"",renderMode:"in-image",placement:"center",slotId:null,hierarchy:"supporting",maxChars:null,language:null,source:"user"}}function Uj(){const{t}=Te(),i=Se(v=>v.activePlan),l=Se(v=>v.selectedCardId),o=Se(v=>v.selectedTextFieldId),r=Se(v=>v.updateCard),u=Se(v=>v.updateTextField),d=Se(v=>v.addTextField),g=Se(v=>v.removeTextField),p=Se(v=>v.selectTextField),y=Se(v=>v.retryCard),m=i?.cards.find(v=>v.id===l)||i?.cards[0];return m?h.jsxs("aside",{className:"card-news-inspector",children:[h.jsx("div",{className:"section-title",children:t("cardNews.inspector")}),h.jsxs("div",{className:"card-news-inspector-group",children:[h.jsx("span",{className:"card-news-inspector-label",children:t("cardNews.cardTitle")}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.headline")}),h.jsx("input",{value:m.headline,disabled:m.locked,onChange:v=>r(m.id,{headline:v.target.value})})]})]}),h.jsxs("div",{className:"card-news-inspector-group",children:[h.jsxs("div",{className:"card-news-inspector-row",children:[h.jsx("span",{className:"card-news-inspector-label",children:t("cardNews.textFields")}),h.jsx("button",{type:"button",className:"secondary-btn",disabled:m.locked,onClick:()=>d(m.id,kj()),children:t("cardNews.addTextField")})]}),m.textFields.length?m.textFields.map(v=>h.jsx(Lj,{field:v,locked:m.locked,selected:o===v.id,onSelect:()=>p(v.id),onChange:x=>u(m.id,v.id,x),onRemove:()=>g(m.id,v.id)},v.id)):h.jsx("p",{className:"card-news-muted",children:t("cardNews.noTextFields")})]}),h.jsxs("details",{className:"card-news-inspector-group card-news-advanced-prompt",children:[h.jsx("summary",{children:t("cardNews.designPrompt")}),h.jsxs("label",{className:"card-news-field",children:[h.jsx("span",{children:t("cardNews.visualPrompt")}),h.jsx("textarea",{value:m.visualPrompt,disabled:m.locked,onChange:v=>r(m.id,{visualPrompt:v.target.value})})]})]}),m.imageFilename?h.jsxs("div",{className:"card-news-generated-meta",children:[h.jsx("span",{children:t("cardNews.generatedMeta")}),h.jsx("code",{children:m.imageFilename}),h.jsx("span",{children:m.status})]}):null,m.locked?h.jsx("p",{className:"card-news-locked-help",children:t("cardNews.lockedHelp")}):null,h.jsx("button",{type:"button",className:`secondary-btn${m.locked?" active":""}`,onClick:()=>r(m.id,{locked:!m.locked}),children:m.locked?t("cardNews.locked"):t("cardNews.unlocked")}),h.jsx("button",{type:"button",className:"secondary-btn",disabled:m.locked||!["draft","error"].includes(m.status),onClick:()=>{y(m.id)},children:t("cardNews.retryCard")})]}):h.jsxs("aside",{className:"card-news-inspector card-news-inspector-empty",children:[h.jsx("div",{className:"section-title",children:t("cardNews.inspector")}),h.jsxs("div",{className:"card-news-inspector-empty__mock","aria-hidden":"true",children:[h.jsx("span",{}),h.jsx("strong",{}),h.jsx("i",{}),h.jsx("i",{})]}),h.jsx("p",{children:t("cardNews.noCard")})]})}function qj(){const{t}=Te(),i=Se(o=>o.hydrate),l=Se(o=>o.error);return Y.useEffect(()=>{i()},[i]),h.jsxs("main",{className:"card-news-workspace","aria-label":t("cardNews.workspace"),children:[h.jsxs("div",{className:"card-news-setup",children:[h.jsx(Sj,{}),h.jsx(wj,{})]}),h.jsxs("div",{className:"card-news-main",children:[l?h.jsx("div",{className:"card-news-error",role:"alert",children:l}):null,h.jsx(Rj,{}),h.jsx(Ej,{})]}),h.jsx(Uj,{})]})}function Gj(){const t=W(x=>x.hydrateHistory),i=W(x=>x.loadSessions),l=W(x=>x.startInFlightPolling),o=W(x=>x.reconcileInflight),r=W(x=>x.syncFromStorage),u=W(x=>x.theme),d=W(x=>x.resolvedTheme),g=W(x=>x.settingsOpen),p=W(x=>x.syncThemeFromStorage),y=W(x=>x.refreshResolvedTheme),v=W(x=>x.uiMode)==="node"&&yf?"node":"classic";return Y.useEffect(()=>{t(),i(),o(),l()},[t,i,o,l]),Y.useEffect(()=>{const x=S=>{S.key&&(S.key==="ima2.inFlight"||S.key==="ima2.selectedFilename"?r():S.key==="ima2:theme"&&p())};return window.addEventListener("storage",x),()=>window.removeEventListener("storage",x)},[r,p]),Y.useEffect(()=>{document.documentElement.dataset.theme=d,document.documentElement.style.colorScheme=d},[d]),Y.useEffect(()=>{if(u!=="system")return;const x=window.matchMedia("(prefers-color-scheme: light)");return x.addEventListener("change",y),()=>x.removeEventListener("change",y)},[y,u]),Y.useEffect(()=>{const x=()=>{fN(W.getState)};return window.addEventListener("beforeunload",x),()=>{window.removeEventListener("beforeunload",x)}},[]),h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:`app${g?" app--settings-open":""}`,"data-theme":d,children:[h.jsx(ON,{}),g?h.jsx(dj,{}):v==="classic"?h.jsx(ny,{}):v==="node"?h.jsx(QM,{}):v==="card-news"?h.jsx(qj,{}):h.jsx(ny,{}),v==="card-news"?null:h.jsx(nj,{})]}),h.jsx(xj,{}),h.jsx(fj,{}),h.jsx(hj,{}),h.jsx(yj,{})]})}GS.createRoot(document.getElementById("root")).render(h.jsx(Y.StrictMode,{children:h.jsx(Gj,{})}));
|
|
23
|
-
//# sourceMappingURL=index-
|
|
23
|
+
//# sourceMappingURL=index-BjX_nzuK.js.map
|