@codeyam/codeyam-cli 0.1.0-staging.2ea44f6 → 0.1.0-staging.3ef993e
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/analyzer-template/.build-info.json +8 -8
- package/analyzer-template/log.txt +3 -3
- package/analyzer-template/package.json +1 -1
- package/analyzer-template/packages/aws/package.json +1 -1
- package/analyzer-template/packages/database/src/lib/kysely/tables/editorScenariosTable.ts +73 -0
- package/analyzer-template/packages/database/src/lib/loadEntities.ts +0 -6
- package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +0 -65
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts +6 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js +73 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +0 -6
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +0 -25
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts +2 -0
- package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js +2 -0
- package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js.map +1 -1
- package/analyzer-template/packages/types/src/enums/ProjectFramework.ts +2 -0
- package/analyzer-template/packages/ui-components/package.json +1 -1
- package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts +2 -0
- package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js +2 -0
- package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js.map +1 -1
- package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js +45 -0
- package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js.map +1 -0
- package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js +101 -47
- package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js.map +1 -1
- package/codeyam-cli/src/commands/editor.js +1265 -213
- package/codeyam-cli/src/commands/editor.js.map +1 -1
- package/codeyam-cli/src/commands/init.js +67 -34
- package/codeyam-cli/src/commands/init.js.map +1 -1
- package/codeyam-cli/src/data/techStacks.js +77 -0
- package/codeyam-cli/src/data/techStacks.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js +173 -0
- package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js +46 -0
- package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +508 -1
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js +152 -3
- package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js +140 -12
- package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorJournal.test.js +238 -2
- package/codeyam-cli/src/utils/__tests__/editorJournal.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js +128 -1
- package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorPreview.test.js +191 -5
- package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js +153 -0
- package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js +139 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js +221 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +887 -2
- package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js +213 -0
- package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js +289 -40
- package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js +107 -0
- package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js +129 -0
- package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js +227 -0
- package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js +426 -218
- package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +13 -5
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js +51 -0
- package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/webappDetection.test.js +142 -0
- package/codeyam-cli/src/utils/__tests__/webappDetection.test.js.map +1 -0
- package/codeyam-cli/src/utils/analyzer.js +9 -0
- package/codeyam-cli/src/utils/analyzer.js.map +1 -1
- package/codeyam-cli/src/utils/analyzerFinalization.js +100 -0
- package/codeyam-cli/src/utils/analyzerFinalization.js.map +1 -0
- package/codeyam-cli/src/utils/backgroundServer.js +92 -16
- package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
- package/codeyam-cli/src/utils/database.js +37 -2
- package/codeyam-cli/src/utils/database.js.map +1 -1
- package/codeyam-cli/src/utils/editorAudit.js +91 -3
- package/codeyam-cli/src/utils/editorAudit.js.map +1 -1
- package/codeyam-cli/src/utils/editorDevServer.js +89 -1
- package/codeyam-cli/src/utils/editorDevServer.js.map +1 -1
- package/codeyam-cli/src/utils/editorImageVerifier.js +45 -10
- package/codeyam-cli/src/utils/editorImageVerifier.js.map +1 -1
- package/codeyam-cli/src/utils/editorJournal.js +78 -3
- package/codeyam-cli/src/utils/editorJournal.js.map +1 -1
- package/codeyam-cli/src/utils/editorLoaderHelpers.js +32 -0
- package/codeyam-cli/src/utils/editorLoaderHelpers.js.map +1 -1
- package/codeyam-cli/src/utils/editorPreview.js +43 -2
- package/codeyam-cli/src/utils/editorPreview.js.map +1 -1
- package/codeyam-cli/src/utils/editorScenarioSwitch.js +112 -0
- package/codeyam-cli/src/utils/editorScenarioSwitch.js.map +1 -0
- package/codeyam-cli/src/utils/editorScenarios.js +291 -0
- package/codeyam-cli/src/utils/editorScenarios.js.map +1 -1
- package/codeyam-cli/src/utils/editorSeedAdapter.js +173 -0
- package/codeyam-cli/src/utils/editorSeedAdapter.js.map +1 -0
- package/codeyam-cli/src/utils/entityChangeStatus.js +42 -19
- package/codeyam-cli/src/utils/entityChangeStatus.js.map +1 -1
- package/codeyam-cli/src/utils/entityChangeStatus.server.js +56 -5
- package/codeyam-cli/src/utils/entityChangeStatus.server.js.map +1 -1
- package/codeyam-cli/src/utils/parseRegisterArg.js +31 -0
- package/codeyam-cli/src/utils/parseRegisterArg.js.map +1 -0
- package/codeyam-cli/src/utils/progress.js +2 -2
- package/codeyam-cli/src/utils/progress.js.map +1 -1
- package/codeyam-cli/src/utils/scenarioCoverage.js +75 -0
- package/codeyam-cli/src/utils/scenarioCoverage.js.map +1 -0
- package/codeyam-cli/src/utils/scenariosManifest.js +204 -75
- package/codeyam-cli/src/utils/scenariosManifest.js.map +1 -1
- package/codeyam-cli/src/utils/serverState.js +30 -0
- package/codeyam-cli/src/utils/serverState.js.map +1 -1
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +13 -5
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
- package/codeyam-cli/src/utils/simulationGateMiddleware.js +8 -1
- package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -1
- package/codeyam-cli/src/utils/slugUtils.js +25 -0
- package/codeyam-cli/src/utils/slugUtils.js.map +1 -0
- package/codeyam-cli/src/utils/syncMocksMiddleware.js +2 -2
- package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
- package/codeyam-cli/src/utils/webappDetection.js +21 -0
- package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
- package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js +40 -0
- package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js.map +1 -0
- package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js +567 -0
- package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js.map +1 -0
- package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js +146 -0
- package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js.map +1 -0
- package/codeyam-cli/src/webserver/app/lib/clientErrors.js +65 -0
- package/codeyam-cli/src/webserver/app/lib/clientErrors.js.map +1 -0
- package/codeyam-cli/src/webserver/app/lib/git.js +3 -2
- package/codeyam-cli/src/webserver/app/lib/git.js.map +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{CopyButton-DmJveP3T.js → CopyButton-BPXZwM4t.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-C76mRRiF.js → EntityItem-BcgbViKV.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-CobE682z.js → EntityTypeIcon-CQIG2qda.js} +9 -9
- package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-djPLI-WV.js → ReportIssueModal-BzHcG7SE.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-ZlRKbhrq.js → ScenarioViewer-TSD3C211.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{_index-C96V0n15.js → _index-DLxKhri3.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/{activity.(_tab)-BpKzcsJz.js → activity.(_tab)-BcY3q6nt.js} +6 -6
- package/codeyam-cli/src/webserver/build/client/assets/{agent-transcripts-D9hemwl6.js → agent-transcripts-Bni3iiUj.js} +5 -5
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-project-info-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-coverage-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{book-open-D_nMCFmP.js → book-open-BYOypzCa.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-BH2h1Ea2.js → chevron-down-C_Pmso5S.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{circle-check-DyIKORY6.js → circle-check-BVMi9VA5.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{copy-NDbZjXao.js → copy-n2FB0_Sw.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CC6AbExI.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/{dev.empty-CltMNppm.js → dev.empty-Ii3inc0_.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/editor-COWCNVyV.js +10 -0
- package/codeyam-cli/src/webserver/build/client/assets/editorPreview-CNB06EIa.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-DItJnD8s.js → entity._sha._-DwCV5__E.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha.scenarios._scenarioId.dev-CCa2trIL.js → entity._sha.scenarios._scenarioId.dev-CXSi2aeZ.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-CHMiAog3.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/{files-DO4CZ16O.js → files-BZrlFE1F.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{git-CdN8sCqs.js → git-DdZcvjGh.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/globals-phvmGvat.css +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-BAXYRVEO.js → loader-circle-DaAZ_H2w.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/manifest-6134dc40.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/memory-9gnxSZlb.js +101 -0
- package/codeyam-cli/src/webserver/build/client/assets/{pause-DTAcYxBt.js → pause-f5-1lKBt.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/root-BWAyuj0r.js +67 -0
- package/codeyam-cli/src/webserver/build/client/assets/{search-fKo7v0Zo.js → search-Di64LWVb.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/{settings-DfuTtcJP.js → settings-0OrEMU6J.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{simulations-B3aOzpCZ.js → simulations-DWT-CvLy.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{terminal-BG4heKCG.js → terminal-Br7MOqts.js} +3 -3
- package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-DtSmdtM4.js → triangle-alert-BLdiCuG-.js} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-C-_hOl_g.js +1 -0
- package/codeyam-cli/src/webserver/build/client/sound-test.html +98 -0
- package/codeyam-cli/src/webserver/build/server/assets/index-ChX0hPcu.js +1 -0
- package/codeyam-cli/src/webserver/build/server/assets/init-kSNsMjj8.js +10 -0
- package/codeyam-cli/src/webserver/build/server/assets/server-build-Bm2xIhmh.js +439 -0
- package/codeyam-cli/src/webserver/build/server/index.js +1 -1
- package/codeyam-cli/src/webserver/build-info.json +5 -5
- package/codeyam-cli/src/webserver/editorProxy.js +487 -17
- package/codeyam-cli/src/webserver/editorProxy.js.map +1 -1
- package/codeyam-cli/src/webserver/idleDetector.js +73 -0
- package/codeyam-cli/src/webserver/idleDetector.js.map +1 -0
- package/codeyam-cli/src/webserver/public/sound-test.html +98 -0
- package/codeyam-cli/src/webserver/scripts/codeyam-preload.mjs +21 -3
- package/codeyam-cli/src/webserver/scripts/journalCapture.ts +94 -4
- package/codeyam-cli/src/webserver/server.js +59 -34
- package/codeyam-cli/src/webserver/server.js.map +1 -1
- package/codeyam-cli/src/webserver/terminalServer.js +64 -32
- package/codeyam-cli/src/webserver/terminalServer.js.map +1 -1
- package/codeyam-cli/templates/chrome-extension-react/EXTENSION_SETUP.md +75 -0
- package/codeyam-cli/templates/chrome-extension-react/README.md +46 -0
- package/codeyam-cli/templates/chrome-extension-react/gitignore +15 -0
- package/codeyam-cli/templates/chrome-extension-react/index.html +12 -0
- package/codeyam-cli/templates/chrome-extension-react/package.json +27 -0
- package/codeyam-cli/templates/chrome-extension-react/popup.html +12 -0
- package/codeyam-cli/templates/chrome-extension-react/public/manifest.json +15 -0
- package/codeyam-cli/templates/chrome-extension-react/src/background/service-worker.ts +7 -0
- package/codeyam-cli/templates/chrome-extension-react/src/globals.css +6 -0
- package/codeyam-cli/templates/chrome-extension-react/src/lib/storage.ts +37 -0
- package/codeyam-cli/templates/chrome-extension-react/src/popup/App.tsx +12 -0
- package/codeyam-cli/templates/chrome-extension-react/src/popup/main.tsx +10 -0
- package/codeyam-cli/templates/chrome-extension-react/tsconfig.json +24 -0
- package/codeyam-cli/templates/chrome-extension-react/vite.config.ts +41 -0
- package/codeyam-cli/templates/codeyam-editor-claude.md +84 -5
- package/codeyam-cli/templates/editor-step-hook.py +37 -8
- package/codeyam-cli/templates/expo-react-native/MOBILE_SETUP.md +89 -0
- package/codeyam-cli/templates/expo-react-native/README.md +41 -0
- package/codeyam-cli/templates/expo-react-native/app/(tabs)/_layout.tsx +33 -0
- package/codeyam-cli/templates/expo-react-native/app/(tabs)/index.tsx +12 -0
- package/codeyam-cli/templates/expo-react-native/app/(tabs)/settings.tsx +12 -0
- package/codeyam-cli/templates/expo-react-native/app/_layout.tsx +12 -0
- package/codeyam-cli/templates/expo-react-native/app.json +18 -0
- package/codeyam-cli/templates/expo-react-native/babel.config.js +9 -0
- package/codeyam-cli/templates/expo-react-native/gitignore +12 -0
- package/codeyam-cli/templates/expo-react-native/global.css +3 -0
- package/codeyam-cli/templates/expo-react-native/lib/storage.ts +32 -0
- package/codeyam-cli/templates/expo-react-native/metro.config.js +6 -0
- package/codeyam-cli/templates/expo-react-native/nativewind-env.d.ts +1 -0
- package/codeyam-cli/templates/expo-react-native/package.json +38 -0
- package/codeyam-cli/templates/expo-react-native/tailwind.config.js +10 -0
- package/codeyam-cli/templates/expo-react-native/tsconfig.json +10 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_PATTERNS.md +308 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_UPGRADE.md +304 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/DATABASE.md +126 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/FEATURE_PATTERNS.md +37 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/README.md +53 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/app/lib/prisma.ts +9 -4
- package/codeyam-cli/templates/nextjs-prisma-sqlite/env +4 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +1 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/package.json +1 -0
- package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/seed.ts +4 -1
- package/codeyam-cli/templates/nextjs-prisma-sqlite/seed-adapter.ts +92 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/README.md +52 -0
- package/codeyam-cli/templates/{nextjs-prisma-sqlite/PRISMA_SETUP.md → nextjs-prisma-supabase/SUPABASE_SETUP.md} +37 -17
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/api/todos/route.ts +17 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/globals.css +26 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/layout.tsx +34 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/prisma.ts +20 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/supabase.ts +12 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/app/page.tsx +10 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/env +9 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/eslint.config.mjs +11 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/gitignore +40 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/next.config.ts +11 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/package.json +37 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/postcss.config.mjs +7 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/schema.prisma +27 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/seed.ts +39 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/prisma.config.ts +12 -0
- package/codeyam-cli/templates/nextjs-prisma-supabase/tsconfig.json +34 -0
- package/codeyam-cli/templates/skills/codeyam-dev-mode/SKILL.md +1 -1
- package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +28 -9
- package/package.json +1 -1
- package/packages/database/src/lib/kysely/tables/editorScenariosTable.js +73 -0
- package/packages/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -1
- package/packages/database/src/lib/loadEntities.js +0 -6
- package/packages/database/src/lib/loadEntities.js.map +1 -1
- package/packages/database/src/lib/updateCommitMetadata.js +0 -25
- package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
- package/packages/types/src/enums/ProjectFramework.js +2 -0
- package/packages/types/src/enums/ProjectFramework.js.map +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CMT1jU2q.js +0 -21
- package/codeyam-cli/src/webserver/build/client/assets/editor-Rfq_y0VR.js +0 -10
- package/codeyam-cli/src/webserver/build/client/assets/editorPreview-GNwaLSmC.js +0 -41
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-CF164ouH.js +0 -6
- package/codeyam-cli/src/webserver/build/client/assets/globals-Bd0cs8vw.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/manifest-9ab0aba3.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/memory-Dg0mvYrI.js +0 -96
- package/codeyam-cli/src/webserver/build/client/assets/root-3ciuWk-c.js +0 -67
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-CrAK28Bc.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/index-DCxIbVvl.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-E-peu3XZ.js +0 -367
|
@@ -1,367 +0,0 @@
|
|
|
1
|
-
var lc=Object.defineProperty;var Ha=e=>{throw TypeError(e)};var cc=(e,t,r)=>t in e?lc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Cn=(e,t,r)=>cc(e,typeof t!="symbol"?t+"":t,r),dc=(e,t,r)=>t.has(e)||Ha("Cannot "+r);var Va=(e,t,r)=>(dc(e,t,"read from private field"),r?r.call(e):t.get(e)),Ga=(e,t,r)=>t.has(e)?Ha("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as c,Fragment as ue}from"react/jsx-runtime";import{PassThrough as uc}from"node:stream";import{createReadableStreamFromReadable as mc}from"@react-router/node";import{ServerRouter as pc,useFetcher as De,useLocation as kr,useNavigate as Ct,Link as de,UNSAFE_withComponentProps as We,Meta as hc,Links as fc,ScrollRestoration as gc,Scripts as yc,useLoaderData as Ve,useRevalidator as mt,Outlet as xc,data as Q,useSearchParams as mn,useRouteLoaderData as bc,useParams as ii,useActionData as vc,redirect as qa}from"react-router";import{isbot as wc}from"isbot";import{renderToPipeableStream as Nc}from"react-dom/server";import{useState as M,useEffect as te,useCallback as se,createContext as Js,useContext as Er,useRef as xe,useMemo as ne,forwardRef as Cc,useImperativeHandle as Sc,Component as kc}from"react";import{Settings as Ka,CheckCircle2 as Hs,Bug as li,AlertTriangle as cr,Check as pt,Copy as wt,Loader2 as ct,PencilRuler as Ec,HomeIcon as Ac,GitCommitIcon as Qa,File as Pc,RefreshCw as Mc,BookOpen as dr,FlaskConical as _c,SettingsIcon as jc,PanelsTopLeftIcon as Tc,ComponentIcon as $c,FileText as Za,Code as Xa,Box as Rc,List as Ic,BarChart3 as Dc,Tag as Lc,Image as $n,Code2 as ci,Activity as ns,ChevronDown as it,CircleEqual as Oc,ArrowLeft as Fc,Terminal as ur,Search as Ln,ChevronLeft as zc,ChevronRight as Dt,Save as Bc,MessageSquare as Yc,Pause as di,ListTodo as Uc,PauseCircle as Wc,FileCode as mr,GripVertical as Jc,Ban as Hc,CheckCircle as Vc,FolderOpen as Gc,CodeXml as qc,Zap as Kc,Pencil as Qc,Trash2 as Zc,X as On,Folder as ui,Info as ks,Plus as Vs,Eye as Xc,FolderTree as ed,ChevronsUpDown as mi,ChevronsDownUp as pi}from"lucide-react";import"fetch-retry";import td from"better-sqlite3";import{Pool as nd}from"pg";import*as K from"fs";import Ne,{existsSync as jt,readdirSync as rd,rmSync as rs}from"fs";import*as Y from"path";import ee,{join as eo}from"path";import{OperationNodeTransformer as sd,Kysely as hi,ParseJSONResultsPlugin as ad,SqliteDialect as od,PostgresDialect as id,sql as ot}from"kysely";import*as ld from"kysely/helpers/sqlite";import*as cd from"kysely/helpers/postgres";import Ue from"typescript";import*as be from"fs/promises";import ye,{writeFile as Pn,readFile as Es,mkdir as dd}from"fs/promises";import*as Gs from"os";import As from"os";import ud from"prompts";import pr from"chalk";import*as md from"crypto";import Fn,{randomUUID as qs,createHmac as pd}from"crypto";import{execSync as Ee,spawn as Lt,exec as Ks}from"child_process";import{fileURLToPath as Ar}from"url";import{promisify as Qs}from"util";import hd from"dotenv";import fd,{EventEmitter as Pr}from"events";import{v4 as gd}from"uuid";import Zs from"http";import yd from"net";import{WebSocket as fi}from"ws";import"node-pty";import xd from"openai";import bd from"p-queue";import to from"p-retry";import{DynamoDBClient as Mr,PutItemCommand as vd}from"@aws-sdk/client-dynamodb";import{LRUCache as Xs}from"lru-cache";import"pluralize";import"piscina";import wd from"json5";import{marshall as Nd}from"@aws-sdk/util-dynamodb";import Cd from"v8";import{Prism as Sd}from"react-syntax-highlighter";import{vscDarkPlus as kd}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as Ed}from"node:crypto";import{minimatch as Ps}from"minimatch";import Ad from"react-markdown";import Pd from"remark-gfm";import Md from"react-diff-viewer-continued";const gi=5e3;function _d(e,t,r,s,a){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let l=!1,d=e.headers.get("user-agent"),m=d&&wc(d)||s.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>h(),gi+1e3);const{pipe:p,abort:h}=Nc(n(pc,{context:s,url:e.url}),{[m](){l=!0;const f=new uc({final(g){clearTimeout(u),u=void 0,g()}}),y=mc(f);r.set("Content-Type","text/html"),p(f),o(new Response(y,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const jd=Object.freeze(Object.defineProperty({__proto__:null,default:_d,streamTimeout:gi},Symbol.toStringTag,{value:"Module"}));function Td({id:e,selected:t,onClick:r,icon:s,name:a}){const[o,i]=M(!1);te(()=>{i(!0)},[]);const l=se(()=>{r==null||r(e)},[r,e]);return c("button",{className:`
|
|
2
|
-
w-full px-1.5 py-2 cursor-pointer focus:outline-none
|
|
3
|
-
flex flex-col items-center justify-center gap-1 transition-colors
|
|
4
|
-
${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
|
|
5
|
-
`,onClick:l,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:o&&s}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:a})]})}const _r="/assets/cy-logo-cli-CCKUIm0S.svg";function $d(e){return e.scenarioName&&e.entityName?`${e.entityName} → "${e.scenarioName}"`:e.entityName?e.entityName:e.scenarioId?`Scenario: ${e.scenarioId.slice(0,8)}...`:e.entitySha?`Entity: ${e.entitySha.slice(0,8)}...`:"General feedback"}function Rd({content:e,className:t=""}){const[r,s]=M(!1),a=se(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:a,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?c(ue,{children:[n(pt,{size:14}),"Copied"]}):c(ue,{children:[n(wt,{size:14}),"Copy"]})})}function yi({isOpen:e,onClose:t,context:r,defaultEmail:s="",screenshotDataUrl:a}){const[o,i]=M(""),[l,d]=M(s),[m,u]=M(!1),[p,h]=M(!1),[f,y]=M(null),[g,x]=M(null),v=De(),b=v.state!=="idle",N=!!(r.scenarioId||r.analysisId),C=r.analysisId||r.scenarioId||"",E=()=>{const A=`/codeyam-diagnose ${C}`;return o.trim()?`${A} ${o.trim()}`:A};if(v.data&&!p&&!g){const A=v.data;A.success&&A.reportId?(h(!0),y(A.reportId)):A.error&&x(A.error)}const w=async()=>{x(null);const A=new FormData;if(A.append("issueType","other"),A.append("description",o),A.append("email",l),A.append("source",r.source),A.append("entitySha",r.entitySha||""),A.append("scenarioId",r.scenarioId||""),A.append("analysisId",r.analysisId||""),A.append("currentUrl",r.currentUrl),A.append("entityName",r.entityName||""),A.append("entityType",r.entityType||""),A.append("scenarioName",r.scenarioName||""),A.append("errorMessage",r.errorMessage||""),a)try{const _=await(await fetch(a)).blob();A.append("screenshot",_,"screenshot.jpg")}catch($){console.error("Failed to convert screenshot:",$)}v.submit(A,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},k=()=>{i(""),u(!1),h(!1),y(null),x(null),t()},S=A=>{A.key==="Escape"&&k()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:S,children:c("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[c("div",{className:"flex items-center justify-between mb-6",children:[c("div",{className:"flex items-center gap-3",children:[b?n("div",{className:"animate-spin",children:n(Ka,{size:24,style:{strokeWidth:1.5}})}):p?n(Hs,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(li,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:p?"Report Submitted":"Report Issue"})]}),n("button",{onClick:k,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),p?c("div",{children:[c("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),c("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:k,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):c("div",{children:[c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[c("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:$d(r)}),n("button",{type:"button",onClick:()=>u(!m),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:m?"Hide":"Details"})]}),m&&c("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[c("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),c("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&c("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),a&&c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:a,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:A=>i(A.target.value),placeholder:"Optional: Describe what you expected vs what happened...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),N&&c(ue,{children:[c("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[c("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),c("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:E()}),n(Rd,{content:E(),className:"absolute top-1.5 right-2 px-2 py-1 bg-purple-600 text-white border-none rounded text-[11px] font-medium hover:bg-purple-700 transition-colors"})]})]}),c("div",{className:"relative my-5",children:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),c("div",{className:N?"opacity-75":"",children:[N&&c("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:l,onChange:A=>d(A.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),c("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(cr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),c("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),b&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:v.formData?"Uploading report...":"Creating archive..."})}),g&&c("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(cr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),c("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:g})]})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:k,disabled:b,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void w(),disabled:b,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer",children:b?c(ue,{children:[n("div",{className:"animate-spin",children:n(Ka,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const no={source:"navbar"},ea=Js(void 0);function Id({children:e}){const[t,r]=M(no),s=se(o=>{r(o)},[]),a=se(()=>{r(no)},[]);return n(ea.Provider,{value:{contextData:t,setContextData:s,resetContextData:a},children:e})}function ht(e){const t=Er(ea),r=xe(t);te(()=>{if(r.current)return r.current.setContextData(e),()=>{var s;(s=r.current)==null||s.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function Dd(){const e=Er(ea),t=kr();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:t.pathname,entityName:e.contextData.entityName,entityType:e.contextData.entityType,scenarioName:e.contextData.scenarioName,errorMessage:e.contextData.errorMessage}:{source:"navbar",currentUrl:t.pathname}}function Ld({labs:e,isAdmin:t,editorMode:r}){var w;const s=kr(),a=Ct(),[o,i]=M(),[l,d]=M(!1),[m,u]=M(!1),[p,h]=M(null),f=De();te(()=>{f.state==="idle"&&!f.data&&f.load("/api/generate-report")},[f]);const y=((w=f.data)==null?void 0:w.defaultEmail)||"",g={width:"20px",height:"20px",strokeWidth:1.5},x=(e==null?void 0:e.simulations)??!1,v=[{id:"editor",icon:n(Ec,{style:g}),link:"/editor",name:"Editor",hidden:!r},{id:"dashboard",icon:n(Ac,{style:g}),link:"/",name:"Dashboard",hidden:!x},{id:"simulations",icon:c("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:g,children:[n("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6.75 12.7498L11.325 8.17483C11.6067 7.89873 11.9858 7.7447 12.3803 7.7461C12.7747 7.74751 13.1528 7.90423 13.4325 8.18233L16.5 11.2498",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 8.25C6.82843 8.25 7.5 7.57843 7.5 6.75C7.5 5.92157 6.82843 5.25 6 5.25C5.17157 5.25 4.5 5.92157 4.5 6.75C4.5 7.57843 5.17157 8.25 6 8.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M15 2.25H3C2.17157 2.25 1.5 2.92157 1.5 3.75V11.25C1.5 12.0784 2.17157 12.75 3 12.75H15C15.8284 12.75 16.5 12.0784 16.5 11.25V3.75C16.5 2.92157 15.8284 2.25 15 2.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),link:"/simulations",name:"Simulations",hidden:!x},{id:"git",icon:n(Qa,{style:g}),link:"/git",name:"Git",hidden:!x},{id:"files",icon:n(Pc,{style:g}),link:"/files",name:"Files",hidden:!x},{id:"activity",icon:n(Mc,{style:g}),link:"/activity",name:"Activity",hidden:!x},{id:"memory",icon:n(dr,{style:g}),link:"/memory",name:"Memory"},{id:"labs",icon:n(_c,{style:g}),link:"/labs",name:"Labs"},{id:"settings",icon:n(jc,{style:g}),link:"/settings",name:"Settings"},{id:"commits",icon:n(Qa,{style:g}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(Tc,{style:g}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n($c,{style:g}),link:"/components",name:"Components",hidden:!0}],b=se(k=>{const S=v.find(A=>A.id===k);S!=null&&S.link&&a(S.link),i(A=>A===k?void 0:k)},[v,a]);te(()=>{const k={editor:["editor"],dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],memory:["memory","agent-transcripts"],files:["files"],labs:["labs"],settings:["settings"],pages:["pages"],components:["components"]};for(const[S,A]of Object.entries(k))if(A.some($=>$==="/"?s.pathname==="/":s.pathname.includes($))){i(S);return}i(void 0)},[s]);const N=async()=>{u(!0);try{const{default:k}=await import("html2canvas-pro"),A=(await k(document.body)).toDataURL("image/jpeg",.8);h(A),d(!0)}catch(k){console.error("Screenshot capture failed:",k),d(!0)}finally{u(!1)}},C=()=>{d(!1),h(null)},E=Dd();return c(ue,{children:[c("div",{id:"sidebar",className:"sticky top-0 w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[c("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(de,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:_r,alt:"CodeYam",className:"h-6"})})}),v.filter(k=>!k.hidden).map(k=>n(Td,{id:k.id,selected:k.id===o,onClick:b,icon:k.icon,name:k.name},`sidebar-button-${k.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:c("button",{onClick:()=>void N(),disabled:m,className:"w-full px-1.5 py-2 flex flex-col items-center justify-center gap-1 text-[#568B94] hover:text-[#CBF3FA] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",children:[n("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",children:m?n(ct,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(li,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:m?"Capturing...":`Report
|
|
6
|
-
Bug`})]})})]}),l&&n(yi,{isOpen:!0,onClose:C,context:E,defaultEmail:y,screenshotDataUrl:p??void 0})]})}const xi=Js(void 0);function Od({children:e}){const[t,r]=M([]),s=se((o,i="info",l=5e3)=>{const m={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:l};r(u=>[...u,m])},[]),a=se(o=>{r(i=>i.filter(l=>l.id!==o))},[]);return n(xi.Provider,{value:{toasts:t,showToast:s,closeToast:a},children:e})}function ta(){const e=Er(xi);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Fd({toast:e,onClose:t}){te(()=>{const a=e.duration||5e3;if(a>0){const o=setTimeout(()=>{t(e.id)},a);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return c("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function zd({toasts:e,onClose:t}){return e.length===0?null:c("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
|
|
7
|
-
@keyframes slideIn {
|
|
8
|
-
from {
|
|
9
|
-
transform: translateX(400px);
|
|
10
|
-
opacity: 0;
|
|
11
|
-
}
|
|
12
|
-
to {
|
|
13
|
-
transform: translateX(0);
|
|
14
|
-
opacity: 1;
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
`}),e.map(r=>n(Fd,{toast:r,onClose:t},r.id))]})}function St(e,t){const[r,s]=M(""),[a,o]=M(!1),[i,l]=M(null),[d,m]=M(!1);te(()=>{t&&(m(!1),o(!1),l(null))},[t]),te(()=>{if(!e||!t){t||s("");return}const p=async()=>{if(!d)try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const g=(await f.text()).trim().split(`
|
|
18
|
-
`).filter(b=>b.length>0);if(g.length<3){o(!1),m(!1),l(null),s("");return}const x=g.filter(b=>b.includes("CodeYam Log Level 1"));if(x.length>0){const b=x[x.length-1];s(b.replace(/.*CodeYam Log Level 1: /,""))}const v=g.find(b=>b.includes("$$INTERACTIVE_SERVER_URL$$:"));if(v){const b=v.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(b),m(!0)}g.some(b=>b.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};p().catch(()=>{});const h=setInterval(()=>{p().catch(()=>{})},500);return()=>clearInterval(h)},[e,t,d]);const u=se(()=>{s(""),o(!1),l(null),m(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:a,resetLogs:u}}function $t({projectSlug:e,onClose:t}){const[r,s]=M("Loading logs..."),[a,o]=M(!0),[i,l]=M(!0),[d,m]=M("all"),u=xe(null);return te(()=>{const p=async()=>{try{const h=await fetch(`/api/logs/${e}`);if(h.ok){const f=await h.text();if(d==="all")s(f);else{const y=f.trim().split(`
|
|
19
|
-
`).filter(g=>{if(g.length===0)return!1;const x=g.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=d});s(y.map(g=>g.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
|
|
20
|
-
`))}i&&u.current&&setTimeout(()=>{var y;(y=u.current)==null||y.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else s(`Error: ${h.status} - ${await h.text()}`)}catch(h){s(`Error fetching logs: ${h.message}`)}};if(p().catch(()=>{}),a){const h=setInterval(()=>{p().catch(()=>{})},2e3);return()=>clearInterval(h)}},[e,a,i,d]),te(()=>{const p=h=>{h.key==="Escape"&&t()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:c("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:p=>p.stopPropagation(),children:[c("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[c("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),c("div",{className:"flex items-center gap-4",children:[c("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),c("select",{value:d,onChange:p=>m(p.target.value==="all"?"all":Number(p.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:a,onChange:p=>o(p.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:p=>l(p.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function Xe({type:e,size:t="default"}){const r={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#06b6d5",bgColor:"bg-[#e6fbff]",bgHex:"#e6fbff"},type:{iconColor:"#db2627",bgColor:"bg-[#ffe1e1]",bgHex:"#ffe1e1"},data:{iconColor:"#2563eb",bgColor:"bg-blue-100",bgHex:"#dbeafe"},index:{iconColor:"#ea580c",bgColor:"bg-orange-100",bgHex:"#ffedd5"},functionCall:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},class:{iconColor:"#059669",bgColor:"bg-emerald-100",bgHex:"#d1fae5"},method:{iconColor:"#0891b2",bgColor:"bg-cyan-100",bgHex:"#cffafe"},other:{iconColor:"#6b7280",bgColor:"bg-gray-100",bgHex:"#f3f4f6"}},s=r[e]||r.other,a=t==="large"?18:14,o=t==="large"?32:18,i=()=>{switch(e){case"library":return n(ci,{size:a,color:s.iconColor});case"visual":return n($n,{size:a,color:s.iconColor});case"type":return n(Lc,{size:a,color:s.iconColor});case"data":return n(Dc,{size:a,color:s.iconColor});case"index":return n(Ic,{size:a,color:s.iconColor});case"functionCall":return n(Xa,{size:a,color:s.iconColor});case"class":return n(Rc,{size:a,color:s.iconColor});case"method":return n(Xa,{size:a,color:s.iconColor});case"other":return n(Za,{size:a,color:s.iconColor});default:return n(Za,{size:a,color:s.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${s.bgColor}`,style:{width:`${o}px`,height:`${o}px`},children:i()})}function bi({filePath:e,maxLength:t=60,className:r,style:s}){const o=((l,d)=>{if(l.length<=d)return l;const m="...",u=d-m.length,p=Math.ceil(u*.4),h=Math.floor(u*.6),f=l.slice(0,p),y=l.slice(-h),g=f.lastIndexOf("/"),x=y.indexOf("/"),v=g>p*.5?f.slice(0,g+1):f,b=x!==-1&&x<h*.5?y.slice(x):y;return`${v}${m}${b}`})(e,t),i=o!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...s,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:o})}function ss({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:s=50,showScenarioCount:a=!1,scenarioCount:o=0,additionalContent:i}){return c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"flex items-center gap-1",children:[n(Xe,{type:e.entityType||"other"}),c(de,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,a&&o>0&&` (${o})`]}),n(bi,{filePath:e.filePath,maxLength:s,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const as={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function Bd({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:s=!1,queuedJobCount:a=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var V,I,O;const[d,m]=M(!1),[u,p]=M(!1),[h,f]=M(null),[y,g]=M(new Set),[x,v]=M(new Set),[b,N]=M(!1),C=!!i||o.length>0,E=!!i,w=(i==null?void 0:i.entities)||r,k=!!(e!=null&&e.analysisCompletedAt),S=(e==null?void 0:e.readyToBeCaptured)??0,A=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||k&&(S===0||A>=S);const $=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,_=C,{lastLine:j}=St(t,_),D=E||o.length>0,R=new Set(((V=i==null?void 0:i.entities)==null?void 0:V.map(z=>z.sha))||[]),T=l.filter(z=>!(z.currentEntityShas||[]).some(P=>R.has(P))),U=(()=>{const L=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&$){const P=e.analysisCompletedAt||e.createdAt;if(new Date(P).getTime()>L)return!0}if(T.length>0){const P=T[0],q=P.analysisCompletedAt||P.archivedAt||P.createdAt;if(q&&new Date(q).getTime()>L)return!0}return!1})();return te(()=>{const z=(i==null?void 0:i.id)||null;C&&!u&&z!==h&&p(!0),!C&&h!==null&&f(null)},[C,i==null?void 0:i.id,u,h]),c(ue,{children:[c("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&c("div",{onClick:()=>{p(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[D?n(ct,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(ns,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:D?"Analyzing...":"Activity: No Activity Yet"}),D&&n("button",{onClick:z=>{z.stopPropagation(),m(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u&&c("div",{children:[c("div",{className:"flex items-center justify-between px-3 py-2",children:[c("div",{className:"flex items-center gap-2",children:[D?n(ct,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(ns,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:D?"Analyzing...":"Activity"})]}),c("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>m(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{p(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(it,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),c("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[D&&i&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(ns,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:w.length>0?c("div",{className:"space-y-1.5",children:[(b?w:w.slice(0,3)).map(z=>n(ss,{entity:z,nameSize:"11px",pathSize:"10px",pathMaxLength:150},z.sha)),w.length>3&&n("button",{onClick:()=>N(z=>!z),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:as,"aria-label":b?"Show fewer entities":`Show ${w.length-3} more entities`,children:b?"Show less":`+${w.length-3} more`}),j&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:j})]}):c("div",{children:[i.entityNames&&i.entityNames.length>0?c("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((z,L)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:z},L)),i.entityNames.length>5&&c("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):c("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((I=i.entityShas)==null?void 0:I.length)||0," ",((O=i.entityShas)==null?void 0:O.length)===1?"entity":"entities","..."]}),j&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:j})]})})]}),o.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Oc,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:o.map(z=>{var q,H;const L=y.has(z.id),P=L?z.entities:z.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:z.entities.length>0?c("div",{className:"space-y-1.5",children:[P.map(W=>n(ss,{entity:W,nameSize:"10px",pathSize:"9px",pathMaxLength:120},W.sha)),z.entities.length>3&&n("button",{onClick:()=>{g(W=>{const Z=new Set(W);return Z.has(z.id)?Z.delete(z.id):Z.add(z.id),Z})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:as,"aria-label":L?"Show fewer entities":`Show ${z.entities.length-3} more entities`,children:L?"Show less":`+${z.entities.length-3} more`})]}):c("div",{style:{fontSize:"10px",color:"#343434"},children:[z.type==="analysis"&&n(ue,{children:z.entityNames&&z.entityNames.length>0?c("div",{className:"space-y-0.5",children:[z.entityNames.slice(0,5).map((W,Z)=>n("div",{children:W},Z)),z.entityNames.length>5&&c("div",{className:"italic",children:["+",z.entityNames.length-5," more"]})]}):`Analyzing ${((q=z.entityShas)==null?void 0:q.length)||0} ${((H=z.entityShas)==null?void 0:H.length)===1?"entity":"entities"}`}),z.type==="recapture"&&"Recapturing scenario",z.type==="debug-setup"&&"Setting up debug environment"]})},z.id)})})]}),U&&T.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Hs,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Recently Completed"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:T.slice(0,3).map((z,L)=>{const P=z.entities||[],q=z.analysisCompletedAt||z.archivedAt||z.createdAt||"",H=(()=>{if(!q)return"";const F=Date.now()-new Date(q).getTime(),J=Math.floor(F/6e4),G=Math.floor(F/36e5);return G>0?`${G}h ago`:J>0?`${J}m ago`:"just now"})(),W=x.has(L),B=(W?P:P.slice(0,3)).map(F=>{var J,G,X;return{...F,scenarioCount:((X=(G=(J=F.analyses)==null?void 0:J[0])==null?void 0:G.scenarios)==null?void 0:X.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:P.length>0&&c("div",{className:"space-y-1.5",children:[B.map((F,J)=>c("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(ss,{entity:F,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:F.scenarioCount})}),J===0&&H&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:H})]},F.sha)),P.length>3&&n("button",{onClick:()=>{v(F=>{const J=new Set(F);return J.has(L)?J.delete(L):J.add(L),J})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:as,"aria-label":W?"Show fewer entities":`Show ${P.length-3} more entities`,children:W?"Show less":`+${P.length-3} more`})]})},L)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(de,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n($t,{projectSlug:t,onClose:()=>m(!1)})]})}function et(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function zn(e){const{file_id:t,project_id:r,commit_id:s,file_path:a,entity_type:o,entity_branches:i,analyses:l,commit:d,created_at:m,updated_at:u,...p}=e,h=(i??[]).map(g=>g.branch_id),f=l?l.map(kt):void 0,y=d?Qt(d):void 0;return et({...p,fileId:t,projectId:r,commitId:s,filePath:a,entityType:o,commit:y,analyses:f,branchIds:h,createdAt:m,updatedAt:u})}function na(e){return et({id:e.id,projectId:e.project_id,name:e.name,path:e.path,deleted:!!e.deleted,metadata:e.metadata??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0})}function ra(e){const{branches:t,files:r,analyzed_at:s,content_changed_at:a,created_at:o,updated_at:i,github_token:l,configuration:d,team_id:m,...u}=e;return et({...u,branches:t?t.map(cn):void 0,files:r?r.map(na):void 0,analyzedAt:s,contentChangedAt:a,createdAt:o,updatedAt:i})}function Yd(e){const{id:t,project_id:r,user_id:s,scenario_id:a,thumbs_up:o,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return et({id:t,projectId:r,userId:s,scenarioId:a,thumbsUp:!!o,user:l})}function Ud(e){const{id:t,project_id:r,user_id:s,scenario_id:a,text:o,created_at:i,updated_at:l,user:d}=e,m=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return et({id:t,projectId:r,userId:s,scenarioId:a,text:o,createdAt:i,updatedAt:l,user:m})}function vi(e){const{project_id:t,analysis_id:r,previous_version_id:s,analysis:a,user_scenarios:o,scenario_comments:i,approved:l,...d}=e,m=a?kt(a):void 0,u=o?o.map(Yd):void 0,p=i?i.map(Ud):void 0;return et({...d,projectId:t,analysisId:r,previousVersionId:s,analysis:m,userScenarios:u,comments:p})}function Wd(e){return et({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?kt(e.analysis):void 0,entity:e.entity?zn(e.entity):void 0,branch:e.branch?cn(e.branch):void 0,createdAt:e.created_at})}function kt(e){const{project_id:t,commit_id:r,file_id:s,file_path:a,entity_sha:o,entity_type:i,entity_name:l,previous_analysis_id:d,file:m,entity:u,commit:p,project:h,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:x,branch_commit_sha:v,committed_at:b,completed_at:N,created_at:C,updated_at:E,indirect:w,...k}=e,S=u?zn(u):void 0,A=m?na(m):void 0,$=h?ra(h):void 0,_=p?Qt(p):void 0,j=f?f.map(vi):void 0,D=y?y.map(Wd):void 0,R=D?D.map(T=>T.branch):void 0;return et({...k,projectId:t,commitId:r,fileId:s,filePath:a,entitySha:o,entityType:i,entityName:l,previousAnalysisId:d,entity:S,file:A,commit:_,project:$,scenarios:j,analysisBranches:D,branches:R,dependencyAnalyzedTreeSha:g,analyzedTreeSha:x,branchCommitSha:v,committedAt:b,completedAt:N,createdAt:C,updatedAt:E,indirect:!!w})}function sa(e){return et({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?Qt(e.commit):void 0,branch:e.branch?cn(e.branch):void 0})}function Jd(e){const{project_id:t,commit_id:r,created_at:s,updated_at:a,success:o,...i}=e;return et({...i,projectId:t,commitId:r,createdAt:s,updatedAt:a,success:!!o})}function Qt(e){const{project_id:t,branch_id:r,branch:s,background_jobs:a,merged_branch_id:o,mergedBranch:i,ai_message:l,html_url:d,author:m,analyses:u,entities:p,commit_branches:h,committed_at:f,analyzed_at:y,...g}=e,x=s?cn(s):void 0,v=i?cn(i):void 0,b=(a==null?void 0:a.length)>0?Jd(a[a.length-1]):void 0,N=(u??[]).map(kt),C=(p??[]).map(zn),E=(h==null?void 0:h.length)>0?h.map(sa):void 0;return m&&(m.username=m.preferredUsername??m.username),et({...g,projectId:t,branchId:r,branch:x,backgroundJob:b,mergedBranchId:o,mergedBranch:v,aiMessage:l,htmlUrl:d,author:m,analyses:N,entities:C,commitBranches:E,committedAt:f,analyzedAt:y})}function cn(e){const{project_id:t,content_changed_at:r,commits:s,analysis_branches:a,active_at:o,created_at:i,updated_at:l,primary:d,...m}=e,u=s?s.map(Qt):void 0,p=a?a.flatMap(h=>kt(h.analysis)):void 0;return et({...m,projectId:t,contentChangedAt:r,commits:u,analyses:p,activeAt:o,createdAt:i,updatedAt:l,primary:!!d})}var Cr;class Hd{constructor(){Ga(this,Cr,new Vd)}transformQuery(t){return Va(this,Cr).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Cr=new WeakMap;class Vd extends sd{transformValue(t){return{...super.transformValue(t),value:typeof t.value=="boolean"?t.value?1:0:t.value}}transformPrimitiveValueList(t){return{...t,values:t.values.map(r=>typeof r=="boolean"?r?1:0:r)}}}const ae=()=>null,Gd={analyzed_at:ae(),configuration:ae(),content_changed_at:ae(),created_at:ae(),description:ae(),github_token:ae(),id:ae(),metadata:ae(),name:ae(),path:ae(),slug:ae(),team_id:ae(),updated_at:ae()},qd=Object.keys(Gd),Kd={active:ae(),analysis_id:ae(),branch_id:ae(),created_at:ae(),entity_sha:ae(),id:ae()},Qd=Object.keys(Kd),Zd={active_at:ae(),content_changed_at:ae(),created_at:ae(),id:ae(),metadata:ae(),name:ae(),primary:ae(),project_id:ae(),ref:ae(),sha:ae(),updated_at:ae()},wi=Object.keys(Zd),Xd={ai_message:ae(),analyzed_at:ae(),author_github_username:ae(),branch_id:ae(),committed_at:ae(),created_at:ae(),files:ae(),html_url:ae(),id:ae(),merged_branch_id:ae(),message:ae(),metadata:ae(),project_id:ae(),sha:ae(),title:ae(),url:ae()},Ni=Object.keys(Xd),eu=Ni.filter(e=>e!=="files"),tu={commit_id:ae(),created_at:ae(),description:ae(),documentation:ae(),entity_type:ae(),file_id:ae(),file_path:ae(),metadata:ae(),name:ae(),project_id:ae(),quality:ae(),sha:ae(),updated_at:ae()},Ci=Object.keys(tu),nu={active:ae(),branch_id:ae(),entity_sha:ae()},ru=Object.keys(nu),su={created_at:ae(),deleted:ae(),id:ae(),metadata:ae(),name:ae(),path:ae(),project_id:ae(),updated_at:ae()},au=Object.keys(su),ou={analysis_id:ae(),approved:ae(),created_at:ae(),description:ae(),id:ae(),metadata:ae(),name:ae(),previous_version_id:ae(),project_id:ae()},hr=Object.keys(ou),iu=!!Zt("ENABLE_QUERY_LOGGING"),lu=!!Zt("ENABLE_QUERY_ERROR_LOGGING");Zt("USE_LOCAL_POSTGRESQL_FOR_TESTING");let Jn;function _e(){if(!Jn){const e=ki();if(e==="sqlite")Jn=cu();else if(e==="postgresql")Jn=du();else throw new Error(`Unknown database type: ${e}`)}return Jn}function cu(e){if(e||(e=Zt("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=K.existsSync(e),r=Y.dirname(e);if(!K.existsSync(r))K.mkdirSync(r,{recursive:!0,mode:493});else try{K.chmodSync(r,493)}catch(a){console.warn(`Warning: Could not set permissions on database directory: ${a.message}`)}const s=new td(e,{readonly:!1,fileMustExist:!1});if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const a=s.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&a.count===0&&(console.error("CodeYam DB ERROR: Database file existed but projects table is missing!"),console.error("This likely means SQLite created a new empty database instead of opening the existing one."),console.error("Possible causes: corruption, WAL file issues, or file locking problems."))}catch(a){console.error("CodeYam DB ERROR: Failed to verify database schema:",a)}return new hi({dialect:new od({database:s}),plugins:[new ad,new Hd],log:Si})}function du(){const e=mu();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new nd({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,s)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new hi({dialect:new id({pool:t}),log:Si})}let os=null;function tn(){return os||(os=uu(ki())),os}function Si(e){e.level==="error"?lu&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):iu&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function uu(e){if(e==="sqlite")return ld;if(e==="postgresql")return cd;throw new Error(`Unknown database type: ${e}`)}function ki(){if(Zt("SQLITE_PATH"))return"sqlite";if(Zt("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function mu(){const e=Zt("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function Zt(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var qe=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(qe||{});const jr="Default Scenario";let pu="<main>";function hu(){return pu}function ro(e,...t){Pe(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function Pe(...e){const t=hu(),r=e.map(a=>{if(a)return typeof a=="string"?a:a instanceof Error?`${a.name}: ${a.message}
|
|
21
|
-
${a.stack}`:typeof a=="object"?fu(a):String(a)}).filter(Boolean).join(`
|
|
22
|
-
`),s=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(s+`
|
|
23
|
-
`);return}console.log(s.replace(/\n/g,"\r"))}function fu(e,t=2){function r(s,a=new WeakMap){return s===null||typeof s!="object"?s:a.has(s)?`"[Circular: ${s.constructor.name}]"`:(a.set(s,!0),Array.isArray(s)?`[${s.map(l=>{const d=r(l,a);return typeof l=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(s).map(([i,l])=>{let d;return typeof l>"u"?null:(typeof l=="function"?d=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?d=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?d=r(l,a):typeof l=="string"?d=`"${l.replace(/"/g,'\\"')}"`:d=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(s){const a=r(e);if(!t)return a;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(o){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:o,pureStringifyError:s,serialized:a}),a}}}function fr(e,t){try{let r=function(o){var i,l;if(Ue.isFunctionDeclaration(o)&&Sn(o)){const d=((i=o.name)==null?void 0:i.text)||"default",m=o.getText(s),u=is(o);a.push({name:d,code:m,sha:Ut(t,d,m),entityType:"function",isDefault:u})}else if(Ue.isClassDeclaration(o)&&Sn(o)){const d=((l=o.name)==null?void 0:l.text)||"default",m=o.getText(s),u=is(o),p=m.includes("React.")||m.includes("jsx")||m.includes("tsx");a.push({name:d,code:m,sha:Ut(t,d,m),entityType:p?"component":"class",isDefault:u})}else if(Ue.isInterfaceDeclaration(o)&&Sn(o)){const d=o.name.text,m=o.getText(s);a.push({name:d,code:m,sha:Ut(t,d,m),entityType:"interface",isDefault:!1})}else if(Ue.isTypeAliasDeclaration(o)&&Sn(o)){const d=o.name.text,m=o.getText(s);a.push({name:d,code:m,sha:Ut(t,d,m),entityType:"type",isDefault:!1})}else if(Ue.isVariableStatement(o)&&Sn(o)){const d=is(o);o.declarationList.declarations.forEach(m=>{var u;if(Ue.isIdentifier(m.name)){const p=m.name.text,h=o.getText(s),f=((u=m.initializer)==null?void 0:u.getText(s))||"",y=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));a.push({name:p,code:h,sha:Ut(t,p,h),entityType:y?"component":"variable",isDefault:d})}})}else if(Ue.isExportAssignment(o)){const d=o.getText(s);a.push({name:"default",code:d,sha:Ut(t,"default",d),entityType:"unknown",isDefault:!0})}else if(Ue.isExportDeclaration(o)&&o.exportClause&&Ue.isNamedExports(o.exportClause)){const d=o.getText(s);for(const m of o.exportClause.elements){const u=m.name.text;a.push({name:u,code:d,sha:Ut(t,u,d),entityType:"unknown",isDefault:!1})}}Ue.forEachChild(o,r)};const s=Ue.createSourceFile(t,e,Ue.ScriptTarget.Latest,!0),a=[];return r(s),a}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Sn(e){if(!Ue.canHaveModifiers(e))return!1;const t=Ue.getModifiers(e);return t?t.some(r=>r.kind===Ue.SyntaxKind.ExportKeyword):!1}function is(e){if(!Ue.canHaveModifiers(e))return!1;const t=Ue.getModifiers(e);return t?t.some(r=>r.kind===Ue.SyntaxKind.DefaultKeyword):!1}function Ut(e,t,r){const s=Fn.createHash("sha256");return s.update(`${e}:${t}:${r}`),s.digest("hex").substring(0,40)}function gu(e){var m;const{webapp:t,port:r,environmentVariables:s,packageManager:a}=e,o=t==null?void 0:t.startCommand;if(!o)return`${a} ${a==="npm"?"run ":""}dev`;const i=((m=o.args)==null?void 0:m.map(u=>u.replace(/\$PORT/g,String(r))))??[],l=[];for(const u of s)if(u.key&&u.value!==void 0){const p=String(u.value).replace(/'/g,"'\\''");l.push(`${u.key}='${p}'`)}if(o.env)for(const[u,p]of Object.entries(o.env)){const f=String(p).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${u}='${f}'`)}const d=l.length>0?l.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${o.command} ${i.join(" ")}`}function yu(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=Y.normalize(e),s=[...t].sort((a,o)=>{var i,l;return(((i=o.path)==null?void 0:i.length)??0)-(((l=a.path)==null?void 0:l.length)??0)});for(const a of s){const o=Y.normalize(a.path??".");if(o==="."||r.startsWith(o+Y.sep)||r===o)return a}return t[0]}function xu(e){const{filePath:t,webapps:r,environmentVariables:s,port:a,packageManager:o}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=yu(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=gu({webapp:i,port:a,environmentVariables:s,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:l,url:`http://localhost:${a}/static/codeyam-sample`}}function Tr(e,t,r=[]){const s=Array.isArray(t)?t:[t];return a=>a.columns(s).doUpdateSet(o=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,o.ref(`excluded.${l}`)]))})}function bu(e){const{jsonObjectFrom:t}=tn();return t(e.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",e.ref("commits.author_github_username")))}async function vu({ids:e,analysisId:t}){const r=_e();try{let s=r.deleteFrom("scenarios");if(e){if(e.length===0)return;s=s.where("id","in",e)}else if(t)s=s.where("analysis_id","=",t);else throw Pe("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:t}),new Error("No deletion criteria provided for scenarios");await s.execute()}catch(s){throw Pe("CodeYam Error: Database error deleting scenarios",s,{ids:e,analysisId:t}),s}}function wu(...e){try{const t=Fn.createHash("sha256");for(const r of e)t.update(r);return t.digest("hex")}catch(t){throw console.log("CodeYam Error: Error generating sha",e),t}}function ls(e,t){return t.map(r=>Nu(e,r))}function Nu(e,t){return ot` ${ot.ref(e)}.${ot.ref(t)}`.as(t)}function Cu(e,t,r){return t.map(s=>Su(e,s,r))}function Su(e,t,r){return ot` ${ot.ref(e)}.${ot.ref(t)}`.as(`_cy_${r}:${t}`)}function ku(e,...t){const r={};for(const[s,a]of Object.entries(e)){const o=s.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,l]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=a;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${s}'`);continue}r[s]=a}return r}const Eu=50;function Au(e,t){return e.length<=t?[e]:Array.from({length:Math.ceil(e.length/t)},(r,s)=>e.slice(s*t,s*t+t))}function so({projectId:e,ids:t,fileIds:r,entityName:s,entityShas:a,commitIds:o,branchCommitSha:i,limit:l,excludeMetadata:d}){const m=_e(),{jsonObjectFrom:u,jsonArrayFrom:p}=tn();let h=d?m.selectFrom("analyses").select(["analyses.id","analyses.project_id","analyses.file_id","analyses.commit_id","analyses.entity_sha","analyses.entity_name","analyses.entity_type","analyses.file_path","analyses.status","analyses.created_at","analyses.updated_at","analyses.tree_sha","analyses.analyzed_tree_sha","analyses.dependency_analyzed_tree_sha","analyses.previous_analysis_id","analyses.branch_commit_sha","analyses.indirect","analyses.committed_at","analyses.completed_at"]):m.selectFrom("analyses").selectAll("analyses");if(e&&(h=h.where("project_id","=",e)),t){if(t.length===0)return null;h=h.where("id","in",t)}if(r){if(r.length===0)return null;h=h.where("file_id","in",r)}if(o){if(o.length===0)return null;h=h.where("commit_id","in",o)}return s&&(h=h.where("entity_name","=",s)),a&&(h=h.where("entity_sha","in",a)),i&&(h=h.where("branch_commit_sha","=",i)),l&&(h=h.limit(l)),d?m.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[p(f.selectFrom("scenarios").select(ls("scenarios",hr)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),p(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):m.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(ls("entities",Ci)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),p(f.selectFrom("scenarios").select(ls("scenarios",hr)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),p(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function Rt(e){const{ids:t,fileIds:r,entityShas:s,commitIds:a}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:s,key:"entityShas"},commit_id:{arr:a,key:"commitIds"}}).find(([d,{arr:m}])=>(m==null?void 0:m.length)>0);let l=[];if(i){const[d,{arr:m,key:u}]=i,p=Au(m,Eu),h=[];for(let f=0;f<p.length;f++){const y=p[f],x=await so({...e,[u]:y}).execute();x&&h.push(...x)}l=h}else{const m=await so(e).execute();if(!m||m.length===0)return Pe("CodeYam: No analyses found",null,e),null;l=m}return l.length===0?null:l.map(kt)}catch(o){return Pe("CodeYam Error: Database error in loadAnalyses",o,e),null}}function Pu(e,t){const{jsonArrayFrom:r,jsonObjectFrom:s}=tn();let a=e.selectFrom("analysis_branches").select(Qd).select(o=>s(o.selectFrom("branches").select(wi).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(a=t(a)),r(a)}async function Et({id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:p,includeBranches:h}){const f=_e(),y=Date.now();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):l?g=g.where("analyzed_tree_sha","=",l):s&&(g=g.where("file_id","=",s)),o&&(g=g.where("entity_name","=",o)),a?g=g.where("commit_id","=",a):g=g.orderBy("created_at","desc").limit(1),t&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:v}=tn();g=g.select(C=>{const E=[];return E.push(x(C.selectFrom("entities").select(Ci).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&E.push(x(C.selectFrom("files").select(au).whereRef("files.id","=","analyses.file_id")).as("file")),m&&E.push(x(C.selectFrom("projects").select(qd).whereRef("projects.id","=","analyses.project_id")).as("project")),p&&E.push(v(C.selectFrom("scenarios").select(hr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),h&&E.push(Pu(C,w=>w.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&E.push(x(C.selectFrom("commits").select(Ni).select(w=>bu(w).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),E});const b=await g.executeTakeFirst(),N=Date.now()-y;if(!b)return Pe("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:p,includeBranches:h}),null;if(N>100&&u){const C=b.commit,E=C!=null&&C.files?JSON.stringify(C.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${N}ms (files: ${Math.round(E/1024)}KB)`,{id:b.id,entityName:b.entity_name})}return kt(b)}catch(g){return Pe("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:p,includeBranches:h}),null}}async function Ei({projectId:e,ids:t,names:r,includeInactive:s}){const a=_e();try{let o=a.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];o=o.where("id","in",t)}if(r){if(r.length===0)return[];o=o.where("name","in",r)}return s||(o=o.where("active_at","is not",null)),(await o.execute()).map(cn)}catch(o){return Pe("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:s}),[]}}async function Mu({projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}){const o=_e();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(a,m=>m.select(Cu("branches",wi,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),s!==void 0&&(i=i.where("commit_branches.active","=",s));const l=await i.execute();return!l||l.length===0?null:l.map(m=>ku(m,"branch")).map(sa)}catch(i){return Pe("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}),null}}async function _u(e){if(e.length===0)return new Map;const t=_e();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),s=new Set;if(r.forEach(o=>{o.branch_id&&s.add(o.branch_id),o.merged_branch_id&&s.add(o.merged_branch_id)}),s.size===0)return new Map;const a=await t.selectFrom("branches").selectAll().where("id","in",Array.from(s)).execute();return new Map(a.map(o=>[o.id,o]))}catch(r){return Pe("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function ju(e){if(e.length===0)return new Map;const t=_e(),{jsonObjectFrom:r,jsonArrayFrom:s}=tn();try{const a=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),s(i.selectFrom("scenarios").select(hr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return a.forEach(i=>{const l=o.get(i.commit_id)||[];l.push(i),o.set(i.commit_id,l)}),o}catch(a){return Pe("CodeYam Error: Loading analyses for commits",a,{commitIds:e}),new Map}}async function Tu(e){if(e.length===0)return new Map;const t=_e();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),s=new Map;return r.forEach(a=>{const o=s.get(a.commit_id)||[];o.push(a),s.set(a.commit_id,o)}),s}catch(r){return Pe("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function gr({projectId:e,branchId:t,ids:r,shas:s,fileNames:a,limit:o=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const l=_e(),{jsonObjectFrom:d}=tn(),m=Date.now();try{let u;if(i){const b=eu.map(N=>`commits.${N}`);u=l.selectFrom("commits").select(b)}else u=l.selectFrom("commits").selectAll("commits").select(b=>[d(b.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",b.ref("commits.author_github_username"))).as("author")]);if(e&&(u=u.where("project_id","=",e)),r){if(r.length===0)return[];u=u.where("id","in",r)}if(s){if(s.length===0)return[];u=u.where("sha","in",s)}if(a&&a.length>0){const b=ot.join(a.map(N=>ot`${N}`),ot`, `);u=u.where(ot`
|
|
24
|
-
EXISTS (
|
|
25
|
-
SELECT 1
|
|
26
|
-
FROM json_each(${ot.ref("commits.files")}) AS f
|
|
27
|
-
WHERE json_extract(f.value, '$.fileName') IN (${b})
|
|
28
|
-
)
|
|
29
|
-
`)}t&&(u=u.where("branch_id","=",t));const p=await u.orderBy("committed_at","desc").limit(o).execute(),h=Date.now()-m;if(!p||p.length===0)return[];if(h>100){const b=p.reduce((N,C)=>N+(C.files?JSON.stringify(C.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${h}ms (${p.length} commits, totalFiles: ${Math.round(b/1024)}KB)`)}if(i)return p.map(N=>({...N,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(Qt);const f=p.map(b=>b.id),[y,g,x]=await Promise.all([_u(f),ju(f),Tu(f)]);return p.map(b=>{const N=b.branch_id?y.get(b.branch_id):void 0,C=b.merged_branch_id?y.get(b.merged_branch_id):void 0,E=g.get(b.id)||[],w=x.get(b.id)||[];return{...b,branch:N,mergedBranch:C,analyses:E,entities:w}}).map(Qt)}catch(u){return Pe("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:s,limit:o}),[]}}async function Ze({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:o,excludeMetadata:i}){if(r&&r.length==0||s&&s.length==0||a&&a.length==0||o&&o.length==0)return[];if(o&&o.length>50){const d=[];for(let m=0;m<o.length;m+=50){const u=o.slice(m,m+50),p=await Ze({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:u,excludeMetadata:i});p&&d.push(...p)}return d}const l=_e();try{const u=await(i?l.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):l.selectFrom("entities").selectAll("entities")).$if(!!t,p=>p.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,p=>p.where("entities.project_id","=",e)).$if(!!o,p=>p.where("entities.sha","in",o)).$if(!!s,p=>p.where("entities.file_path","in",s)).$if(!!a,p=>p.where("entities.name","in",a)).$if(!!r,p=>p.where("entities.file_id","in",r)).execute();return!u||u.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:s,shas:o}),null):u.map(zn)}catch(d){return console.log("Load Entities: Error occurred",d,{projectId:e,fileIds:r,filePaths:s,shas:o}),null}}function $u(e,t){const{jsonArrayFrom:r}=tn();let s=e.selectFrom("entity_branches").select(ru);return t&&(s=t(s)),r(s)}async function Ai({projectId:e,sha:t}){const r=_e();try{const s=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(a=>$u(a,o=>o.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return s?zn(s):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&Pe("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(s){return Pe("CodeYam Error: Load Entity: Database error",s,{projectId:e,sha:t}),null}}const cs=1e3;async function Pi({projectId:e,filePaths:t,fileIds:r,fileNames:s}){if(t&&t.length>50){const l=[];for(let d=0;d<t.length;d+=50){const m=t.slice(d,d+50),u=await Pi({projectId:e,filePaths:m,fileIds:r,fileNames:s});u&&l.push(...u)}return l}const a=_e(),o=[];let i=0;try{for(;;){let l=a.selectFrom("files").selectAll().where("project_id","=",e).limit(cs).offset(i);if(t){if(t.length===0)return[];l=l.where("path","in",t)}if(r){if(r.length===0)return[];l=l.where("id","in",r)}if(s){if(s.length===0)return[];l=l.where("name","in",s)}const d=await l.execute();if(!d||d.length===0||(o.push(...d),d.length<cs))break;i+=cs}return o==null?void 0:o.map(na)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function Ru({id:e,slug:t,withBranches:r,withFiles:s,silent:a}){try{let i=_e().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const l=await i.executeTakeFirst();if(!l)return a||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:s}),null;const d=ra(l);return s&&(d.files=await Pi({projectId:d.id})),r&&(d.branches=await Ei({projectId:d.id,includeInactive:!1})),d}catch(o){return a||console.log("CodeYam Error: Error loading project",o),null}}function yr(e,t){const r={...e};for(const s in t){const a=t[s],o=e[s];a!=null&&typeof a=="object"&&!Array.isArray(a)&&o!==void 0&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[s]=yr(o,a):a!==void 0&&(r[s]=a)}return r}async function Tt({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:s,archiveCurrentRun:a,updateCallback:o}){for(let d=0;d<=4;d++)try{return await _e().transaction().execute(async m=>{var f,y;const u=await m.selectFrom("commits").select(["id","metadata"]).$if(!!e,g=>g.where("id","=",e)).$if(!!t,g=>g.where("sha","=",t)).executeTakeFirst();if(!u)return Pe(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const p=u.metadata||{};if(s)s.lastUpdatedAt??(s.lastUpdatedAt=new Date().toISOString()),s.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Previous entity SHAs:",(f=p.currentRun)==null?void 0:f.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",s.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",a)),r=yr(r??{},{currentRun:s});else if(!r&&!o)return p;const h=r?yr(p,r):p;if(a&&h.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",h.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${h.currentRun.analyzerPid}, capture=${h.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${h.currentRun.analysesCompleted}, captures=${h.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((y=h.historicalRuns)==null?void 0:y.length)||0}`);const g={...h.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(g,null,2)),h.historicalRuns=[...h.historicalRuns||[],g],console.log(`[updateCommitMetadata] Historical runs after archiving: ${h.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(h.historicalRuns.map(x=>({entityShas:x.currentEntityShas,archivedAt:x.archivedAt,completed:{analyses:x.analysesCompleted,captures:x.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(h);try{return await m.updateTable("commits").set({metadata:JSON.stringify(h)}).where("id","=",u.id).returning(["id"]).executeTakeFirst()?h:(Pe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),p)}catch(g){return Pe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,g),p}})}catch(m){const u=m instanceof Error&&m.message.includes("database is locked");if(u&&d<4){const p=250*Math.pow(2,d);await new Promise(h=>setTimeout(h,p));continue}return Pe(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}${u?` after ${d+1} attempts`:""}`,m),null}return null}async function Mi(e,t,r="analysis"){try{return await _e().transaction().execute(async s=>{const a=await s.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!a)return Pe(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=kt(a);return t(o.metadata,o),await s.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(Pe(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(s){return Pe(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,s,{analysisId:e,source:r}),null}}async function pn(e,t,r="capture"){for(let o=0;o<=4;o++)try{return await _e().transaction().execute(async i=>{const l=await i.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!l)return Pe(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const d=kt(l);return t(d.status,d),await i.updateTable("analyses").set({status:JSON.stringify(d.status)}).where("id","=",e).returningAll().executeTakeFirst()?d.status:(Pe(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(i){const l=i instanceof Error&&i.message.includes("database is locked");if(l&&o<4){const d=250*Math.pow(2,o);await new Promise(m=>setTimeout(m,d));continue}return Pe(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})${l?` after ${o+1} attempts`:""}`,i,{analysisId:e,source:r}),null}return null}async function dn({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:s}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await _e().transaction().execute(async a=>{const o=await a.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!o)return Pe(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!s)return i;const l=r?yr(i,r):i;s&&await s(l,ra(o));try{return await a.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",o.id).returningAll().executeTakeFirst()?l:(Pe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return Pe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(a){return Pe(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,a),null}}const Iu=()=>crypto.randomUUID();function Du(e){const{id:t,projectId:r,analysisId:s,previousVersionId:a,analysis:o,metadata:i,data:l,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??Iu(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:s,previous_version_id:a}}async function Lu(e){if(e.length===0)return[];const t=_e(),r=e.map(Du);try{return(await t.insertInto("scenarios").values(r).onConflict(Tr(r[0],"id",["created_at"])).returningAll().execute()).map(vi)}catch(s){return Pe("CodeYam Error: Database error upserting scenarios",s,{scenarioCount:e.length}),null}}const Ou=()=>crypto.randomUUID();function Fu(e){const{id:t,commitId:r,branchId:s,...a}=e;return delete a.commit,delete a.branch,{...a,id:t??Ou(),commit_id:r,branch_id:s}}async function ao(e){if(e.length===0)return[];const t=_e(),r=e.map(Fu);try{return(await t.insertInto("commit_branches").values(r).onConflict(Tr(r[0],"id",["created_at"])).returningAll().execute()).map(sa)}catch(s){return Pe("CodeYam Error: Database error upserting commit branches",s,{commitBranchCount:e.length,commitBranchIds:e.map(a=>a.id)}),[]}}async function zu(e,t){const r=_e(),s={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(s).onConflict(Tr(s,"username",[])).returningAll().executeTakeFirst()||null}catch(a){return Pe("CodeYam Error: Error upserting github user",a,{username:e,avatarUrl:t}),null}}const Bu=()=>crypto.randomUUID();function Yu(e,t){const{id:r,projectId:s,branchId:a,mergedBranchId:o,aiMessage:i,htmlUrl:l,analyzedAt:d,committedAt:m,author:u,metadata:p,files:h,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??Bu(),project_id:s??String(t),metadata:p?JSON.stringify(p):void 0,files:h?JSON.stringify(h):void 0,branch_id:a,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:l,ai_message:i,analyzed_at:d,committed_at:m}}async function Uu({projectId:e,commits:t}){const r=_e();try{const s=t.reduce((i,l)=>{const{author:d}=l;return d!=null&&d.username&&(d!=null&&d.avatarUrl)&&(i[d.username]=d.avatarUrl),i},{});for(const i in s)await zu(i,s[i]);const a=t.map(i=>Yu(i,e));return(await r.insertInto("commits").values(a).onConflict(Tr(a[0],"id",["created_at"])).returningAll().execute()).map(Qt)}catch(s){return Pe("CodeYam Error: Error saving commits",s,{projectId:e,commitCount:t.length,commitIds:t.map(a=>a.id).filter(Boolean)}),[]}}const xr=Y.join(Gs.homedir(),".codeyam","secrets.json"),br=Y.join(process.cwd(),".codeyam","secrets.json");async function Ot(){let e={};try{if(K.existsSync(br)){const o=await be.readFile(br,"utf8");e=JSON.parse(o)}}catch{console.warn(pr.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(K.existsSync(xr)){const o=await be.readFile(xr,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(pr.yellow("⚠ Could not read home secrets file, falling back to environment variables"))}const t={},r=e.OPENAI_API_KEY||process.env.OPENAI_API_KEY;r&&(t.OPENAI_API_KEY=r);const s=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;s&&(t.ANTHROPIC_API_KEY=s);const a=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return a&&(t.GROQ_API_KEY=a),t}async function Wu(e,t=!0){const r=t?xr:br,s=Y.dirname(r);await be.mkdir(s,{recursive:!0}),await be.writeFile(r,JSON.stringify(e,null,2)),await be.chmod(r,384)}function Ju(e=!0){return e?xr:br}async function oo(){const e=await Ot(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function Hu(e){console.log(),console.log(pr.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const s=await ud({type:"password",name:"key",message:"OpenAI API Key",validate:a=>a&&!a.startsWith("sk-")?"OpenAI API key should start with sk-":!0});s.key&&(t.OPENAI_API_KEY=s.key);break}return t}async function Vu(e=!0){const t=await oo();if(t.isValid)return t.secrets;const r=await Hu(t.missing),a={...await Ot(),...r};await Wu(a,e);const o=Ju(e);return console.log(pr.green(`✓ Configuration saved to ${o}`)),(await oo()).secrets}function Gu(e){const t=Y.resolve(e),r=Y.parse(t).root;return t===r||t===Y.resolve(Gs.homedir())}function _i(e=process.cwd()){let t=Y.resolve(e);const r=Y.parse(t).root;for(;t!==r;){if(Gu(t))return null;const s=Y.join(t,".codeyam","config.json");if(K.existsSync(s))return t;t=Y.dirname(t)}return null}let ji=_i();function me(){return ji}function qu(e){ji=e}function Ti(e){const t={...e};for(const r in e)if(r.includes(".")){const s=r.replace(/\./g,"");t[s]=e[r]}return t}const Ku={"Accordion.Item":e=>`<CYAccordion.Root type="single" collapsible>${e}</CYAccordion.Root>`,"Accordion.Header":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1">${e}</CYAccordion.Item></CYAccordion.Root>`,"Accordion.Trigger":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1"><CYAccordion.Header>${e}</CYAccordion.Header></CYAccordion.Item></CYAccordion.Root>`,"Accordion.Content":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1">${e}</CYAccordion.Item></CYAccordion.Root>`,"AlertDialog.Trigger":e=>`<CYAlertDialog.Root>${e}</CYAlertDialog.Root>`,"AlertDialog.Portal":e=>`<CYAlertDialog.Root>${e}</CYAlertDialog.Root>`,"AlertDialog.Overlay":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal>${e}</CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Content":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal>${e}</CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Title":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Description":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Action":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Cancel":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"Avatar.Image":e=>`<CYAvatar.Root>${e}</CYAvatar.Root>`,"Avatar.Fallback":e=>`<CYAvatar.Root>${e}</CYAvatar.Root>`,"Checkbox.Indicator":e=>`<CYCheckbox.Root>${e}</CYCheckbox.Root>`,"Collapsible.Trigger":e=>`<CYCollapsible.Root>${e}</CYCollapsible.Root>`,"Collapsible.Content":e=>`<CYCollapsible.Root>${e}</CYCollapsible.Root>`,"ContextMenu.Trigger":e=>`<CYContextMenu.Root>${e}</CYContextMenu.Root>`,"ContextMenu.Portal":e=>`<CYContextMenu.Root>${e}</CYContextMenu.Root>`,"ContextMenu.Content":e=>`<CYContextMenu.Root><CYContextMenu.Portal>${e}</CYContextMenu.Portal></CYContextMenu.Root>`,"ContextMenu.Item":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.CheckboxItem":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.RadioGroup":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.RadioItem":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.RadioGroup value="item-1">${e}</CYContextMenu.RadioGroup></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.ItemIndicator":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.CheckboxItem checked>${e}</CYContextMenu.CheckboxItem></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Label":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Separator":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Sub":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.SubTrigger":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.Sub>${e}</CYContextMenu.Sub></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.SubContent":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.Sub>${e}</CYContextMenu.Sub></CYContextMenu.Content></CYContextMenu.Root>`,"Dialog.Trigger":e=>`<CYDialog.Root>${e}</CYDialog.Root>`,"Dialog.Portal":e=>`<CYDialog.Root>${e}</CYDialog.Root>`,"Dialog.Overlay":e=>`<CYDialog.Root><CYDialog.Portal>${e}</CYDialog.Portal></CYDialog.Root>`,"Dialog.Content":e=>`<CYDialog.Root><CYDialog.Portal>${e}</CYDialog.Portal></CYDialog.Root>`,"Dialog.Title":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"Dialog.Description":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"Dialog.Close":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"DropdownMenu.Trigger":e=>`<CYDropdownMenu.Root>${e}</CYDropdownMenu.Root>`,"DropdownMenu.Portal":e=>`<CYDropdownMenu.Root>${e}</CYDropdownMenu.Root>`,"DropdownMenu.Content":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Portal>${e}</CYDropdownMenu.Portal></CYDropdownMenu.Root>`,"DropdownMenu.Item":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.CheckboxItem":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.RadioGroup":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.RadioItem":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.RadioGroup value="item-1">${e}</CYDropdownMenu.RadioGroup></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.ItemIndicator":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.CheckboxItem checked>${e}</CYDropdownMenu.CheckboxItem></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Label":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Separator":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Sub":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.SubTrigger":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.Sub>${e}</CYDropdownMenu.Sub></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.SubContent":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.Sub>${e}</CYDropdownMenu.Sub></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"Form.Field":e=>`<CYForm.Root>${e}</CYForm.Root>`,"Form.Label":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Control":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Message":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.ValidityState":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Submit":e=>`<CYForm.Root>${e}</CYForm.Root>`,"HoverCard.Trigger":e=>`<CYHoverCard.Root>${e}</CYHoverCard.Root>`,"HoverCard.Portal":e=>`<CYHoverCard.Root>${e}</CYHoverCard.Root>`,"HoverCard.Content":e=>`<CYHoverCard.Root><CYHoverCard.Portal>${e}</CYHoverCard.Portal></CYHoverCard.Root>`,"Menubar.Menu":e=>`<CYMenubar.Root>${e}</CYMenubar.Root>`,"Menubar.Trigger":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Portal":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Content":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Item":e=>`<CYMenubar.Root><CYMenubar.Menu><CYMenubar.Content>${e}</CYMenubar.Content></CYMenubar.Menu></CYMenubar.Root>`,"NavigationMenu.List":e=>`<CYNavigationMenu.Root>${e}</CYNavigationMenu.Root>`,"NavigationMenu.Item":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List>${e}</CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Trigger":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item>${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Content":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item><CYNavigationMenu.Trigger />{/* Dummy trigger for context */}${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Link":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item>${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Indicator":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item><CYNavigationMenu.Trigger />{/* Dummy trigger for context */}</CYNavigationMenu.Item>${e}</CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Viewport":e=>`<CYNavigationMenu.Root>${e}</CYNavigationMenu.Root>`,"Popover.Trigger":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Popover.Portal":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Popover.Content":e=>`<CYPopover.Root><CYPopover.Portal>${e}</CYPopover.Portal></CYPopover.Root>`,"Popover.Close":e=>`<CYPopover.Root><CYPopover.Content>${e}</CYPopover.Content></CYPopover.Root>`,"Popover.Anchor":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Progress.Indicator":e=>`<CYProgress.Root value={50}>${e}</CYProgress.Root>`,"RadioGroup.Item":e=>`<CYRadioGroup.Root>${e}</CYRadioGroup.Root>`,"RadioGroup.Indicator":e=>`<CYRadioGroup.Root><CYRadioGroup.Item value="item-1">${e}</CYRadioGroup.Item></CYRadioGroup.Root>`,"ScrollArea.Viewport":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"ScrollArea.Scrollbar":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"ScrollArea.Thumb":e=>`<CYScrollArea.Root><CYScrollArea.Scrollbar orientation="vertical">${e}</CYScrollArea.Scrollbar></CYScrollArea.Root>`,"ScrollArea.Corner":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"Select.Trigger":e=>`<CYSelect.Root>${e}</CYSelect.Root>`,"Select.Value":e=>`<CYSelect.Root><CYSelect.Trigger>${e}</CYSelect.Trigger></CYSelect.Root>`,"Select.Icon":e=>`<CYSelect.Root><CYSelect.Trigger>${e}</CYSelect.Trigger></CYSelect.Root>`,"Select.Portal":e=>`<CYSelect.Root>${e}</CYSelect.Root>`,"Select.Content":e=>`<CYSelect.Root><CYSelect.Portal>${e}</CYSelect.Portal></CYSelect.Root>`,"Select.Viewport":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.Item":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.ItemText":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Item value="item-1">${e}</CYSelect.Item></CYSelect.Content></CYSelect.Root>`,"Select.ItemIndicator":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Item value="item-1">${e}</CYSelect.Item></CYSelect.Content></CYSelect.Root>`,"Select.Group":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.Label":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Group>${e}</CYSelect.Group></CYSelect.Content></CYSelect.Root>`,"Select.Separator":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Slider.Track":e=>`<CYSlider.Root>${e}</CYSlider.Root>`,"Slider.Range":e=>`<CYSlider.Root><CYSlider.Track>${e}</CYSlider.Track></CYSlider.Root>`,"Slider.Thumb":e=>`<CYSlider.Root>${e}</CYSlider.Root>`,"Switch.Thumb":e=>`<CYSwitch.Root>${e}</CYSwitch.Root>`,"Tabs.List":e=>`<CYTabs.Root defaultValue="tab1">${e}</CYTabs.Root>`,"Tabs.Trigger":e=>`<CYTabs.Root defaultValue="tab1"><CYTabs.List>${e}</CYTabs.List></CYTabs.Root>`,"Tabs.Content":e=>`<CYTabs.Root defaultValue="tab1">${e}</CYTabs.Root>`,"Toast.Root":e=>`<CYToast.Provider>${e}</CYToast.Provider>`,"Toast.Title":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Description":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Action":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Close":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Viewport":e=>`<CYToast.Provider>${e}</CYToast.Provider>`,"ToggleGroup.Item":e=>`<CYToggleGroup.Root type="single">${e}</CYToggleGroup.Root>`,"Toolbar.Button":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.Link":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.Separator":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.ToggleGroup":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.ToggleItem":e=>`<CYToolbar.Root><CYToolbar.ToggleGroup type="single">${e}</CYToolbar.ToggleGroup></CYToolbar.Root>`,"Tooltip.Root":e=>`<CYTooltip.Provider>${e}</CYTooltip.Provider>`,"Tooltip.Trigger":e=>`<CYTooltip.Provider><CYTooltip.Root>${e}</CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Portal":e=>`<CYTooltip.Provider><CYTooltip.Root>${e}</CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Content":e=>`<CYTooltip.Provider><CYTooltip.Root><CYTooltip.Portal>${e}</CYTooltip.Portal></CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Arrow":e=>`<CYTooltip.Provider><CYTooltip.Root><CYTooltip.Content>${e}</CYTooltip.Content></CYTooltip.Root></CYTooltip.Provider>`};Ti(Ku);const Qu={"Command.Input":e=>`<CYCommand>${e}</CYCommand>`,"Command.List":e=>`<CYCommand>${e}</CYCommand>`,"Command.Item":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Group":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Separator":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Empty":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Loading":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Shortcut":e=>`<CYCommand><CYCommand.List><CYCommand.Item value="x">${e}</CYCommand.Item></CYCommand.List></CYCommand>`,"Command.Dialog":e=>`<CYCommand.Dialog open>${e}</CYCommand.Dialog>`};Ti(Qu);function Mn(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const a=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const l=t[i];l&&typeof l=="object"&&!Array.isArray(l)||Array.isArray(l)?o[i]=Mn(a[i],l,r):o[i]=l}return o}const s={...e};for(const a in t)if(t[a]===null)s[a]=null;else if(Array.isArray(t[a])){const o=Array.isArray(e[a])?e[a]:[];s[a]=[];for(let i=0;i<t[a].length;i++){const l=t[a][i];typeof l=="object"&&l!==null?s[a][i]=Mn(o[i],l,r):s[a][i]=l}}else typeof t[a]=="object"&&t[a]!==null?s[a]=Mn(s[a]??{},t[a],r):s[a]=t[a];return s}catch(s){throw console.log("CodeYam: Error merging data",e,t),s}}async function Zu({projectId:e,commit:t,branch:r}){var l,d,m,u,p,h,f;let s;const a={commitId:t.id,branchId:r.id,active:!0},o=await Mu({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){s=(l=o.sort((g,x)=>{var v,b,N,C;return(((b=(v=g.branch.metadata)==null?void 0:v.permanent)==null?void 0:b.order)??999)-(((C=(N=x.branch.metadata)==null?void 0:N.permanent)==null?void 0:C.order)??999)})[0])==null?void 0:l.branch,s&&((m=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:m.order)!==void 0&&(((p=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:p.order)<=((f=(h=s.metadata)==null?void 0:h.permanent)==null?void 0:f.order)?s=r:a.active=!1);const y=o.filter(g=>g.active&&g.branch.id!==s.id||!g.active&&g.branch.id===s.id);y.length>0&&await ao(y.map(g=>({...g,active:g.branchId===s.id})))}(o==null?void 0:o.find(y=>y.branchId===a.branchId))||await ao([a])}function Ft(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=me();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return ee.join(e,".codeyam","db.sqlite3")}async function Be(){const e=await Vu();process.env.SQLITE_PATH=Ft(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Re(e){await Be();const t=await Ru({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await Ei({projectId:t.id,names:["_local"]}),s=r==null?void 0:r[0];if(!s)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:t,branch:s}}async function Xu(e,t,r){await Be();const s=me(),a=wu(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(d=>{let m="";if(s)try{if(m=Ee(`git diff HEAD -- "${d}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!m)try{const u=Ee(`cat "${d}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const p=u.split(`
|
|
30
|
-
`);m=`@@ -0,0 +1,${p.length} @@
|
|
31
|
-
${p.map(h=>`+${h}`).join(`
|
|
32
|
-
`)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:m}}),i={sha:a,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${a}`,htmlUrl:`local://codeyam/${e.slug}/${a}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:o,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},l=await Uu({projectId:e.id,commits:[i]});if(!l||l.length===0)throw new Error("Failed to create fake commit");return await Zu({projectId:e.id,commit:l[0],branch:t}),l[0]}async function nn(){await Be();const e=await Ze({excludeMetadata:!0});if(!e||e.length===0)return[];const t=new Map;for(const d of e){const m=`${d.name}::${d.filePath}`,u=t.get(m);(!u||d.createdAt&&u.createdAt&&d.createdAt>u.createdAt)&&t.set(m,d)}const r=[...t.values()],s=e.map(d=>d.sha),a=await Rt({entityShas:s,excludeMetadata:!0}),o=new Map;if(a)for(const d of a)o.has(d.entitySha)||o.set(d.entitySha,[]),o.get(d.entitySha).push(d);const i=new Map;for(const d of e){const m=`${d.name}::${d.filePath}`,u=i.get(m)||[];u.push(d.sha),i.set(m,u)}return r.map(d=>{const m=o.get(d.sha)||[];if(m.length>0)return{...d,analyses:m};const u=`${d.name}::${d.filePath}`,p=i.get(u)||[];for(const h of p){if(h===d.sha)continue;const f=o.get(h);if(f&&f.length>0)return{...d,analyses:f}}return{...d,analyses:[]}})}async function $r(e,t){await Be();const r=await Rt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const s=await Ai({projectId:r[0].projectId,sha:e});if(s)for(const a of r)a.entity=s}return r||[]}async function Rr(e){if(await Be(),e.name&&e.projectId){const r=await Rt({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const s=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,l=!e.filePath||o.filePath===e.filePath;return i&&l});if(s.length>0)return s.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),s[0];const a=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(a.length>0)return a.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),a[0]}}const t=await Rt({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function $i(e){await Be();const t=await Rt({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function Xt(e){await Be();const t=await Te();if(!t)return null;const{project:r}=await Re(t);return await Ai({projectId:r.id,sha:e})}async function Ri(e){var s,a,o,i,l,d,m,u;await Be();const t=[],r=[];if((s=e.metadata)!=null&&s.importedExports&&e.metadata.importedExports.length>0){const p=e.metadata.importedExports;for(const h of p){if(!h.filePath||!h.name)continue;const f=h.resolvedFilePath??h.filePath,y=h.resolvedName??h.name;let g=await Ze({projectId:e.projectId,filePaths:[f],names:[y]});if((!g||g.length===0)&&h.resolvedIsDefault&&(g=await Ze({projectId:e.projectId,filePaths:[f],names:["default"]})),g&&g.length>0){const x=g[0],v=await Rt({entityShas:[x.sha],limit:1});let b,N,C;if(v&&v.length>0&&v[0].scenarios){const E=v[0],w=E.scenarios||[],k=w.length,S=w.find($=>{var _,j;return(j=(_=$.metadata)==null?void 0:_.screenshotPaths)==null?void 0:j[0]});S&&(b=(o=(a=S.metadata)==null?void 0:a.screenshotPaths)==null?void 0:o[0],N=S.name),C={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||E.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:k,timestamp:E.createdAt?new Date(E.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else C={status:"not_analyzed"};t.push({...x,screenshotPath:b,scenarioName:N,analysisStatus:C})}}}if((l=e.metadata)!=null&&l.importedBy){const p=[];for(const h in e.metadata.importedBy)for(const f in e.metadata.importedBy[h]){const y=e.metadata.importedBy[h][f];y.shas&&p.push(...y.shas)}if(p.length>0){const h=await Ze({projectId:e.projectId,shas:p});if(h)for(const f of h){const y=await Rt({entityShas:[f.sha],limit:1});let g,x,v;if(y&&y.length>0&&y[0].scenarios){const b=y[0],N=b.scenarios||[],C=N.length,E=N.find(k=>{var S,A;return(A=(S=k.metadata)==null?void 0:S.screenshotPaths)==null?void 0:A[0]});E&&(g=(m=(d=E.metadata)==null?void 0:d.screenshotPaths)==null?void 0:m[0],x=E.name),v={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||b.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:C,timestamp:b.createdAt?new Date(b.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else v={status:"not_analyzed"};r.push({...f,screenshotPath:g,scenarioName:x,analysisStatus:v})}}}return{importedEntities:t,importingEntities:r}}async function Te(){try{const e=me();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await ye.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function hn(){await Be();try{const e=await Te();if(!e)return null;const{project:t,branch:r}=await Re(e),s=await gr({projectId:t.id,branchId:r.id,limit:1,skipRelations:!0});return s&&s.length>0?s[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function Ir(){try{const e=me();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await ye.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function Ii(e){try{const t=me();if(!t)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const r=ee.join(t,e.filePath);return await ye.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function Di(e){try{const t=me();if(!t||!e.filePath)return!1;const r=ee.join(t,e.filePath),a=(await ye.stat(r)).mtime.getTime(),o=e.updatedAt||e.createdAt;if(!o)return!1;const i=new Date(o).getTime();return a>i+1e3}catch{return!1}}async function Li(e){if(await Be(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await Ze({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),s=await Rt({entityShas:r}),a=new Map;if(s)for(const i of s)a.has(i.entitySha)||a.set(i.entitySha,[]),a.get(i.entitySha).push(i);for(const[i,l]of a.entries())l.sort((d,m)=>{const u=new Date(d.createdAt||0).getTime();return new Date(m.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:a.get(i.sha)||[]}));return o.sort((i,l)=>{var u,p;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",m=((p=l.analyses[0])==null?void 0:p.createdAt)||l.createdAt||"";return new Date(m).getTime()-new Date(d).getTime()}),o}async function Oi(e){try{const t=me();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=ee.join(t,".codeyam","config.json"),s=await ye.readFile(r,"utf8"),a=JSON.parse(s),o={...a,...e},i=JSON.stringify(o,null,2);if(await ye.writeFile(r,i,"utf8"),a.projectSlug){const l={};e.universalMocks!==void 0&&(l.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(l.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(l.webapps=e.webapps),await dn({projectSlug:a.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const em=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:nn,getAnalysesForEntity:$r,getAnalysisForExactEntitySha:$i,getCurrentCommit:hn,getEntityBySha:Xt,getEntityCodeFromFilesystem:Ii,getEntityHistory:Li,getLatestAnalysisForEntity:Rr,getProjectConfig:Ir,getProjectSlug:Te,getRelatedEntities:Ri,hasFileBeenModifiedSinceEntity:Di,requireBranchAndProject:Re,updateProjectConfig:Oi},Symbol.toStringTag,{value:"Module"})),Fi="secrets.json";function zi(e){return ee.join(e,".codeyam",Fi)}function Bi(){return ee.join(As.homedir(),".codeyam",Fi)}async function Dr(e){let t={};try{const r=Bi(),s=await ye.readFile(r,"utf-8");t=JSON.parse(s)}catch{}try{const r=zi(e),s=await ye.readFile(r,"utf-8"),a=JSON.parse(s);t={...t,...a}}catch{}return t}async function tm(e,t,r=!0){const s=r?Bi():zi(e),a=ee.dirname(s);await ye.mkdir(a,{recursive:!0}),await ye.writeFile(s,JSON.stringify(t,null,2)+`
|
|
33
|
-
`,"utf-8")}async function nm(e){const t=await Dr(e);return!!(t.ANTHROPIC_API_KEY&&t.ANTHROPIC_API_KEY.length>0)||!!(t.OPENAI_API_KEY&&t.OPENAI_API_KEY.length>0)||!!(t.GROQ_API_KEY&&t.GROQ_API_KEY.length>0)||!!(t.OPENROUTER_API_KEY&&t.OPENROUTER_API_KEY.length>0)}const rm=3;let kn=0;async function Hn(e){if(!e||e.length===0)return[];if(kn>=rm)return console.warn(`[Loader] Circuit breaker open (${kn} consecutive timeouts), skipping entity fetch for ${e.length} entities`),[];const t=Math.min(Math.max(e.length*2e3,1e4),6e4);return new Promise(r=>{let s=!1;const a=setTimeout(()=>{s||(s=!0,kn++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);Ze({shas:e,excludeMetadata:!0}).then(o=>{s||(s=!0,clearTimeout(a),kn=0,r(o||[]))}).catch(()=>{s||(s=!0,clearTimeout(a),kn++,r([]))})})}function sm({sourcePath:e,destinationPath:t,excludes:r,silent:s}){if(process.platform!=="darwin")return!1;if(jt(t))try{if(rd(t).length>0)return!1;rs(t,{recursive:!0})}catch{return!1}try{Ee(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const a of r)if(a.includes("*"))try{Ee(`rm -rf "${eo(t,a)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const o=eo(t,a);jt(o)&&rs(o,{recursive:!0,force:!0})}return s||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(jt(t))try{rs(t,{recursive:!0})}catch{}return!1}}async function am({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:s=!1,silent:a=!1,extraArgs:o=[]}){const i=Date.now();if(!s&&o.length===0&&sm({sourcePath:e,destinationPath:t,excludes:r,silent:a})){if(!a){const d=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${d}s]`)}return}return new Promise((l,d)=>{const m=e.endsWith("/")?e:`${e}/`,u=t.endsWith("/")?t:`${t}/`,p=["-a","--no-specials"];s||p.push("--delete","--force"),p.push(...o);for(const f of r)p.push(`--exclude=${f}`);p.push(m,u);const h=Lt("rsync",p);h.on("exit",f=>{if(f===0){if(!a){const y=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${y}s]`)}l()}else console.error(`CodeYam Error: rsync failed with code: ${f}`,JSON.stringify({rsyncArgs:p},null,2)),d(new Error(`rsync failed with exit code ${f}`))}),h.on("error",f=>{a||console.log("Error occurred:",f),d(f)})})}const om=Qs(Ks);async function im(e){return new Promise(t=>setTimeout(t,e))}function lm(e){try{return process.kill(e,0),!0}catch{return!1}}async function Yi(e){try{const{stdout:t}=await om(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
|
|
34
|
-
`).filter(a=>a.trim()).map(a=>parseInt(a.trim(),10)).filter(a=>!isNaN(a)),s=[...r];for(const a of r){const o=await Yi(a);s.push(...o)}return s}catch{return[]}}function io(e,t,r){try{process.kill(e,t)}catch(s){r==null||r(`Error sending ${t} to process ${e}: ${s}`)}}async function cm(e,t,r){const s=await Yi(e);for(const a of s.reverse())await io(a,t,r);await io(e,t,r)}async function Rn(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let s=0;async function a(o,i){await cm(e,o,t);for(let l=0;l<i;l++)if(await im(1e3),s+=1e3,!await lm(e))return t(`Process tree ${e} successfully killed with ${o} after ${s/1e3} seconds.`),!0;return t(`Process tree still running after ${o}...`),!1}if(await a("SIGINT",5)||await a("SIGTERM",5))return!0;for(let o=0;o<r;o++)if(await a("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${s/1e3} seconds.`),!1}function dm(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:Ed(),createdAt:t}}hd.config({quiet:!0});var Ui=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(Ui||{});class um extends fd{constructor(){super(...arguments),this.processes=new Map}register(t){const r=gd(),{process:s,type:a,name:o,metadata:i,parentId:l}=t,d={id:r,type:a,name:o,pid:s.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:d,process:s}),l){const p=this.processes.get(l);p&&(p.info.children=p.info.children||[],p.info.children.push(r))}const m=(p,h)=>{this.handleProcessExit(r,p,h)},u=p=>{this.handleProcessError(r,p)};return s.on("exit",m),s.on("error",u),s.__cleanup=()=>{s.removeListener("exit",m),s.removeListener("error",u)},this.emit("processStarted",d),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const s=this.processes.get(t);if(!s)throw new Error(`Process not found: ${t}`);const{info:a,process:o}=s;if(a.state==="completed"||a.state==="failed"||a.state==="killed")return;if(r.shutdownChildren&&a.children&&a.children.length>0&&await Promise.all(a.children.map(l=>this.shutdown(l,r))),o.pid)try{await Rn(o.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,100)),a.state==="running"&&(a.state="killed",a.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const s=this.listByType(t);await Promise.all(s.map(a=>this.shutdown(a.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(s=>this.shutdown(s.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,s=Date.now();for(const[a,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&s-i.endedAt>r){const l=o.process.__cleanup;l&&l(),this.processes.delete(a)}}}handleProcessExit(t,r,s){const a=this.processes.get(t);if(!a)return;const{info:o}=a;o.endedAt=Date.now(),o.exitCode=r,o.signal=s,r===0?o.state="completed":s?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const s=this.processes.get(t);if(!s)return;const{info:a}=s;a.endedAt=Date.now(),a.state="failed",a.metadata={...a.metadata,error:r.message},this.emit("processExited",a)}}let ds=null;function mm(){return ds||(ds=new um),ds}const pm={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function hm({command:e,args:t,workingDir:r,outputOptions:s=pm,processName:a,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${a}`},l=Lt(e,t,{cwd:r,env:i});return mm().register({process:l,type:Ui.Other,name:a,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const p=f=>{const y=ee.join(r,"log.txt");K.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},h=(f,y="")=>{const g=new Date().toLocaleString();return f.split(`
|
|
35
|
-
`).map(v=>v.trim()?`[${g}]${y} ${v}`:v).join(`
|
|
36
|
-
`)};l.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=h(y);s.stdoutToConsole&&console.log(g),s.stdoutToFile&&p(g+`
|
|
37
|
-
`),s.stdoutCallback&&s.stdoutCallback(y)}),l.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=h(y,"<STDERR>");s.stderrToConsole&&console.error(g),s.stderrToFile&&p(g+`
|
|
38
|
-
`),s.stderrCallback&&s.stderrCallback(y)}),l.on("exit",function(f){u(f)})}),process:l}}function fm(e){const t=[];return Object.keys(e).forEach(r=>{const s=e[r];s!==void 0&&(typeof s=="boolean"?s&&t.push(`--${r}`):s!==null&&t.push(`--${r}`,String(s)))}),t}function gm({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:s}){const a=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
|
|
39
|
-
`);K.writeFileSync(`${e}/.env`,a);const o=fm(r);return hm({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:s,processName:"analyzer",env:t})}const ym="/tmp/codeyam/local-dev";function Wi(e){return Y.join(ym,e)}function Ji(e){return Y.join(Wi(e),"codeyam")}function ut(e){return Y.join(Wi(e),"project")}function Lr(e){return Y.join(Ji(e),"log.txt")}const xm=[".sync-metadata.json","__codeyamMocks__"];async function bm(e,t={}){const{port:r,silent:s=!0}=t,a=ut(e);if(r)try{Ee(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}try{Ee(`lsof +D "${a}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}await new Promise(o=>setTimeout(o,500))}async function vm(e,t={}){const{killProcesses:r=!0,port:s,silent:a=!0}=t,o=ut(e),i=[],l=[];if(!K.existsSync(o))return{removed:i,errors:l};r&&await bm(e,{port:s,silent:a});for(const d of xm){const m=Y.join(o,d);if(K.existsSync(m))try{(await be.stat(m)).isDirectory()?await be.rm(m,{recursive:!0,force:!0}):await be.unlink(m),i.push(d)}catch(u){l.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:l}}const wm=Y.dirname(Ar(import.meta.url));function Nm(e){let t=e;for(;t!==Y.dirname(t);){const r=Y.join(t,"package.json");if(K.existsSync(r))try{if(JSON.parse(K.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=Y.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function Or(){const e=Nm(wm);return Y.join(e,"analyzer-template")}function fn(e){return Ji(e)}function Cm(){const e=Or();return K.existsSync(Y.join(e,".finalized"))}async function lo(e){const t=Or(),r=fn(e);if(!K.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await be.mkdir(Y.dirname(r),{recursive:!0}),await am({sourcePath:t,destinationPath:r,silent:!0})}function gn(e,t,r,s){const a=fn(e);if(!K.existsSync(a))throw new Error(`Analyzer not found at ${a}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return gm({absoluteCodeyamRootPath:a,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function Sm(e){const t=Or(),r=fn(e),s=Y.join(t,".build-info.json"),a=Y.join(r,".build-info.json");if(!K.existsSync(s))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!K.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!K.existsSync(a))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(K.readFileSync(s,"utf8")),i=JSON.parse(K.readFileSync(a,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function Bn(e,t){const r=fn(e);if(!K.existsSync(r)){t.update("Creating analyzer..."),await lo(e);return}const s=Sm(e);s.isFresh||(t.update(`Updating analyzer (${s.reason})...`),await lo(e))}async function aa(e){await vm(e,{killProcesses:!1})}const km=Y.dirname(Ar(import.meta.url));function Fr(){let e=km;for(;e!==Y.dirname(e);){const t=Y.join(e,"package.json");if(K.existsSync(t))try{if(JSON.parse(K.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=Y.dirname(e)}return null}function ln(e){if(!K.existsSync(e))return null;try{return JSON.parse(K.readFileSync(e,"utf8"))}catch{return null}}function Em(){const e=Fr();if(e){const t=[Y.join(e,"src/webserver/build-info.json"),Y.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const s=ln(r);if(s!=null&&s.semanticVersion)return s.semanticVersion}}return"unknown"}function Am(){const e=Fr();if(e){const t=Y.join(e,"package.json");try{const r=JSON.parse(K.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const oa=Em(),us=Am();function ia(){if(us!=="unknown"&&us!=="0.1.0")return us;const e=Fr();if(e)for(const t of[Y.join(e,"src/webserver/build-info.json"),Y.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=ln(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function Hi(e){const t=Fr();let r=null;if(t){const d=[Y.join(t,"src/webserver/build-info.json"),Y.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const m of d)if(r=ln(m),r)break}const s=Or(),a=Y.join(s,".build-info.json"),o=ln(a);let i=null;if(e){const d=fn(e),m=Y.join(d,".build-info.json");i=ln(m)}let l=!1;return o&&i?l=o.buildTime>i.buildTime:o&&!i&&e&&(l=!0),{cliVersion:oa,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:l}}function zr(e){const t=fn(e),r=Y.join(t,".build-info.json"),s=ln(r);return(s==null?void 0:s.version)??null}function Vi(){const e=me();return e?Y.join(e,".codeyam","server.json"):null}function Gi(){const e=Vi();if(!e||!K.existsSync(e))return null;try{const t=K.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function Pm(){const e=Vi();if(e)try{K.unlinkSync(e)}catch{}}const Mm="/assets/globals-Bd0cs8vw.css";function co({text:e,subtext:t,linkText:r,linkTo:s}){const[a,o]=M(!1);return a?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:c("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),c("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(de,{to:s,className:"shrink-0 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors",children:r})]}),n("button",{type:"button",onClick:()=>o(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function _m({version:e}){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:c("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[c("div",{className:"flex items-center gap-3",children:[n("span",{className:"font-mono text-sm font-semibold tracking-widest text-cyblack-100",children:"CODEYAM"}),e&&n("span",{className:"font-mono text-xs text-gray-400",children:e})]}),c("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://blog.codeyam.com/",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Read the Blog"}),n("span",{className:"text-cygray-30",children:"|"}),n("a",{href:"https://discord.gg/x4uAgaRdwF",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function jm({serverVersion:e}){const[t,r]=M("stale"),[s,a]=M(null),o=async()=>{r("restarting"),a(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let l=0;const d=30,m=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}l++,l<d?setTimeout(()=>void u(),m):(a("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){a(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),c("div",{className:"flex-1",children:[t==="stale"&&c(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),c("p",{className:"text-xs text-amber-700 mt-0.5",children:["Server version: ",e,". A newer version of CodeYam CLI is installed. Restart the server to get the latest features."]}),s&&n("p",{className:"text-xs text-red-600 mt-1",children:s})]}),t==="restarting"&&c(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),t==="reconnecting"&&c(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),t==="stale"&&n("button",{type:"button",onClick:()=>void o(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&c("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[c("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function At({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:s="",duration:a=2e3,ariaLabel:o,icon:i=!1,iconSize:l=14}){const[d,m]=M(!1),u=se(()=>{navigator.clipboard.writeText(e).then(()=>{m(!0),setTimeout(()=>m(!1),a)}).catch(p=>{console.error("Failed to copy:",p)})},[e,a]);return n("button",{onClick:u,className:`cursor-pointer ${s}`,disabled:d,"aria-label":o||(d?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?d?n(pt,{size:l,className:"text-green-500"}):n(wt,{size:l}):d?r:t})}function Tm({currentVersion:e,latestVersion:t}){const[r,s]=M(!1);if(r)return null;const a="npm install -g @codeyam/codeyam-cli@latest && codeyam stop && codeyam";return n("div",{className:"bg-emerald-100 border rounded border-emerald-700 shadow-sm mx-6 mt-6",children:c("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-emerald-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M7 11l5-5m0 0l5 5m-5-5v12"})})}),c("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),c("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),c("div",{className:"shrink-0 flex items-center gap-2",children:[n("code",{className:"text-xs bg-emerald-200 text-emerald-900 px-2 py-1.5 rounded font-mono",children:a}),n(At,{content:a,label:"Copy",copiedLabel:"Copied!",className:"px-3 py-1.5 bg-emerald-600 text-white text-xs font-medium rounded hover:bg-emerald-700 transition-colors"})]})]}),n("button",{type:"button",onClick:()=>s(!0),className:"shrink-0 ml-4 p-1 rounded text-emerald-600 hover:text-emerald-800 hover:bg-emerald-200 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}let En=null,Vn=0;const $m=3600*1e3;function Rm(e,t){const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let a=0;a<Math.max(r.length,s.length);a++){const o=r[a]??0,i=s[a]??0;if(isNaN(o)||isNaN(i))return!1;if(o>i)return!0;if(o<i)return!1}return!1}async function Im(){const e=ia();if(En&&Date.now()-Vn<$m)return En;try{const t=new AbortController,r=setTimeout(()=>t.abort(),5e3),s=await fetch("https://registry.npmjs.org/@codeyam/codeyam-cli/latest",{signal:t.signal});if(clearTimeout(r),!s.ok){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return En=l,Vn=Date.now(),l}const o=(await s.json()).version;if(!o){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return En=l,Vn=Date.now(),l}const i={updateAvailable:Rm(o,e),latestVersion:o,currentVersion:e};return En=i,Vn=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function vr(e){return Y.join(e,".codeyam","queue.json")}function _n(e){const t=vr(e);if(!K.existsSync(t))return{paused:!1,jobs:[]};try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function Dm(e,t){const r=vr(e),s=Y.dirname(r);K.existsSync(s)||K.mkdirSync(s,{recursive:!0});try{K.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(a){throw console.error("Failed to save queue state:",a),a}}const Sr=class Sr extends Pr{constructor(t){super(),this.watcher=null,this.debounceTimers=new Map,this.DEBOUNCE_MS=300,this.options=t}start(){try{this.watcher=Ne.watch(this.options.projectRootPath,{recursive:!0},(t,r)=>{if(!r||!/\.(ts|tsx|js|jsx|css|scss|json|svg|html)$/.test(r)||Sr.IGNORED_DIRS.some(a=>r.includes(a+"/")||r.includes(a+"\\")))return;const s=this.debounceTimers.get(r);s&&clearTimeout(s),this.debounceTimers.set(r,setTimeout(()=>{this.debounceTimers.delete(r),this.syncFile(r)},this.DEBOUNCE_MS))}),console.log(`[InteractiveSyncWatcher] Watching ${this.options.projectRootPath} for changes`)}catch(t){console.error("[InteractiveSyncWatcher] Failed to start:",t)}}syncFile(t){const r=ee.join(this.options.projectRootPath,t),s=ee.join(this.options.tmpProjectPath,t);try{if(!Ne.existsSync(r)){Ne.existsSync(s)&&(Ne.unlinkSync(s),console.log(`[InteractiveSyncWatcher] Removed: ${t}`));return}const a=ee.dirname(s);Ne.existsSync(a)||Ne.mkdirSync(a,{recursive:!0}),Ne.copyFileSync(r,s);const o=ee.basename(t);console.log(`[InteractiveSyncWatcher] Synced: ${t}`);const i={type:"file-synced",fileName:o,filePath:t,timestamp:Date.now()};this.emit("sync",i)}catch(a){console.error(`[InteractiveSyncWatcher] Error syncing ${t}:`,a);const o={type:"error",fileName:ee.basename(t),filePath:t,timestamp:Date.now()};this.emit("sync",o)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null);for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),console.log("[InteractiveSyncWatcher] Stopped")}};Sr.IGNORED_DIRS=["node_modules",".git",".codeyam","__codeyamMocks__",".next","dist","build",".turbo",".vercel","coverage",".cache"];let Ms=Sr,Lm=class extends Pr{constructor(){super(),this.setMaxListeners(20)}emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}};const _s="__codeyam_dev_mode_event_emitter__";globalThis[_s]||(globalThis[_s]=new Lm);const uo=globalThis[_s],js=new Map;async function Om(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Fm(e,t,r);else if(e.type==="baseline")await zm(e,t,r);else if(e.type==="recapture")await Bm(e,t,r);else if(e.type==="capture-only")await Ym(e,t,r);else if(e.type==="debug-setup")await Um(e,t,r);else if(e.type==="interactive-start")await Wm(e,t,r);else if(e.type==="interactive-stop")await Jm(e,t,r);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(s){throw console.error(`[Queue] Job ${e.id} failed:`,s),s}}async function Fm(e,t,r){var g,x,v,b;const{projectSlug:s,commitSha:a,entityShas:o}=e;if(!a)throw new Error("Analysis job missing commitSha");const i=o||[],{project:l}=await Re(s);await aa(s),await Bn(s,{update:N=>console.log(`[Queue] ${N}`)});const d=zr(s),m={...await Ot(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Ft(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},u=(x=(g=l.metadata)==null?void 0:g.webapps)==null?void 0:x[0];if(!u)throw new Error("No webapps found in project metadata");const p=e.onlyDataStructure,h={packageManager:((v=l.metadata)==null?void 0:v.packageManager)||"npm",absoluteProjectRootPath:ut(s),port:0,noServer:!0,framework:u.framework,...p?{}:{orchestrateCapture:"local-sequential"}},f=gn(s,m,h),y=N=>{try{return process.kill(N,0),!0}catch{return!1}};await Tt({commitSha:a,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((b=e.filePaths)==null?void 0:b.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const N=new Promise((C,E)=>setTimeout(()=>E(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,N]),await Tt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await Tt({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(C=>setTimeout(C,2e3))}finally{if(f.process.pid)try{y(f.process.pid)&&await Rn(f.process.pid,()=>{})}catch{}}}catch(N){if(console.error(`[Queue] Analysis job ${e.id} failed:`,N),f.process.pid&&y(f.process.pid))try{await Rn(f.process.pid,()=>{})}catch{}try{await Tt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:N instanceof Error?N.message:String(N)}}),r==null||r.notifyChange("commit")}catch(C){console.error("[Queue] Failed to update commit metadata after job failure:",C)}throw N}}async function zm(e,t,r){var h,f,y;const{projectSlug:s,commitSha:a}=e;if(!a)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${s}`);const{project:o}=await Re(s);await aa(s),await Bn(s,{update:g=>console.log(`[Queue] ${g}`)});const i=zr(s),l={...await Ot(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Ft(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(h=o.metadata)==null?void 0:h.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const m={packageManager:((y=o.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:ut(s),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=gn(s,l,m),p=g=>{try{return process.kill(g,0),!0}catch{return!1}};await Tt({commitSha:a,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const g=new Promise((x,v)=>setTimeout(()=>v(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,g]),await Tt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${s}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(u.process.pid)try{p(u.process.pid)&&await Rn(u.process.pid,()=>{})}catch{}}}async function Bm(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Recapture job missing analysisId");const l=await Et({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:v}=await import("./index-DCxIbVvl.js"),b=v(),N=await b.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let C={};N!=null&&N.metadata&&(typeof N.metadata=="string"?C=JSON.parse(N.metadata):C=N.metadata),C.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",l.entitySha).execute()}await pn(a,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Re(s);await Bn(s,{update:v=>console.log(`[Queue] ${v}`)});const m=zr(s),u={...await Ot(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Ft(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...m?{ANALYZER_VERSION:m}:{}},p={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ut(s),port:void 0,noServer:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??qe.Next,orchestrateCapture:"local-sequential"},h=gn(s,u,p);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function Ym(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Capture-only job missing analysisId");const l=await Et({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:v}=await import("./index-DCxIbVvl.js"),b=v(),N=await b.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let C={};N!=null&&N.metadata&&(typeof N.metadata=="string"?C=JSON.parse(N.metadata):C=N.metadata),C.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",l.entitySha).execute()}await pn(a,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Re(s);await Bn(s,{update:v=>console.log(`[Queue] ${v}`)});const m=zr(s);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await Ot(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Ft(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...m?{ANALYZER_VERSION:m}:{}},p={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ut(s),port:void 0,noServer:!0,fast:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??qe.Next,orchestrateCapture:"local-sequential"},h=gn(s,u,p);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function Um(e,t,r){var h,f,y,g;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Debug setup job missing analysisId");const i=await Et({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:l}=await Re(s);await aa(s),await Bn(s,{update:x=>console.log(`[Queue] ${x}`)});const d={...await Ot(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Ft(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};o&&(d.SCENARIO_IDS=o);const m={packageManager:((h=l.metadata)==null?void 0:h.packageManager)||"npm",absoluteProjectRootPath:ut(s),port:void 0,noServer:!1,framework:((g=(y=(f=l.metadata)==null?void 0:f.webapps)==null?void 0:y[0])==null?void 0:g.framework)||qe.Next},p=await gn(s,d,m).promise;if(p!==0)throw new Error(`Prep process exited with code ${p}`)}async function Wm(e,t,r){var x,v,b,N;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Interactive start job missing analysisId");const i=await Et({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:l}=await Re(s),d={...await Ot(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Ft(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};o&&(d.SCENARIO_IDS=o);const m=ut(s),u=ee.join(m,".next","dev","lock");if(Ne.existsSync(u)){console.log("[Queue] Found stale .next/dev/lock, cleaning up old processes");try{const C=Ee(`pgrep -f ${JSON.stringify(m)} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(C)for(const E of C.split(`
|
|
40
|
-
`).filter(Boolean))try{process.kill(parseInt(E,10),"SIGTERM"),console.log(`[Queue] Killed stale process ${E}`)}catch{}}catch{}try{Ne.unlinkSync(u),console.log("[Queue] Removed stale lock file")}catch{}}const p=Ne.existsSync(m)&&Ne.existsSync(ee.join(m,"package.json")),h={packageManager:((x=l.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:m,port:void 0,noServer:!1,fast:p,framework:((N=(b=(v=l.metadata)==null?void 0:v.webapps)==null?void 0:b[0])==null?void 0:N.framework)||qe.Next};await pn(a,C=>{C.readyToBeCaptured=!0});const f=gn(s,d,h);await Mi(a,C=>{C.interactiveMode={pid:f.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${a}, PID: ${f.process.pid}`);const y=ut(s),g=new Ms({projectRootPath:t,tmpProjectPath:y});g.on("sync",C=>{C.type==="file-synced"?uo.emitFileSynced(C.fileName,C.filePath):C.type==="error"&&uo.emitError(C.fileName,C.filePath)}),g.start(),js.set(a,g),console.log(`[Queue] File sync watcher started for analysis ${a}`)}async function Jm(e,t,r){var m;const{projectSlug:s,analysisId:a}=e;if(!a)throw new Error("Interactive stop job missing analysisId");const o=await Et({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${a} not found`);const i=(m=o.metadata)==null?void 0:m.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${a}`);return}const l=js.get(a);l&&(l.stop(),js.delete(a),console.log(`[Queue] File sync watcher stopped for analysis ${a}`));const d=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${a}, killing PID: ${d}`);try{try{process.kill(d,0)}catch{console.log(`[Queue] Process ${d} already exited`);return}await Rn(d,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${d}`)}catch(u){throw console.error(`[Queue] Failed to kill process ${d}:`,u),u}finally{await Mi(a,u=>{u.interactiveMode=null})}}class Hm{constructor(t,r){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=t,this.state={paused:!1,jobs:[]},r&&(typeof r=="function"?this.notifier={notifyChange:()=>r()}:this.notifier=r)}start(){this.state=_n(this.projectRoot),this.state.currentlyExecuting&&(console.log(`[Queue] Clearing stale currentlyExecuting job from previous session: ${this.state.currentlyExecuting.id}`),this.state.currentlyExecuting=void 0,this.save()),this.state.jobs.length>0?(this.state.paused=!0,this.save(),console.log(`[Queue] Found ${this.state.jobs.length} queued jobs from previous session (paused)`)):this.state.paused=!1}enqueue(t){const r=t.commitSha||qs(),s={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(s),this.save(),console.log(`[Queue] Enqueued job ${r} (${s.type})`);const a=new Promise((o,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:a}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(a=>a.id!==t);const s=this.state.jobs.length<r;if(s){console.log(`[Queue] Removed job ${t}`),this.save();const a=this.completionCallbacks.get(t);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return s}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const s=this.completionCallbacks.get(r.id);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const s=this.state.jobs.findIndex(i=>i.id===t);if(s===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const a=r==="up"?s-1:s+1;if(a<0||a>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[s];return this.state.jobs[s]=this.state.jobs[a],this.state.jobs[a]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${s} -> ${a})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await Om(t,this.projectRoot,this.notifier),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"success",completedAt:new Date().toISOString()});const r=this.completionCallbacks.get(t.id);r&&(r(),this.completionCallbacks.delete(t.id)),console.log(`[Queue] Job ${t.id} completed successfully`)}catch(r){console.error(`[Queue] Job ${t.id} failed:`,r),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"error",error:(r==null?void 0:r.message)||"Unknown error",completedAt:new Date().toISOString()});const s=this.completionCallbacks.get(t.id);s&&(s(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){Dm(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class Vm{constructor(t,r,s=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=s}start(){const t=vr(this.projectRoot);if(!K.existsSync(t)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(t)}watchDirectory(){const t=vr(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=K.watch(r,(s,a)=>{a==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(s){console.error("[QueueFileWatcher] Failed to watch directory:",s)}}watchFile(t){try{this.watcher=K.watch(t,r=>{r==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(r){console.error("[QueueFileWatcher] Failed to watch queue file:",r)}}notifyChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.onChange(),this.debounceTimer=null},this.debounceMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}class Gm{constructor(t,r,s){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=s,this.cachedState=_n(r)}start(){this.cachedState=_n(this.projectRoot),console.log(`[ProxyQueue] Connected to background server at ${this.serverInfo.url}`),console.log(`[ProxyQueue] Current queue has ${this.cachedState.jobs.length} jobs`),this.fileWatcher=new Vm(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,s;const a=new Promise((i,l)=>{r=i,s=l}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),s(i)}),{jobId:o,completion:a}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${s}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${s}`)}this.refreshState()}getState(){return this.cachedState=_n(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=_n(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${this.serverInfo.url}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function qm(e){const t=Y.join(e,".codeyam","server.json");if(!K.existsSync(t))return null;try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function Km(e){try{return process.kill(e,0),!0}catch{return!1}}async function Qm(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}async function Zm(e){const t=qm(e);return!t||!Km(t.pid)||!await Qm(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class Xm extends Pr{constructor(){super();Cn(this,"watcher",null);Cn(this,"dbPath",null);Cn(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=Ft();const{default:r}=await import("chokidar"),s=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(s,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",a=>{const o=Date.now(),i=new Date(o).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${a}`),console.log(`[dbNotifier] Timestamp: ${i} (${o})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:o})}).on("error",a=>{console.error("Database watcher error:",a),this.emit("error",a)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const s=Date.now(),a=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${a} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:s})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const dt=new Xm;let qt=null,jn=null;async function ep(){if(!qt){if(jn){await jn;return}jn=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||_i()||process.cwd();if(qu(e),console.log(`[GlobalQueue] Project root: ${e}`),await Be(),process.env.NODE_ENV==="development")try{const r=ee.join(e,".codeyam","config.json"),a=JSON.parse(await Ne.promises.readFile(r,"utf8")).projectSlug;a&&(await dn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),console.log("[GlobalQueue] Labs & Simulations auto-enabled for dev mode"))}catch(r){console.warn("[GlobalQueue] Could not auto-enable labs:",r)}const t=await Zm(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new Gm(t,e,()=>{dt.notifyChange("unknown")});await r.start(),qt=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new Hm(e,dt);await r.start(),qt=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await jn}}async function Pt(){return qt||await ep(),qt}function tp(){return qt||(jn&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const np=()=>[{rel:"stylesheet",href:Mm},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],rp={currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown",npmUpdate:null,labs:null,simulationsEnabled:!1,isSimulationsReady:!1,isAdmin:!1,editorMode:!1,displayVersion:ia()};async function sp({request:e,context:t}){var r,s,a,o,i,l,d,m,u,p,h;try{const f=e.signal,y=()=>{if(f.aborted)throw new Response(null,{status:499})};y();const g=me()||process.cwd(),[x,v,b]=await Promise.all([Te(),Dr(g),Im().catch(()=>null)]);if(!x)throw new Error("Project slug not found");const{project:N,branch:C}=await Re(x);y();const E=await gr({projectId:N.id,branchId:C.id,limit:20,skipRelations:!0});y();const w=E.length>0?E[0]:null,k=t.analysisQueue||tp(),S=k==null?void 0:k.getState();y();const A=await Promise.all(((S==null?void 0:S.jobs)||[]).map(async G=>{var le;const X=await Hn(G.entityShas||[]);return X.length===0&&((le=G.entityShas)!=null&&le.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",G.id),{...G,entities:X}}));let $=null;if(S!=null&&S.currentlyExecuting){const G=S.currentlyExecuting,X=await Hn(G.entityShas||[]);X.length===0&&((r=G.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",G.id),$={...G,entities:X}}const _=$?A.filter(G=>G.id!==$.id):A;let j=((a=(s=w==null?void 0:w.metadata)==null?void 0:s.currentRun)==null?void 0:a.currentEntityShas)||[];if(j.length===0){const G=((o=w==null?void 0:w.metadata)==null?void 0:o.historicalRuns)||[];if(G.length>0){const le=[...G].sort((ve,oe)=>{const pe=ve.archivedAt||ve.createdAt||"";return(oe.archivedAt||oe.createdAt||"").localeCompare(pe)})[0];if(le){const ve=le.analysisCompletedAt||le.createdAt;if(ve){const oe=new Date(ve).getTime(),Ce=Date.now()-1440*60*1e3;oe>Ce&&(j=le.currentEntityShas||[])}}}}const D=await Hn(j),R=[];v.ANTHROPIC_API_KEY&&R.push("ANTHROPIC_API_KEY"),v.GROQ_API_KEY&&R.push("GROQ_API_KEY"),v.OPENAI_API_KEY&&R.push("OPENAI_API_KEY"),v.OPENROUTER_API_KEY&&R.push("OPENROUTER_API_KEY"),y();const T=[];for(const G of E){const X=((i=G.metadata)==null?void 0:i.historicalRuns)||[];for(const le of X)T.push(le)}T.sort((G,X)=>{const le=G.archivedAt||G.analysisCompletedAt||G.createdAt||"";return(X.archivedAt||X.analysisCompletedAt||X.createdAt||"").localeCompare(le)});const U=new Set(((l=$==null?void 0:$.entities)==null?void 0:l.map(G=>G.sha))||[]),I=T.filter(G=>!(G.currentEntityShas||[]).some(le=>U.has(le))).slice(0,3),O=new Set;for(const G of I)for(const X of G.currentEntityShas||[])O.add(X);const z=await Hn(Array.from(O)),L=new Map;for(const G of z)L.set(G.sha,G);const P=I.map(G=>({...G,entities:(G.currentEntityShas||[]).map(X=>L.get(X)).filter(X=>X!=null)})),q=Gi(),H=(q==null?void 0:q.cliVersion)??"unknown",W=H!=="unknown"&&H!==oa,Z=((m=(d=N.metadata)==null?void 0:d.labs)==null?void 0:m.simulations)??!1,B=Z?Cm():!1,F=((u=N.metadata)==null?void 0:u.editorMode)??!1,J={currentRun:(p=w==null?void 0:w.metadata)==null?void 0:p.currentRun,projectSlug:x,currentEntities:D,availableAPIKeys:R,queuedJobCount:_.length,queueJobs:_,currentlyExecuting:$,historicalRuns:P,isServerOutOfDate:W,serverVersion:H,npmUpdate:b!=null&&b.updateAvailable&&b.latestVersion?{latestVersion:b.latestVersion,currentVersion:b.currentVersion}:null,labs:((h=N.metadata)==null?void 0:h.labs)??null,simulationsEnabled:Z,isSimulationsReady:B,isAdmin:!!process.env.CODEYAM_ADMIN,editorMode:F,displayVersion:ia()};return Q(J)}catch(f){return f instanceof Response&&f.status===499||console.error("Failed to load root data:",f),Q(rp)}}function ap(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:s,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l,isServerOutOfDate:d,serverVersion:m,npmUpdate:u,labs:p,simulationsEnabled:h,isSimulationsReady:f,isAdmin:y,editorMode:g,displayVersion:x}=Ve(),{toasts:v,closeToast:b}=ta(),N=mt(),C=xe(N),E=kr();te(()=>{C.current=N},[N]);const w=E.pathname.startsWith("/entity/")&&E.pathname.includes("/edit/")||E.pathname.startsWith("/dev/")||E.pathname.startsWith("/editor"),k=E.pathname.includes("/fullscreen")||E.pathname.startsWith("/editor");return te(()=>{const S=new EventSource("/api/events");let A=null,$=0;const _=2e3;return S.addEventListener("message",j=>{const D=JSON.parse(j.data);if(D.type==="queue")C.current.revalidate(),$=Date.now();else if(D.type==="db-change"||D.type==="unknown"){const R=Date.now(),T=R-$;T<_?(A&&clearTimeout(A),A=setTimeout(()=>{C.current.revalidate(),$=Date.now(),A=null},_-T)):(C.current.revalidate(),$=R)}}),S.addEventListener("error",j=>{console.error("SSE connection error:",j)}),()=>{A&&clearTimeout(A),S.close()}},[]),c(ue,{children:[c("div",{className:`min-h-screen ${w?"":"grid"} bg-cygray-10`,style:w?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!w&&n(Ld,{labs:p,isAdmin:y,editorMode:g}),c("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[d&&n(jm,{serverVersion:m}),u&&u.currentVersion&&n(Tm,{currentVersion:u.currentVersion,latestVersion:u.latestVersion}),h&&s.length===0&&n(co,{text:"No AI API keys configured. Please provide an AI API key at your earliest convenience.",subtext:"An API key is required for stable, frequent use of CodeYam",linkText:"Configure API Keys",linkTo:"/settings"}),h&&!f&&n(co,{text:"Simulations enabled but not yet configured",subtext:"Run /codeyam-setup in Claude Code to install the analyzer and configure your dev server",linkText:"View Labs",linkTo:"/labs"}),n("div",{className:"flex-1",children:n(xc,{})}),n(_m,{version:x})]})]}),n(zd,{toasts:v,onClose:b}),!k&&h&&n(Bd,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l})]})}const op=We(function(){return c("html",{lang:"en",children:[c("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(hc,{}),n(fc,{})]}),c("body",{children:[n(Od,{children:n(Id,{children:n(ap,{})})}),n(gc,{}),n(yc,{})]})]})}),ip=Object.freeze(Object.defineProperty({__proto__:null,default:op,links:np,loader:sp},Symbol.toStringTag,{value:"Module"}));function Gn(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function rn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:o=!0,refreshTrigger:i=0}){const l=De(),[d,m]=M(null),[u,p]=M(!1),[h,f]=M(!1),[y,g]=M(!1),x=xe(!1),v=xe(null),b=xe(null),N=xe(null),[C,E]=M(0),[w,k]=M(0),S=xe(null),A=xe(!1),{interactiveUrl:$,resetLogs:_}=St(a,o),j=xe(t),D=xe(i);te(()=>{D.current!==i&&(D.current=i,d&&(console.log("[useInteractiveMode] Manual refresh triggered"),f(!0),g(!1),E(0),k(T=>T+1),A.current=!1,S.current&&(clearTimeout(S.current),S.current=null)))},[i,d]),te(()=>{if(j.current!==t&&(j.current=t,v.current&&b.current&&r)){let T=v.current;if(N.current&&s){const I=Gn(N.current),O=Gn(s);I!==O&&(T=T.replace(I,O),N.current=s)}const U=Gn(b.current),V=Gn(r);T=T.replace(U,V),b.current=r,m(T),f(!0),g(!1),E(0),k(I=>I+1),A.current=!1,S.current&&(clearTimeout(S.current),S.current=null);return}},[t,r,s]),te(()=>{if($){const T=$+"?width=600px";v.current=T,r&&(b.current=r),s&&(N.current=s),m(T),p(!1),f(!0)}},[$]),te(()=>{const T=U=>{U.data.type==="codeyam-resize"&&(A.current||(A.current=!0,S.current&&(clearTimeout(S.current),S.current=null),E(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{f(!1)})})))};return window.addEventListener("message",T),()=>window.removeEventListener("message",T)},[]);const R=()=>{A.current=!1,S.current&&clearTimeout(S.current);const T=300*Math.pow(2,C);S.current=setTimeout(()=>{A.current||(C<2?(E(U=>U+1),k(U=>U+1),f(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),f(!1)))},T)};return te(()=>{o&&!x.current&&t&&e&&(x.current=!0,p(!0),g(!1),m(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(U){console.error("[useInteractiveMode] Failed to clear log file:",U)}_(),l.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[o,t,e,_,a]),te(()=>{const T=e,U=()=>{if(x.current&&T){const I=new URLSearchParams({action:"stop",analysisId:T});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const O=navigator.sendBeacon("/api/interactive-mode",I);console.log("[useInteractiveMode] sendBeacon result:",O),O||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:I,keepalive:!0}).catch(z=>console.error("Failed to stop interactive mode:",z)))}},V=()=>{U()};return window.addEventListener("beforeunload",V),()=>{window.removeEventListener("beforeunload",V),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:x.current,analysisId:T}),U()}},[e]),{interactiveServerUrl:d,isStarting:u,isLoading:h,showIframe:y,iframeKey:w,onIframeLoad:R}}const qn=10,lp=1024;function la({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:s,onHoverChange:a,hideLabel:o=!1,lightMode:i=!1}){const[l,d]=M(null),m=xe(null),u=ne(()=>[...s].sort((b,N)=>b.width-N.width),[s]),{fittingPresets:p,overflowPresets:h}=ne(()=>{const b=[],N=[];for(const C of u)C.width<=lp?b.push(C):N.push(C);return N.sort((C,E)=>E.width-C.width),{fittingPresets:b,overflowPresets:N}},[u]),f=se(b=>{if(!m.current)return null;const N=m.current.getBoundingClientRect(),C=b-N.left,E=N.width,w=E/2,S=(p.length>0?p[p.length-1].width:0)/2,A=w-S,$=w+S,_=h.length>0?(h.length-1)*qn:0;if(h.length>0){if(C<A){if(C<=_){const D=Math.min(Math.floor(C/qn),h.length-1);return h[D]}return h[h.length-1]}if(C>$){const D=E-C;if(D<=_){const R=Math.min(Math.floor(D/qn),h.length-1);return h[R]}return h[h.length-1]}}const j=Math.abs(C-w);for(let D=p.length-1;D>=0;D--){const R=p[D],T=p[D-1],U=R.width/2,V=T?T.width/2:0;if(j<=U&&j>=V)return R}return p[0]||h[h.length-1]||null},[p,h]),y=se(b=>{const N=f(b.clientX);d(N),a==null||a(N)},[f,a]),g=se(()=>{d(null),a==null||a(null)},[a]),x=se(b=>{const N=f(b.clientX);N&&r(N)},[f,r]),v=l||{name:t,width:e};return c("div",{ref:m,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:x,children:[l&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${l.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:p.map(b=>{const N=b.width===e,C=(l==null?void 0:l.name)===b.name,E=b.width/2;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${E}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${E}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:h.map((b,N)=>{const C=N*qn,E=b.width===e,w=(l==null?void 0:l.name)===b.name;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${C}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${E||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${C}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${E||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:c("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${l?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[v.name," - ",v.width,"px"]})})]})}function Br({width:e,height:t,onSave:r,onCancel:s}){const[a,o]=M(""),[i,l]=M(""),d=()=>{const u=a.trim();if(!u){l("Please enter a name for this custom size");return}r(u)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[c("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),c("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),c("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),c("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:a,onChange:u=>{o(u.target.value),l("")},onKeyDown:u=>{u.key==="Enter"&&a.trim()&&d(),u.key==="Escape"&&s()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:s,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:d,disabled:!a.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function Yr(e){const[t,r]=M([]),s=e?`codeyam-custom-sizes-${e}`:null;te(()=>{if(!s||typeof window>"u"){r([]);return}try{const l=localStorage.getItem(s);if(l){const d=JSON.parse(l);Array.isArray(d)&&r(d)}}catch(l){console.error("[useCustomSizes] Failed to load custom sizes:",l),r([])}},[s]);const a=se(l=>{if(!(!s||typeof window>"u"))try{localStorage.setItem(s,JSON.stringify(l))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[s]),o=se((l,d,m)=>{r(u=>{const p=u.findIndex(y=>y.name===l),h={name:l,width:d,height:m};let f;return p>=0?(f=[...u],f[p]=h):f=[...u,h],a(f),f})},[a]),i=se(l=>{r(d=>{const m=d.filter(u=>u.name!==l);return a(m),m})},[a]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function It(){return c("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
|
|
41
|
-
.loader {
|
|
42
|
-
width: 48px;
|
|
43
|
-
height: 48px;
|
|
44
|
-
border: 3px solid rgba(0, 92, 117, 0.2);
|
|
45
|
-
border-radius: 50%;
|
|
46
|
-
display: inline-block;
|
|
47
|
-
position: relative;
|
|
48
|
-
box-sizing: border-box;
|
|
49
|
-
animation: rotation 1s linear infinite;
|
|
50
|
-
}
|
|
51
|
-
.loader::after {
|
|
52
|
-
content: '';
|
|
53
|
-
box-sizing: border-box;
|
|
54
|
-
position: absolute;
|
|
55
|
-
left: 50%;
|
|
56
|
-
top: 50%;
|
|
57
|
-
transform: translate(-50%, -50%);
|
|
58
|
-
width: 56px;
|
|
59
|
-
height: 56px;
|
|
60
|
-
border-radius: 50%;
|
|
61
|
-
border: 3px solid;
|
|
62
|
-
border-color: #005c75 transparent;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
@keyframes rotation {
|
|
66
|
-
0% {
|
|
67
|
-
transform: rotate(0deg);
|
|
68
|
-
}
|
|
69
|
-
100% {
|
|
70
|
-
transform: rotate(360deg);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
`})]})}const mo=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],cp=80;function un(){const[e,t]=M(0);return te(()=>{const r=setInterval(()=>{t(s=>(s+1)%mo.length)},cp);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:mo[e]})}async function dp({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw Q("Invalid parameters",{status:400});const s=await Xt(t);if(!s)throw Q("Entity not found",{status:404});const a=await Rr(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(d=>d.id===r))||null;if(!o)throw Q("Scenario not found",{status:404});const i=await Te();return Q({entity:s,scenario:o,analysis:a,projectSlug:i})}const ms=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],up=We(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=Ve(),o=Ct(),[i]=mn(),[l,d]=M(null),[m,u]=M(1440),[p,h]=M({name:"Desktop",width:1440,height:900}),[f,y]=M(!1),[g,x]=M(null),{customSizes:v,addCustomSize:b}=Yr(a),N=ne(()=>[...ms,...v],[v]),{interactiveServerUrl:C,isStarting:E,isLoading:w,showIframe:k,iframeKey:S,onIframeLoad:A}=rn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0}),{lastLine:$}=St(a,E||w),_=()=>{o(`/entity/${t.sha}`)},j=(H,W)=>{u(H);const Z=N.find(F=>F.width===H&&F.height===W);d(Z||null),h({name:(Z==null?void 0:Z.name)||"Custom",width:H,height:W})},D=H=>{d(H),u(H.width),h({name:H.name,width:H.width,height:H.height})},R=H=>{b(H,p.width,p.height??900),y(!1),h(W=>({...W,name:H}))},T=((s==null?void 0:s.scenarios)||[]).filter(H=>{var W;return!((W=H.metadata)!=null&&W.sameAsDefault)}),U=T.findIndex(H=>H.id===(r==null?void 0:r.id)),V=U+1,I=T.length,O=U>0,z=U<T.length-1,L=()=>{if(O){const H=T[U-1],W=encodeURIComponent(`/entity/${t.sha}/scenarios/${H.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${H.id}/fullscreen?from=${W}`)}},P=()=>{if(z){const H=T[U+1],W=encodeURIComponent(`/entity/${t.sha}/scenarios/${H.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${H.id}/fullscreen?from=${W}`)}},q=E||w||!k;return c("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[c("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:_r,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),c("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:L,disabled:!O,className:`${O?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:"text-gray-400 text-sm",children:[V,"/",I]}),n("button",{onClick:P,disabled:!z,className:`${z?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),c("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&c("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:_,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),c("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${ms[ms.length-1].width}px`,width:"100%"},children:n(la,{currentViewportWidth:m,currentPresetName:p.name,onDevicePresetClick:D,devicePresets:N,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),c("div",{className:"relative z-10 flex items-center gap-2",children:[c("div",{className:"relative w-28 h-5",children:[c("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(g==null?void 0:g.name)||p.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),c("select",{value:p.name,onChange:H=>{const W=N.find(Z=>Z.name===H.target.value);W&&D(W)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[N.map(H=>n("option",{value:H.name,children:H.name},H.name)),p.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:p.width,onChange:H=>{const W=parseInt(H.target.value,10);!isNaN(W)&&W>0&&j(W,p.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:p.height??900}),p.name==="Custom"&&n("button",{onClick:()=>y(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
|
|
74
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
75
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
76
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
77
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
78
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:C?c("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${p.width}px`,maxHeight:`${p.height}px`},children:[q&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(It,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),$&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(un,{}),$]})]})]})}),n("iframe",{src:C,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:A,style:{opacity:k?1:0}},S)]}):c("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(It,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),$&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(un,{}),$]})]})]})}),f&&n(Br,{width:p.width,height:p.height??900,onSave:R,onCancel:()=>y(!1)})]})}),mp=Object.freeze(Object.defineProperty({__proto__:null,default:up,loader:dp},Symbol.toStringTag,{value:"Module"}));function qi({serverUrl:e,isStarting:t,projectSlug:r,devServerError:s,onStartServer:a,notificationsEnabled:o,onToggleNotifications:i}){const[l,d]=M(null),m=xe(null);te(()=>{if(!r)return;const f=new EventSource("/api/dev-mode-events");return f.onmessage=y=>{try{const g=JSON.parse(y.data);g.type==="file-synced"&&(d(g.fileName),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{d(null)},5e3))}catch{}},()=>{f.close(),m.current&&clearTimeout(m.current)}},[r]);let u;s?u="error":t?u="starting":e?u="running":u="stopped";const p={starting:"bg-yellow-400",running:"bg-green-400",stopped:"bg-gray-400",error:"bg-red-400"},h={starting:"Starting...",running:e||"Running",stopped:"Stopped",error:"Error"};return c("div",{className:"bg-[#1e1e1e] border-t border-[#3d3d3d] h-7 flex items-center px-4 gap-4 shrink-0 text-xs font-mono",children:[c("div",{className:"flex items-center gap-2",children:[n("div",{className:`w-2 h-2 rounded-full ${p[u]}`}),c("span",{className:"text-gray-400",children:["Server:"," ",n("span",{className:"text-gray-300",children:h[u]})]}),(u==="stopped"||u==="error")&&a&&n("button",{onClick:a,className:"ml-1 px-2.5 py-0.5 bg-[#005c75] hover:bg-[#007a9a] text-white text-[11px] font-medium rounded transition-colors cursor-pointer border-none leading-tight",children:"Start Server"})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"}),l&&c(ue,{children:[c("div",{className:"flex items-center gap-1.5",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2",children:n("path",{d:"M20 6L9 17l-5-5"})}),c("span",{className:"text-green-400",children:["Synced: ",l]})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"})]}),n("div",{className:"flex-1"}),i&&n("button",{onClick:i,className:`text-[11px] rounded transition-colors cursor-pointer ${o?"text-green-400 hover:text-green-300":"text-gray-500 hover:text-gray-300"}`,title:o?"Click to turn off notifications":"Click to get notified when Claude finishes",children:o?"Notifications On":"Notifications Off"})]})}async function pp(e,t){try{const{WebglAddon:s}=await import("@xterm/addon-webgl"),a=new s;return a.onContextLoss(()=>{t==null||t("webgl","canvas",new Error("WebGL context lost")),a.dispose(),po(e).then(o=>{o||t==null||t("canvas","dom",new Error("Canvas fallback failed after context loss"))})}),e.loadAddon(a),{type:"webgl",dispose:()=>a.dispose()}}catch(s){t==null||t("webgl","canvas",s)}const r=await po(e);return r||(t==null||t("canvas","dom",new Error("Canvas addon failed")),{type:"dom",dispose:()=>{}})}async function po(e){try{const{CanvasAddon:t}=await import("@xterm/addon-canvas"),r=new t;return e.loadAddon(r),{type:"canvas",dispose:()=>r.dispose()}}catch{return null}}const hp=`
|
|
79
|
-
.xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
|
|
80
|
-
.xterm.focus, .xterm:focus { outline: none; }
|
|
81
|
-
.xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
|
|
82
|
-
.xterm .xterm-helper-textarea { padding: 0; border: 0; margin: 0; position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -5; white-space: nowrap; overflow: hidden; resize: none; }
|
|
83
|
-
.xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
|
|
84
|
-
.xterm .composition-view.active { display: block; }
|
|
85
|
-
.xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
|
|
86
|
-
.xterm .xterm-screen { position: relative; }
|
|
87
|
-
.xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
|
|
88
|
-
.xterm .xterm-scroll-area { visibility: hidden; }
|
|
89
|
-
.xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
|
|
90
|
-
.xterm.enable-mouse-events { cursor: default; }
|
|
91
|
-
.xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
|
|
92
|
-
.xterm.column-select.focus { cursor: crosshair; }
|
|
93
|
-
.xterm .xterm-accessibility:not(.debug), .xterm .xterm-message { position: absolute; left: 0; top: 0; bottom: 0; right: 0; z-index: 10; color: transparent; pointer-events: none; }
|
|
94
|
-
.xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
|
|
95
|
-
.xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
|
|
96
|
-
.xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
|
|
97
|
-
.xterm-dim { opacity: 1 !important; }
|
|
98
|
-
.xterm-underline-1 { text-decoration: underline; }
|
|
99
|
-
.xterm-underline-2 { text-decoration: double underline; }
|
|
100
|
-
.xterm-underline-3 { text-decoration: wavy underline; }
|
|
101
|
-
.xterm-underline-4 { text-decoration: dotted underline; }
|
|
102
|
-
.xterm-underline-5 { text-decoration: dashed underline; }
|
|
103
|
-
.xterm-overline { text-decoration: overline; }
|
|
104
|
-
.xterm-strikethrough { text-decoration: line-through; }
|
|
105
|
-
.xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
|
|
106
|
-
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
|
|
107
|
-
.xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
|
|
108
|
-
.xterm-decoration-top { z-index: 2; position: relative; }
|
|
109
|
-
`;function fp(){if(document.getElementById("xterm-css"))return;const e=document.createElement("style");e.id="xterm-css",e.textContent=hp,document.head.appendChild(e)}const Ki=Cc(function({entityName:t,entityType:r,entitySha:s,entityFilePath:a,scenarioName:o,scenarioDescription:i,analysisId:l,projectSlug:d,onRefreshPreview:m,onShowResults:u,onHideResults:p,editorMode:h,onIdleChange:f,notificationsEnabled:y},g){const x=xe(null),v=xe(null),b=xe(null),N=xe(null),C=xe(null),E=xe(!1),w=xe(0),k=xe(!1),S=xe(f);S.current=f;const A=xe(y);A.current=y;const $=se(()=>{var _;(_=b.current)==null||_.focus()},[]);return Sc(g,()=>({sendInput(_){const j=N.current;j&&j.readyState===WebSocket.OPEN&&(j.send(JSON.stringify({type:"input",data:_})),setTimeout(()=>{j.readyState===WebSocket.OPEN&&j.send(JSON.stringify({type:"input",data:"\r"}))},100))},focus(){var _;(_=b.current)==null||_.focus()},scrollToBottom(){var j;const _=(j=x.current)==null?void 0:j.querySelector(".xterm-viewport");_&&(_.scrollTop=_.scrollHeight)}})),te(()=>{const _=x.current;if(!_)return;let j=!1;return fp(),Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),import("@xterm/addon-web-links")]).then(([D,R,T])=>{if(j)return;const U=new D.Terminal({cursorBlink:!0,scrollback:5e3,fontSize:13,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},linkHandler:{activate(W,Z){try{const B=new URL(Z),F=B.searchParams.get("scenario");if(F&&B.pathname==="/editor"){const J=new BroadcastChannel("codeyam-editor");J.postMessage({type:"switch-scenario",scenarioId:F}),J.close();return}}catch{}window.open(Z,"_blank")}}}),V=new R.FitAddon;U.loadAddon(V),U.loadAddon(new T.WebLinksAddon),U.open(_);let I=null;pp(U,(W,Z,B)=>{console.warn(`[Terminal] Renderer fallback: ${W} → ${Z}`,B)}).then(W=>{if(j){W.dispose();return}console.log(`[Terminal] Using ${W.type} renderer`),I=W.dispose}),requestAnimationFrame(()=>{try{V.fit()}catch{}}),b.current=U,U.focus(),setTimeout(()=>U.focus(),100),setTimeout(()=>U.focus(),500);const O=window.location.protocol==="https:"?"wss:":"ws:",z=window.location.host;function L(W){const Z=new URLSearchParams;return Z.set("entityName",t),r&&Z.set("entityType",r),s&&Z.set("entitySha",s),a&&Z.set("entityFilePath",a),o&&Z.set("scenarioName",o),i&&Z.set("scenarioDescription",i),l&&Z.set("analysisId",l),d&&Z.set("projectSlug",d),h&&Z.set("editorMode","true"),W&&Z.set("reconnectId",W),`${O}//${z}/ws/terminal?${Z.toString()}`}function P(W){const Z=L(W),B=new WebSocket(Z);N.current=B,B.onopen=()=>{w.current=0,k.current=!1,B.send(JSON.stringify({type:"resize",cols:U.cols,rows:U.rows}))},B.onmessage=F=>{var J,G;try{const X=JSON.parse(F.data);if(X.type==="session-id"){C.current=X.sessionId;return}if(X.type==="refresh-preview"){m==null||m(X.path);return}if(X.type==="show-results"){u==null||u();return}if(X.type==="hide-results"){p==null||p();return}if(X.type==="claude-idle"){if(console.log("[Terminal] Received claude-idle, notifications:",A.current,"permission:",typeof Notification<"u"?Notification.permission:"N/A"),(J=S.current)==null||J.call(S,!0),A.current&&typeof Notification<"u"&&Notification.permission==="granted"){const le=new Notification("Claude is ready for you",{body:"Claude has finished and is waiting for your input.",tag:"claude-idle"});le.onclick=()=>{window.focus(),le.close()}}return}X.type==="output"&&(U.write(X.data),(G=S.current)==null||G.call(S,!1))}catch{U.write(F.data)}},B.onclose=()=>{if(E.current){U.write(`\r
|
|
110
|
-
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
111
|
-
`);return}const F=w.current;if(F<5&&C.current){const J=1e3*Math.pow(2,Math.min(F,3));w.current=F+1,U.write(`\r
|
|
112
|
-
\x1B[33m[Reconnecting...]\x1B[0m\r
|
|
113
|
-
`),setTimeout(()=>{E.current||P(C.current)},J)}else k.current?U.write(`\r
|
|
114
|
-
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
115
|
-
`):(k.current=!0,U.write(`\r
|
|
116
|
-
\x1B[33m[Starting new session...]\x1B[0m\r
|
|
117
|
-
`),C.current=null,w.current=0,P())},B.onerror=()=>{}}P(),U.onData(W=>{const Z=N.current;Z&&Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"input",data:W}))});let q=null;const H=new ResizeObserver(()=>{q&&clearTimeout(q),q=setTimeout(()=>{let W;try{W=V.proposeDimensions()}catch{return}if(!W||W.cols===U.cols&&W.rows===U.rows)return;const Z=_.querySelector(".xterm-viewport");let B,F=!0;Z&&(B=Z.scrollTop,F=Z.scrollTop+Z.clientHeight>=Z.scrollHeight-10),V.fit(),Z&&B!==void 0&&(F?Z.scrollTop=Z.scrollHeight:Z.scrollTop=B);const J=N.current;J&&J.readyState===WebSocket.OPEN&&J.send(JSON.stringify({type:"resize",cols:U.cols,rows:U.rows}))},150)});H.observe(_),v.current=()=>{var W;q&&clearTimeout(q),H.disconnect(),E.current=!0,(W=N.current)==null||W.close(),N.current=null,I==null||I(),U.dispose(),b.current=null}}),()=>{var D;j=!0,(D=v.current)==null||D.call(v),v.current=null}},[]),n("div",{ref:x,onClick:$,className:"w-full h-full",style:{padding:"4px 0 0 8px"}})});function Ge({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:a}){const[o,i]=M("loading"),[l,d]=M(!1),m=xe(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,p=()=>{i("success"),d(!0)},h=()=>{i("error"),d(!1)};return te(()=>{i("loading"),d(!1);const f=m.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?c("div",{className:"relative w-full h-full flex items-center justify-center",title:a,children:[n("img",{ref:m,src:u,alt:r,onLoad:p,onError:h,className:s||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&c("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:a,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function gp({scenarios:e,currentScenarioId:t,entitySha:r,cacheBuster:s}){const a=Ct();return e.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8",children:n("p",{className:"text-gray-500 text-sm",children:"No scenarios found"})}):n("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map(o=>{var d,m;const i=o.id===t,l=(m=(d=o.metadata)==null?void 0:d.screenshotPaths)==null?void 0:m[0];return c("button",{onClick:()=>{a(`/entity/${r}/scenarios/${o.id}/dev`)},className:`w-full text-left rounded-lg overflow-hidden border transition-colors cursor-pointer flex ${i?"border-[#005c75] bg-[#1a3a44]":"border-[#3d3d3d] bg-[#252525] hover:border-[#555]"}`,children:[n("div",{className:"w-24 h-20 shrink-0 bg-[#1a1a1a]",children:n(Ge,{screenshotPath:l,cacheBuster:s,alt:o.name,className:"w-full h-full object-cover object-top"})}),c("div",{className:"p-2.5 min-w-0 flex-1",children:[c("div",{className:"text-white text-sm font-medium truncate",children:[i&&n("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-[#005c75] mr-1.5 relative top-[-1px]"}),o.name]}),o.description&&n("div",{className:"text-gray-400 text-xs mt-1 line-clamp-2",children:o.description})]})]},o.id)})})}function en(e,t){const r=new Map;for(const s of e)r.set(t(s),s);return[...r.values()]}function vt(e){return e.replace(/[^a-zA-Z0-9_]+/g,"_")}function ca(e){return e.replace("T"," ").replace(/\.\d{3}Z$/,"")}function Ts(e,t,r){const s=e&&e.startsWith("/");return s&&t?`${t}${e}`:e&&!s?e:t||r||null}function yp(e){const{activeAnalyzedScenario:t,analyzedPreviewUrl:r,activeScenarioId:s,scenarios:a,proxyUrl:o,devServerUrl:i,zoomComponent:l}=e;if(t&&r)return r;if(t&&!r)return null;if(s){const m=a.find(u=>u.id===s);if(m!=null&&m.url){const u=o||i;return u?m.url.startsWith("/")?`${u}${m.url}`:m.url:null}}const d=o||i;if(!d)return null;if(l&&s){const m=a.find(p=>p.id===s),u=m?vt(m.name):"Default";return`${d}/__codeyam__/${l}/${u}`}return d}function Qi(e,t){if(!e||!t)return e;try{const r=new URL(e),s=t.indexOf("?");return s>=0?(r.pathname=t.slice(0,s),r.search=t.slice(s)):(r.pathname=t,r.search=""),r.href}catch{return e}}function xp(e,t){const r=t.width,s=t.height??900,a=e.width,o=e.height;return r<=a&&s<=o?1:Math.min(a/r,o/s)}async function bp({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw Q("Invalid parameters",{status:400});const s=await Xt(t);if(!s)throw Q("Entity not found",{status:404});const a=await Rr(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(d=>d.id===r))||null;if(!o)throw Q("Scenario not found",{status:404});const i=await Te();return Q({entity:s,scenario:o,analysis:a,projectSlug:i})}const ps=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],vp=We(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=Ve(),o=Ct(),i=xe(null),l=xe(null),[d,m]=M(null),[u,p]=M(1440),[h,f]=M({name:"Desktop",width:1440,height:900}),[y,g]=M(!1),[x,v]=M(null),[b,N]=M("chat"),[C,E]=M(0),[w,k]=M(null),S=se(oe=>{k(oe||null),E(pe=>pe+1)},[]),{customSizes:A,addCustomSize:$}=Yr(a),_=ne(()=>[...ps,...A],[A]),{interactiveServerUrl:j,isStarting:D,isLoading:R,showIframe:T,iframeKey:U,onIframeLoad:V}=rn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0,refreshTrigger:C}),I=ne(()=>Qi(j,w),[j,w]),{lastLine:O}=St(a,D||R),z=()=>{o(`/entity/${t.sha}`)},L=(oe,pe)=>{p(oe);const Ce=_.find(Me=>Me.width===oe&&Me.height===pe);m(Ce||null),f({name:(Ce==null?void 0:Ce.name)||"Custom",width:oe,height:pe})},P=oe=>{m(oe),p(oe.width),f({name:oe.name,width:oe.width,height:oe.height})},q=oe=>{$(oe,h.width,h.height??900),g(!1),f(pe=>({...pe,name:oe}))},H=()=>{var pe;N("chat"),(pe=l.current)==null||pe.sendInput("Create a new scenario for this entity based on the work we've just done. Create a name and description that reflects what the live preview is showing. Use the scenario data you've changed to create a new scenario in the database. If the data structure was fixed in any way you need to update that in the database as well and backfill all existing scenarios, then save to the database and capture a screenshot. Remember the database is at `.codeyam/db.sqlite3`, the scenarios table has all scenarios and the analyses table contains the scenariosDataStructure is its metadata.")},W=((s==null?void 0:s.scenarios)||[]).filter(oe=>{var pe;return!((pe=oe.metadata)!=null&&pe.sameAsDefault)}),Z=W.findIndex(oe=>oe.id===(r==null?void 0:r.id)),B=Z+1,F=W.length,J=Z>0,G=Z<W.length-1,X=()=>{if(J){const oe=W[Z-1];o(`/entity/${t.sha}/scenarios/${oe.id}/dev`)}},le=()=>{if(G){const oe=W[Z+1];o(`/entity/${t.sha}/scenarios/${oe.id}/dev`)}},ve=D||R||!T;return c("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[c("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:_r,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),c("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:X,disabled:!J,className:`${J?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:"text-gray-400 text-sm",children:[B,"/",F]}),n("button",{onClick:le,disabled:!G,className:`${G?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),c("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&c("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]}),n("span",{className:"bg-[#005c75] text-white text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider ml-2",children:"Dev Mode"})]}),n("button",{onClick:z,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close dev mode",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),c("div",{className:"flex-1 flex min-h-0",children:[c("div",{className:"flex-1 flex flex-col min-w-0",children:[c("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${ps[ps.length-1].width}px`,width:"100%"},children:n(la,{currentViewportWidth:u,currentPresetName:h.name,onDevicePresetClick:P,devicePresets:_,hideLabel:!0,onHoverChange:v,lightMode:!0})})}),c("div",{className:"relative z-10 flex items-center gap-2",children:[c("div",{className:"relative w-28 h-5",children:[c("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(x==null?void 0:x.name)||h.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),c("select",{value:h.name,onChange:oe=>{const pe=_.find(Ce=>Ce.name===oe.target.value);pe&&P(pe)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[_.map(oe=>n("option",{value:oe.name,children:oe.name},oe.name)),h.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:h.width,onChange:oe=>{const pe=parseInt(oe.target.value,10);!isNaN(pe)&&pe>0&&L(pe,h.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"x"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:h.height??900}),h.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
|
|
118
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
119
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
120
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
121
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
122
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:j?c("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${h.width}px`,maxHeight:`${h.height}px`},children:[ve&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(It,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the dev server to be ready"}),O&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(un,{}),O]})]})]})}),n("iframe",{ref:i,src:I||j,className:"w-full h-full border-none",title:`Dev mode preview: ${r==null?void 0:r.name}`,onLoad:V,style:{opacity:T?1:0}},U)]}):c("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(It,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Dev Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment with live preview"}),O&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(un,{}),O]})]})]})})]}),c("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-l border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden",children:[c("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[c("div",{className:"flex items-center gap-0",children:[c("button",{onClick:()=>N("chat"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${b==="chat"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Chat",b==="chat"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),c("button",{onClick:()=>N("scenarios"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${b==="scenarios"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Scenarios",b==="scenarios"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),b==="chat"&&n("button",{onClick:H,disabled:!j,className:"px-3 py-1 text-[11px] font-medium rounded bg-[#005c75] text-white hover:bg-[#004a5c] transition-colors disabled:bg-gray-600 disabled:text-gray-400 disabled:cursor-not-allowed cursor-pointer",children:"Save Scenario"})]}),n("div",{style:{display:b==="chat"?"flex":"none"},className:"flex-1 overflow-hidden flex-col",children:n(Ki,{ref:l,entityName:t.name,entityType:t.entityType,entitySha:t.sha,entityFilePath:t.filePath||t.localFilePath,scenarioName:r==null?void 0:r.name,scenarioDescription:r==null?void 0:r.description,analysisId:s==null?void 0:s.id,projectSlug:a,onRefreshPreview:S})}),b==="scenarios"&&n(gp,{scenarios:W,currentScenarioId:r==null?void 0:r.id,entitySha:t.sha,cacheBuster:0})]})]}),n(qi,{serverUrl:j,isStarting:D,projectSlug:a}),y&&n(Br,{width:h.width,height:h.height??900,onSave:q,onCancel:()=>g(!1)})]})}),wp=Object.freeze(Object.defineProperty({__proto__:null,default:vp,loader:bp},Symbol.toStringTag,{value:"Module"}));async function Np({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{url:r,filename:s,viewportWidth:a,viewportHeight:o}=t;if(!r||!s)return new Response(JSON.stringify({error:"url and filename are required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=process.env.CODEYAM_ROOT_PATH||process.cwd(),l=Y.join(i,".codeyam","journal","screenshots");await be.mkdir(l,{recursive:!0});const d=s.replace(/[^a-zA-Z0-9_\-T]/g,"_"),m=Y.join(l,`${d}.png`),u=Y.dirname(new URL(import.meta.url).pathname);let p=u;for(let v=0;v<5;v++){const b=Y.dirname(p);if(Y.basename(b)==="webserver"||Y.basename(p)==="webserver"){p=Y.basename(p)==="webserver"?p:b;break}p=b}const h=[Y.join(p,"scripts","journalCapture.ts"),Y.join(p,"app","lib","journalCapture.ts"),Y.join(i,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),Y.resolve(u,"..","lib","journalCapture.ts")];let f="";for(const v of h)try{await be.access(v),f=v;break}catch{}f||(console.warn(`[editor-journal-screenshot] journalCapture.ts not found in any of: ${h.join(", ")}`),f=h[0]);const y=JSON.stringify({url:r,outputPath:m,viewportWidth:a,viewportHeight:o}),g=await new Promise(v=>{const b=Lt("npx",["tsx",f,y],{cwd:i,env:{...process.env}});let N="",C="";b.stdout.on("data",E=>{N+=E.toString()}),b.stderr.on("data",E=>{C+=E.toString()}),b.on("close",E=>{v(E===0?{success:!0,output:N}:{success:!1,output:N,error:C||`Process exited with code ${E}`})}),b.on("error",E=>{v({success:!1,output:"",error:E.message})})});if(!g.success)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:g.error}),{status:500,headers:{"Content-Type":"application/json"}});const x=`screenshots/${d}.png`;return new Response(JSON.stringify({success:!0,path:x}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-screenshot] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Cp=Object.freeze(Object.defineProperty({__proto__:null,action:Np},Symbol.toStringTag,{value:"Module"})),Zi=Js({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),da=()=>{const e=Er(Zi);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Ur=({children:e})=>{const[t,r]=M({height:720,width:1200}),[s,a]=M(1),[o,i]=M(1200),l=xe(null),d=se(({height:p,width:h})=>{r(f=>({height:p??f.height,width:h??f.width}))},[]),m=se(p=>{a(p)},[]),u=se(p=>{i(p)},[]);return n(Zi.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:l,scale:s,updateScale:m,maxWidth:o,updateMaxWidth:u},children:e})},Sp=typeof window<"u";function kp(){const[e,t]=M(null);return te(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const Ep=1200,Ap=720,ho=30,Pp=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:s=1440,defaultHeight:a=900,onDataOverride:o,onIframeLoad:i,onScaleChange:l,onDimensionChange:d})=>{const m=kp(),[u,p]=M(!1),[h,f]=M(!1),[y,g]=M(Ep),[x,v]=M(Ap),[b,N]=M(null),[C,E]=M(null),{dimensions:w,updateDimensions:k,iframeRef:S,updateScale:A,updateMaxWidth:$}=da(),_=ne(()=>Math.min(1,y/w.width),[y,w.width]),j=C!==null?C:_;te(()=>{u||(A(j),l==null||l(j))},[j,A,l,u]),te(()=>{$(y)},[y,$]);const D=se(()=>{p(!0),E(_)},[_]),R=se(()=>{p(!1),E(null)},[]),T=se((z,L)=>{const P=C!==null?C:1,q=Math.round(L.size.width/P);k({width:q}),d==null||d(q,w.height)},[k,C,d,w.height]),U=se(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);te(()=>{const z=L=>{if(L.data.type==="codeyam-resize"){if(t&&L.data.name!==t||w.height===L.data.height||L.data.height===0)return;k({height:L.data.height})}};return window.addEventListener("message",z),()=>{window.removeEventListener("message",z)}},[S,t,s,w,k]),te(()=>{h&&o&&o(S.current)},[h,o,S]),te(()=>{if(!t)return;const z=setInterval(()=>{var L,P;(P=(L=S==null?void 0:S.current)==null?void 0:L.contentWindow)==null||P.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(z)},[t,S]),te(()=>{const z=()=>{const L=document.getElementById("scenario-container");if(!L)return;const P=L.getBoundingClientRect(),q=L.clientWidth-ho*2,H=window.innerHeight-P.top-ho*2,W=Math.max(H,400),Z=window.innerHeight-P.top;g(q),v(W),N(Z)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),te(()=>{k({width:s,height:a})},[s,a,k]);const V=ne(()=>w.width*j,[w.width,j]),I=ne(()=>{const z=w.height,L=z*j;return z&&z!==720&&z!==900&&L<x?L:x},[w.height,x,j]),O=se(()=>{window.history.back()},[]);return!Sp||!m?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):c("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:b?{height:`${b}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
|
|
123
|
-
.react-resizable-handle-e {
|
|
124
|
-
display: flex !important;
|
|
125
|
-
align-items: center !important;
|
|
126
|
-
justify-content: center !important;
|
|
127
|
-
width: 6px !important;
|
|
128
|
-
height: 48px !important;
|
|
129
|
-
right: -8px !important;
|
|
130
|
-
top: 50% !important;
|
|
131
|
-
transform: translateY(-50%) !important;
|
|
132
|
-
cursor: ew-resize !important;
|
|
133
|
-
background: #d1d5db !important;
|
|
134
|
-
border-radius: 3px !important;
|
|
135
|
-
opacity: 0 !important;
|
|
136
|
-
transition: all 0.2s ease !important;
|
|
137
|
-
}
|
|
138
|
-
.react-resizable-handle-e:hover {
|
|
139
|
-
opacity: 0.8 !important;
|
|
140
|
-
background: #9ca3af !important;
|
|
141
|
-
}
|
|
142
|
-
.react-resizable:hover .react-resizable-handle-e {
|
|
143
|
-
opacity: 0.4 !important;
|
|
144
|
-
}
|
|
145
|
-
`}),n(m,{width:V,height:I,minConstraints:[300,200],maxConstraints:[y,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:D,onResizeStop:R,onResize:T,children:n("div",{className:"overflow-auto",style:{width:`${V}px`,height:`${I}px`},children:n("div",{style:{width:`${w.width}px`,height:`${w.height}px`,transform:`scale(${j})`,transformOrigin:"top left"},children:r?n("iframe",{ref:S,className:"w-full h-full rounded-lg",src:r,onLoad:U,sandbox:"allow-scripts allow-same-origin"}):c("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:O,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function Mp({presets:e,customSizes:t,currentWidth:r,currentHeight:s,scale:a,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:l,className:d=""}){const[m,u]=M(!1),[p,h]=M(String(r)),[f,y]=M(String(s)),[g,x]=M(!1),[v,b]=M(!1),N=xe(null);te(()=>{g||h(String(r))},[r,g]),te(()=>{v||y(String(s))},[s,v]),te(()=>{const j=D=>{N.current&&!N.current.contains(D.target)&&u(!1)};return document.addEventListener("mousedown",j),()=>document.removeEventListener("mousedown",j)},[]);const C=ne(()=>{const j=e.find(R=>R.width===r&&R.height===s);if(j)return j.name;const D=t.find(R=>R.width===r&&R.height===s);return D?D.name:"Custom"},[e,t,r,s]),E=C==="Custom",w=j=>{o(j.width,j.height),u(!1)},k=j=>{const D=j.target.value;h(D);const R=parseInt(D,10);!isNaN(R)&&R>0&&o(R,s)},S=j=>{const D=j.target.value;y(D);const R=parseInt(D,10);!isNaN(R)&&R>0&&o(r,R)},A=()=>{x(!1);const j=parseInt(p,10);(isNaN(j)||j<=0)&&h(String(r))},$=()=>{b(!1);const j=parseInt(f,10);(isNaN(j)||j<=0)&&y(String(s))},_=j=>{(j.key==="Enter"||j.key==="Escape")&&j.target.blur()};return c("div",{className:`flex items-center gap-3 ${d}`,children:[c("div",{className:"relative",ref:N,children:[c("button",{onClick:()=>u(!m),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:C}),n("svg",{className:`w-4 h-4 transition-transform ${m?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),m&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:c("div",{className:"py-1",children:[e.length>0&&c(ue,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(j=>c("button",{onClick:()=>w(j),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${C===j.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:j.name}),c("span",{className:"text-xs text-gray-500",children:[j.width," x ",j.height]})]},j.name))]}),t.length>0&&c(ue,{children:[n("div",{className:"border-t border-gray-100 my-1"}),n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...t].sort((j,D)=>j.width-D.width).map(j=>c("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${C===j.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[c("button",{onClick:()=>w(j),className:"flex-1 text-left px-3 py-2 text-sm flex justify-between items-center gap-4 whitespace-nowrap cursor-pointer",children:[n("span",{children:j.name}),c("span",{className:"text-xs text-gray-500",children:[j.width," x ",j.height]})]}),l&&n("button",{onClick:D=>{D.stopPropagation(),C===j.name&&e.length>0&&o(e[0].width,e[0].height),l(j.name)},className:"p-1.5 mr-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded cursor-pointer transition-colors",title:"Remove custom size",children:n("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},j.name))]})]})})]}),c("div",{className:"flex items-center gap-1 text-sm",children:[c("div",{className:"flex items-center",children:[n("input",{type:"text",value:p,onChange:k,onFocus:()=>x(!0),onBlur:A,onKeyDown:_,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),c("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:S,onFocus:()=>b(!0),onBlur:$,onKeyDown:_,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),a!==void 0&&a<1&&c("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(a*100),"%)"]})]}),E&&n("button",{onClick:i,className:"px-3 py-1.5 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors",children:"Save Custom Size"})]})}function hs(e,t,r){if(Array.isArray(e)){if(!isNaN(parseInt(t)))return e[parseInt(t)];for(const s of e)if(s.name===t||s.title===t||s.id===t)return s}return e[t]}function $s(e){return e&&(typeof e=="object"||Array.isArray(e))}function _p(e){return Array.isArray(e)?e.length:void 0}function jp(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((s,a)=>a.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((a,o)=>{const i=$s(t[a]),l=$s(t[o]);return i&&!l?1:!i&&l?-1:a.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((a,o)=>a.localeCompare(o))}}function Tp({scenarioFormData:e,handleInputChange:t}){return c("div",{className:"p-3 flex flex-col gap-3",children:[c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),c("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function $p({path:e,namedPath:t,isArray:r,count:s,onClick:a}){const o=se(()=>{a&&a(e)},[a,e]);return c("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),c("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],s!==void 0&&` (${s})`]})]}),c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var Xi=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Xi||{});const Rp=({name:e,value:t,options:r,onChange:s})=>{const a=se(o=>{s({target:{name:e,value:o.target.value}})},[e,s]);return n("select",{name:e,value:t,onChange:a,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((o,i)=>n("option",{value:o.trim(),children:o.trim()},i))})},Ip=({name:e,value:t,onChange:r})=>{const s=se(a=>{const o=a.target.checked;r({target:{name:e,value:o}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:s,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
|
|
146
|
-
bg-gray-300 checked:bg-blue-600
|
|
147
|
-
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
148
|
-
after:bg-white after:rounded-full after:transition-transform
|
|
149
|
-
checked:after:translate-x-4`})})};function Dp({dataType:e,path:t,value:r,onChange:s}){const a=ne(()=>t[t.length-1],[t]),o=ne(()=>t.join("-"),[t]),i=se(d=>{s(t,d.target.value)},[s,t]),l=se(d=>{s(t,d.target.value)},[s,t]);return c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:a==="~~codeyam-code~~"?"Dynamic Field":a}),e.includes("|")?n(Rp,{name:o,value:r,options:e.split("|"),onChange:i}):e===Xi.BOOLEAN?n(Ip,{name:o,value:r??!1,onChange:l}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function Lp({analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:a}){const[o,i]=M(!1),[l,d]=M(""),m=se(async()=>{if(!a){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const p=e.scenarios.find(x=>x.name===t);if(!p)throw new Error("Scenario not found");const h=e.scenarios.find(x=>x.name===jr),f=await a(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const y=(x,v)=>{const b=Object.assign({},x);return g(x)&&g(v)&&Object.keys(v).forEach(N=>{g(v[N])?N in x?b[N]=y(x[N],v[N]):Object.assign(b,{[N]:v[N]}):Object.assign(b,{[N]:v[N]})}),b},g=x=>x&&typeof x=="object"&&!Array.isArray(x);p.metadata.data=y(y((h==null?void 0:h.metadata.data)||{},p.metadata.data),f.data||{}),s(p),i(!1),d("")}catch(p){console.error("Error generating AI data:",p),i(!1)}},[e,l,r,t,s,a]),u=se(p=>{d(p.target.value)},[]);return c("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:l}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void m(),children:o?c(ue,{children:[c("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function Op({namedPath:e,path:t,last:r,onClick:s}){const a=se(()=>s(r?t.slice(0,-1):t),[r,t,s]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:a,children:e[e.length-1]})}function Fp({dataItem:e,onClick:t}){const r=se(()=>t([]),[t]),s=ne(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return c("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&c("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(s).map((a,o)=>c("div",{className:"flex items-center gap-1",children:[n(Op,{namedPath:e.namedPath.slice(0,o+s+1),path:e.path.slice(0,o+s+1),last:o+s===e.namedPath.length-1,onClick:t}),o+s<e.namedPath.length-1&&n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${a}-${o+s}`))]})}function fo({analysis:e,scenarioName:t,dataItem:r,onClick:s,onChange:a,onAIResult:o,onGenerateData:i,saveFeedback:l}){const d=ne(()=>r.data,[r]),m=ne(()=>jp(r),[r]);return c("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Fp,{dataItem:r,onClick:s}),c("div",{className:"flex flex-col gap-3",children:[n(Lp,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),m==null?void 0:m.map((u,p)=>{var f;if($s(d[u])){let y=u;isNaN(Number(u))||(y=d[u].name??d[u].title??d[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const g=[...r.path,u],x=[...r.namedPath,y];return n($p,{path:g,namedPath:x,isArray:Array.isArray(d),count:_p(d[u]),onClick:s},`data-${u}-${p}`)}if(u==="id")return null;const h=[...r.path,u];return n(Dp,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:h,value:d[u],onChange:a},`InputField-${h.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),c("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:l!=null&&l.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(l==null?void 0:l.message)&&!(l!=null&&l.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${l.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:l.message})]})}function go({title:e,children:t,defaultOpen:r=!1,borderT:s=!1,borderB:a=!1}){const[o,i]=M(r),l=[];return s&&l.push("border-t"),a&&l.push("border-b"),c("div",{className:`${l.join(" ")} border-gray-300`,children:[c("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const zp=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:s,shouldCreateNewScenario:a,onSave:o,onNavigate:i,iframeRef:l,onGenerateData:d,saveFeedback:m})=>{const u=se((k,S)=>{const A=Object.assign({},k),$=_=>_&&typeof _=="object"&&!Array.isArray(_);return $(k)&&$(S)&&Object.keys(S).forEach(_=>{$(S[_])?_ in k?A[_]=u(k[_],S[_]):Object.assign(A,{[_]:S[_]}):Object.assign(A,{[_]:S[_]})}),A},[]),[p,h]=M({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,y]=M(null),g=ne(()=>({...p.data}),[p]),x=ne(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),v=ne(()=>{const k={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(k).reduce((S,A)=>{if(A.includes(".")){const[$,_]=A.split(".");S[$]||(S[$]={}),S[$][_]=k[A]}else S[A]=k[A];return S},{})},[r]),b=se(async k=>{k.preventDefault();const S=k.target.querySelector('input[name="recapture"]'),A=(S==null?void 0:S.value)==="true",$={mockData:p.data.mockData??{},argumentsData:p.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:p.name,shouldRecapture:A,dataToSave:$,rawFormData:p.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify($,null,2).substring(0,1e3));const _=s==null?void 0:s.scenarios.map(j=>!a&&j.name===e.name?{...j,name:p.name,description:p.description,metadata:{...j.metadata,data:$}}:j);a&&_.push({name:p.name,description:p.description,metadata:{data:$,interactiveExamplePath:s==null?void 0:s.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",_),o&&await o(_,{recapture:A}),i&&i(p.name)},[s,e.name,p,g,a,o,i]),N=se(k=>{h(S=>({...S,[k.target.name]:k.target.value}))},[]),C=se(k=>{y(S=>{if(!S)return null;for(const A of[{arguments:k.metadata.data.argumentsData},k.metadata.data.mockData]){let $=A;for(const _ of S.path)if($=hs($,_),!$)break;$&&(S.data=$)}return{...S}}),h({name:k.name,description:k.description,data:k.metadata.data})},[]),E=se((k,S)=>{h(A=>{for(const $ of[{"Function Arguments":A.data.argumentsData},{"Retrieved Data":A.data.mockData}]){let _=$;for(const j of k.slice(0,-1))if(_=hs(_,j),!_)break;if(_){const j=_[k[k.length-1]];y(D=>D?(D.namedPath[D.namedPath.length-1]===j&&(D.namedPath[D.namedPath.length-1]=S.toString()),D.data[k[k.length-1]]=S,{...D}):null),_[k[k.length-1]]=S}}return{...A}})},[]),w=se(k=>{var _,j,D;if(k.length===0){y(null);return}let S=x;const A=[];let $=v;for(const R of k){if(A.push(isNaN(parseInt(R))?R:((_=S[R])==null?void 0:_.name)??((j=S[R])==null?void 0:j.title)??((D=S[R])==null?void 0:D.id)??R),S=hs(S,R),!S){console.log("Data not found",S,R),y(null);return}Array.isArray($)?$=$[0]:$=$[R]}y({path:k,namedPath:A,data:S,structure:$})},[x,v]);return te(()=>{const k=S=>{var A;S.data.type==="codeyam-log"&&((A=S.data.data)!=null&&A.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",S.data.data)};return window.addEventListener("message",k),()=>window.removeEventListener("message",k)},[]),te(()=>{var k;if((k=l==null?void 0:l.current)!=null&&k.contentWindow){const S={arguments:g.argumentsData??[],...g.mockData??{}},A={type:"codeyam-override-data",name:e.name,data:JSON.stringify(S)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:A.type,name:A.name,dataPreview:JSON.stringify(S).substring(0,200)+"...",fullData:S}),l.current.contentWindow.postMessage(A,"*")}},[g,e,l]),n("form",{method:"post",onSubmit:k=>void b(k),children:f?n(fo,{analysis:s,scenarioName:p.name,dataItem:f,onClick:w,onChange:E,onAIResult:C,onGenerateData:d,saveFeedback:m}):c(ue,{children:[n(go,{title:"Edit Name and Description",borderT:!0,children:n(Tp,{scenarioFormData:p,handleInputChange:N})}),e.metadata.data&&n(go,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(fo,{analysis:s,scenarioName:p.name,dataItem:{path:[],namedPath:[],data:x,structure:v},onClick:w,onChange:E,onAIResult:C,onGenerateData:d,saveFeedback:m})})]})})};function Wr({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:s,isLoading:a,showIframe:o,iframeKey:i,onIframeLoad:l,onScaleChange:d,onDimensionChange:m,projectSlug:u,defaultWidth:p=1440,defaultHeight:h=900,retryCount:f=0}){const{lastLine:y}=St(u??null,s||a);return r?c("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(Pp,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:p,defaultHeight:h,onIframeLoad:l,onScaleChange:d,onDimensionChange:m},i)}),!o&&(s||a)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(It,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(un,{}),y]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:c("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(It,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(un,{}),y]})]})]})})}const Bp=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Yp({params:e}){var d,m;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const s=await $r(t,!0),a=s&&s.length>0?s[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(d=a.scenarios)==null?void 0:d.find(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(m=a.scenarios)==null?void 0:m.find(u=>u.name===jr),l=await Te();return Q({analysis:a,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:l})}function Up(){var R,T,U;const e=Ve(),t=e.analysis,r=e.scenario,s=e.defaultScenario,a=e.entitySha,o=e.projectSlug,i=Ct(),{iframeRef:l}=da(),[d,m]=M(!1),[u,p]=M(null),[h,f]=M(null),[y,g]=M(!1),[x,v]=M(!1),[b,N]=M(null),{interactiveServerUrl:C,isStarting:E,isLoading:w,showIframe:k,iframeKey:S,onIframeLoad:A}=rn({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),$=se(async(V,I)=>{m(!0),p(null),f(null),console.log("[EditScenario] Starting save with options:",I),console.log("[EditScenario] Scenarios to save:",V);try{const O={analysis:t,scenarios:V};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:V.length,scenarioNames:V.map(P=>P.name)});const z=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)}),L=await z.json();if(console.log("[EditScenario] API response:",L),!z.ok||!L.success)throw new Error(L.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),I!=null&&I.recapture&&r.id&&C){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:C}),p("Changes saved. Capturing screenshot...");const P={serverUrl:C,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",P);const q=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});console.log("[EditScenario] Capture response status:",q.status);const H=await q.json();if(console.log("[EditScenario] Capture response body:",H),!q.ok||!H.success)throw console.error("[EditScenario] Capture failed:",H),new Error(H.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",H),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),p("Recapture successful")}else if(I!=null&&I.recapture&&!C){console.log("[EditScenario] No running server, using queued recapture");const P=new FormData;P.append("analysisId",t.id||""),P.append("scenarioId",r.id||"");const q=await fetch("/api/recapture-scenario",{method:"POST",body:P}),H=await q.json();if(!q.ok||!H.success)throw new Error(H.error||"Failed to trigger recapture");console.log("Recapture queued:",H),f(H.jobId),p("Changes saved. Screenshot recapture queued.")}else p("Changes saved successfully.")}catch(O){console.error("Error saving scenarios:",O),p(`Error: ${O instanceof Error?O.message:String(O)}`)}finally{m(!1)}},[t,r.id,C]),_=se(V=>{},[]),j=se(async(V,I)=>{var L;const O=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:V,existingScenarios:t.scenarios,scenariosDataStructure:(L=t.metadata)==null?void 0:L.scenariosDataStructure,editingMockName:r.name,editingMockData:I==null?void 0:I.data})}),z=await O.json();if(!O.ok||!z.success)throw new Error(z.error||"Failed to generate scenario data");return z.data},[t,r.name]),D=se(async()=>{var V;if(!r.id){N("Cannot delete scenario without ID");return}g(!0),N(null);try{const I=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((V=r.metadata)==null?void 0:V.screenshotPaths)||[]})}),O=await I.json();if(!I.ok||!O.success)throw new Error(O.error||"Failed to delete scenario");i(`/entity/${a}`)}catch(I){console.error("[EditScenario] Error deleting scenario:",I),N(I instanceof Error?I.message:"Failed to delete scenario"),v(!1)}finally{g(!1)}},[r.id,(R=r.metadata)==null?void 0:R.screenshotPaths,a,i]);return c("div",{className:"h-screen bg-gray-50 flex flex-col",children:[c("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:c(de,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(T=t.entity)==null?void 0:T.name]})}),c("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[c("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(zp,{currentScenario:r,defaultScenario:s,dataStructure:((U=t.metadata)==null?void 0:U.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:$,onNavigate:_,iframeRef:l,onGenerateData:j,saveFeedback:{isSaving:d,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(de,{to:`/entity/${a}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),c("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?c("div",{className:"space-y-3",children:[c("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void D(),disabled:y,className:"flex-1 px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors",children:y?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>v(!1),disabled:y,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md text-sm font-medium hover:bg-gray-200 disabled:opacity-50 transition-colors",children:"Cancel"})]})]}):n("button",{onClick:()=>v(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),b&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:b})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Wr,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:C,isStarting:E,isLoading:w,showIframe:k,iframeKey:S,onIframeLoad:A,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Wp=We(function(){return n(Ur,{children:n(Up,{})})}),Jp=Object.freeze(Object.defineProperty({__proto__:null,default:Wp,loader:Yp,meta:Bp},Symbol.toStringTag,{value:"Module"}));function Hp(e){return Fn.createHash("sha256").update(JSON.stringify(e)).digest("hex")}function Vp(e){const t=e.match(/^(GET|POST|PUT|DELETE|PATCH)\s+(\/\S+)$/);return t?{method:t[1],pathPattern:t[2]}:{method:null,pathPattern:e}}function Gp(e){const t=[],r=e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(s,a)=>(t.push(a),"([^/]+)"));return{regex:new RegExp(`^${r}$`),paramNames:t}}function qp(e,t){if(t.includes(e))return e;const r=e.lastIndexOf("/");if(r>0){const s=e.substring(0,r);if(t.includes(s))return s}return null}function Kp(){let e=[],t={},r=null,s=null,a=!1,o=null;function i(m){const u=[],p=m.routes;if(p&&typeof p=="object")for(const[h,f]of Object.entries(p)){const{method:y,pathPattern:g}=Vp(h),{regex:x,paramNames:v}=Gp(g),b=typeof f=="object"&&f!==null?f:{body:f};u.push({method:y,pathPattern:g,pathRegex:x,paramNames:v,response:{body:b.body,status:typeof b.status=="number"?b.status:200}})}return u}function l(m){const u=m.state;if(u&&typeof u=="object"){a=!0,t={};for(const[p,h]of Object.entries(u))t[p]=Array.isArray(h)?JSON.parse(JSON.stringify(h)):[];r=JSON.stringify(u)}else a=!1,t={},r=null}return{loadScenario(m){const u=Hp(m);s&&u===s||(s=u,o=m,e=i(m),l(m))},matchRequest(m,u,p){if(!o&&e.length===0&&!a)return null;const h=Object.keys(t);if(a){const y=qp(u,h);if(y&&m==="GET"&&y===u)return{body:t[y],status:200};if(y){const g=d(m,u);if(m==="POST"&&y===u&&g){const x=t[y],v=typeof p=="object"&&p!==null?{...p}:{};if(!("id"in v)){const b=x.reduce((N,C)=>{const E=typeof C.id=="number"?C.id:0;return Math.max(N,E)},0);v.id=b+1}return x.push(v),{body:v,status:g.response.status}}if(m==="DELETE"&&g&&g.params){const x=g.params.id,v=t[y],b=v.findIndex(N=>String(N.id)===String(x));return b===-1?{body:{error:"Not found"},status:404}:(v.splice(b,1),{body:null,status:g.response.status})}if(m==="PUT"&&g&&g.params){const x=g.params.id,v=t[y],b=v.findIndex(C=>String(C.id)===String(x));if(b===-1)return{body:{error:"Not found"},status:404};const N=typeof p=="object"&&p!==null?{...p}:v[b];return v[b]=N,{body:N,status:g.response.status}}}}const f=d(m,u);if(f)return{body:f.response.body??null,status:f.response.status,params:f.params};if(o&&m==="GET"){const y=u.match(/^\/api\/(.+)$/);if(y){const g=y[1];if(g in o&&g!=="routes"&&g!=="state")return{body:o[g],status:200}}}return null},resetState(){if(r){const m=JSON.parse(r);t={};for(const[u,p]of Object.entries(m))t[u]=Array.isArray(p)?JSON.parse(JSON.stringify(p)):[]}},getState(){return{...t}}};function d(m,u){for(const p of e)if(p.method!==null&&p.method===m&&p.paramNames.length===0&&p.pathRegex.exec(u))return{response:p.response};if(m==="GET"){for(const p of e)if(p.method===null&&p.paramNames.length===0&&p.pathRegex.exec(u))return{response:p.response}}for(const p of e)if(p.paramNames.length>0){if((p.method??"GET")!==m)continue;const f=p.pathRegex.exec(u);if(f){const y={};for(let g=0;g<p.paramNames.length;g++)y[p.paramNames[g]]=f[g+1];return{response:p.response,params:y}}}return null}}const el="__codeyam_editor_proxy__",Qp=500;let bt={data:null,timestamp:0};const yo=10*1024*1024;function tl(){return globalThis[el]??null}function nl(e){globalThis[el]=e}function rl(){const e="__codeyam_mock_state__";return globalThis[e]||(globalThis[e]=Kp()),globalThis[e]}function sl(){const e=tl();return e?`http://localhost:${e.port}`:null}function Zp(){const e=Date.now();if(bt.data!==null&&e-bt.timestamp<Qp)return bt.data;const t=me()||process.env.CODEYAM_ROOT_PATH||process.cwd(),r=ee.join(t,".codeyam","active-scenario.json");try{if(!Ne.existsSync(r))return bt={data:null,timestamp:e},null;const a=JSON.parse(Ne.readFileSync(r,"utf-8")).scenarioId;if(!a)return bt={data:null,timestamp:e},null;const o=ee.join(t,".codeyam","editor-scenarios",`${a}.json`);if(!Ne.existsSync(o))return console.log(`[editorProxy] Scenario data file not found: ${o}`),bt={data:null,timestamp:e},null;const i=JSON.parse(Ne.readFileSync(o,"utf-8"));return bt={data:i,timestamp:e},rl().loadScenario(i),i}catch(s){return console.warn("[editorProxy] Error reading scenario data:",s),bt={data:null,timestamp:e},null}}function Xp(e){return new Promise(t=>{const r=[];let s=0;e.on("data",a=>{s+=a.length,s>yo?(t(null),e.resume()):r.push(a)}),e.on("end",()=>{s>yo||t(Buffer.concat(r))}),e.on("error",()=>{t(null)})})}function xo(e,t,r,s){const a=new URL(r),o={...e.headers,host:`${a.hostname}:${a.port}`};s&&(o["content-length"]=String(s.length));const i={hostname:a.hostname,port:a.port,path:e.url,method:e.method,headers:o},l=Zs.request(i,d=>{t.writeHead(d.statusCode||200,d.headers),d.pipe(t,{end:!0})});l.on("error",d=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${d.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),s&&s.length>0?l.end(s):l.end()}function eh(e,t,r){const s=new URL(r),a={hostname:s.hostname,port:s.port,path:e.url,method:e.method,headers:{...e.headers,host:`${s.hostname}:${s.port}`}},o=Zs.request(a,i=>{t.writeHead(i.statusCode||200,i.headers),i.pipe(t,{end:!0})});o.on("error",i=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${i.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),e.pipe(o,{end:!0})}function th(e,t,r,s){const a=new URL(s),o=parseInt(a.port,10)||80;console.log(`[editorProxy] WebSocket upgrade: ${e.url} → ${a.hostname}:${o}`);const i=yd.connect(o,a.hostname,()=>{const l=`${e.method} ${e.url} HTTP/${e.httpVersion}\r
|
|
150
|
-
`,d=Object.entries(e.headers).filter(([,m])=>m!=null).map(([m,u])=>`${m}: ${Array.isArray(u)?u.join(", "):u}`).join(`\r
|
|
151
|
-
`);i.write(l+d+`\r
|
|
152
|
-
\r
|
|
153
|
-
`),r.length>0&&i.write(r),i.pipe(t,{end:!0}),t.pipe(i,{end:!0})});i.on("error",l=>{console.warn(`[editorProxy] WebSocket proxy error: ${l.message}`),t.destroy()}),t.on("error",()=>{i.destroy()})}function nh(e,t){const r=me()||process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","proxy-config.json");try{Ne.mkdirSync(ee.dirname(s),{recursive:!0}),Ne.writeFileSync(s,JSON.stringify({proxyUrl:`http://localhost:${e}`,devServerUrl:t}),"utf-8"),console.log(`[editorProxy] Wrote proxy config to ${s}`)}catch(a){console.warn("[editorProxy] Failed to write proxy-config.json:",a)}}function rh(){const e=me()||process.env.CODEYAM_ROOT_PATH||process.cwd(),t=ee.join(e,".codeyam","proxy-config.json");try{Ne.existsSync(t)&&Ne.unlinkSync(t)}catch{}}async function al(e){await ol();const{targetUrl:t}=e;let r=e.port;console.log(`[editorProxy] Starting proxy (requested port ${r}, target ${t})`);const s=rl(),a=Zs.createServer((i,l)=>{(async()=>{const m=new URL(i.url||"/",`http://localhost:${r}`).pathname,u=i.method||"GET";if(u==="OPTIONS"){l.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Max-Age":"86400"}),l.end();return}if(Zp(),u==="POST"||u==="PUT"||u==="DELETE"||u==="PATCH"){const f=await Xp(i);if(f===null){xo(i,l,t,null);return}let y;if(f.length>0)try{y=JSON.parse(f.toString("utf-8"))}catch{}const g=s.matchRequest(u,m,y);if(g){console.log(`[editorProxy] Intercepted ${u} ${m} → mock response (status ${g.status})`),l.writeHead(g.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data"}),l.end(g.body!=null?JSON.stringify(g.body):"");return}xo(i,l,t,f);return}const h=s.matchRequest(u,m);if(h){console.log(`[editorProxy] Intercepted ${u} ${m} → mock response (status ${h.status})`),l.writeHead(h.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data"}),l.end(h.body!=null?JSON.stringify(h.body):"");return}eh(i,l,t)})()});a.on("upgrade",(i,l,d)=>{th(i,l,d,t)});const o=10;for(let i=0;i<o;i++){const l=r+i;try{return await new Promise((m,u)=>{a.once("error",u),a.listen(l,"0.0.0.0",()=>{a.removeListener("error",u),m()})}),r=l,nl({server:a,port:r,targetUrl:t}),nh(r,t),console.log(`[editorProxy] Proxy started on port ${r}, forwarding to ${t}`),{port:r}}catch(d){if((d==null?void 0:d.code)==="EADDRINUSE"&&i<o-1){console.log(`[editorProxy] Port ${l} in use, trying ${l+1}`);continue}return console.error("[editorProxy] Failed to start proxy:",d),null}}return null}async function ol(){const e=tl();if(e)return console.log(`[editorProxy] Stopping proxy on port ${e.port}`),rh(),new Promise(t=>{e.server.close(()=>{console.log("[editorProxy] Proxy stopped"),t()}),nl(null),setTimeout(t,2e3)})}function sr(){bt={data:null,timestamp:0}}async function il(){const e=sl();if(e)return console.log(`[editorProxy] Proxy already running at ${e}`),e;const t=globalThis.__codeyam_editor_dev_server__;if(!t||t.status!=="running"||!t.url)return console.log("[editorProxy] Cannot start proxy — dev server not running"),null;const r=parseInt(process.env.CODEYAM_PORT||"3111",10);console.log(`[editorProxy] Proxy not running, starting on-demand (port ${r+1}, target ${t.url})`);const s=await al({port:r+1,targetUrl:t.url});if(s){const a=`http://localhost:${s.port}`;return console.log(`[editorProxy] On-demand proxy started at ${a}`),a}return console.error("[editorProxy] Failed to start on-demand proxy"),null}function ll(e){const t=[];for(const r of e.split(`
|
|
154
|
-
`))r.includes("[JournalCapture] Page console.error:")?t.push(r.replace(/.*\[JournalCapture\] Page console\.error:\s*/,"")):r.includes("[JournalCapture] Network failed:")&&t.push(r.replace(/.*\[JournalCapture\] /,""));return t}async function cl(e,t,r,s){const a=Y.join(e,".codeyam","editor-scenarios","client-errors.json");let o={};try{const i=await be.readFile(a,"utf8");o=JSON.parse(i)}catch{}for(const[i,l]of Object.entries(o))i!==t&&l.scenarioName===r&&delete o[i];o[t]={scenarioName:r,capturedAt:new Date().toISOString(),errors:s},await be.mkdir(Y.dirname(a),{recursive:!0}),await be.writeFile(a,JSON.stringify(o,null,2),"utf8")}async function sh(e){const t=Y.join(e,".codeyam","editor-scenarios","client-errors.json");try{const r=await be.readFile(t,"utf8");return JSON.parse(r)}catch{return{}}}function ah(e){var a,o;const t=ee.join(e,"package.json");if(!Ne.existsSync(t))return{error:"No package.json found."};let r="npm",s=["run","dev"];try{const i=JSON.parse(Ne.readFileSync(t,"utf8"));if(Ne.existsSync(ee.join(e,"pnpm-lock.yaml"))?r="pnpm":Ne.existsSync(ee.join(e,"yarn.lock"))?r="yarn":Ne.existsSync(ee.join(e,"bun.lockb"))&&(r="bun"),!((a=i.scripts)!=null&&a.dev))if((o=i.scripts)!=null&&o.start)s=["run","start"];else return{error:'No "dev" or "start" script found in package.json.'}}catch{}return{command:r,args:s}}const oh=[/Local:\s+(https?:\/\/[^\s]+)/,/Ready on\s+(https?:\/\/[^\s]+)/i,/started at\s+(https?:\/\/[^\s]+)/i,/listening on\s+(https?:\/\/[^\s]+)/i,/http:\/\/localhost:\d+/];function ih(e){for(const t of oh){const r=e.match(t);if(r){const s=r[1]||r[0];return lh(s).trim()}}return null}function lh(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function dl(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}function ch(e){const{exitCode:t,uptime:r,retryCount:s}=e,a=r<1e4;return t!==0&&t!==null&&a&&s===0?{action:"retry"}:t!==0&&t!==null?{action:"error"}:{action:"stopped"}}function ul(e){let r=Y.dirname(new URL(e).pathname);for(let s=0;s<5;s++){const a=Y.dirname(r);if(Y.basename(a)==="webserver"||Y.basename(r)==="webserver")return Y.basename(r)==="webserver"?r:a;r=a}return r}async function Rs(e,t){const r=[Y.join(e,"scripts","journalCapture.ts"),Y.join(e,"app","lib","journalCapture.ts"),Y.join(t,"codeyam-cli","src","webserver","app","lib","journalCapture.ts")];for(const s of r)try{return await be.access(s),s}catch{}return r[0]}function ml(e,t,r){return new Promise(s=>{const a=e.endsWith(".ts"),l=Lt(a?"npx":e,a?["tsx",e,t]:[t],{cwd:r,env:{...process.env}});let d="",m="";l.stdout.on("data",u=>{d+=u.toString()}),l.stderr.on("data",u=>{m+=u.toString()}),l.on("close",u=>{s(u===0?{success:!0,output:d}:{success:!1,output:d,error:m||`Process exited with code ${u}`})}),l.on("error",u=>{s({success:!1,output:"",error:u.message})})})}function pl(e){return Y.join(e,".codeyam","scenarios-manifest.json")}function hl(e){const t=pl(e);try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function fl(e,t){const r=pl(e),s=Y.dirname(r);K.mkdirSync(s,{recursive:!0}),K.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}function dh(e,t){const r=hl(e)||{version:1,updatedAt:"",scenarios:[]},s=r.scenarios.findIndex(a=>a.id===t.id);s>=0?r.scenarios[s]=t:r.scenarios.push(t),r.updatedAt=new Date().toISOString(),fl(e,r)}function uh(e,t){const r=hl(e);r&&(r.scenarios=r.scenarios.filter(s=>s.id!==t),r.updatedAt=new Date().toISOString(),fl(e,r))}const gl=globalThis.__codeyamTerminalSessions??(globalThis.__codeyamTerminalSessions=new Set);globalThis.__codeyamDetachedPtys??(globalThis.__codeyamDetachedPtys=new Map);function ua(e){const t=JSON.stringify({type:"refresh-preview",...e&&{path:e}});let r=0;for(const s of gl)try{s.ws.readyState===fi.OPEN&&(s.ws.send(t),r++)}catch{}return r}function mh(){const e=JSON.stringify({type:"hide-results"});let t=0;for(const r of gl)try{r.ws.readyState===fi.OPEN&&(r.ws.send(e),t++)}catch{}return t}const ph=Object.freeze(Object.defineProperty({__proto__:null,broadcastHideResults:mh,broadcastPreviewRefresh:ua},Symbol.toStringTag,{value:"Module"}));function hh(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Ee("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return fh(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function fh(e){const t=e.trim().split(`
|
|
155
|
-
`).filter(s=>s.length>0),r=[];for(const s of t){const a=s[0],o=s[1];let i=s.slice(2).replace(/^[ \t]+/,""),l,d=!1,m;if(a==="A"||o==="A")l="added",d=a==="A";else if(a==="M"||o==="M")l="modified",d=a==="M";else if(a==="D"||o==="D")l="deleted",d=a==="D";else if(a==="R"||o==="R"){l="renamed",d=a==="R";const u=i.indexOf(" -> ");u!==-1&&(m=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(l="untracked",d=!1):(l="modified",d=a!==" "&&a!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),p=ee.join(u,i);try{const h=(y,g)=>{const x=Ne.readdirSync(y,{withFileTypes:!0}),v=[];for(const b of x){const N=ee.join(y,b.name),C=ee.relative(u,N);b.isDirectory()?v.push(...h(N,g)):b.isFile()&&v.push(C)}return v},f=h(p,u);for(const y of f)r.push({path:y,status:l,staged:d,...m&&{oldPath:m}})}catch(h){console.error(`Failed to expand directory ${i}:`,h)}}else r.push({path:i,status:l,staged:d,...m&&{oldPath:m}})}return r}function gh(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ee("git branch --show-current",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch(r){return console.error("Failed to get current branch:",r),null}}function yh(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const s=Ee('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(s)return s[1];try{return Ee("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Ee("git show-ref --verify --quiet refs/heads/master",{cwd:t,stdio:["pipe","pipe","ignore"]}),"master"}catch{return"main"}}}catch(r){return console.error("Failed to get default branch:",r),"main"}}function xh(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ee('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
156
|
-
`).filter(s=>s.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function Jr(){const e=me();return e?hh(e):[]}function bh(){const e=me();return e?gh(e):null}function vh(){const e=me();return e?yh(e):"main"}function wh(){const e=me();return e?xh(e):[]}function yl(e,t){const r=me();return r?Nh(e,t,r):[]}function Nh(e,t,r){const s=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ee(`git diff --name-status ${e}...${t}`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
157
|
-
`).filter(i=>i.length>0).map(i=>{const l=i.split(" "),d=l[0];let m=l[1],u,p;return d==="A"?p="added":d==="M"?p="modified":d==="D"?p="deleted":d.startsWith("R")?(p="renamed",u=l[1],m=l[2]):p="modified",{path:m,status:p,...u&&{oldPath:u}}})}catch(a){return console.error("Failed to get branch diff:",a),[]}}function xl(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=Ee(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let a="";try{a=Ne.readFileSync(ee.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),a=""}return{oldContent:s,newContent:a,fileName:e}}catch(s){return console.error(`Failed to get diff for ${e}:`,s),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Ch(e){const t=me();return t?xl(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Sh(e,t,r,s){const a=s||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=Ee(`git show ${t}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=Ee(`git show ${r}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:o,newContent:i,fileName:e}}catch(o){return console.error(`Failed to get branch diff for ${e}:`,o),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function ar(e,t,r){const s=me();return s?Sh(e,t,r,s):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function bl(e,t){const r=new Map;for(const s of e)s.status!=="deleted"&&(t||s.status==="added"||s.status==="untracked"?r.set(s.path,"new"):s.status==="modified"&&r.set(s.path,"edited"));return r}function Nt(e){if(!e||e==="/")return"Home";const r=e.split("?")[0].replace(/^\//,"").split("/")[0];return r.charAt(0).toUpperCase()+r.slice(1)}function vl(e,t,r){var o;const s=[],a=new Set;for(const i of e){let l=null,d=null;if(i.componentName&&i.componentPath)l=i.componentName,d=i.componentPath;else if(!i.componentName&&i.url!==void 0){const m=Nt(i.url);t[m]&&(l=m,d=t[m])}if(l&&d&&!a.has(l)){a.add(l);const m=r.find(u=>u.name===l);s.push({name:l,filePath:d,importedBy:(o=m==null?void 0:m.metadata)==null?void 0:o.importedBy})}}return s}function kh(e,t){const r=[],s=new Set(t);for(const a of e)s.has(a.name)||(s.add(a.name),r.push({name:a.name,filePath:a.filePath}));return r}function Is(e,t){return!t||Object.keys(t).length===0?e:e.filter(([r])=>t[r])}function Eh(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>t[r.name])}function Ah(e,t,r){if(!t||Object.keys(t).length===0)return e;const s=r?[...r].some(a=>t[a]):!1;return e.filter(a=>{const o=a.name.indexOf(" - ");if(o!==-1){const i=a.name.slice(0,o);return i==="App"?s:!!t[i]}else return s})}function Ph(e){const t=new Map;for(const r of e){const s=r.importedBy;if(!s||typeof s!="object")continue;const a=new Set;for(const o of Object.keys(s))for(const i of Object.keys(s[o]))a.add(i);a.size>0&&t.set(r.name,a)}return t}function Mh(e,t){const r=new Map;for(const s of t){const a=e.get(s.filePath);a&&r.set(s.name,a)}return r}const _h=20;function wl(e,t,r=_h){const s={};if(t.length===0||e.size===0)return s;const a=new Map;for(const m of t)a.set(m.name,m);const o=Ph(t),i=Mh(e,t);for(const[m,u]of i)s[m]={status:u};const l=new Map;for(const[m]of i)l.set(m,new Set([m]));const d=[];for(const[m]of i)d.push({name:m,depth:0});for(;d.length>0;){const{name:m,depth:u}=d.shift();if(u>=r)continue;const p=l.get(m)||new Set,h=o.get(m);if(h)for(const f of h){if(!a.has(f))continue;l.has(f)||l.set(f,new Set);const y=l.get(f);let g=!1;for(const x of p)y.has(x)||(y.add(x),g=!0);g&&d.push({name:f,depth:u+1})}}for(const[m,u]of l){if(i.has(m))continue;const p=[];for(const h of u){const f=a.get(h),y=i.get(h);f&&y&&p.push({name:h,filePath:f.filePath,changeType:y})}p.sort((h,f)=>h.name.localeCompare(f.name)),s[m]={status:"impacted",impactedBy:p.length>0?p:void 0}}return s}async function jh(e,t,r){const s=Y.join(e,".codeyam","journal"),a=Y.join(s,"index.json");Y.join(s,"screenshots");let o;try{const l=await be.readFile(a,"utf8");o=JSON.parse(l)}catch{return}let i=!1;for(const l of o.entries)if(!l.commitSha&&l.scenarioScreenshots)for(let d=0;d<l.scenarioScreenshots.length;d++){const m=l.scenarioScreenshots[d];if(m.name!==t)continue;const u=Y.join(s,m.path);try{await be.copyFile(r,u),i=!0,console.log(`[editor-register-scenario] Updated journal screenshot for "${t}" in entry "${l.title}"`)}catch(p){console.warn(`[editor-register-scenario] Failed to update journal screenshot: ${p instanceof Error?p.message:p}`)}}i&&dt.notifyChange("journal")}const Th=dl;async function $h({request:e}){var t;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const r=await e.json(),{name:s,description:a,componentName:o,componentPath:i}=r;if(!s)return new Response(JSON.stringify({error:"name is required"}),{status:400,headers:{"Content-Type":"application/json"}});const l=await Te();if(!l)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:d}=await Re(l),m=_e(),u=qs();await m.insertInto("editor_scenarios").values({id:u,project_id:d.id,name:s,description:a||null,component_name:o||null,component_path:i||null,url:r.url||null}).execute();const p=process.env.CODEYAM_ROOT_PATH||process.cwd();if(r.mockData){const N=Y.join(p,".codeyam","editor-scenarios");await be.mkdir(N,{recursive:!0}),await be.writeFile(Y.join(N,`${u}.json`),JSON.stringify(r.mockData,null,2))}dt.notifyChange("scenario"),console.log(`[editor-register-scenario] Starting auto-capture for scenario "${s}" (id: ${u})`);const h=r.url&&r.url.startsWith("/"),f=!r.url||h?await il():null,y=Th(),g=Ts(r.url||null,f,y);console.log(`[editor-register-scenario] Capture URL resolution: explicit=${r.url||"none"}, isPath=${h}, proxy=${f||"none"}, devServer=${y||"none"} → using ${g||"none"}`);let x=null,v=null,b=[];if(g){const N=vt(s),C=Y.join(p,".codeyam","active-scenario.json");await be.writeFile(C,JSON.stringify({scenarioId:u,scenarioSlug:N,timestamp:new Date().toISOString()})),sr(),console.log(`[editor-register-scenario] Active scenario set to "${N}" (${u}), cache invalidated`),await new Promise(D=>setTimeout(D,500));const E=Y.join(p,".codeyam","editor-scenarios","screenshots");await be.mkdir(E,{recursive:!0});const w=Y.join(E,`${u}.png`),k=ul(import.meta.url),S=await Rs(k,p);console.log(`[editor-register-scenario] Capture script: ${S}`);const A=JSON.stringify({url:g,outputPath:w,viewportWidth:1280,viewportHeight:720,...o?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Running Playwright capture: url=${g}, output=${w}`);const $=Date.now(),_=await ml(S,A,p),j=Date.now()-$;if(console.log(`[editor-register-scenario] Capture ${_.success?"succeeded":"FAILED"} in ${j}ms`),_.success||(console.warn(`[editor-register-scenario] Capture stdout: ${_.output.slice(0,500)}`),console.warn(`[editor-register-scenario] Capture stderr: ${(_.error||"").slice(0,500)}`)),b=ll(_.output),await cl(p,u,s,b),b.length>0&&console.warn(`[editor-register-scenario] ${b.length} client-side error(s) detected:`,b),_.success){x=`screenshots/${u}.png`;try{await m.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await m.updateTable("editor_scenarios").set({screenshot_path:x}).where("id","=",u).execute(),dt.notifyChange("scenario"),await jh(p,s,w)}else v=_.error||"Unknown capture error",console.warn(`[editor-register-scenario] Screenshot capture failed (non-blocking): ${v}`)}else console.log("[editor-register-scenario] Skipping screenshot — no capture URL available (dev server not running?)");if(console.log(`[editor-register-scenario] Done: scenario="${s}", screenshot=${x?"captured":"skipped"}`),g&&x)try{const N=me()||process.cwd(),C=Y.join(N,".codeyam","editor-step.json");let E=null;try{const w=K.readFileSync(C,"utf8");E=JSON.parse(w).featureStartedAt||null}catch{}if(E){const w=ca(E),k=await m.selectFrom("editor_scenarios").selectAll().where("project_id","=",d.id).orderBy("created_at","asc").execute(),S=en(k,$=>`${$.name}::${$.url||"/"}`),A=Jr();if(A.length>0){let $=!1;try{const{execSync:z}=await import("child_process"),L=z("git rev-list --count HEAD",{cwd:N,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();$=parseInt(L,10)<=1}catch{$=!0}const _=bl(A,$),j={},D=Y.join(N,"app");if(K.existsSync(D)){const z=(L,P)=>{for(const q of K.readdirSync(L,{withFileTypes:!0}))if(q.name!=="codeyam-isolate"){if(q.isDirectory())z(Y.join(L,q.name),P?`${P}/${q.name}`:q.name);else if(q.name==="page.tsx"||q.name==="page.js"){const H=Nt(P?`/${P}`:"/");j[H]=P?`app/${P}/${q.name}`:`app/${q.name}`}}};z(D,"")}let R=[];try{await Be(),R=await Ze({})||[]}catch{}const T=S.map(z=>({componentName:z.component_name||null,componentPath:z.component_path||null,url:z.url??null})),U=vl(T,j,R),V=wl(_,U),I=S.filter(z=>z.created_at<w),O=new Map;for(const z of I){const L=z.component_name||Nt(z.url);((t=V[L])==null?void 0:t.status)==="impacted"&&O.set(L,z)}if(O.size>0){console.log(`[editor-register-scenario] Recapturing ${O.size} impacted older scenario(s): ${[...O.keys()].join(", ")}`);const z=await Rs(p),L=Y.join(p,".codeyam","editor-scenarios","screenshots");for(const[q,H]of O)try{const W=vt(H.name),Z=Y.join(p,".codeyam","active-scenario.json");await be.writeFile(Z,JSON.stringify({scenarioId:H.id,scenarioSlug:W,timestamp:new Date().toISOString()})),sr(),await new Promise(X=>setTimeout(X,300));const B=Ts(H.url||null,f,y);if(!B)continue;const F=Y.join(L,`${H.id}.png`),J=JSON.stringify({url:B,outputPath:F,viewportWidth:1280,viewportHeight:720,...H.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Recapturing "${H.name}" (entity: ${q})`);const G=await runCapture(z,J,p);G.success?(await m.updateTable("editor_scenarios").set({screenshot_path:`screenshots/${H.id}.png`}).where("id","=",H.id).execute(),console.log(`[editor-register-scenario] Recapture succeeded for "${H.name}"`)):console.warn(`[editor-register-scenario] Recapture failed for "${H.name}": ${G.error}`)}catch(W){console.warn(`[editor-register-scenario] Recapture error for "${H.name}": ${W instanceof Error?W.message:W}`)}const P=Y.join(p,".codeyam","active-scenario.json");await be.writeFile(P,JSON.stringify({scenarioId:u,scenarioSlug:vt(s),timestamp:new Date().toISOString()})),sr(),dt.notifyChange("scenario")}}}}catch(N){console.warn(`[editor-register-scenario] Recapture of impacted scenarios failed (non-blocking): ${N instanceof Error?N.message:N}`)}try{const N=new Date().toISOString();dh(p,{id:u,name:s,description:a||null,componentName:o||null,componentPath:i||null,url:r.url||null,mockDataFile:`editor-scenarios/${u}.json`,screenshotFile:x?`editor-scenarios/${x}`:null,createdAt:N,updatedAt:N})}catch(N){console.warn(`[editor-register-scenario] Failed to update manifest (non-blocking): ${N instanceof Error?N.message:N}`)}try{ua(r.url||void 0)}catch{}return new Response(JSON.stringify({success:!0,scenario:{id:u,name:s,description:a,componentName:o||null,componentPath:i||null,screenshotPath:x,url:r.url||null},screenshotCaptured:x!==null,captureError:v,clientErrors:b}),{headers:{"Content-Type":"application/json"}})}catch(r){const s=r instanceof Error?r.message:String(r);return console.error("[editor-register-scenario] Error:",r),new Response(JSON.stringify({error:s}),{status:500,headers:{"Content-Type":"application/json"}})}}const Rh=Object.freeze(Object.defineProperty({__proto__:null,action:$h},Symbol.toStringTag,{value:"Module"}));function Ih({executionFlows:e,selections:t,onChange:r,disabled:s=!1}){const a=se(i=>t.some(l=>l.flowId===i),[t]),o=se(i=>{a(i.id)?r(t.filter(l=>l.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,a]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const l=a(i.id),d=i.usedInScenarios.length>0;return c("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[c("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:l,onChange:()=>o(i),disabled:s,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!d&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),l&&i.requiredValues.length>0&&c("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((m,u)=>c("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:m.attributePath})," ",n("span",{className:"text-gray-400",children:m.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:m.value})]},u))})]})]},i.id)})})}function ma(e,t){const r=(e||[]).map(d=>({...d,usedInScenarios:[]})),s=new Map;r.forEach(d=>{s.set(d.id,d)});const a=[];t.forEach(d=>{var u;const m=((u=d.metadata)==null?void 0:u.coveredFlows)||[];m.forEach(p=>{const h=s.get(p);h&&h.usedInScenarios.push({id:d.id||"",name:d.name})}),a.push({scenario:d,coveredFlowIds:m})});const o=r.length,i=r.filter(d=>d.usedInScenarios.length>0).length,l=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:l,scenariosWithFlows:a}}function Dh(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const Lh=({data:e})=>[{title:e!=null&&e.entity?`Create Scenario - ${e.entity.name} - CodeYam`:"Create Scenario - CodeYam"},{name:"description",content:"Create a new scenario"}];async function Oh({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await $r(t,!0),s=r&&r.length>0?r[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const a=(i=s.scenarios)==null?void 0:i.find(l=>l.name===jr);if(!a)throw new Response("Default scenario not found",{status:404});const o=await Te();return Q({analysis:s,defaultScenario:a,entity:s.entity,entitySha:t,projectSlug:o})}function Fh(){var O;const{analysis:e,defaultScenario:t,entity:r,entitySha:s,projectSlug:a}=Ve(),o=Ct(),{iframeRef:i}=da(),[l,d]=M(""),[m,u]=M(400),[p,h]=M(!1),[f,y]=M(!1),[g,x]=M(!1),[v,b]=M(null),[N,C]=M(null),[E,w]=M([]),k=ne(()=>{var L;return!((L=e==null?void 0:e.metadata)!=null&&L.executionFlows)||!(e!=null&&e.scenarios)?[]:ma(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:S,isStarting:A,isLoading:$,showIframe:_,iframeKey:j,onIframeLoad:D}=rn({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:a,enabled:!0}),R=se(async()=>{var z,L,P,q;if(!l.trim()&&E.length===0){b("Please describe how you want to change the scenario or select execution flows");return}y(!0),b(null),C("Generating scenario with AI...");try{const H=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:(z=e.metadata)==null?void 0:z.scenariosDataStructure,flowSelections:E.length>0?E:void 0})}),W=await H.json();if(!H.ok||!W.success)throw new Error(W.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",W.data);const Z=W.data;if(!Z.name||!Z.data)throw new Error("AI response missing required fields (name or data)");C("Saving new scenario..."),x(!0);const B={name:Z.name,description:Z.description||l,metadata:{data:Z.data,interactiveExamplePath:(L=t.metadata)==null?void 0:L.interactiveExamplePath}},F=[...e.scenarios||[],B],J=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:F})}),G=await J.json();if(!J.ok||!G.success)throw new Error(G.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",G);const X=(q=(P=G.analysis)==null?void 0:P.scenarios)==null?void 0:q.find(le=>le.name===Z.name);if(!(X!=null&&X.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),C("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${s}`),1e3);return}if(S){C("Capturing screenshot...");const le=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:S,scenarioId:X.id,projectId:e.projectId,viewportWidth:1440})}),ve=await le.json();!le.ok||!ve.success?(console.error("[CreateScenario] Capture failed:",ve),C("Scenario created! (Screenshot capture failed)")):C("Scenario created and captured!")}else C("Scenario created!");setTimeout(()=>{o(`/entity/${s}/scenarios/${X.id}`)},1e3)}catch(H){console.error("[CreateScenario] Error:",H),b(H instanceof Error?H.message:String(H)),C(null)}finally{y(!1),x(!1)}},[l,E,e,t,s,S,o]),T=f||g,U=se(()=>{h(!0)},[]),V=se(z=>{if(!p)return;const L=z.clientX;L>=250&&L<=600&&u(L)},[p]),I=se(()=>{h(!1)},[]);return te(()=>(p?(document.addEventListener("mousemove",V),document.addEventListener("mouseup",I)):(document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",I)),()=>{document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",I)}),[p,V,I]),c("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-end h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:()=>void o(`/entity/${s}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),c("div",{className:"flex items-end gap-8 shrink-0",children:[n(de,{to:`/entity/${s}/scenarios`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-medium border-b-2",style:{color:"#005C75",borderColor:"#005C75"},children:c("span",{className:"flex items-center gap-2",children:["Scenarios",n("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((O=e==null?void 0:e.scenarios)==null?void 0:O.length)||0})]})}),n(de,{to:`/entity/${s}/related`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Related Entities"}),n(de,{to:`/entity/${s}/code`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Code"}),n(de,{to:`/entity/${s}/data`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Data Structure"}),n(de,{to:`/entity/${s}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),c("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[c("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${m}px`},children:[c("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),k.length>0&&c("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[c("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Execution Flows"," ",E.length>0&&c("span",{className:"text-blue-600",children:["(",E.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(Ih,{executionFlows:k,selections:E,onChange:w,disabled:T})})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:l,onChange:z=>d(z.target.value),placeholder:"e.g., Show an empty state with no items...",className:"w-full h-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:T})]}),c("div",{className:"space-y-2",children:[n("button",{onClick:()=>void R(),disabled:T||!l.trim()&&E.length===0,className:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium cursor-pointer transition-colors hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed",children:T?"Creating...":"Create Scenario"}),N&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:N}),v&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:v})]})]}),c("div",{onMouseDown:U,style:{width:"20px",position:"absolute",top:0,left:`${m-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:p?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
|
|
158
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
159
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
160
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
161
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
162
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(Wr,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:S,isStarting:A,isLoading:$,showIframe:_,iframeKey:j,onIframeLoad:D,projectSlug:a,defaultWidth:1440,defaultHeight:900})})]})]})}const zh=We(function(){return n(Ur,{children:n(Fh,{})})}),Bh=Object.freeze(Object.defineProperty({__proto__:null,default:zh,loader:Oh,meta:Lh},Symbol.toStringTag,{value:"Module"})),Yh=dl;async function Uh({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioId:r,url:s,viewportWidth:a,viewportHeight:o}=t;if(!r)return new Response(JSON.stringify({error:"scenarioId is required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=await Te();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:l}=await Re(i),d=_e(),m=await d.selectFrom("editor_scenarios").selectAll().where("id","=",r).where("project_id","=",l.id).executeTakeFirst();if(!m)return new Response(JSON.stringify({error:"Scenario not found"}),{status:404,headers:{"Content-Type":"application/json"}});const u=s??m.url??null,p=u&&u.startsWith("/"),h=!u||p?await il():null,f=Yh(),y=Ts(u,h,f);if(console.log(`[editor-capture-scenario] URL resolution: explicit=${s||"none"}, db=${m.url||"none"}, proxy=${h||"none"}, devServer=${f||"none"} → captureUrl=${y||"none"}`),!y)return new Response(JSON.stringify({error:"Cannot determine capture URL — no proxy or dev server running"}),{status:400,headers:{"Content-Type":"application/json"}});console.log(`[editor-capture-scenario] Starting capture for scenario "${m.name}" (id: ${r}), url: ${y}`);const g=process.env.CODEYAM_ROOT_PATH||process.cwd(),x=vt(m.name),v=Y.join(g,".codeyam","active-scenario.json");await be.writeFile(v,JSON.stringify({scenarioId:r,scenarioSlug:x,timestamp:new Date().toISOString()})),sr(),console.log(`[editor-capture-scenario] Active scenario set to "${x}", cache invalidated`),await new Promise(j=>setTimeout(j,500));const b=Y.join(g,".codeyam","editor-scenarios","screenshots");await be.mkdir(b,{recursive:!0});const N=Y.join(b,`${r}.png`),C=ul(import.meta.url),E=await Rs(C,g);console.log(`[editor-capture-scenario] Capture script: ${E}`);const w=JSON.stringify({url:y,outputPath:N,viewportWidth:a||1280,viewportHeight:o||720,...m.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-capture-scenario] Running Playwright capture: url=${y}, output=${N}`);const k=Date.now(),S=await ml(E,w,g),A=Date.now()-k;if(console.log(`[editor-capture-scenario] Capture ${S.success?"succeeded":"FAILED"} in ${A}ms`),!S.success)return console.warn(`[editor-capture-scenario] Capture stdout: ${S.output.slice(0,500)}`),console.warn(`[editor-capture-scenario] Capture stderr: ${(S.error||"").slice(0,500)}`),new Response(JSON.stringify({error:"Failed to capture screenshot",details:S.error}),{status:500,headers:{"Content-Type":"application/json"}});const $=`screenshots/${r}.png`;try{await d.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await d.updateTable("editor_scenarios").set({screenshot_path:$}).where("id","=",r).execute();const _=ll(S.output);return await cl(g,r,m.name,_),_.length>0&&console.warn(`[editor-capture-scenario] ${_.length} client-side error(s) detected:`,_),dt.notifyChange("scenario"),new Response(JSON.stringify({success:!0,screenshotPath:$,clientErrors:_}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-capture-scenario] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Wh=Object.freeze(Object.defineProperty({__proto__:null,action:Uh},Symbol.toStringTag,{value:"Module"}));async function Jh({params:e}){const t=e["*"];if(!t)return new Response("Image path is required",{status:400});const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","editor-scenarios","screenshots",t),a=ee.resolve(s),o=ee.resolve(ee.join(r,".codeyam","editor-scenarios","screenshots"));if(!a.startsWith(o))return new Response("Invalid path",{status:403});try{await ye.access(s);const i=await ye.readFile(s),l=ee.extname(s).toLowerCase(),d=l===".png"?"image/png":l===".jpg"||l===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Image not found",{status:404})}}const Hh=Object.freeze(Object.defineProperty({__proto__:null,loader:Jh},Symbol.toStringTag,{value:"Module"}));async function Vh({params:e,request:t}){const r=e["*"];if(!r)return new Response("Image path is required",{status:400});const s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=ee.join(s,".codeyam","journal","screenshots",r),o=ee.resolve(a),i=ee.resolve(ee.join(s,".codeyam","journal","screenshots"));if(!o.startsWith(i))return new Response("Invalid path",{status:403});try{const l=await ye.stat(a),d=`"${l.mtimeMs.toString(36)}-${l.size.toString(36)}"`;if(t.headers.get("if-none-match")===d)return new Response(null,{status:304,headers:{ETag:d}});const u=await ye.readFile(a),p=ee.extname(a).toLowerCase(),h=p===".png"?"image/png":p===".jpg"||p===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(u,{status:200,headers:{"Content-Type":h,"Cache-Control":"public, max-age=0, must-revalidate",ETag:d}})}catch{return new Response("Image not found",{status:404})}}const Gh=Object.freeze(Object.defineProperty({__proto__:null,loader:Vh},Symbol.toStringTag,{value:"Module"}));async function qh({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioSlug:r,scenarioId:s,scenarioName:a}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({error:"scenarioSlug is required"}),{status:400,headers:{"Content-Type":"application/json"}});const o=me()||process.cwd(),i=ee.join(o,".codeyam"),l=ee.join(i,"active-scenario.json");Ne.mkdirSync(i,{recursive:!0}),Ne.writeFileSync(l,JSON.stringify({scenarioSlug:r,scenarioName:a||null,scenarioId:s||null,dataFile:s?`.codeyam/editor-scenarios/${s}.json`:null,switchedAt:new Date().toISOString()},null,2));const d=ua();return new Response(JSON.stringify({success:!0,scenarioSlug:r,refreshedClients:d}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Kh=Object.freeze(Object.defineProperty({__proto__:null,action:qh},Symbol.toStringTag,{value:"Module"}));var fe;(e=>{(t=>{t.OPENAI_GPT5_1="openai/gpt-5.1",t.OPENAI_GPT5="openai/gpt-5",t.OPENAI_GPT5_MINI="openai/gpt-5-mini",t.OPENAI_GPT5_NANO="openai/gpt-5-nano",t.OPENAI_GPT4_1="openai/gpt-4.1",t.OPENAI_GPT4_1_MINI="openai/gpt-4.1-mini",t.OPENAI_GPT4_O="openai/gpt-4o",t.OPENAI_GPT4_O_MINI="openai/gpt-4o-mini",t.OPENAI_GPT_OSS_120B_GROQ="openai/gpt-oss-120b-groq",t.OPENAI_GPT_OSS_120B_DEEPINFRA="openai/gpt-oss-120b-deepinfra",t.QWEN3_235B_INSTRUCT_DEEPINFRA="qwen/qwen3-235b-instruct-deepinfra",t.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA="qwen/qwen3-coder-480b-instruct-deepinfra",t.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA="google/gemini-2.5-pro-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA="google/gemini-2.5-flash-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER="google/gemini-2.5-flash-lite-openrouter",t.META_LLAMA_4_MAVERICK_OPENROUTER="meta-llama/llama-4-maverick-openrouter",t.DEEPSEEK_V3_1_TERMINUS_OPENROUTER="deepseek/v3.1-terminus-openrouter",t.ANTHROPIC_CLAUDE_4_5_HAIKU="anthropic/claude-4.5-haiku",t.ANTHROPIC_CLAUDE_4_5_SONNET="anthropic/claude-4.5-sonnet",t.ANTHROPIC_CLAUDE_4_5_OPUS="anthropic/claude-4.5-opus",t.PHIND_CODELLAMA="phind/codellama",t.GOOGLE_GEMINI_PRO="google/gemini-pro",t.GOOGLE_PALM_2_CODE_CHAT_32K="google/palm-2-code-chat-32k",t.META_CODELLAMA_34B_INSTRUCT="meta-llama/codellama-34b-instruct",t.OPENAI_GPT4_PREVIEW="openai/gpt-4-preview"})(e.Model||(e.Model={}))})(fe||(fe={}));function Nl(e,t){return e?Object.values(fe.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const Cl=Nl(process.env.DEFAULT_SMALLER_MODEL,fe.Model.OPENAI_GPT4_1_MINI),Qh=Nl(process.env.DEFAULT_LARGER_MODEL,fe.Model.OPENAI_GPT4_1),lt={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},fs={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Zh={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},gs={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},Mt={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},Xh={[fe.Model.OPENAI_GPT5_1]:{id:fe.Model.OPENAI_GPT5_1,provider:lt,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[fe.Model.OPENAI_GPT5]:{id:fe.Model.OPENAI_GPT5,provider:lt,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[fe.Model.OPENAI_GPT5_MINI]:{id:fe.Model.OPENAI_GPT5_MINI,provider:lt,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[fe.Model.OPENAI_GPT5_NANO]:{id:fe.Model.OPENAI_GPT5_NANO,provider:lt,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[fe.Model.OPENAI_GPT4_1]:{id:fe.Model.OPENAI_GPT4_1,provider:lt,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[fe.Model.OPENAI_GPT4_1_MINI]:{id:fe.Model.OPENAI_GPT4_1_MINI,provider:lt,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[fe.Model.OPENAI_GPT4_O]:{id:fe.Model.OPENAI_GPT4_O,provider:lt,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[fe.Model.OPENAI_GPT4_O_MINI]:{id:fe.Model.OPENAI_GPT4_O_MINI,provider:lt,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[fe.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:fe.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:fs,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[fe.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:fe.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:fs,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[fe.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:fe.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:fs,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[fe.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:fe.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Zh,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[fe.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:fe.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:Mt,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[fe.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:fe.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:Mt,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[fe.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:fe.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:Mt,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[fe.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:fe.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:Mt,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[fe.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:fe.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:Mt,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[fe.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:fe.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:gs,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[fe.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:fe.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:gs,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[fe.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:fe.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:gs,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[fe.Model.PHIND_CODELLAMA]:{id:fe.Model.PHIND_CODELLAMA,provider:lt,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[fe.Model.GOOGLE_GEMINI_PRO]:{id:fe.Model.GOOGLE_GEMINI_PRO,provider:Mt,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[fe.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:fe.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:Mt,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[fe.Model.META_CODELLAMA_34B_INSTRUCT]:{id:fe.Model.META_CODELLAMA_34B_INSTRUCT,provider:Mt,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[fe.Model.OPENAI_GPT4_PREVIEW]:{id:fe.Model.OPENAI_GPT4_PREVIEW,provider:lt,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function Hr(e){const t=Xh[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function ef(e){return Hr(e).maxCompletionTokens}function tf(e){return Hr(e).pricing}const bo=1e6;function nf({model:e,usage:t}){const r=tf(e);return r?t.prompt_tokens*(r.input/bo)+t.completion_tokens*(r.output/bo):null}function rf({chatRequest:e,chatCompletion:t,model:r}){if("error"in t&&t.error)return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),error:JSON.stringify(t.error)};const s=t.usage||{prompt_tokens:0,completion_tokens:0},a=nf({model:r,usage:s});return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,cost:a?Math.round(a*1e5)/1e5:void 0}}function sf({messages:{system:e,prompt:t},model:r,responseType:s,jsonSchema:a}){const o=r??Cl,i=Hr(o);ef(o);const l=[];return e&&l.push({role:"system",content:e}),l.push({role:"user",content:[{type:"text",text:t}]}),{messages:l,model:i.apiModelName,response_format:s==="json_schema"&&a?{type:"json_schema",json_schema:{name:a.name,schema:a.schema,strict:a.strict!==!1}}:{type:s&&s=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}const Ds="/tmp/codeyam-e2e-tracking";let ys,xs;function af(){return ys===void 0&&(ys=process.env.CODEYAM_E2E_TRACK_DATA==="true"),ys}function of(){return xs===void 0&&(xs=!process.env.CODEYAM_LLM_FIXTURES_DIR),xs}function lf(){K.existsSync(Ds)||K.mkdirSync(Ds,{recursive:!0})}function cf(e){const t=JSON.stringify(e,null,0);return md.createHash("md5").update(t).digest("hex")}function df(e,t,r){return[e].join("_")+".json"}function Sl(e,t,r,s){if(!af())return;lf();const a=df(e),o=Y.join(Ds,a),i=cf(t);if(of()){const l={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:s,dataHash:i,data:t};K.writeFileSync(o,JSON.stringify(l,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(K.existsSync(o)){const l=JSON.parse(K.readFileSync(o,"utf-8")),d={matches:i===l.dataHash,firstRunHash:l.dataHash};if(d.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{d.differences=Ls(l.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${l.dataHash}`),console.log(` Second run hash: ${i}`);const m=o.replace(".json","_DIFF.json");K.writeFileSync(m,JSON.stringify({checkpoint:e,entityName:r,scenarioName:s,firstRun:l.data,secondRun:t,differences:d.differences},null,2)),console.log(` Diff saved to: ${m}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function Ls(e,t,r=""){const s=[];if(typeof e!=typeof t)return s.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),s;if(e===null||t===null)return e!==t&&s.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),s;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&s.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const a=Math.max(e.length,t.length);for(let o=0;o<a;o++)s.push(...Ls(e[o],t[o],`${r}[${o}]`));return s}if(typeof e=="object"&&typeof t=="object"){const a=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...a,...o]));for(const l of i){const d=e[l],m=t[l];l in e?l in t?s.push(...Ls(d,m,`${r?r+".":""}${l}`)):s.push(`${r?r+".":""}${l}: missing in second run`):s.push(`${r?r+".":""}${l}: missing in first run`)}return s}if(e!==t){const a=JSON.stringify(e),o=JSON.stringify(t);a.length<100&&o.length<100?s.push(`${r||"root"}: ${a} vs ${o}`):s.push(`${r||"root"}: values differ (${a.length} chars vs ${o.length} chars)`)}return s}Qs(Ks);const Kn=new bd({concurrency:100,timeout:1200*1e3,autoStart:!0}),vo={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},_t={};async function Os({type:e,systemMessage:t,prompt:r,jsonResponse:s=!0,jsonSchema:a,model:o=Cl,attempts:i=0}){var k,S,A,$,_,j,D;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await uf(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${Kn.size}, running=${Kn.pending}]`);const l=Date.now();let d,m=0;const u=Hr(o),p=process.env[u.provider.apiKeyEnvVar];if(!p)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const h=new xd({apiKey:p,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:a?"json_schema":s?"json_object":"text",jsonSchema:a},y=sf(f),g=await Kn.add(()=>(d=Date.now(),to(async()=>{const R=Date.now(),T=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],U=setInterval(()=>{const V=Math.floor((Date.now()-R)/1e3),I=Math.floor(V/10)%T.length;ro(1,`${T[I]} [type=${e}, model=${o}, elapsed=${V}s]`)},1e4);try{return await h.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(U)}},{...vo,onFailedAttempt:R=>{m++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:R,prompt:r,systemMessage:t,attempts:i,retryCount:m})}})));if(!g)throw new Error("Completion call returned no result");const x=g,v=Date.now(),b=rf({chatRequest:f,chatCompletion:x,model:o});if(!b)throw new Error("Failed to get LLM call stats");b.retries=m,b.wait_ms=d-l,b.duration_ms=v-l;const N=(k=x.choices)==null?void 0:k[0];let C=null;if(N){if(!N.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:x,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");C=(S=N.message)==null?void 0:S.content}let E=C;C&&(E=C.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const w=s?E&&(((A=E.match(/\{[\s\S]*\}/))==null?void 0:A[0])??E):E;if(!w){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:w,rawCompletion:C,chatCompletion:x,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await Os({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(w.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:C,prompt:r,systemMessage:t}),new Error("Empty completion");if(s)try{JSON.parse(w)}catch(R){if(console.log("CodeYam Error: Invalid JSON in completion",{error:R.message,model:o,completion:w.substring(0,500),rawCompletion:C==null?void 0:C.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:R.message});const T=`Your previous response contained invalid JSON with the following error:
|
|
163
|
-
|
|
164
|
-
${R.message}
|
|
165
|
-
|
|
166
|
-
Here was your previous response:
|
|
167
|
-
\`\`\`
|
|
168
|
-
${w}
|
|
169
|
-
\`\`\`
|
|
170
|
-
|
|
171
|
-
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,U=await Kn.add(()=>to(async()=>{const L=Date.now(),P=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],q=setInterval(()=>{const H=Math.floor((Date.now()-L)/1e3),W=Math.floor(H/10)%P.length;ro(1,`${P[W]} [type=${e}, model=${o}, elapsed=${H}s]`)},1e4);try{return await h.chat.completions.create({...y,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:w},{role:"user",content:T}]},{timeout:300*1e3})}finally{clearInterval(q)}},{...vo,onFailedAttempt:L=>{console.log("CodeYam Error: Correction call failed",{error:L,attempts:i})}}));if(!U)throw new Error("Correction call returned no result");const V=U,I=(j=(_=($=V.choices)==null?void 0:$[0])==null?void 0:_.message)==null?void 0:j.content;let O=I;I&&(O=I.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const z=O&&(((D=O.match(/\{[\s\S]*\}/))==null?void 0:D[0])??O);if(!z)throw new Error("Correction attempt returned empty completion");try{JSON.parse(z),console.log("CodeYam: JSON correction successful");const L=Date.now();return b.duration_ms=L-l,{finishReason:V.choices[0].finish_reason,completion:z,stats:b}}catch(L){return console.log("CodeYam Error: Corrected JSON still invalid",{error:L.message,correctedCompletion:z.substring(0,500)}),await Os({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${R.message}`)}return Sl(`completionCall_${e}`,{completion:w,finishReason:x.choices[0].finish_reason}),{finishReason:x.choices[0].finish_reason,completion:w,stats:b}}async function uf(e,t,r){var o,i,l,d,m;const s=await import("fs"),a=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!s.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const u=s.readdirSync(t).filter(b=>b.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const p={};for(const b of u)try{const N=s.readFileSync(a.join(t,b),"utf-8"),C=JSON.parse(N);p[C.prompt_type]||(p[C.prompt_type]=[]),p[C.prompt_type].push(C)}catch(N){console.warn(`Failed to parse LLM fixture file ${b}:`,N)}for(const b of Object.keys(p))p[b].sort((N,C)=>{const E=N.created_at??0,w=C.created_at??0;return E-w});const h=p[e];if(!h||h.length===0){const b=Object.keys(p).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${b}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&r){const b=r.match(/Scenario name must match exactly: "([^"]+)"/),N=b==null?void 0:b[1];if(N){const C={};for(const w of h)try{const S=((o=JSON.parse(w.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";C[S]||(C[S]=[]),C[S].push(w)}catch{}const E=C[N];if(E&&E.length>0){const w=`${t}::${e}::${N}`;_t[w]===void 0&&(_t[w]=0);const k=_t[w];_t[w]=(k+1)%E.length,f=E[k],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${N}' [${k+1}/${E.length}]`)}else{const w=Object.keys(C).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${N}'. Available: [${w}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const b=`${t}::${e}`;_t[b]===void 0&&(_t[b]=0);const N=_t[b];_t[b]=(N+1)%h.length,f=h[N],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${N+1}/${h.length}]`)}let g;try{g=((d=(l=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:l.message)==null?void 0:d.content)||f.response}catch{g=f.response}let x=g;g&&(x=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const v=x&&(((m=x.match(/\{[\s\S]*\}/))==null?void 0:m[0])??x);return Sl(`completionCall_${e}`,{completion:v||"",finishReason:"stop"}),{finishReason:"stop",completion:v||"",stats:{model:f.model??"fixture",prompt_type:e,system_message:f.system_message??"",prompt_text:f.prompt_text??"",response:f.response??"",input_tokens:f.input_tokens??0,output_tokens:f.output_tokens??0,cost:f.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(u){throw console.error("CodeYam Test Error: Failed to replay LLM call:",u),u}}function wo(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function mf(e){const{propsJson:t,...r}=e,s=JSON.stringify(t,null,2),a=qs(),o=Date.now(),i={...r,id:a,created_at:o,props:s};let l;const d=`${i.object_id}_${a}.json`;if(process.env.DYNAMODB_PATH?l=Y.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=Y.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),l)try{const u=Y.dirname(l);return await be.mkdir(u,{recursive:!0}),await be.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:a}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const m=wo();if(!m)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,p]of Object.entries(i))typeof p>"u"&&console.log(`CodeYam Warning: LLM call ${a} property ${u} with explicit value 'undefined'`);try{return await new Mr().send(new vd({TableName:wo(),Item:Nd(i,{removeUndefinedValues:!0})})),{id:a}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${m}`,u),{id:"-1"}}}new Mr({});new Mr({});new Mr({});const pf=3,hf=2,pa=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+pf*String(t).length*(1+hf)});new Xs(pa());new Xs(pa());new Xs(pa());class ff{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,s){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),s&&(this.byClassAndMethod.has(s)||this.byClassAndMethod.set(s,new Map),this.byClassAndMethod.get(s).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){var s;return(s=this.byClassAndMethod.get(t))==null?void 0:s.get(r)}}class gf{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class yf{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class xf{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class bf{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class vf{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];if(s.addType(o,"function"),s.addEquivalence(o.withParameter(1),r.withElement("*")),a.args.length>1){const i=a.args[1];s.addEquivalence(o.withParameter(0),i)}}}isComplete(){return!0}}class wf{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.getLastFunctionCallSegment();a&&a.args.forEach(o=>{s.addEquivalence(t,o)}),s.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class Nf{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.withReturnValues();s.addType(a,"unknown")}isComplete(){return!0}}class Cf{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>2)for(let o=2;o<a.args.length;o++){const i=a.args[o];s.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class Sf{getReturnType(){return"number"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0)for(let o=0;o<a.args.length;o++)s.addEquivalence(r.withElement("*"),t.withParameter(o))}isComplete(){return!0}}class kf{getReturnType(){return"string"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class Ef{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Af{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Pf{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown"),s.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class Mf{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class _f{getReturnType(){return"object"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"array")}}isComplete(){return!0}}class jf{getReturnType(){return"string[]"}addEquivalences(t,r,s){s.addType(r,"string"),s.addType(t,"string[]"),s.addEquivalence(t.withReturnValues().withElement("*"),r)}isComplete(){return!0}}class Tf{getReturnType(){return"unknown"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r),s.addEquivalence(t.withProperty("functionCallReturnValue"),o.withProperty("returnValue"))}}isComplete(){return!0}}class $f{getReturnType(){return"unknown"}addEquivalences(t,r,s){t.getLastFunctionCallSegment()}isComplete(){return!0}}class Rf{getReturnType(){return"array"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(s.addType(t.withParameter(1),"function"),a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}function If(){const e=new ff;return e.register("filter",new gf,"Array"),e.register("map",new Ef,"Array"),e.register("flatMap",new Af,"Array"),e.register("join",new kf,"Array"),e.register("find",new bf,"Array"),e.register("findLast",new Mf,"Array"),e.register("at",new Pf,"Array"),e.register("reduce",new vf,"Array"),e.register("concat",new wf,"Array"),e.register("slice",new Nf,"Array"),e.register("splice",new Cf,"Array"),e.register("push",new Sf,"Array"),e.register("some",new yf,"Array"),e.register("every",new xf,"Array"),e.register("fromEntries",new _f,"Object"),e.register("split",new jf,"String"),e.register("then",new Tf,"Promise"),e.register("useState",new Rf,"React"),e.register("useMemo",new $f,"React"),e}If();new Set(Object.getOwnPropertyNames(Array.prototype).filter(e=>typeof Array.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(String.prototype).filter(e=>typeof String.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Number.prototype).filter(e=>typeof Number.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Boolean.prototype).filter(e=>typeof Boolean.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Date.prototype).filter(e=>typeof Date.prototype[e]=="function"));const Df=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Lf=new Set(["find","findLast","at","pop","shift"]),Of=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),Ff=new Set([...Df,...Lf,...Of]),zf=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Bf=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Yf=new Set([...zf,...Bf]);[...Ff,...Yf];class Uf{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,s)=>{const a=" ".repeat(this.depth),o=this.timestamps?`[${Date.now()}] `:"";s?console.info(`${o}${a}${r}`,JSON.stringify(s)):console.info(`${o}${a}${r}`)},this.enabled=t.enabled,this.pathPatterns=t.pathPatterns??[],this.scopePatterns=t.scopePatterns??[],this.maxDepth=t.maxDepth??50,this.output=t.output??this.defaultOutput,this.timestamps=t.timestamps??!1}shouldTrace(t){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||t.path&&this.pathPatterns.length>0&&this.pathPatterns.some(r=>r.test(t.path))||t.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(r=>r.test(t.scope)))}trace(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[TRACE] ${t}`,r))}traceEnter(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[ENTER] ${t}`,r),this.depth++)}traceExit(t,r={}){this.depth>0&&this.depth--,this.shouldTrace(r)&&this.output(`[EXIT] ${t}`,r)}traceWarn(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[WARN] ${t}`,r))}enable(){this.enabled=!0}disable(){this.enabled=!1}resetDepth(){this.depth=0}getStats(){return{traceCount:this.traceCount,currentDepth:this.depth,enabled:this.enabled}}reset(){this.depth=0,this.traceCount=0}}new Uf({enabled:!1});function Wt(e,t){const r={added:{},removed:{},changed:{}},s=new Set(Object.keys(e??{})),a=new Set(Object.keys(t??{}));for(const o of a)s.has(o)||(r.added[o]=t[o]);for(const o of s)a.has(o)||(r.removed[o]=e[o]);for(const o of s)a.has(o)&&e[o]!==t[o]&&(r.changed[o]={from:e[o],to:t[o]});return r}function Wf(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function Qn(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let Jf=0;class ha{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++Jf,this.enabled=(t==null?void 0:t.enabled)??!1,this.outputPath=(t==null?void 0:t.outputPath)??"/tmp/codeyam/transform-trace.json",this.enabled&&console.log(`[Tracer] Initialized (id=${this.tracerId}, output=${this.outputPath})`)}log(t){this.isEnabled()&&console.log(`[Tracer] ${t}`)}isEnabled(){const t=process.env.CODEYAM_TRACE_TRANSFORMS;return t==="1"||t==="true"?!0:this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}setOutputPath(t){this.outputPath=t}setProjectSlug(t){this.projectSlug=t}startEntity(t){if(!this.isEnabled())return;this.currentEntity=t.name;const r=this.traces.get(t.name);if(r){this.log(`startEntity: ${t.name} already exists, preserving ${r.stages.length} stages`);return}this.log(`startEntity: ${t.name}`),this.traces.set(t.name,{entityName:t.name,entityType:t.entityType,filePath:t.filePath,stages:[],operations:[]})}snapshot(t,r,s){var d,m,u,p;if(!this.isEnabled())return;const a=this.traces.get(t);if(!a)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,s);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const o=JSON.parse(JSON.stringify(s)),i={stage:r,timestamp:Date.now(),data:o},l=a.stages[a.stages.length-1];if(l&&(i.diffFromPrevious={signatureSchema:Wt(l.data.signatureSchema,o.signatureSchema),returnValueSchema:Wt(l.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||l.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const h=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(l.data.dependencySchemas??{})]);for(const f of h){const y=(d=l.data.dependencySchemas)==null?void 0:d[f],g=(m=o.dependencySchemas)==null?void 0:m[f];for(const x of new Set([...Object.keys(y??{}),...Object.keys(g??{})])){const v=`${f}::${x}`,b=(u=y==null?void 0:y[x])==null?void 0:u.returnValueSchema,N=(p=g==null?void 0:g[x])==null?void 0:p.returnValueSchema,C=Wt(b,N);Wf(C)&&(i.diffFromPrevious.dependencySchemas[v]=C)}}}a.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const s=this.traces.get(t);s&&s.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}computeFlushSummary(){var a;const t={},r=new Map;for(const[o,i]of this.traces){let l=0;for(const d of i.stages){if(!d.diffFromPrevious)continue;const u=`${((a=i.stages[i.stages.indexOf(d)-1])==null?void 0:a.stage)??"start"}→${d.stage}`;if(t[u]||(t[u]={added:0,removed:0,changed:0}),d.diffFromPrevious.signatureSchema){const p=d.diffFromPrevious.signatureSchema;t[u].added+=Object.keys(p.added).length,t[u].removed+=Object.keys(p.removed).length,t[u].changed+=Object.keys(p.changed).length,l+=Qn(p)}if(d.diffFromPrevious.returnValueSchema){const p=d.diffFromPrevious.returnValueSchema;t[u].added+=Object.keys(p.added).length,t[u].removed+=Object.keys(p.removed).length,t[u].changed+=Object.keys(p.changed).length,l+=Qn(p)}}r.set(o,l)}const s=[...r.entries()].sort((o,i)=>i[1]-o[1]).slice(0,10).map(([o])=>o);return{stageChangeCounts:t,entitiesWithMostChanges:s}}flush(){if(!this.isEnabled())return;if(this.traces.size===0){this.log("flush: no traces to write");return}const t=Array.from(this.traces.keys()),r=t.map(m=>`${m}(${this.traces.get(m).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const{stageChangeCounts:s,entitiesWithMostChanges:a}=this.computeFlushSummary(),o={timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},i={stageChangeCounts:s,entitiesWithMostChanges:a},l=Y.dirname(this.outputPath);K.existsSync(l)||K.mkdirSync(l,{recursive:!0});const d=K.openSync(this.outputPath,"w");try{K.writeSync(d,`{
|
|
172
|
-
"meta": `),K.writeSync(d,JSON.stringify(o,null,2)),K.writeSync(d,`,
|
|
173
|
-
"summary": `),K.writeSync(d,JSON.stringify(i,null,2)),K.writeSync(d,`,
|
|
174
|
-
"entities": {`);let m=!0;for(const[u,p]of this.traces)m||K.writeSync(d,","),K.writeSync(d,`
|
|
175
|
-
${JSON.stringify(u)}: `),K.writeSync(d,JSON.stringify(p,null,2)),m=!1;K.writeSync(d,`
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
`),this.log(`flush: wrote trace to ${this.outputPath}`)}finally{K.closeSync(d)}}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=K.readFileSync(t,"utf-8"),s=JSON.parse(r),a=new ha({enabled:!1});a.projectSlug=s.meta.projectSlug;for(const[o,i]of Object.entries(s.entities))a.traces.set(o,i);return a}getSummary(){var a,o,i;const t={},r=new Map;for(const[l,d]of this.traces){let m=0;for(let u=1;u<d.stages.length;u++){const p=d.stages[u],f=`${((a=d.stages[u-1])==null?void 0:a.stage)??"start"}→${p.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=p.diffFromPrevious)!=null&&o.signatureSchema){const y=p.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,m+=Qn(y)}if((i=p.diffFromPrevious)!=null&&i.returnValueSchema){const y=p.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,m+=Qn(y)}}r.set(l,m)}const s=[...r.entries()].sort((l,d)=>d[1]-l[1]).slice(0,10).map(([l,d])=>({name:l,totalChanges:d}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:s}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(s=>({stage:s.stage,diffFromPrevious:s.diffFromPrevious?{signatureSchema:s.diffFromPrevious.signatureSchema,returnValueSchema:s.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const s=this.traces.get(t);return s?r?s.operations.filter(a=>a.path&&r.test(a.path)):s.operations:[]}tracePath(t,r){var o,i;const s=this.traces.get(t),a=[];if(!s)return{entityName:t,path:r,history:a};for(const l of s.stages){const d=(o=l.data.signatureSchema)==null?void 0:o[r],m=(i=l.data.returnValueSchema)==null?void 0:i[r],u=d??m;u!==void 0&&a.push({stage:l.stage,value:u})}for(const l of s.operations)l.path===r&&a.push({operation:l.operation,stage:l.stage,value:l.after??l.before,context:l.context});return{entityName:t,path:r,history:a}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const s=this.traces.get(t);if(!s)return[];const a=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of s.stages){for(const[l,d]of Object.entries(i.data.signatureSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:d,schemaType:"signature"});for(const[l,d]of Object.entries(i.data.returnValueSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:d,schemaType:"returnValue"});for(const[l,d]of Object.entries(i.data.dependencySchemas??{}))for(const[m,u]of Object.entries(d))for(const[p,h]of Object.entries(u.returnValueSchema??{}))o.test(p)&&a.push({stage:i.stage,path:`${l}/${m}::${p}`,type:h,schemaType:"dependency"})}return a}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let s=r.stages[r.stages.length-1];for(let d=r.stages.length-1;d>=0;d--)if(Object.keys(r.stages[d].data.dependencySchemas??{}).length>0){s=r.stages[d];break}if(!s)return[];const a=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(d,m)=>{const u=d.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const p=u[1],h=u[2]==="[]";if(a.has(p))return;const f=p+(h?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:d,type:m})};for(const[,d]of Object.entries(s.data.dependencySchemas??{}))for(const[,m]of Object.entries(d))for(const[u,p]of Object.entries(m.returnValueSchema??{}))i(u,p);const l=[];for(const[d,m]of o)new Set(m.map(p=>p.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&l.push({propertyName:d,paths:m.map(p=>({...p,stage:s.stage}))});return l.sort((d,m)=>{const u=new Set(d.paths.map(h=>h.type)).size;return new Set(m.paths.map(h=>h.type)).size-u}),l}getStageDiffSummary(t,r,s){const a=this.traces.get(t);if(!a)return null;const o=a.stages.find(h=>h.stage===r),i=a.stages.find(h=>h.stage===s);if(!o||!i)return null;const l={added:[],removed:[],typeChanged:[]},d=o.data.returnValueSchema??{},m=i.data.returnValueSchema??{},u=new Set(Object.keys(d)),p=new Set(Object.keys(m));for(const h of p)u.has(h)?d[h]!==m[h]&&l.typeChanged.push({path:h,from:d[h],to:m[h]}):l.added.push(`${h}: ${m[h]}`);for(const h of u)p.has(h)||l.removed.push(`${h}: ${d[h]}`);return l}traceSchemaTransform(t,r,s,a,o){if(!this.enabled)return a(s),s;const i={...s};a(s);const l=Wt(i,s);for(const[d,m]of Object.entries(l.added))this.operation(t,{operation:r,path:d,before:void 0,after:m,context:{...o,changeType:"added"}});for(const[d,m]of Object.entries(l.removed))this.operation(t,{operation:r,path:d,before:m,after:void 0,context:{...o,changeType:"removed"}});for(const[d,{from:m,to:u}]of Object.entries(l.changed))this.operation(t,{operation:r,path:d,before:m,after:u,context:{...o,changeType:"changed"}});return s}traceSchemaTransformResult(t,r,s,a,o){if(!this.enabled)return;const i=Wt(s,a);for(const[l,d]of Object.entries(i.added))this.operation(t,{operation:r,path:l,before:void 0,after:d,context:{...o,changeType:"added"}});for(const[l,d]of Object.entries(i.removed))this.operation(t,{operation:r,path:l,before:d,after:void 0,context:{...o,changeType:"removed"}});for(const[l,{from:d,to:m}]of Object.entries(i.changed))this.operation(t,{operation:r,path:l,before:d,after:m,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,s,a,o="both"){if(!this.enabled){for(const i in s)for(const l in s[i]){const d=s[i][l];(o==="signature"||o==="both")&&d.signatureSchema&&a(d.signatureSchema),(o==="returnValue"||o==="both")&&d.returnValueSchema&&a(d.returnValueSchema)}return}for(const i in s)for(const l in s[i]){const d=s[i][l],m={filePath:i,dependencyName:l};(o==="signature"||o==="both")&&d.signatureSchema&&this.traceSchemaTransform(t,r,d.signatureSchema,a,{...m,schemaType:"signature"}),(o==="returnValue"||o==="both")&&d.returnValueSchema&&this.traceSchemaTransform(t,r,d.returnValueSchema,a,{...m,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,s,a){var i;if(!this.enabled){a();return}const o={};for(const l in s){o[l]={};for(const d in s[l]){const m=s[l][d];o[l][d]={sig:{...m.signatureSchema||{}},rv:{...m.returnValueSchema||{}}}}}a();for(const l in s)for(const d in s[l]){const m=s[l][d],u=(i=o[l])==null?void 0:i[d],p={filePath:l,dependencyName:d};if(m.signatureSchema){const h=(u==null?void 0:u.sig)||{},f=Wt(h,m.signatureSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...p,schemaType:"signature",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...p,schemaType:"signature",changeType:"changed"}})}if(m.returnValueSchema){const h=(u==null?void 0:u.rv)||{},f=Wt(h,m.returnValueSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...p,schemaType:"returnValue",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...p,schemaType:"returnValue",changeType:"changed"}})}}}}function Hf(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const No=new ha({enabled:Hf(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{No.isEnabled()&&No.flush()});function kl(e){if(e==null)return null;const t=e.match(/```json\s*([\s\S]*?)\s*```/);t&&(e=t[1]),e=e.replace(/"[^"]+"\s*:\s*undefined\s*,?\s*/g,""),e=e.replace(/,(\s*[}\]])/g,"$1");try{return wd.parse(e)}catch(r){const a=r.message.match(/invalid character .* at (\d+):(\d+)/);if(a){const o=parseInt(a[2],10);if(e.substring(o-2,o-1)==='"')return e=e.substring(0,o-2)+"\\"+e.substring(o-2),kl(e)}return null}}function Vf({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:s}){let a="";return s&&s.length>0&&(a=`
|
|
179
|
-
User-selected Execution Flow Values:
|
|
180
|
-
The user has specifically requested these values be used in the scenario:
|
|
181
|
-
${s.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
|
|
182
|
-
`)}
|
|
183
|
-
|
|
184
|
-
IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
|
|
185
|
-
`),`Mock Scenario Data Structure:
|
|
186
|
-
\`\`\`
|
|
187
|
-
${JSON.stringify(r,null,2)}
|
|
188
|
-
\`\`\`
|
|
189
|
-
Existing Mock Scenario Data:
|
|
190
|
-
\`\`\`
|
|
191
|
-
${JSON.stringify(t,null,2)}
|
|
192
|
-
\`\`\`
|
|
193
|
-
${a}
|
|
194
|
-
New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
|
|
195
|
-
`}function Gf({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}){const o=s.find(i=>i.name===jr);return`Mock Scenario Data Structure:
|
|
196
|
-
\`\`\`
|
|
197
|
-
${JSON.stringify({props:a.arguments,dataVariables:a.dataForMocks},null,2)}
|
|
198
|
-
\`\`\`
|
|
199
|
-
|
|
200
|
-
Existing Mock Scenario Data:
|
|
201
|
-
\`\`\`
|
|
202
|
-
${JSON.stringify(s.map(i=>({name:i.name,data:Mn(o.metadata.data,i.metadata.data)})),null,2)}
|
|
203
|
-
\`\`\`
|
|
204
|
-
|
|
205
|
-
Mock Scenario that should be edited: "${t}"
|
|
206
|
-
${r?`The portion of the data that should be edited:
|
|
207
|
-
\`\`\`
|
|
208
|
-
${JSON.stringify(r,null,2)}
|
|
209
|
-
\`\`\``:""}
|
|
210
|
-
|
|
211
|
-
How this data should be changed: "${e}"
|
|
212
|
-
`}async function qf({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,flowSelections:o,model:i}){const l=t?Gf({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}):Vf({description:e,existingScenarios:s,scenariosDataStructure:a,flowSelections:o}),d=await Os({type:"guessScenarioDataFromDescription",systemMessage:t?Qf(r):Kf,prompt:l,model:i??Qh});await mf({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,model:i},...d.stats});const{completion:m}=d;return m?kl(m):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const Kf=`
|
|
213
|
-
You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
|
|
214
|
-
|
|
215
|
-
Your goal is to add one scenario to the list of existing scenarios by generating an english name, proper description, and a JSON data structure that describes the data that would be used in a scenario for the code.
|
|
216
|
-
|
|
217
|
-
The data for the scenario will be merged with the "Default Scenario" data, so you don't need to replicate any data in the default scenario but must overwrite any data that should be different.
|
|
218
|
-
|
|
219
|
-
You must respond with valid JSON following this format of this TS type definition:
|
|
220
|
-
\`\`\`
|
|
221
|
-
export type ScenarioData = {
|
|
222
|
-
name: string;
|
|
223
|
-
description: string;
|
|
224
|
-
data: {
|
|
225
|
-
mockData: { [key: string]: unknown };
|
|
226
|
-
argumentsData: { [key: string]: unknown };
|
|
227
|
-
};
|
|
228
|
-
};
|
|
229
|
-
|
|
230
|
-
\`\`\`
|
|
231
|
-
`,Qf=e=>`
|
|
232
|
-
You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
|
|
233
|
-
|
|
234
|
-
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
235
|
-
${e?`
|
|
236
|
-
We only want to edit a specific portion of the data, which is provided in the "The portion of the data that should be edited" section. You should only change the data that is provided in this section.`:""}
|
|
237
|
-
|
|
238
|
-
Always return the complete data structure for the scenario, with both mockData and argumentsData, even if you only changed a small portion of the data.
|
|
239
|
-
|
|
240
|
-
You must respond with valid JSON following this type definition:
|
|
241
|
-
\`\`\`
|
|
242
|
-
{
|
|
243
|
-
data: {
|
|
244
|
-
mockData: { [key: string]: unknown };
|
|
245
|
-
argumentsData: { [key: string]: unknown };
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
\`\`\`
|
|
249
|
-
`;async function Zf({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:s,scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:l}=t;if(!r&&(!l||l.length===0))return Q({error:"Missing required field: description or flowSelections"},{status:400});const d=await qf({description:r||"",existingScenarios:s??[],scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:l}),m=(d==null?void 0:d.data)||d;return Q({success:!0,data:m})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),Q({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const Xf=Object.freeze(Object.defineProperty({__proto__:null,action:Zf},Symbol.toStringTag,{value:"Module"}));function eg(e){const t=new Map;for(const r of[...e].reverse()){const s=t.get(r.date)||[];s.push(r),t.set(r.date,s)}return t}function tg(e){const t=new Map;for(const r of e){const s=r.name.indexOf(" - "),a=s!==-1?r.name.slice(0,s):"App",o=t.get(a)||[];o.push(r),t.set(a,o)}return[...t.entries()].sort(([r],[s])=>r==="App"?-1:s==="App"?1:r.localeCompare(s))}function ng(e,t){const r=e.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${t.toISOString().replace(/:/g,"-").replace(/\.\d+Z$/,"")}_${r}.png`}function rg(e){const{title:t,timeStr:r,type:s,description:a,allScenarioNames:o,screenshot:i,scenarioScreenshots:l,commitSha:d,commitMessage:m,featureName:u,userPrompt:p}=e,h=["","---","",`### ${t}`,`**Time:** ${r}`,`**Type:** ${s}`];if(u&&h.push(`**Feature:** ${u}`),p&&h.push(`**Prompt:** ${p}`),o.length>0&&h.push(`**Scenarios:** ${o.join(", ")}`),h.push(""),h.push(a),i&&(h.push(""),h.push(``)),l.length>0){h.push(""),h.push("**Scenario Screenshots:**");for(const f of l)h.push(""),h.push(``)}return d&&m&&(h.push(""),h.push(`**Commit:** \`${d}\` — ${m}`)),h.push(""),h.join(`
|
|
250
|
-
`)}function sg(e,t){return e.findIndex(r=>r.time===t)}function ag(e){return!!e.commitSha}function og(e,t){return t.commitSha!==void 0&&(e.commitSha=t.commitSha),t.commitMessage!==void 0&&(e.commitMessage=t.commitMessage),t.description!==void 0&&(e.description=t.description),t.scenarios!==void 0&&(e.scenarios=t.scenarios),t.scenarioScreenshots!==void 0&&(e.scenarioScreenshots=t.scenarioScreenshots),e}function ig(e,t,r,s){const a=`
|
|
251
|
-
**Commit:** \`${r}\` — ${s||"no message"}
|
|
252
|
-
`,o=`### ${t}`,i=e.lastIndexOf(o);if(i===-1)return null;const l=e.indexOf(`
|
|
253
|
-
---
|
|
254
|
-
`,i+1),d=l!==-1?l:e.length;return e.slice(0,d)+a+e.slice(d)}async function Co(e){console.log(`[editorScenarioLookup] Looking up screenshots for ${e.length} scenarios: ${e.join(", ")}`);try{const t=await Te();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up scenarios"),[];const{project:r}=await Re(t),a=await _e().selectFrom("editor_scenarios").select(["name","screenshot_path","id"]).where("project_id","=",r.id).where("name","in",e).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] DB query returned ${a.length} matching scenarios:`,a.map(d=>({name:d.name,screenshot_path:d.screenshot_path,id:d.id})));const o=a.filter(d=>!d.screenshot_path);o.length>0&&console.warn(`[editorScenarioLookup] ${o.length} scenarios have no screenshot_path:`,o.map(d=>d.name));const i=a.filter(d=>d.screenshot_path),l=en(i,d=>d.name).map(d=>({name:d.name,screenshotPath:d.screenshot_path,scenarioId:d.id}));return console.log(`[editorScenarioLookup] Found ${l.length} scenarios with screenshots`),l}catch(t){return console.error("[editorScenarioLookup] Failed to look up scenario screenshots:",t),[]}}async function El(){console.log("[editorScenarioLookup] Looking up all scenario screenshots for the current session");try{const e=await Te();if(!e)return console.warn("[editorScenarioLookup] No project slug found — cannot look up session scenarios"),[];const{project:t}=await Re(e),r=_e(),s=me()||process.cwd();let a=null;const o=Y.join(s,".codeyam","editor-step.json");try{const u=K.readFileSync(o,"utf8");a=JSON.parse(u).featureStartedAt||null}catch{return console.warn("[editorScenarioLookup] No editor-step.json found — cannot determine session start"),[]}if(!a)return console.warn("[editorScenarioLookup] No featureStartedAt found in editor-step.json"),[];const i=ca(a),l=await r.selectFrom("editor_scenarios").select(["name","screenshot_path","id"]).where("project_id","=",t.id).where("created_at",">=",i).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] Query returned ${l.length} scenarios since ${a}`);const d=l.filter(u=>u.screenshot_path),m=en(d,u=>u.name).map(u=>({name:u.name,screenshotPath:u.screenshot_path,scenarioId:u.id}));return console.log(`[editorScenarioLookup] Found ${m.length} session scenarios with screenshots`),m}catch(e){return console.error("[editorScenarioLookup] Failed to look up session scenario screenshots:",e),[]}}async function Fs(e,t,r){const s=Y.join(t,".codeyam","journal","screenshots");await be.mkdir(s,{recursive:!0});const a=[];for(const o of e){const i=Y.join(t,".codeyam","editor-scenarios",o.screenshotPath),l=ng(o.name,r),d=Y.join(s,l);console.log(`[editorScenarioLookup] Copying scenario screenshot: "${o.name}" from ${i} → ${d}`);try{await be.access(i),await be.copyFile(i,d),a.push({name:o.name,path:`screenshots/${l}`}),console.log(`[editorScenarioLookup] Successfully copied screenshot for "${o.name}"`)}catch(m){console.warn(`[editorScenarioLookup] Scenario screenshot not found: ${i}`,m instanceof Error?m.message:m)}}return console.log(`[editorScenarioLookup] Scenario screenshot summary: ${a.length} scenarios have screenshots embedded`),a}async function lg({request:e}){if(e.method!=="PATCH")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{time:r,commitSha:s,commitMessage:a,description:o,includeSessionScenarios:i}=t;if(!r)return new Response(JSON.stringify({error:"time is required to identify the entry"}),{status:400,headers:{"Content-Type":"application/json"}});const l=process.env.CODEYAM_ROOT_PATH||process.cwd(),d=Y.join(l,".codeyam","journal"),m=Y.join(d,"index.json");console.log(`[editor-journal-update] Updating entry with time="${r}"`);let u={entries:[]};try{const g=await be.readFile(m,"utf8");u=JSON.parse(g)}catch{return new Response(JSON.stringify({error:"No journal index found"}),{status:404,headers:{"Content-Type":"application/json"}})}const p=sg(u.entries,r);if(p===-1)return new Response(JSON.stringify({error:`No journal entry found with time "${r}"`}),{status:404,headers:{"Content-Type":"application/json"}});const h=u.entries[p];if(ag(h))return console.log(`[editor-journal-update] Rejected: entry "${h.title}" already committed (${h.commitSha}). Create a new entry instead.`),new Response(JSON.stringify({error:`Journal entry already committed (${h.commitSha}). Create a new entry via POST /api/editor-journal-entry instead of updating.`}),{status:409,headers:{"Content-Type":"application/json"}});let f,y;if(i){const g=await El();g.length>0&&(f=g.map(x=>x.name),y=await Fs(g,l,new Date))}if(og(h,{commitSha:s,commitMessage:a,description:o,scenarios:f,scenarioScreenshots:y}),u.entries[p]=h,await be.writeFile(m,JSON.stringify(u,null,2),"utf8"),console.log("[editor-journal-update] Updated index.json"),s)try{const g=h.date,x=Y.join(d,`${g}.md`);let v="";try{v=await be.readFile(x,"utf8")}catch{}if(v){const b=ig(v,h.title,s,a||null);b&&(await be.writeFile(x,b,"utf8"),console.log(`[editor-journal-update] Appended commit line to ${x}`))}}catch(g){console.warn("[editor-journal-update] Failed to update markdown:",g)}return dt.notifyChange("journal"),console.log(`[editor-journal-update] Done: updated entry "${h.title}"`),new Response(JSON.stringify({success:!0,entry:h}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-update] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const cg=Object.freeze(Object.defineProperty({__proto__:null,action:lg},Symbol.toStringTag,{value:"Module"}));async function dg({request:e}){try{const t=process.env.CODEYAM_ROOT_PATH||process.cwd(),r=await sh(t);let s=0;const a={};for(const[o,i]of Object.entries(r))i.errors.length>0&&(a[o]=i,s+=i.errors.length);return new Response(JSON.stringify({hasErrors:s>0,totalErrors:s,scenarios:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-client-errors] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const ug=Object.freeze(Object.defineProperty({__proto__:null,loader:dg},Symbol.toStringTag,{value:"Module"}));async function mg({request:e}){try{const r=(await nn()||[]).filter(i=>i.analyses&&i.analyses.length>0).map(i=>{var y;const l=i.analyses[0],d=l.scenarios||[],m=!((y=l.status)!=null&&y.finishedAt),u=i.entityType||"visual",h=u==="library"||u==="functionCall"?d.some(g=>{var x;return!!((x=g.metadata)!=null&&x.executionResult)}):d.some(g=>{var x,v,b,N;return((v=(x=g.metadata)==null?void 0:x.screenshotPaths)==null?void 0:v[0])&&!((b=g.metadata)!=null&&b.noScreenshotSaved)&&!((N=g.metadata)!=null&&N.sameAsDefault)}),f=d.length;return{name:i.name,entityType:u,filePath:i.filePath||"",hasScreenshot:h,isAnalyzing:m,scenarioCount:f}}),s=r.filter(i=>i.hasScreenshot),a=r.filter(i=>!i.hasScreenshot&&!i.isAnalyzing).map(i=>i.name),o=r.filter(i=>i.isAnalyzing).length;return new Response(JSON.stringify({entities:r,summary:{total:r.length,withScreenshots:s.length,missingScreenshots:a,analyzing:o}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-entity-status] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const pg=Object.freeze(Object.defineProperty({__proto__:null,loader:mg},Symbol.toStringTag,{value:"Module"}));function hg(e){const t={},r=Y.join(e,"app");if(!K.existsSync(r))return t;const s=(a,o)=>{for(const i of K.readdirSync(a,{withFileTypes:!0}))if(i.name!=="codeyam-isolate"){if(i.isDirectory())s(Y.join(a,i.name),o?`${o}/${i.name}`:i.name);else if(i.name==="page.tsx"||i.name==="page.js"){const l=o?`app/${o}/${i.name}`:`app/${i.name}`;t[Nt(o?`/${o}`:"/")]=l}}};return s(r,""),t}function fg(e){try{const t=Ee("git rev-list --count HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();return parseInt(t,10)<=1}catch{return!0}}function gg(e){try{const t=Y.join(e,".codeyam","editor-step.json"),r=K.readFileSync(t,"utf8");return JSON.parse(r).featureStartedAt||null}catch{return null}}function Al(e){try{const t=Y.join(e,".codeyam","editor-step.json"),r=K.readFileSync(t,"utf8");return JSON.parse(r).feature||null}catch{return null}}function Pl(e){try{const t=Y.join(e,".codeyam","editor-user-prompt.txt");return K.readFileSync(t,"utf8").trim()||null}catch{return null}}async function fa(e){const{projectRoot:t,scenarioInputs:r,glossaryInputs:s}=e,a=hg(t),o=new Set(Object.keys(a)),i=Jr();if(i.length===0)return{entityChangeStatus:{},pageEntityNames:o};const l=fg(t),d=bl(i,l);let m=[];try{await Be(),m=await Ze({})||[]}catch{}const u=vl(r,a,m);let p=u;if(s&&s.length>0){const f=new Set(u.map(g=>g.name)),y=kh(s,f);p=[...u,...y]}return{entityChangeStatus:wl(d,p),pageEntityNames:o}}async function yg({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{title:r,type:s,description:a,scenarios:o,includeSessionScenarios:i,screenshot:l,commitSha:d,commitMessage:m}=t;if(console.log(`[editor-journal-entry] Creating journal entry: title="${r}", type="${s}", scenarios=${JSON.stringify(o||[])}, includeSessionScenarios=${!!i}, screenshot=${l||"none"}`),!r||!s||!a)return console.warn("[editor-journal-entry] Missing required fields:",{title:!!r,type:!!s,description:!!a}),new Response(JSON.stringify({error:"title, type, and description are required"}),{status:400,headers:{"Content-Type":"application/json"}});const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),p=Y.join(u,".codeyam","journal");await be.mkdir(p,{recursive:!0});const h=new Date,f=h.toISOString().split("T")[0],y=h.toISOString();let g=o||[];const x=i?await El():o&&o.length>0?await Co(o):[];i&&x.length>0&&(g=x.map(R=>R.name));const v=await Fs(x,u,h),b=Y.join(p,"index.json");let N={entries:[]};try{const R=await be.readFile(b,"utf8");N=JSON.parse(R)}catch{}let C,E=new Set;try{const R=me()||process.cwd(),T=await Te();if(T){const{project:U}=await Re(T),I=await _e().selectFrom("editor_scenarios").select(["name","component_name","component_path","url"]).where("project_id","=",U.id).orderBy("created_at","asc").execute(),z=en(I,P=>`${P.name}::${P.url||"/"}`).map(P=>({componentName:P.component_name||null,componentPath:P.component_path||null,url:P.url??null})),L=await fa({projectRoot:R,scenarioInputs:z});E=L.pageEntityNames,Object.keys(L.entityChangeStatus).length>0&&(C=L.entityChangeStatus)}}catch{}if(C&&Object.keys(C).length>0){const R=new Set(x.map(U=>U.name)),T=Object.entries(C).filter(([,U])=>U.status==="impacted").map(([U])=>U);if(T.length>0){const U=[];for(const V of T)x.some(O=>(O.name.includes(" - ")?O.name.split(" - ")[0]:pageNameFromUrl(null))===V||O.name.startsWith(V+" - "))||U.push(V);if(U.length>0)try{const V=await Co(U.flatMap(I=>[I]));if(V.length>0){const I=await Fs(V.filter(O=>!R.has(O.name)),u,h);v.push(...I),g.push(...I.map(O=>O.name))}}catch{}}}let w=v,k=g;if(C&&Object.keys(C).length>0){w=Ah(v,C,E);const R=new Set(w.map(T=>T.name));k=g.filter(T=>R.has(T))}const S=Al(u),A=Pl(u),$=Y.join(p,`${f}.md`);let _="";try{_=await be.readFile($,"utf8")}catch{_=`# Development Journal — ${f}
|
|
255
|
-
`}const j=rg({title:r,timeStr:y,type:s,description:a,allScenarioNames:k,screenshot:l||null,scenarioScreenshots:w,commitSha:d||null,commitMessage:m||null,featureName:S,userPrompt:A});await be.writeFile($,_+j,"utf8"),console.log(`[editor-journal-entry] Written daily markdown: ${$}`);const D={date:f,time:y,title:r,type:s,description:a,scenarios:k,screenshot:l||null,scenarioScreenshots:w,commitSha:d||null,commitMessage:m||null,entityChangeStatus:C,featureName:S,userPrompt:A};return N.entries.push(D),await be.writeFile(b,JSON.stringify(N,null,2),"utf8"),console.log(`[editor-journal-entry] Updated index.json (now ${N.entries.length} entries)`),dt.notifyChange("journal"),console.log(`[editor-journal-entry] Done: title="${r}", scenarioScreenshotsEmbedded=${w.length}`),new Response(JSON.stringify({success:!0,entry:D,scenarioScreenshotsFound:w.length}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-entry] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const xg=Object.freeze(Object.defineProperty({__proto__:null,action:yg},Symbol.toStringTag,{value:"Module"}));function bg({request:e}){const t={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const r=me()||process.cwd();let o=new URL(e.url).searchParams.get("scenarioId");if(!o){const d=Y.join(r,".codeyam","active-scenario.json");if(!K.existsSync(d))return new Response(JSON.stringify({}),{headers:t});o=JSON.parse(K.readFileSync(d,"utf-8")).scenarioId||null}if(!o)return new Response(JSON.stringify({}),{headers:t});const i=Y.join(r,".codeyam","editor-scenarios",`${o}.json`);if(!K.existsSync(i))return new Response(JSON.stringify({}),{headers:t});const l=K.readFileSync(i,"utf-8");return new Response(l,{headers:t})}catch{return new Response(JSON.stringify({}),{headers:t})}}const vg=Object.freeze(Object.defineProperty({__proto__:null,loader:bg},Symbol.toStringTag,{value:"Module"}));async function wg(e,t){const r=me();if(!r)return{entityCalls:[],analysisCalls:[]};const s=Y.join(r,".codeyam","llm-calls");try{await be.access(s)}catch{return{entityCalls:[],analysisCalls:[]}}const a=[],o=[];try{const l=(await be.readdir(s)).filter(v=>v.endsWith(".json")),d=`${e}_`,m=t?`${t}_`:null,u=[],p=[];for(const v of l)v.startsWith(d)||m&&v.startsWith(m)?u.push(v):p.push(v);const h=u.map(async v=>{try{const b=Y.join(s,v),N=await be.readFile(b,"utf-8");return JSON.parse(N)}catch{return null}}),f=p.map(async v=>{try{const b=Y.join(s,v),N=await be.readFile(b,"utf-8"),C=JSON.parse(N);return C.object_id===e||t&&C.object_id===t?C:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(h),Promise.all(f)]),x=[...y,...g].filter(v=>v!==null);for(const v of x)v.object_id===e?a.push(v):t&&v.object_id===t&&o.push(v);a.sort((v,b)=>b.created_at-v.created_at),o.sort((v,b)=>b.created_at-v.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:a,analysisCalls:o}}async function Ng({params:e,request:t}){const{entitySha:r}=e;if(!r)return Q({error:"Entity SHA is required"},{status:400});const a=new URL(t.url).searchParams.get("analysisId")||void 0,o=await wg(r,a);return Q(o)}const Cg=Object.freeze(Object.defineProperty({__proto__:null,loader:Ng},Symbol.toStringTag,{value:"Module"}));function Sg(e){try{const t=Y.join(e,"package.json"),r=JSON.parse(K.readFileSync(t,"utf8")),s={...r.dependencies,...r.devDependencies};return s.vitest?"vitest":s.jest?"jest":null}catch{return null}}function kg(e,t){var i;const s=JSON.parse(t).testResults||[],a=[];for(const l of s)for(const d of l.assertionResults||[]){const m=d.ancestorTitles||[],u=d.title||d.fullName||"unknown",p=m.length>0?`${m.join(" > ")} > ${u}`:u;a.push({title:u,fullName:p,status:d.status==="passed"?"passed":d.status==="failed"?"failed":"skipped",duration:d.duration,failureMessages:(i=d.failureMessages)!=null&&i.length?d.failureMessages:void 0})}const o=a.some(l=>l.status==="failed");return{testFilePath:e,status:o?"failed":"passed",testCases:a}}async function Ml(e,t){const r=Sg(e);if(!r)return{testFilePath:t,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};const s=Y.isAbsolute(t)?t:Y.join(e,t);if(!K.existsSync(s))return{testFilePath:t,status:"error",testCases:[],errorMessage:"Test file not found"};const a=Y.join(Gs.tmpdir(),`codeyam-test-result-${Date.now()}.json`);return new Promise(o=>{var p;let i,l;r==="vitest"?(l="node",i=["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",a,t]):(l="./node_modules/.bin/jest",i=["--json","--outputFile",a,"--testPathPatterns",t]);const d=Lt(l,i,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let m="";(p=d.stderr)==null||p.on("data",h=>{m+=h.toString()});const u=setTimeout(()=>{d.kill("SIGTERM"),o({testFilePath:t,status:"error",testCases:[],errorMessage:"Test timed out after 30 seconds"})},3e4);d.on("close",()=>{clearTimeout(u);try{const h=K.readFileSync(a,"utf8");K.unlinkSync(a),o(kg(t,h))}catch{o({testFilePath:t,status:"error",testCases:[],errorMessage:m.trim().slice(0,500)||"Test runner failed to produce output"})}}),d.on("error",h=>{clearTimeout(u),o({testFilePath:t,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${h.message}`})})})}async function Eg({request:e}){const r=new URL(e.url).searchParams.get("testFile");if(!r)return new Response(JSON.stringify({status:"error",errorMessage:"Missing testFile parameter",testCases:[],testFilePath:""}),{headers:{"Content-Type":"application/json"}});const s=me()||process.cwd();try{const a=await Ml(s,r);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}catch(a){const o=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({testFilePath:r,status:"error",testCases:[],errorMessage:o}),{status:500,headers:{"Content-Type":"application/json"}})}}const Ag=Object.freeze(Object.defineProperty({__proto__:null,loader:Eg},Symbol.toStringTag,{value:"Module"}));function So(e,t){var r,s;try{return((s=(r=Ee(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:s.trim())??null}catch(a){return console.error(`Failed to get commit SHA for ${e}:`,a),""}}function Pg(e,t,r,s){const a=Fn.createHash("sha256");return a.update(`${e}:${t}:${r}:${s}`),a.digest("hex").substring(0,16)}function _l(){const e=me();if(!e)throw new Error("No project root found");const t=ee.join(e,".codeyam","cache","branch-entity-diff");return Ne.existsSync(t)||Ne.mkdirSync(t,{recursive:!0}),t}function Mg(e){try{const t=_l(),r=ee.join(t,`${e}.json`);if(!Ne.existsSync(r))return null;const s=Ne.readFileSync(r,"utf8");return JSON.parse(s)}catch(t){return console.error("Failed to read cache:",t),null}}function _g(e,t){try{const r=_l(),s=ee.join(r,`${e}.json`);Ne.writeFileSync(s,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function jg(e,t,r){const s=fr(t,e),a=fr(r,e),o=new Map(s.map(u=>[u.name,u])),i=new Map(a.map(u=>[u.name,u])),l=[],d=[],m=[];for(const[u,p]of i){const h=o.get(u);h?h.sha!==p.sha&&d.push({name:u,baseSha:h.sha,compareSha:p.sha,entityType:p.entityType}):l.push(p)}for(const[u,p]of o)i.has(u)||m.push(p);return{filePath:e,newEntities:l,modifiedEntities:d,deletedEntities:m}}function Tg(e,t){const r=me();if(!r)throw new Error("No project root found");const s=So(e,r),a=So(t,r);if(!s||!a)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=Pg(e,t,s,a),i=Mg(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const l=yl(e,t),d=[];for(const u of l)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const p=ar(u.path,e,t),h=fr(p.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:h})}else if(u.status==="added"){const p=ar(u.path,e,t),h=fr(p.newContent,u.path);d.push({filePath:u.path,newEntities:h,modifiedEntities:[],deletedEntities:[]})}else{const p=ar(u.path,e,t),h=jg(u.path,p.oldContent,p.newContent);(h.newEntities.length>0||h.modifiedEntities.length>0||h.deletedEntities.length>0)&&d.push(h)}const m={baseBranch:e,compareBranch:t,baseCommitSha:s,compareCommitSha:a,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return _g(o,m),m}function $g({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),s=t.searchParams.get("compare");if(!r||!s)return Q({error:"Missing required parameters: base and compare"},{status:400});const a=Tg(r,s);return Q(a)}catch(t){return console.error("Failed to compute branch entity diff:",t),Q({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const Rg=Object.freeze(Object.defineProperty({__proto__:null,loader:$g},Symbol.toStringTag,{value:"Module"}));async function Ig({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:s,projectId:a,viewportWidth:o=1440}=t;if(!r||!s||!a)return Q({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${r}`),console.log(`[Capture] Scenario ID from request: ${s}`);const i=me();if(!i)return Q({error:"Project root not found"},{status:500});const l=Y.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:s,projectId:a,projectRoot:i,viewportWidth:o}),m=await new Promise(h=>{const f=Y.join(i,".codeyam","db.sqlite3"),y=Lt("npx",["tsx",l,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",x="";y.stdout.on("data",v=>{const b=v.toString();g+=b;const N=b.trim().split(`
|
|
256
|
-
`);for(const C of N)C.includes("[Capture]")&&console.log(C)}),y.stderr.on("data",v=>{const b=v.toString();x+=b,console.error("[Capture:Error]",b.trim())}),y.on("close",v=>{h(v===0?{success:!0,output:g}:{success:!1,output:g,error:x||`Process exited with code ${v}`})}),y.on("error",v=>{console.error("[Capture] Failed to spawn child process:",v),h({success:!1,output:"",error:v.message})})});if(!m.success)return Q({error:"Failed to capture screenshot",details:m.error},{status:500});const u=m.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return Q({error:"Failed to parse capture result"},{status:500});const p=JSON.parse(u[1]);return Q(p)}catch(t){return console.error("[Capture] Error:",t),Q({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const Dg=Object.freeze(Object.defineProperty({__proto__:null,action:Ig},Symbol.toStringTag,{value:"Module"}));function Lg(e){const t=e||process.cwd();try{return Ee("git rev-parse HEAD",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch(r){throw new Error(`Failed to get HEAD SHA: ${r}`)}}function Og(e){const t=e||process.cwd();try{return Ee("git rev-parse --git-dir",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),!0}catch{return!1}}function Fg(e){if(Og(e))return!1;Ee("git init",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]});try{Ee('git config user.email "codeyam@local"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Ee('git config user.name "CodeYam"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}catch{}return!0}function zg(e){Ee("git add -A",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}function Bg(e,t){return Ee(`git commit -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Lg(e)}function Yg(e){return/^[0-9a-f]{7,40}$/i.test(e)}function Ug(e,t){try{return Ee(`git cat-file -t ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"}),!0}catch{return!1}}function Wg(e,t){try{return{stashed:!Ee(`git stash push -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:"pipe"}).includes("No local changes")}}catch{return{stashed:!1}}}function Jg(e,t){Ee(`git checkout ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"})}async function Hg({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{commitSha:r}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({success:!1,error:"commitSha is required"}),{status:400,headers:{"Content-Type":"application/json"}});if(!Yg(r))return new Response(JSON.stringify({success:!1,error:"Invalid commit SHA format"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();if(console.log(`[editor-load-commit] Loading commit ${r} in ${s}`),!Ug(s,r))return new Response(JSON.stringify({success:!1,error:`Commit ${r} not found`}),{status:400,headers:{"Content-Type":"application/json"}});const{stashed:a}=Wg(s,"codeyam: auto-stash before time travel");a&&console.log("[editor-load-commit] Stashed uncommitted changes");try{Jg(s,r),console.log(`[editor-load-commit] Checked out ${r}`)}catch(o){const i=o instanceof Error?o.message:String(o);return console.error("[editor-load-commit] Checkout failed:",i),new Response(JSON.stringify({success:!1,error:`Checkout failed: ${i}`}),{status:500,headers:{"Content-Type":"application/json"}})}try{const i=await(await fetch(`http://localhost:${process.env.CODEYAM_PORT||"3111"}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})})).json();console.log("[editor-load-commit] Dev server restart:",i)}catch(o){console.warn("[editor-load-commit] Dev server restart warning:",o)}return new Response(JSON.stringify({success:!0,stashed:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-load-commit] Error:",t),new Response(JSON.stringify({success:!1,error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Vg=Object.freeze(Object.defineProperty({__proto__:null,action:Hg},Symbol.toStringTag,{value:"Module"}));async function Gg(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Be();const s=await Et({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const a=_e(),o=s.entitySha,i=await a.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let l={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await a.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!s.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=s.scenarios)==null?void 0:f.length)||0} scenarios`),await pn(e,y=>{if(y){if(y.readyToBeCaptured=!0,y.scenarios)for(const g of y.scenarios)delete g.finishedAt,delete g.startedAt,delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt,delete g.error,delete g.errorStack;delete y.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=me();if(!d)throw new Error("Project root not found");const m=Y.join(d,".codeyam","config.json"),u=JSON.parse(K.readFileSync(m,"utf8")),{projectSlug:p}=u;if(!p)throw new Error("Project slug not found in config");const{jobId:h}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:p,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${h}`),{jobId:h}}async function qg(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Be();const s=await Et({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=(u=s.scenarios)==null?void 0:u.find(p=>p.id===t);if(!a)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${a.name}`),await pn(e,p=>{if(p&&(p.readyToBeCaptured=!0,delete p.finishedAt,p.scenarios)){const h=p.scenarios.find(f=>f.name===a.name);h&&(delete h.finishedAt,delete h.startedAt,delete h.error,delete h.errorStack,delete h.screenshotStartedAt,delete h.screenshotFinishedAt,delete h.interactiveStartedAt,delete h.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${a.name} for recapture`);const o=me();if(!o)throw new Error("Project root not found");const i=Y.join(o,".codeyam","config.json"),l=JSON.parse(K.readFileSync(i,"utf8")),{projectSlug:d}=l;if(!d)throw new Error("Project slug not found in config");const{jobId:m}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${m}`),{jobId:m}}async function Kg({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Pt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a||!o)return Q({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${a}, scenario ${o}`);const i=await qg(a,o,r);return console.log("[API] Scenario recapture queued",i),Q({success:!0,message:"Scenario recapture queued",...i})}catch(s){return console.log("[API] Error during scenario recapture:",s),Q({error:"Failed to recapture scenario",details:s instanceof Error?s.message:String(s)},{status:500})}}const Qg=Object.freeze(Object.defineProperty({__proto__:null,action:Kg},Symbol.toStringTag,{value:"Module"}));async function zs(e){try{return await ye.stat(e),!0}catch{return!1}}async function jl(){try{const e=me();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await ye.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function Zg(){return`/private/tmp/claude-501/-${(me()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const or="/tmp/claude-rule-markers",Xg=/<system-reminder>[\s\S]*?<\/system-reminder>/g,ko=2e3;function e0(e,t){if(e==="Read"||e==="Write"||e==="Edit")return String(t.file_path||"");if(e==="Glob")return String(t.pattern||"");if(e==="Grep"){const r=String(t.pattern||""),s=String(t.path||"");return s?`"${r}" in ${s}`:`"${r}"`}if(e==="Bash"){const r=String(t.command||"");return r.length>100?r.slice(0,100)+"...":r}if(e==="Task")return String(t.description||String(t.prompt||"").slice(0,80));for(const r of Object.values(t))if(typeof r=="string"&&r)return r.slice(0,80);return""}const t0=["no,","no ","that's not","thats not","that is not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","dont do","shouldn't","should not","try again","let me clarify","to clarify","that broke","that failed","error","bug"];function n0(e){const t=[],r=new Set;for(const s of e)if(!(s.type!=="tool_call"||!s.name||!s.input)){if(s.name==="Write"||s.name==="Edit"){const a=String(s.input.file_path||"");if(a.includes(".claude/rules/")){const o=a.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${s.name}:${o}`;r.has(i)||(r.add(i),s.name==="Write"?t.push({action:"created",filePath:o,content:String(s.input.content||"")}):t.push({action:"modified",filePath:o,oldString:String(s.input.old_string||""),newString:String(s.input.new_string||"")}))}}else if(s.name==="Bash"){const a=String(s.input.command||"");if(a.includes("codeyam memory touch")){const o=`touch:${a}`;r.has(o)||(r.add(o),t.push({action:"touched",filePath:a}))}}}return t}function r0(e){if(!e)return;const t="### Session transcript",r=e.indexOf(t);if(r===-1)return;let s=e.slice(r+t.length).trim();const a=s.indexOf(`
|
|
257
|
-
###`);return a!==-1&&(s=s.slice(0,a).trim()),s||void 0}function s0(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const s of t0)if(r.includes(s))return!0}return!1}function a0(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type==="assistant"){const a=(s.message||{}).model;if(typeof a=="string"&&a)return a}}catch{continue}}}function o0(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type!=="result")continue;const a={subtype:String(s.subtype||"unknown"),is_error:!!s.is_error};if(typeof s.duration_ms=="number"&&(a.duration_ms=s.duration_ms),typeof s.duration_api_ms=="number"&&(a.duration_api_ms=s.duration_api_ms),typeof s.num_turns=="number"&&(a.num_turns=s.num_turns),typeof s.total_cost_usd=="number"&&(a.total_cost_usd=s.total_cost_usd),s.usage&&typeof s.usage=="object"){a.usage={};for(const o of["input_tokens","output_tokens","cache_read_input_tokens","cache_creation_input_tokens"])typeof s.usage[o]=="number"&&(a.usage[o]=s.usage[o])}return Array.isArray(s.errors)&&s.errors.length>0&&(a.errors=s.errors.map(String)),a}catch{continue}}}function i0(e){const t=[],r={};for(const s of e){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const d=(o.message||{}).content,m=o.timestamp||"";if(i==="user"){if(typeof d=="string")t.push({type:"user_prompt",text:d,timestamp:m,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(d)){for(const u of d)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const p=u,h=String(p.tool_use_id||"");let f=p.content;const y=!!p.is_error;typeof f=="string"&&(f=f.replace(Xg,"").trim()),t.push({type:"tool_result",tool_use_id:h,tool_name:r[h]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:y,timestamp:m})}}}else if(i==="assistant"&&Array.isArray(d))for(const u of d){if(typeof u!="object"||u===null)continue;const p=u;if(p.type==="text"){const h=String(p.text||"").trim();h&&t.push({type:"assistant_text",text:h,timestamp:m})}else if(p.type==="tool_use"){const h=String(p.id||""),f=String(p.name||"unknown"),y=p.input||{};r[h]=f,t.push({type:"tool_call",tool_use_id:h,name:f,input:y,timestamp:m})}}}return t}function l0(e,t){return e.type==="user_prompt"||e.type==="assistant_text"?(e.text||"").toLowerCase().includes(t):e.type==="tool_call"?(e.name||"").toLowerCase().includes(t)?!0:JSON.stringify(e.input||{}).toLowerCase().includes(t):e.type==="tool_result"?(e.content||"").toLowerCase().includes(t):!1}const sn=20;async function Eo(e){const r=(await ye.readFile(e.filePath,"utf-8")).split(`
|
|
258
|
-
`),s=i0(r);if(s.length===0)return null;const a=s.find(N=>N.type==="user_prompt"),o=e.stem,i=a0(r);let l=(a==null?void 0:a.slug)||"",d=(a==null?void 0:a.timestamp)||"";d||(d=new Date(e.mtime).toISOString());let m;if(e.filePath.endsWith(".log")){e.stem.endsWith("-stale")?l=l||"rule-reflection/stale":e.stem.endsWith("-conversation")?l=l||"rule-reflection/conversation":e.stem.endsWith("-interruption")?l=l||"rule-reflection/interruption":l=l||"rule-reflection";const N=e.filePath.replace(/\.log$/,".context");if(await zs(N))try{m=await ye.readFile(N,"utf-8")}catch{}}const u=s.filter(N=>N.type==="tool_call").length,p=s.filter(N=>N.type==="assistant_text").length,h=s.filter(N=>N.type==="tool_result"&&N.is_error&&N.content!=="Sibling tool call errored"),f=h.length,y=h.map(N=>{const C=N.content||"Unknown error";return C.length>150?C.slice(0,150)+"...":C});for(const N of s)N.type==="tool_call"&&N.name&&N.input&&(N.summary=e0(N.name,N.input));for(const N of s)N.type==="tool_result"&&N.content&&N.content.length>ko&&(N.truncated=!0,N.fullLength=N.content.length,N.content=N.content.slice(0,ko));const g=n0(s),x=s0(s),v=r0(m),b=o0(r);return{id:o,slug:l,timestamp:d,model:i,sourceFile:e.filePath,stats:{toolCalls:u,textBlocks:p,errors:f,errorMessages:y},entries:s,context:m,conversationSnippet:v,ruleChanges:g,hasConfusion:x,sessionResult:b}}async function c0(){const e=Zg(),t=or,r=[];if(await zs(e)){const i=await ye.readdir(e);for(const l of i)if(l.endsWith(".output")){const d=ee.join(e,l),m=await ye.stat(d);r.push({filePath:d,stem:l.replace(".output",""),mtime:m.mtimeMs})}}const s=new Set,a=await jl(),o=[];a&&o.push(ee.join(t,a)),o.push(t);for(const i of o){if(!await zs(i))continue;const l=await ye.readdir(i);for(const d of l){if(!d.endsWith(".log")||s.has(d))continue;s.add(d);const m=ee.join(i,d),u=await ye.stat(m);r.push({filePath:m,stem:d.replace(".log",""),mtime:u.mtimeMs})}}return r.sort((i,l)=>l.mtime-i.mtime),r}async function d0({request:e}){var t;try{const r=new URL(e.url),s=((t=r.searchParams.get("search"))==null?void 0:t.toLowerCase())||"",a=Math.max(1,parseInt(r.searchParams.get("page")||"1",10)),o=await c0();if(!s){const u=o.length,p=(a-1)*sn,h=o.slice(p,p+sn),f=[];for(const y of h){const g=await Eo(y);g&&f.push(g)}return Response.json({agents:f,total:u,page:a,pageSize:sn})}const i=[];for(const u of o){const p=await Eo(u);if(!p)continue;(p.id.toLowerCase().includes(s)||p.slug.toLowerCase().includes(s)||p.entries.some(f=>l0(f,s)))&&i.push(p)}const l=i.length,d=(a-1)*sn,m=i.slice(d,d+sn);return Response.json({agents:m,total:l,page:a,pageSize:sn})}catch(r){return console.error("[api.agent-transcripts] Error:",r),Response.json({error:"Failed to load agent transcripts",details:r instanceof Error?r.message:String(r)},{status:500})}}const u0=Object.freeze(Object.defineProperty({__proto__:null,loader:d0},Symbol.toStringTag,{value:"Module"})),Tl="__codeyam_editor_dev_server__",Ao=30;function ga(){return globalThis[Tl]??null}function $l(e){globalThis[Tl]=e}function bs(e,t){const r=[ee.join(e,".next","dev","lock"),ee.join(e,"node_modules",".vite","deps","_lock")];for(const s of r)try{Ne.existsSync(s)&&(Ne.unlinkSync(s),console.log(`[editor-dev-server] Removed stale lock file: ${s}`))}catch(a){console.warn(`[editor-dev-server] Failed to remove lock file ${s}:`,a)}if(t)try{const s=Ee(`lsof -ti:${t}`,{encoding:"utf8"}).trim();s&&(Ee(`lsof -ti:${t} | xargs kill`),console.log(`[editor-dev-server] Killed orphaned process(es) on port ${t}: ${s}`))}catch{}}function m0({request:e}){const t=ga();return t?new Response(JSON.stringify({status:t.status,url:t.url,proxyUrl:sl(),pid:t.pid,errorMessage:t.status==="error"?t.errorMessage:null}),{headers:{"Content-Type":"application/json"}}):new Response(JSON.stringify({status:"stopped",url:null,proxyUrl:null}),{headers:{"Content-Type":"application/json"}})}async function p0({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{action:r}=t;return r==="start"?Bs():r==="stop"?Po():r==="restart"?(Po(),await new Promise(s=>setTimeout(s,1e3)),Bs()):new Response(JSON.stringify({error:'Invalid action. Use "start", "stop", or "restart".'}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}function h0(){let t=ee.dirname(new URL(import.meta.url).pathname);for(let s=0;s<5;s++){const a=ee.dirname(t);if(ee.basename(a)==="webserver"||ee.basename(t)==="webserver"){t=ee.basename(t)==="webserver"?t:a;break}t=a}const r=[ee.join(t,"scripts","codeyam-preload.mjs"),ee.join(t,"scripts","codeyam-preload.mjs")];for(const s of r)if(Ne.existsSync(s))return s;return console.warn("[editor-dev-server] codeyam-preload.mjs not found, SSR fetch interception disabled"),null}function Bs(e=!1){var g,x;const t=ga();if(t&&t.status!=="stopped"&&t.status!=="error")return new Response(JSON.stringify({status:t.status,url:t.url,message:"Dev server is already running"}),{headers:{"Content-Type":"application/json"}});const r=me()||process.cwd(),s=ah(r);if("error"in s)return new Response(JSON.stringify({error:s.error}),{status:400,headers:{"Content-Type":"application/json"}});const{command:a,args:o}=s;bs(r,3e3),bs(r,3001),bs(r,5173),console.log(`[editor-dev-server] Starting: ${a} ${o.join(" ")} in ${r}`);const l=parseInt(process.env.CODEYAM_PORT||"3111",10)+1,d=h0(),m=process.env.NODE_OPTIONS||"",u=d?`${m} --import ${d}`.trim():m,p=Lt(a,o,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1",...u?{NODE_OPTIONS:u}:{},CODEYAM_PROXY_URL:`http://localhost:${l}`},detached:!0});p.unref();const h=e?((t==null?void 0:t.retryCount)??0)+1:0,f={process:p,url:null,status:"starting",errorMessage:null,stderrBuffer:[],pid:p.pid||0,startedAt:Date.now(),retryCount:h};$l(f);const y=(v,b)=>{const N=v.toString();if(b){const C=N.split(`
|
|
259
|
-
`).filter(E=>E.trim());f.stderrBuffer.push(...C),f.stderrBuffer.length>Ao&&(f.stderrBuffer=f.stderrBuffer.slice(-Ao))}if(f.status==="starting"){const C=ih(N);if(C){f.url=C,f.status="running",console.log(`[editor-dev-server] URL detected: ${f.url}`);const E=parseInt(process.env.CODEYAM_PORT||"3111",10);al({port:E+1,targetUrl:f.url})}}};return(g=p.stdout)==null||g.on("data",v=>y(v,!1)),(x=p.stderr)==null||x.on("data",v=>y(v,!0)),p.on("exit",v=>{console.log(`[editor-dev-server] Process exited with code ${v}`);const b=Date.now()-f.startedAt,N=ch({exitCode:v??null,uptime:b,retryCount:f.retryCount});N.action==="retry"?(console.log(`[editor-dev-server] Quick failure (${b}ms), auto-retrying...`),f.status="stopped",Bs(!0)):N.action==="error"?(f.status="error",f.errorMessage=f.stderrBuffer.length>0?f.stderrBuffer.join(`
|
|
260
|
-
`):`Dev server exited with code ${v}`,console.error(`[editor-dev-server] Server failed: ${f.errorMessage}`)):f.status="stopped"}),p.on("error",v=>{console.error("[editor-dev-server] Process error:",v),f.status="error",f.errorMessage=v.message}),new Response(JSON.stringify({status:"starting",pid:p.pid,message:`Starting ${a} ${o.join(" ")}`}),{headers:{"Content-Type":"application/json"}})}function Po(){const e=ga();if(!e||e.status==="stopped")return new Response(JSON.stringify({status:"stopped",message:"No server to stop"}),{headers:{"Content-Type":"application/json"}});ol();try{e.process.pid&&process.kill(-e.process.pid,"SIGTERM")}catch{try{e.process.kill("SIGTERM")}catch{}}return e.status="stopped",$l(null),new Response(JSON.stringify({status:"stopped",message:"Dev server stopped"}),{headers:{"Content-Type":"application/json"}})}const f0=Object.freeze(Object.defineProperty({__proto__:null,action:p0,loader:m0},Symbol.toStringTag,{value:"Module"}));async function g0({params:e,request:t}){const{projectSlug:r}=e;if(!r)return new Response("Project slug is required",{status:400});if(t.method!=="DELETE")return new Response("Method not allowed",{status:405});const s=Lr(r);try{return await Pn(s,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(a){console.error("[api.logs] Error clearing log file:",a);const o=a instanceof Error?a.message:String(a);return new Response(`Error clearing log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function y0({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=Lr(t);try{if(!jt(r))return new Response("No logs available yet. Analysis may not have started.",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});const s=await Es(r,"utf-8");return!s||s.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(s,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(s){console.error("[api.logs] Error reading log file:",s);const a=s instanceof Error?s.message:String(s);return new Response(`Error reading log file: ${a}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const x0=Object.freeze(Object.defineProperty({__proto__:null,action:g0,loader:y0},Symbol.toStringTag,{value:"Module"}));function b0({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return Response.json({error:"Missing path parameter"},{status:400});const s=me()||process.cwd(),a=Y.resolve(s,r);if(!a.startsWith(s+Y.sep)&&a!==s)return Response.json({error:"Path outside project root"},{status:403});const o=xl(r,s);return Response.json(o)}const v0=Object.freeze(Object.defineProperty({__proto__:null,loader:b0},Symbol.toStringTag,{value:"Module"}));async function w0(){const e=await Te();if(!e)return Response.json({error:"No project configured"},{status:400});const{project:t}=await Re(e),r=_e(),s=process.env.CODEYAM_PORT||"3111",a=me()||process.cwd(),o=await r.selectFrom("editor_scenarios").select(["id","name","component_name","component_path","url"]).where("project_id","=",t.id).orderBy("created_at","asc").execute(),i=en(o,m=>`${m.name}::${m.url||"/"}`);let l={};try{const m=i.map(p=>({componentName:p.component_name||null,componentPath:p.component_path||null,url:p.url??null}));l=(await fa({projectRoot:a,scenarioInputs:m})).entityChangeStatus}catch{}const d=i.map(m=>{let u=null;m.component_name?u=m.component_name:u=Nt(m.url??null);const p=u?l[u]:void 0;return{id:m.id,name:m.name,componentName:m.component_name||null,changeStatus:(p==null?void 0:p.status)||null,link:`http://localhost:${s}/editor?scenario=${m.id}&ref=link`}});return Response.json({scenarios:d})}const N0=Object.freeze(Object.defineProperty({__proto__:null,loader:w0},Symbol.toStringTag,{value:"Module"}));async function C0(e,t){var o,i,l,d,m,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Be();const r=await Et({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const s=(o=r.scenarios)==null?void 0:o.find(p=>p.id===t);if(!s)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${s.name}`);const a={returnValue:{status:"success",data:((d=(l=(i=s.metadata)==null?void 0:i.data)==null?void 0:l.argumentsData)==null?void 0:d[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(m=s.metadata)==null?void 0:m.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),a}async function S0({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),s=t.get("scenarioId");if(!r||!s)return Q({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${s}`);const a=await C0(r,s);return console.log("[API] Function execution completed successfully"),Q({success:!0,result:a})}catch(t){return console.log("[API] Error during function execution:",t),Q({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const k0=Object.freeze(Object.defineProperty({__proto__:null,action:S0},Symbol.toStringTag,{value:"Module"}));function E0({request:e}){return Q({status:"ok"})}async function A0({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Pt()),!r)return console.error("[Interactive Mode API] Queue not initialized"),Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("action"),o=s.get("analysisId"),i=s.get("scenarioId");if(!a||!o)return Q({error:"Missing required fields: action and analysisId"},{status:400});if(a!=="start"&&a!=="stop")return Q({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await Te();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return Q({error:"Project not initialized"},{status:500});if(a==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:l});return Q({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:l});return Q({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(s){console.error("[Interactive Mode API] Error:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),Q({error:"Failed to control interactive mode",details:a},{status:500})}}const P0=Object.freeze(Object.defineProperty({__proto__:null,action:A0,loader:E0},Symbol.toStringTag,{value:"Module"}));async function M0({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:s}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),s&&s.length>0){const a=me();if(a)for(const o of s){const i=ee.join(a,".codeyam","captures","screenshots",o);try{await ye.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(l){console.log(`[API] Could not delete screenshot ${i}:`,l instanceof Error?l.message:l)}}}await vu({ids:[r]});try{const a=me()||process.cwd();uh(a,r)}catch{}return console.log(`[API] Scenario ${r} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(t){return console.error("[API] Error deleting scenario:",t),Response.json({error:"Failed to delete scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const _0=Object.freeze(Object.defineProperty({__proto__:null,action:M0},Symbol.toStringTag,{value:"Module"}));class j0 extends Pr{emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}emitRefreshPreview(){this.emit("event",{type:"refresh-preview",timestamp:Date.now()})}}const Ys="__codeyam_dev_mode_event_emitter__";if(!globalThis[Ys]){const e=new j0;e.setMaxListeners(20),globalThis[Ys]=e}const Mo=globalThis[Ys];function T0({request:e}){const t=new ReadableStream({start(r){const s=new TextEncoder;r.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
261
|
-
|
|
262
|
-
`));let a=!1;const o=()=>{if(!a){a=!0,Mo.off("event",i),clearInterval(l);try{r.close()}catch{}}},i=d=>{try{r.enqueue(s.encode(`data: ${JSON.stringify(d)}
|
|
263
|
-
|
|
264
|
-
`))}catch{o()}};Mo.on("event",i);const l=setInterval(()=>{try{r.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
265
|
-
|
|
266
|
-
`))}catch{o()}},3e4);e.signal.addEventListener("abort",o)}});return new Response(t,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const $0=Object.freeze(Object.defineProperty({__proto__:null,loader:T0},Symbol.toStringTag,{value:"Module"})),In="/tmp/codeyam",Us=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",Rl=500,R0=Rl*1024*1024;function Gt(e,t){try{return Ee(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function ir(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Il(e){return Gt("config user.email",e)}function I0(e){const t=Y.join(e,".codeyam","debug-report.md");if(!K.existsSync(t))return null;try{return K.readFileSync(t,"utf8")}catch{return null}}function D0(e,t=20){const r=Y.join(In,"local-dev",e,"codeyam","log.txt");if(!K.existsSync(r))return[];try{return K.readFileSync(r,"utf8").split(`
|
|
267
|
-
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function L0(e){try{const t=await fetch(`${Us}/api/reports/check-base`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseSha:e})});if(!t.ok)return!1;const{hasBase:r}=await t.json();return r}catch{return!1}}function O0(e,t){try{Ee(`git archive HEAD | gzip > "${t}"`,{cwd:e,stdio:"pipe",shell:"/bin/bash"})}catch(r){throw new Error(`Failed to create base archive: ${r.message}`)}}function F0(e){const{projectRoot:t,projectSlug:r,outputPath:s,metadata:a,screenshot:o,onProgress:i}=e,l=i||(()=>{}),d=Date.now(),m=Y.join(In,`delta-staging-${d}`),u=Y.join(m,"delta");K.mkdirSync(u,{recursive:!0});try{const p=Gt("diff --binary HEAD",t)||"";K.writeFileSync(Y.join(u,"tracked.patch"),p?p+`
|
|
268
|
-
`:"");const h=Gt("ls-files --others --exclude-standard",t);if(h){const x=Y.join(u,"untracked");K.mkdirSync(x,{recursive:!0});for(const v of h.split(`
|
|
269
|
-
`).filter(Boolean)){const b=Y.join(t,v),N=Y.join(x,v);if(K.existsSync(b)){const C=Y.dirname(N);K.mkdirSync(C,{recursive:!0}),K.statSync(b).isFile()&&K.copyFileSync(b,N)}}}const f=Y.join(t,".codeyam");if(K.existsSync(f)){const x=Y.join(u,"codeyam");K.cpSync(f,x,{recursive:!0})}K.writeFileSync(Y.join(u,"meta.json"),JSON.stringify(a,null,2));const y=Y.join(In,"local-dev",r,"codeyam","log.txt");K.existsSync(y)?K.copyFileSync(y,Y.join(u,"codeyam-log.txt")):K.writeFileSync(Y.join(u,"codeyam-log.txt"),`# Log file not found
|
|
270
|
-
`);const g=Y.join(t,".codeyam","debug-report.md");K.existsSync(g)&&(K.copyFileSync(g,Y.join(u,"debug-report.md")),l("Debug report included")),o&&o.length>0&&(K.writeFileSync(Y.join(u,"screenshot.jpg"),o),l(`Screenshot included (${ir(o.length)})`));try{Ee(`tar -czf "${s}" -C "${m}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{K.rmSync(m,{recursive:!0,force:!0})}}async function z0(e){const{projectRoot:t,projectSlug:r,feedback:s,screenshot:a,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const l=Gt("rev-parse HEAD",t);if(!l)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=Gt("rev-parse --abbrev-ref HEAD",t)||"unknown",m=Gt("status --porcelain",t),u=Gt("remote get-url origin",t),p=m!==null&&m.length>0,h=Hi(r),f=I0(t);let y=s;f&&(y={...s||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam-diagnose workflow"));const g={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:l,branch:d,isDirty:p,remoteUrl:u},versions:{cli:h.cliVersion,webserver:h.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},x=Date.now(),v=Y.join(In,`base-${l}-${x}.tar.gz`),b=Y.join(In,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const N=await L0(l);let C=null;N?i("Server already has base, skipping..."):(i("Generating base archive..."),O0(t,v),C=K.statSync(v).size,i(`Base archive: ${ir(C)}`)),i("Generating delta archive..."),F0({projectRoot:t,projectSlug:r,outputPath:b,metadata:g,screenshot:a,onProgress:o});const w=K.statSync(b).size;i(`Delta archive: ${ir(w)}`);const k=(C||0)+w;if(k>R0)throw K.existsSync(v)&&K.unlinkSync(v),K.unlinkSync(b),new Error(`Bundle too large: ${ir(k)} (max: ${Rl} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:N?null:v,deltaPath:b,metadata:g,baseSha:l,baseSize:C,deltaSize:w}}async function B0(e){const{basePath:t,deltaPath:r,projectSlug:s,metadata:a,baseSha:o,deltaSize:i,onProgress:l}=e,d=l||(()=>{}),m=K.statSync(r),u=t?K.statSync(t):null,p=m.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const h=await fetch(`${Us}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:s,fileSizeBytes:p,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:a.timestamp,git:a.git,versions:a.versions,system:a.system,feedback:a.feedback}})});if(!h.ok){const N=await h.json();throw new Error(N.error||`Server returned ${h.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await h.json(),x=[];if(t&&g){d("Uploading base...");const N=K.readFileSync(t);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:N}).then(C=>{if(!C.ok)throw new Error(`Base upload failed: ${C.status}`)}))}d("Uploading delta...");const v=K.readFileSync(r);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(N=>{if(!N.ok)throw new Error(`Delta upload failed: ${N.status}`)})),await Promise.all(x),d("Confirming upload...");const b=await fetch(`${Us}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!b.ok){const N=await b.json();throw new Error(N.error||`Confirm failed: ${b.status}`)}return t&&K.existsSync(t)&&K.unlinkSync(t),K.unlinkSync(r),{bundleId:f}}async function Y0({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),s=t.get("description"),a=t.get("email"),o=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),d=t.get("analysisId"),m=t.get("currentUrl"),u=t.get("entityName"),p=t.get("entityType"),h=t.get("scenarioName"),f=t.get("errorMessage"),y=t.get("screenshot");let g=s||void 0;!g&&u&&(h?g=`Issue on ${u} scenario "${h}"`:g=`Issue on ${u}`);let x;if(y&&y.size>0){const k=await y.arrayBuffer();x=Buffer.from(k),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const v=me();if(!v)return Q({error:"Project root not found"},{status:500});const b=await Te();if(!b)return Q({error:"Project slug not found"},{status:500});const N={issueType:r||"other",description:g,email:a||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:d||void 0,currentUrl:m||void 0,recentActivity:D0(b,20),entityName:u||void 0,entityType:p||void 0,scenarioName:h||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${b}...`),console.log(`[Bundle] Context: ${N.source}, issue: ${N.issueType}`);const C=await z0({projectRoot:v,projectSlug:b,feedback:N,screenshot:x,onProgress:k=>{console.log(`[Bundle] ${k}`)}}),E=(C.baseSize||0)+C.deltaSize;console.log(`[Bundle] Archives created: delta=${C.deltaSize} bytes${C.basePath?`, base=${C.baseSize} bytes`:" (base reused)"}`);const w=await B0({basePath:C.basePath,deltaPath:C.deltaPath,projectSlug:b,metadata:C.metadata,baseSha:C.baseSha,deltaSize:C.deltaSize,onProgress:k=>{console.log(`[Bundle] ${k}`)}});return console.log(`[Bundle] Upload complete: ${w.bundleId}`),Q({success:!0,reportId:w.bundleId,size:E})}catch(t){return console.error("[Bundle] Error:",t),Q({error:t.message||"Failed to generate bundle"},{status:500})}}function U0(){const e=me(),t=e?Il(e):null;return Q({defaultEmail:t})}const W0=Object.freeze(Object.defineProperty({__proto__:null,action:Y0,loader:U0},Symbol.toStringTag,{value:"Module"}));async function J0({request:e}){try{const r=new URL(e.url).searchParams.get("date"),s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=Y.join(s,".codeyam","journal","index.json");let o={entries:[]};try{const l=await be.readFile(a,"utf8");o=JSON.parse(l)}catch{}let i=o.entries;return r&&(i=i.filter(l=>l.date===r)),new Response(JSON.stringify({entries:i}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const H0=Object.freeze(Object.defineProperty({__proto__:null,loader:J0},Symbol.toStringTag,{value:"Module"}));function Dl(e){if(!K.existsSync(e))return qe.Unknown;try{const t=JSON.parse(K.readFileSync(e,"utf8")),r={...t.dependencies,...t.devDependencies};return r.next?qe.Next:r["@remix-run/node"]||r["@remix-run/react"]||r["react-router"]?qe.Remix:r["react-scripts"]?qe.CRA:qe.Unknown}catch{return qe.Unknown}}function V0(e,t){let r=e;const s=Y.resolve(t);for(;;){const a=Y.resolve(r);if(K.existsSync(Y.join(a,"pnpm-lock.yaml")))return"pnpm";if(K.existsSync(Y.join(a,"yarn.lock")))return"yarn";if(K.existsSync(Y.join(a,"package-lock.json")))return"npm";if(a===s)break;const o=Y.dirname(a);if(o===a)break;r=o}throw new Error(`Could not detect package manager in ${e} or any parent directory up to ${t}`)}function G0(e){const t=/cd\s+([^\s;&|]+)\s*(?:&&|;)/,r=e.match(t);return r?r[1]:null}function q0(e){const t=Y.join(e,"package.json");if(!K.existsSync(t))return{isWebApp:!1};if(Dl(t)===qe.Unknown)return{isWebApp:!1};try{const a=JSON.parse(K.readFileSync(t,"utf8")).scripts||{},o=["remix","react-router","next dev","vite","react-scripts","webpack-dev-server","parcel"],l=Object.keys(a).filter(d=>["dev","start","serve","build"].some(m=>d.includes(m))).filter(d=>o.some(m=>a[d].includes(m)));if(l.length===0)return{isWebApp:!1};for(const d of l){const m=a[d],u=G0(m);if(u){const p=Y.join(e,u);if(K.existsSync(p)&&K.statSync(p).isDirectory())return{isWebApp:!0,actualPath:p}}}return{isWebApp:!0}}catch{return{isWebApp:!1}}}function Ll(e,t=e,r=0,s=3){if(r>s)return[];const a=[],o=q0(t);if(o.isWebApp){const l=o.actualPath||t,d=Y.relative(e,l);return a.push(d||"."),a}const i=["node_modules",".git",".next","dist","build",".cache","coverage",".codeyam"];try{const l=K.readdirSync(t,{withFileTypes:!0});for(const d of l)if(d.isDirectory()&&!i.includes(d.name)){const m=Y.join(t,d.name);a.push(...Ll(e,m,r+1,s))}}catch{}return a}function K0(e){const t=Ll(e);return t.length===0?[]:t.map(s=>{const a=Y.join(e,s),o=Y.join(a,"package.json"),i=Dl(o),l=V0(a,e);let d;if(i===qe.Remix||i===qe.Next){const p=Y.join(a,"app");K.existsSync(p)&&K.statSync(p).isDirectory()&&(d="app")}const m=Q0(s,e),u=m?{command:"sh",args:["-c",`${l} run ${m} -- --port $PORT`]}:void 0;return{path:s,framework:i,packageManager:l,appDirectory:d,startCommand:u}})}function Q0(e,t){const r=Y.join(t,e),s=Y.join(r,"package.json");if(!K.existsSync(s))return null;try{const o=JSON.parse(K.readFileSync(s,"utf8")).scripts||{},i=["dev","start","serve"];for(const l of i)if(o[l])return l;return null}catch{return null}}async function Z0({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=me()||process.cwd(),r=ee.join(t,".codeyam","config.json");let s=[];try{s=K0(t)}catch{}if(Ne.existsSync(r)){const i=JSON.parse(Ne.readFileSync(r,"utf8"));i.webapps=s,Ne.writeFileSync(r,JSON.stringify(i,null,2))}const a=await Te();if(a)try{await dn({projectSlug:a,metadataUpdate:{webapps:s}})}catch{}let o=!1;if(s.length>0)try{const i=process.env.CODEYAM_PORT||"3111",d=await(await fetch(`http://localhost:${i}/api/editor-dev-server`)).json();(d.status==="stopped"||d.status===void 0)&&(await fetch(`http://localhost:${i}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}),o=!0)}catch{}return new Response(JSON.stringify({success:!0,webapps:s,devServerStarted:o,message:`Detected ${s.length} webapp(s)`}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const X0=Object.freeze(Object.defineProperty({__proto__:null,action:Z0},Symbol.toStringTag,{value:"Module"}));function Kt(){const e=process.memoryUsage(),t=Cd.getHeapStatistics();return{process:{rss:Math.round(e.rss/1024/1024),heapTotal:Math.round(e.heapTotal/1024/1024),heapUsed:Math.round(e.heapUsed/1024/1024),external:Math.round(e.external/1024/1024),arrayBuffers:Math.round(e.arrayBuffers/1024/1024)},heap:{totalHeapSize:Math.round(t.total_heap_size/1024/1024),totalHeapSizeExecutable:Math.round(t.total_heap_size_executable/1024/1024),totalPhysicalSize:Math.round(t.total_physical_size/1024/1024),totalAvailableSize:Math.round(t.total_available_size/1024/1024),usedHeapSize:Math.round(t.used_heap_size/1024/1024),heapSizeLimit:Math.round(t.heap_size_limit/1024/1024),mallocedMemory:Math.round(t.malloced_memory/1024/1024),peakMallocedMemory:Math.round(t.peak_malloced_memory/1024/1024)},system:{totalMemory:Math.round(As.totalmem()/1024/1024),freeMemory:Math.round(As.freemem()/1024/1024)}}}function ey(){const e=Kt();console.log(`
|
|
271
|
-
[Memory Profiler] Detailed Statistics:`),console.log(" Process Memory:"),console.log(` RSS: ${e.process.rss} MB (total memory used by process)`),console.log(` Heap Used: ${e.process.heapUsed} MB / ${e.process.heapTotal} MB`),console.log(` External: ${e.process.external} MB (C++ objects)`),console.log(` ArrayBuffers: ${e.process.arrayBuffers} MB`),console.log(" V8 Heap:"),console.log(` Used: ${e.heap.usedHeapSize} MB / ${e.heap.totalHeapSize} MB`),console.log(` Physical: ${e.heap.totalPhysicalSize} MB`),console.log(` Limit: ${e.heap.heapSizeLimit} MB`),console.log(` Malloced: ${e.heap.mallocedMemory} MB (peak: ${e.heap.peakMallocedMemory} MB)`),console.log(" System:"),console.log(` Total: ${e.system.totalMemory} MB`),console.log(` Free: ${e.system.freeMemory} MB`);const t=(e.heap.usedHeapSize/e.heap.heapSizeLimit*100).toFixed(1);return console.log(` Heap Usage: ${t}% of limit`),e}function ty(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Kt();global.gc();const t=Kt(),r=e.process.heapUsed-t.process.heapUsed;return console.log(`[Memory Profiler] GC freed ${r} MB`),console.log(`[Memory Profiler] Heap: ${t.process.heapUsed} MB (was ${e.process.heapUsed} MB)`),!0}else return console.log("[Memory Profiler] GC not available. Start Node with --expose-gc to enable."),!1}function ny(){const e=Kt(),t=e.heap.usedHeapSize/e.heap.heapSizeLimit*100,r={highHeapUsage:t>80,highExternalMemory:e.process.external>200,highArrayBuffers:e.process.arrayBuffers>100,nearHeapLimit:e.heap.totalAvailableSize<100},s=[];return r.highHeapUsage&&s.push(`High heap usage: ${t.toFixed(1)}% of limit`),r.highExternalMemory&&s.push(`High external memory: ${e.process.external} MB`),r.highArrayBuffers&&s.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),r.nearHeapLimit&&s.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:r,warnings:s,hasIssues:s.length>0}}function ry({request:e}){const r=new URL(e.url).searchParams.get("action");try{switch(r){case"snapshot":return Response.json({success:!1,error:"Heap snapshots are disabled because they block the server for several minutes. Use action=leaks instead."},{status:400});case"gc":{const s=ty(),a=Kt();return Response.json({success:s,message:s?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:a})}case"detailed":{const s=ey();return Response.json({success:!0,stats:s})}case"leaks":{const s=ny(),a=Kt();return Response.json({success:!0,leakCheck:s,stats:a})}default:{const s=Kt();return Response.json({success:!0,stats:s,actions:{gc:"/api/memory-profile?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory-profile?action=detailed - Log detailed stats to console",leaks:"/api/memory-profile?action=leaks - Check for memory leak indicators"}})}}}catch(s){return console.error("[Memory API] Error:",s),Response.json({success:!1,error:s.message},{status:500})}}const sy=Object.freeze(Object.defineProperty({__proto__:null,loader:ry},Symbol.toStringTag,{value:"Module"})),Zn=Qs(Ks);async function ay({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const s=r.split(",").map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o));if(s.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const a=await Promise.all(s.map(async o=>{const i=oy(o),l=i?await iy(o):null;return{pid:o,isRunning:i,processName:l}}));return Response.json({processes:a})}function oy(e){try{return process.kill(e,0),!0}catch{return!1}}async function iy(e){if(process.platform==="win32")try{const{stdout:r}=await Zn(`tasklist /FI "PID eq ${e}" /FO CSV /NH`),s=r.match(/"([^"]+)"/);if(!s)return null;const a=s[1];if(a.toLowerCase()==="node.exe")try{const{stdout:o}=await Zn(`wmic process where "ProcessId=${e}" get CommandLine /FORMAT:LIST`),i=o.match(/codeyam-(\w+)/);if(i)return`codeyam-${i[1]}`}catch{}return a}catch{return null}try{const{stdout:r}=await Zn(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:s}=await Zn(`ps -p ${e} -o args=`),a=s.trim(),o=a.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:a.split(" ")[0]||null}catch{return null}}}const ly=Object.freeze(Object.defineProperty({__proto__:null,loader:ay},Symbol.toStringTag,{value:"Module"})),cy=Ar(import.meta.url),dy=Y.dirname(cy);function uy({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Gi(),r=me()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const s=(t==null?void 0:t.port)||3111,a=Y.join(dy,"..","..","..","..","webserver","bootstrap.js"),o=Y.join(r,".codeyam","logs");K.existsSync(o)||K.mkdirSync(o,{recursive:!0});const i=K.openSync(Y.join(o,"background-server.log"),"a"),l=K.openSync(Y.join(o,"background-server-error.log"),"a"),d=new Date().toISOString();K.appendFileSync(Y.join(o,"background-server.log"),`
|
|
272
|
-
[${d}] Server restart requested via dashboard
|
|
273
|
-
`),Pm();const m=Lt("node",[a],{detached:!0,stdio:["ignore",i,l],env:{...process.env,CODEYAM_PORT:s.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});m.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${m.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(t){return console.error("[api.restart-server] Error restarting server:",t),new Response(JSON.stringify({success:!1,error:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const my=Object.freeze(Object.defineProperty({__proto__:null,action:uy},Symbol.toStringTag,{value:"Module"}));async function py({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:s}=t;if(!r||!s)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${s.length} scenarios to save`),s.forEach((l,d)=>{var p,h,f,y,g;const m=(h=(p=l.metadata)==null?void 0:p.data)==null?void 0:h.argumentsData,u=Array.isArray(m)&&m.length>0?JSON.stringify(m[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!((f=l.metadata)!=null&&f.data),mockDataKeys:(g=(y=l.metadata)==null?void 0:y.data)!=null&&g.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(m)?m.length:"not-array",argumentsDataPreview:u})});const a=s.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),o=await Lu(a);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((l,d)=>{var u,p;const m=(p=(u=l.metadata)==null?void 0:u.data)==null?void 0:p.argumentsData;console.log(`[API] Saved scenario ${d}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(m)?m.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const hy=Object.freeze(Object.defineProperty({__proto__:null,action:py},Symbol.toStringTag,{value:"Module"})),fy=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function gy({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("search")||"",s=t.searchParams.get("page")||"1",a=new URLSearchParams;r&&a.set("search",r),s!=="1"&&a.set("page",s);const o=a.toString(),i=new URL(`/api/agent-transcripts${o?`?${o}`:""}`,e.url),d=await(await fetch(i.toString())).json();if(d.error)return Q({agents:[],error:d.error,search:r,page:1,totalPages:1});const m=d.total??(d.agents||[]).length,u=d.pageSize??20;return Q({agents:d.agents||[],error:null,search:r,page:d.page??parseInt(s,10),totalPages:Math.max(1,Math.ceil(m/u))})}catch(t){return console.error("Failed to load agent transcripts:",t),Q({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function yy(e){if(!e)return"";try{return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return e}}function xy(e){if(!e)return"";try{return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}catch{return e}}function by(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function lr({type:e,toolName:t}){const r={user_prompt:"bg-[#00b4d8] text-black",assistant_text:"bg-[#a8dadc] text-black",tool_call:"bg-[#f4a261] text-black",tool_result:"bg-[#2a9d8f] text-black",context:"bg-[#7c3aed] text-white"},s={user_prompt:"USER",assistant_text:"ASSISTANT",tool_call:t||"TOOL",tool_result:"RESULT",context:"CONTEXT"};return n("span",{className:`inline-block px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide ${r[e]||"bg-gray-300 text-black"}`,children:s[e]||e})}function vy({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let s=typeof r=="string"?r:JSON.stringify(r);return s.length>500&&(s=s.slice(0,500)+"..."),c("div",{children:[c("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:s})]},t)})})}function wy({content:e,truncated:t,fullLength:r}){const[s,a]=M(!1);return c("div",{children:[c("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!s&&"..."]}),t&&n("button",{onClick:()=>a(!s),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:s?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function Ny({entry:e,pairedResult:t}){const[r,s]=M(!1),a=yy(e.timestamp||"");return e.type==="user_prompt"?c("div",{className:"my-2",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(lr,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?c("div",{className:"my-2",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(lr,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?c("div",{className:"my-2",children:[c("button",{onClick:()=>s(!r),className:"flex items-center gap-2 w-full text-left bg-white border border-gray-200 rounded-md px-3 py-2 hover:bg-gray-50 cursor-pointer",children:[r?n(it,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(Dt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(lr,{type:"tool_call",toolName:e.name}),n("span",{className:"text-xs text-gray-500 font-mono truncate flex-1",children:e.summary||""}),n("span",{className:"text-[11px] text-gray-400 font-mono flex-shrink-0",children:a})]}),r&&c("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(vy,{input:e.input||{}}),t&&c("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[c("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(wy,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function Cy({context:e}){const[t,r]=M(!1);return c("div",{className:"my-2",children:[c("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(it,{className:"w-3 h-3 text-gray-400"}):n(Dt,{className:"w-3 h-3 text-gray-400"}),n(lr,{type:"context"}),n("span",{className:"text-xs text-gray-500",children:"Full prompt context"})]}),t&&n("pre",{className:"bg-gray-50 border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#7c3aed] max-h-96 overflow-y-auto text-gray-700",children:e})]})}function Sy({snippet:e}){const[t,r]=M(!1),s=e.split(`
|
|
274
|
-
`).filter(l=>l.trim()),a=s.slice(0,4),o=s.length>4,i=t?s:a;return c("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[c("div",{className:"flex items-center gap-2 mb-2",children:[n(Yc,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),c("span",{className:"text-[10px] text-blue-500",children:[s.length," message",s.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((l,d)=>{const m=l.match(/^\[(\w+)\]:\s*(.*)/);if(!m)return null;const[,u,p]=m,h=u==="user";return c("div",{className:"text-xs",children:[c("span",{className:`font-bold ${h?"text-blue-700":"text-gray-500"}`,children:[h?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:p.length>200?p.slice(0,200)+"...":p})]},d)})}),o&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${s.length} messages`})]})}function ky({change:e}){const[t,r]=M(!1),s=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return c("li",{children:[n("button",{onClick:()=>s&&r(!t),className:`text-left w-full ${s?"hover:text-green-900 cursor-pointer":""}`,children:c("span",{className:"inline-flex items-center gap-1",children:[s&&(t?n(it,{className:"w-3 h-3 inline flex-shrink-0"}):n(Dt,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&c("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&c("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&c("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function Ey({changes:e}){const t=e.filter(i=>i.action==="touched"),r=e.filter(i=>i.action!=="touched"),s=r.some(i=>i.action==="created"),a=r.some(i=>i.action==="modified");return c("div",{className:`my-2 border rounded-md p-3 ${s?"bg-green-50 border-green-200 text-green-800 [&_ul]:text-green-700":a?"bg-amber-50 border-amber-200 text-amber-800 [&_ul]:text-amber-700":"bg-gray-50 border-gray-200 text-gray-600 [&_ul]:text-gray-500"}`,children:[n("div",{className:"text-xs font-bold mb-1",children:"Rule Changes:"}),c("ul",{className:"text-xs space-y-0.5 font-mono",children:[r.map((i,l)=>n(ky,{change:i},l)),t.length>0&&c("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function Ay({result:e}){const t=e.is_error,r=t?"bg-red-50 border-red-200":"bg-green-50 border-green-200",s=t?"text-red-800":"text-green-800",a=t?"text-red-700":"text-green-700",o=e.subtype.replace(/^error_/,"").replace(/_/g," "),i=d=>d>=6e4?`${(d/6e4).toFixed(1)}m`:`${(d/1e3).toFixed(1)}s`,l=d=>d>=1e3?`${(d/1e3).toFixed(1)}k`:String(d);return c("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[c("div",{className:`text-xs font-bold mb-1 ${s}`,children:["Session Result: ",o]}),c("div",{className:`text-xs ${a} font-mono space-y-0.5`,children:[c("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&c("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&c("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&c("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&c("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&c("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&c("span",{children:["Input: ",l(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&c("span",{children:["Output: ",l(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&c("span",{children:["Cache read: ",l(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&c("span",{children:["Cache write:"," ",l(e.usage.cache_creation_input_tokens)]})]}),e.errors&&e.errors.length>0&&n("div",{className:"mt-1",children:e.errors.map((d,m)=>n("div",{className:"text-red-700 break-words",children:d},m))})]})]})}function Py({agent:e,defaultOpen:t,isAdmin:r}){var E,w,k;const[s,a]=M(t),[o,i]=M(!1),[l,d]=M(null),[m,u]=M(!1),p=ne(()=>{const S={};for(const A of e.entries)A.type==="tool_result"&&A.tool_use_id&&(S[A.tool_use_id]=A);return S},[e.entries]),h=ne(()=>{const S=new Set;for(const A of e.entries)A.type==="tool_call"&&A.tool_use_id&&p[A.tool_use_id]&&S.add(A.tool_use_id);return S},[e.entries,p]),f=S=>{S.stopPropagation(),i(!0),d(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(A=>A.json()).then(A=>{A.success?d(`Saved to ${A.fixturePath}`):d(`Error: ${A.error}`)}).catch(A=>{d(`Error: ${A instanceof Error?A.message:String(A)}`)}).finally(()=>{i(!1)})},y=(e.ruleChanges||[]).filter(S=>S.action!=="touched"),g=y.filter(S=>S.action==="created"),x=y.filter(S=>S.action==="modified"),v=(e.ruleChanges||[]).filter(S=>S.action==="touched"),b=y.length>0,N=v.length>0,C=b||N;return c("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${e.stats.errors>0?"border-red-300":g.length>0?"border-green-300":x.length>0?"border-amber-300":"border-gray-200"}`,children:[c("button",{onClick:()=>a(!s),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[s?n(it,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(Dt,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm font-bold text-[#005C75] font-mono",children:e.id.slice(0,8)}),e.slug&&n("span",{className:"text-xs text-gray-500",children:e.slug}),e.model&&n("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold bg-purple-100 text-purple-700",title:e.model,children:by(e.model)}),g.length>0&&c("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(dr,{className:"w-3 h-3"}),g.length," rule",g.length!==1?"s":""," ","created"]}),x.length>0&&c("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(dr,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!b&&N&&c("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[v.length," timestamp",v.length!==1?"s":""," ","touched"]}),e.stats.errors>0&&c("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-100 text-red-800",children:[n(cr,{className:"w-3 h-3 flex-shrink-0"}),e.stats.errors," ",e.stats.errors===1?"Error":"Errors"]}),c("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks",((E=e.sessionResult)==null?void 0:E.duration_ms)!=null&&c(ue,{children:[" · ",e.sessionResult.duration_ms>=6e4?`${(e.sessionResult.duration_ms/6e4).toFixed(1)}m`:`${(e.sessionResult.duration_ms/1e3).toFixed(1)}s`]}),((w=e.sessionResult)==null?void 0:w.total_cost_usd)!=null&&c(ue,{children:[" · ","$",e.sessionResult.total_cost_usd.toFixed(2)]})]}),c("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[xy(e.timestamp),r&&b&&c("button",{onClick:f,disabled:o,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-bold bg-gray-100 text-gray-600 hover:bg-gray-200 disabled:opacity-50 cursor-pointer",title:"Save as test fixture",children:[n(Bc,{className:"w-3 h-3"}),o?"Saving...":"Save Fixture"]})]})]}),l&&n("div",{className:`px-4 py-2 text-xs font-mono ${l.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:l}),s&&c("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.sourceFile&&c("div",{className:"flex items-center gap-2 py-2 text-xs text-gray-500 font-mono",children:[n("span",{className:"text-gray-400",children:"FILE:"}),n("span",{className:"truncate",children:e.sourceFile}),n("button",{onClick:S=>{S.stopPropagation(),navigator.clipboard.writeText(e.sourceFile),u(!0),setTimeout(()=>u(!1),2e3)},className:"p-0.5 rounded text-gray-400 hover:text-gray-600 cursor-pointer transition-colors flex-shrink-0",title:"Copy file path",children:m?n(pt,{className:"w-3.5 h-3.5 text-green-500"}):n(wt,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(Ay,{result:e.sessionResult}),e.stats.errors>0&&((k=e.stats.errorMessages)==null?void 0:k.length)>0&&c("div",{className:"my-2 bg-red-50 border border-red-200 rounded-md p-3",children:[c("div",{className:"text-xs font-bold text-red-800 mb-1",children:[e.stats.errors," Error",e.stats.errors!==1?"s":"",":"]}),n("ul",{className:"text-xs text-red-700 space-y-1 font-mono",children:e.stats.errorMessages.map((S,A)=>n("li",{className:"break-words",children:S},A))})]}),e.conversationSnippet&&n(Sy,{snippet:e.conversationSnippet}),C&&n(Ey,{changes:e.ruleChanges}),e.context&&n(Cy,{context:e.context}),e.entries.map((S,A)=>{if(S.type==="tool_result"&&S.tool_use_id&&h.has(S.tool_use_id))return null;const $=S.type==="tool_call"&&S.tool_use_id?p[S.tool_use_id]:void 0;return n(Ny,{entry:S,pairedResult:$},`${e.id}-${A}`)})]})]})}function vs(e,t){const r=new URLSearchParams;t&&r.set("search",t),e>1&&r.set("page",String(e));const s=r.toString();return`/agent-transcripts${s?`?${s}`:""}`}const My=We(function(){const{agents:t,error:r,search:s,page:a,totalPages:o}=Ve(),i=Ct(),l=bc("root"),d=(l==null?void 0:l.isAdmin)??!1,[m,u]=M(s),[p,h]=M(!1),[f,y]=M(0);ht({source:"agent-transcripts-page"});const g=v=>{v.preventDefault(),window.location.href=vs(1,m)},x=()=>{h(!p),y(v=>v+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:r})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8",children:[c("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{i("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(Fc,{className:"w-5 h-5"})}),n(ur,{className:"w-6 h-6 text-[#232323]"}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Agent Transcripts"})]}),n("p",{className:"text-[15px] text-gray-500 ml-14",children:"View background agent transcripts and tool call history"})]}),c("div",{className:"flex items-center gap-4 mb-6",children:[c("form",{onSubmit:g,className:"relative flex-1 max-w-md",children:[n(Ln,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:m,onChange:v=>u(v.target.value),placeholder:"Search transcripts...",className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),n("button",{onClick:x,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:p?"Collapse All":"Expand All"})]}),c("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",a," of ",o,s&&c("span",{children:[" ","matching “",s,"”",n(de,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?c("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(ur,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Agent Transcripts Found"}),n("p",{className:"text-gray-500",children:"Background agent output files will appear here when available."})]}):n("div",{children:t.map(v=>n(Py,{agent:v,defaultOpen:p,isAdmin:d},v.id))},f),o>1&&c("div",{className:"flex items-center justify-center gap-3 mt-8",children:[c("a",{href:a>1?vs(a-1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a>1?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:[n(zc,{className:"w-4 h-4"}),"Prev"]}),c("span",{className:"text-sm text-gray-500 font-mono",children:[a," / ",o]}),c("a",{href:a<o?vs(a+1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a<o?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:["Next",n(Dt,{className:"w-4 h-4"})]})]})]})})}),_y=Object.freeze(Object.defineProperty({__proto__:null,default:My,loader:gy,meta:fy},Symbol.toStringTag,{value:"Module"}));async function jy({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{message:r}=t;if(!r)return new Response(JSON.stringify({error:"message is required"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();console.log(`[editor-commit] Committing with message: "${r}" in ${s}`);const a=Fg(s);a&&console.log("[editor-commit] Initialized new git repository"),zg(s),console.log("[editor-commit] Staged all changes");const o=Bg(s,r);console.log(`[editor-commit] Created commit: ${o}`);try{const{broadcastHideResults:i}=await Promise.resolve().then(()=>ph);i()}catch{}return new Response(JSON.stringify({success:!0,commitSha:o,initialized:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-commit] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Ty=Object.freeze(Object.defineProperty({__proto__:null,action:jy},Symbol.toStringTag,{value:"Module"})),$y=["JSX","React","Element","ReactNode"];function Ry(e){return e.returnType?$y.some(t=>e.returnType.includes(t)):!1}function Iy(e){const t=[],r=[];for(const s of e)Ry(s)?t.push(s):r.push(s);return{components:t,functions:r}}function Dy({components:e,functions:t,scenarioCounts:r,testFileExistence:s,testResults:a}){const o=e.map(f=>{const y=r[f.name]||0;return{name:f.name,filePath:f.filePath,scenarioCount:y,status:y>0?"ok":"missing"}}),i=t.map(f=>{if(!(f.testFile?s[f.testFile]??!1:!1))return{name:f.name,filePath:f.filePath,testFile:f.testFile,testFileExists:!1,status:"missing"};const g=f.testFile&&a?a[f.testFile]:void 0;if(!g)return{name:f.name,filePath:f.filePath,testFile:f.testFile,testFileExists:!0,status:"ok"};let x;return g.passing?g.hasEntityNameDescribe?x="ok":x="name_mismatch":x="failing",{name:f.name,filePath:f.filePath,testFile:f.testFile,testFileExists:!0,testsPassing:g.passing,testsVisibleInUi:g.hasEntityNameDescribe,status:x}}),l=o.filter(f=>f.status==="ok").length,d=o.length-l,m=i.filter(f=>f.status==="ok").length,u=i.filter(f=>f.status==="failing").length,p=i.filter(f=>f.status==="name_mismatch").length,h=i.filter(f=>f.status==="missing").length;return{components:o,functions:i,summary:{totalComponents:o.length,componentsOk:l,componentsMissing:d,totalFunctions:i.length,functionsOk:m,functionsMissing:h,functionsFailing:u,functionsNameMismatch:p,allPassing:d===0&&u===0&&p===0&&h===0}}}async function Ly(){const e=me()||process.cwd(),t=Y.join(e,".codeyam","glossary.json");let r;try{const h=K.readFileSync(t,"utf8");r=JSON.parse(h),Array.isArray(r)||(r=[])}catch{return Response.json({components:[],functions:[],summary:{totalComponents:0,componentsOk:0,componentsMissing:0,totalFunctions:0,functionsOk:0,functionsMissing:0,functionsFailing:0,functionsNameMismatch:0,allPassing:!0}})}if(r.length===0)return Response.json({components:[],functions:[],summary:{totalComponents:0,componentsOk:0,componentsMissing:0,totalFunctions:0,functionsOk:0,functionsMissing:0,functionsFailing:0,functionsNameMismatch:0,allPassing:!0}});const s=Y.join(e,".codeyam","editor-step.json");let a=null;try{const h=K.readFileSync(s,"utf8");a=JSON.parse(h).featureStartedAt||null}catch{}const{components:o,functions:i}=Iy(r),l={},d=await Te();if(d)try{const{project:h}=await Re(d),f=_e();let y=f.selectFrom("editor_scenarios").select(["component_name"]).select(f.fn.count("id").as("count")).where("project_id","=",h.id).where("component_name","is not",null).groupBy("component_name");if(a){const x=a.replace("T"," ").replace(/\.\d{3}Z$/,"");y=y.where("created_at",">=",x)}const g=await y.execute();for(const x of g)x.component_name&&(l[x.component_name]=Number(x.count))}catch{}const m={};for(const h of i)h.testFile&&(m[h.testFile]=K.existsSync(Y.join(e,h.testFile)));const u={};for(const h of i)if(!(!h.testFile||!m[h.testFile]))try{const f=await Ml(e,h.testFile),y=f.status==="passed",g=f.testCases.some(x=>x.fullName.startsWith(h.name));u[h.testFile]={passing:y,hasEntityNameDescribe:g}}catch{u[h.testFile]={passing:!1,hasEntityNameDescribe:!1}}const p=Dy({components:o,functions:i,scenarioCounts:l,testFileExistence:m,testResults:u});return Response.json(p)}const Oy=Object.freeze(Object.defineProperty({__proto__:null,loader:Ly},Symbol.toStringTag,{value:"Module"}));async function Fy({request:e}){try{const t=await e.json(),{pid:r,signal:s="SIGTERM",commitSha:a}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!_o(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,s)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,l=500,d=Date.now();let m=!0;for(;m&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,l)),m=_o(r);if(m){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(a)try{await Tt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:s,message:`Process ${r} killed successfully`,waitedMs:Date.now()-d})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function _o(e){try{return process.kill(e,0),!0}catch{return!1}}const zy=Object.freeze(Object.defineProperty({__proto__:null,action:Fy},Symbol.toStringTag,{value:"Module"})),By=Ar(import.meta.url),Yy=ee.dirname(By),Uy=ee.resolve(Yy,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function Wy(e){const t=[],r=new Set;for(const s of e.split(`
|
|
275
|
-
`)){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const l of i.content){if(typeof l!="object"||l===null)continue;const d=l;if(d.type!=="tool_use")continue;const m=String(d.name||""),u=d.input||{};if(m==="Write"||m==="Edit"){const p=String(u.file_path||"");if(p.includes(".claude/rules/")){const h=p.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${m}:${h}`;r.has(f)||(r.add(f),t.push({action:m==="Write"?"created":"modified",filePath:h}))}}else if(m==="Bash"){const p=String(u.command||"");if(p.includes("codeyam memory touch")){const h=`touch:${p}`;r.has(h)||(r.add(h),t.push({action:"touched",filePath:p}))}}}}return t}async function Jy({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{sessionId:r}=t;if(!r)return Response.json({error:"Missing required field: sessionId"},{status:400});const s=await jl(),a=s?ee.join(or,s):null;let o=a?ee.join(a,`${r}.log`):"";if((!o||!jt(o))&&(o=ee.join(or,`${r}.log`)),!jt(o))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await Es(o,"utf-8");let l=a?ee.join(a,`${r}.context`):"";(!l||!jt(l))&&(l=ee.join(or,`${r}.context`));let d=null;if(jt(l))try{d=await Es(l,"utf-8")}catch{}const m=Wy(i),p=d?["no,","no ","that's not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","shouldn't","try again","that broke","that failed","error","bug"].some(x=>d.toLowerCase().includes(x)):!1,h=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+h,y=ee.join(Uy,f);await dd(y,{recursive:!0}),await Pn(ee.join(y,"agent-log.jsonl"),i),d&&await Pn(ee.join(y,"context.md"),d),await Pn(ee.join(y,"rule-changes.json"),JSON.stringify(m,null,2)),await Pn(ee.join(y,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:p,ruleChangeCount:m.length},null,2));const g=ee.relative(process.cwd(),y);return console.log(`[api.save-fixture] Saved fixture to ${g}`),Response.json({success:!0,fixturePath:g})}catch(t){return console.error("[api.save-fixture] Error:",t),Response.json({error:"Failed to save fixture",details:t instanceof Error?t.message:String(t)},{status:500})}}const Hy=Object.freeze(Object.defineProperty({__proto__:null,action:Jy},Symbol.toStringTag,{value:"Module"}));async function Vy({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=me();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const s=ee.join(r,".codeyam","captures","screenshots",t);try{await ye.access(s);const a=await ye.readFile(s),o=ee.extname(s).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(a,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const Gy=Object.freeze(Object.defineProperty({__proto__:null,loader:Vy},Symbol.toStringTag,{value:"Module"})),jo={visual:{label:"VISUAL",bgColor:"#f9f9f9",textColor:"#9040f5"},library:{label:"LIBRARY",bgColor:"#f9f9f9",textColor:"#06b6d5"},type:{label:"TYPE",bgColor:"#ffe1e1",textColor:"#db2627"},other:{label:"OTHER",bgColor:"#f9f9f9",textColor:"#646464"}};function ya({type:e,className:t=""}){const r=jo[e]||jo.other;return n("div",{className:`inline-flex items-center justify-center px-[4px] rounded-[4px] ${t}`,style:{backgroundColor:r.bgColor,color:r.textColor,height:"15px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-semibold leading-[15px] uppercase",children:r.label})})}const qy={analyzer:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},capture:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},running:{bgColor:"#e8ffe6",textColor:"#00925d",borderColor:"#c3f3bf"},error:{bgColor:"#fee2e2",textColor:"#991b1b",borderColor:"#fecaca"}};function Xn({variant:e,pid:t,label:r,className:s=""}){const a=qy[e],o=r||(e==="analyzer"&&t?`Analyzer: ${t}`:e==="capture"&&t?`Capture: ${t}`:e==="running"?"Running":e==="error"?"Error":"");return n("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${s}`,style:{backgroundColor:a.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:a.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:a.textColor},children:o})})}let To=!1;function Ky(){if(To)return;const e=document.createElement("style");e.textContent=`
|
|
276
|
-
@keyframes strongPulse {
|
|
277
|
-
0%, 100% { opacity: 0.2; }
|
|
278
|
-
50% { opacity: 1; }
|
|
279
|
-
}
|
|
280
|
-
`,document.head.appendChild(e),To=!0}function xa({size:e="medium",className:t=""}){typeof document<"u"&&Ky();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:s,centerDotSize:a,gap:o}=r[e];return c("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}const Qy=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function Zy({request:e,context:t,params:r}){var O,z,L,P,q,H,W,Z;let s=t.analysisQueue;s||(s=await Pt());const a=new URL(e.url),o=parseInt(a.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!s)return Q({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=s.getState(),m=await Te();let u=null;if(m&&((O=d==null?void 0:d.currentlyExecuting)!=null&&O.commitSha)){const{project:B,branch:F}=await Re(m),J=await gr({projectId:B.id,branchId:F.id,shas:[d.currentlyExecuting.commitSha]});u=J&&J.length>0?J[0]:null}else u=await hn();const p=async B=>{const F=await Xt(B);if(!F)return null;const{getAnalysesForEntity:J}=await Promise.resolve().then(()=>em),G=await J(B,!1);return{...F,analyses:G||[]}},h=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async B=>{const F=[];if(B.entityShas&&B.entityShas.length>0){const J=B.entityShas.map(X=>p(X)),G=await Promise.all(J);F.push(...G.filter(X=>X!==null))}return{...B,entities:F}}));let f=null;if(d!=null&&d.currentlyExecuting){const B=d.currentlyExecuting,F=[];if(B.entityShas&&B.entityShas.length>0){const J=B.entityShas.map(X=>p(X)),G=await Promise.all(J);F.push(...G.filter(X=>X!==null))}f={...B,entities:F}}const y=f?h.filter(B=>B.id!==f.id):h,g=((L=(z=u==null?void 0:u.metadata)==null?void 0:z.currentRun)==null?void 0:L.currentEntityShas)||[],v=(await Promise.all(g.map(B=>p(B)))).filter(B=>B!==null),b=[];if(m)try{const{project:B,branch:F}=await Re(m),J=await gr({projectId:B.id,branchId:F.id,limit:100});for(const G of J){const X=((P=G.metadata)==null?void 0:P.historicalRuns)||[];b.push(...X)}}catch(B){console.error("[activity.tsx] Failed to load historical runs from commits:",B)}const N=[...b].sort((B,F)=>{const J=B.lastCaptureAt||B.analysisCompletedAt||B.archivedAt||B.createdAt||"";return(F.lastCaptureAt||F.analysisCompletedAt||F.archivedAt||F.createdAt||"").localeCompare(J)}),C=(o-1)*i,E=C+i,w=N.slice(C,E),k=Math.ceil(N.length/i),S=await Promise.all(w.map(async B=>{const F=B.currentEntityShas||[];if(F.length===0)return{...B,entities:[]};const J=await Promise.all(F.map(G=>p(G)));return{...B,entities:J.filter(G=>G!==null)}})),A=!!f,$=y.length,_=N.filter(B=>{const F=!!B.failedAt,J=B.readyToBeCaptured,G=B.capturesCompleted??0,X=J===void 0?!0:J===0||G>=J;return!F&&!!B.analysisCompletedAt&&X}),j=new Set(((q=f==null?void 0:f.entities)==null?void 0:q.map(B=>B.sha))||[]),D=_.filter(B=>!(B.currentEntityShas||[]).some(J=>j.has(J))),T=(await Promise.all(D.slice(0,3).map(async B=>{const F=B.currentEntityShas||[];if(F.length===0)return{run:B,entities:[]};const J=await Promise.all(F.map(G=>p(G)));return{run:B,entities:J.filter(G=>G!==null)}}))).flatMap(({run:B,entities:F})=>F.map(J=>({...J,runId:B.id,completedAt:B.lastCaptureAt||B.analysisCompletedAt||B.archivedAt||B.createdAt})));let U=[],V=null,I=null;if((W=(H=u==null?void 0:u.metadata)==null?void 0:H.currentRun)!=null&&W.analysisCompletedAt&&v.length>0){const B=v[0].sha;V=v[0];const F=await $r(B);F&&F.length>0&&F[0].scenarios&&(U=F[0].scenarios,I=F[0].status)}return Q({state:{...d,jobs:y,currentlyExecuting:f},currentRun:(Z=u==null?void 0:u.metadata)==null?void 0:Z.currentRun,historicalRuns:S,totalHistoricalRuns:N.length,currentPage:o,totalPages:k,projectSlug:m,commitSha:u==null?void 0:u.sha,queueJobs:y,currentlyExecuting:f,currentEntities:v,tab:l,hasCurrentActivity:A,queuedCount:$,recentCompletedEntities:T,hasMoreCompletedRuns:D.length>3,currentEntityScenarios:U,currentEntityForScenarios:V,currentAnalysisStatus:I})}function Xy({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:s}){const a=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:s>0,count:s}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:a.map(o=>{const i=e===o.id;return n(de,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
|
|
281
|
-
relative pb-4 px-2 text-sm transition-colors cursor-pointer
|
|
282
|
-
${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
|
|
283
|
-
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:c("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
|
|
284
|
-
inline-block w-2 h-2 rounded-full
|
|
285
|
-
${i?"":"bg-gray-400"}
|
|
286
|
-
`,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function ex({currentlyExecuting:e,currentRun:t,state:r,projectSlug:s,commitSha:a,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:d,currentEntityForScenarios:m,currentAnalysisStatus:u}){var R,T,U,V;const[p,h]=M({}),[f,y]=M({isKilling:!1,current:0,total:0}),g=mt(),x=!!e,v=(e==null?void 0:e.entities)||[],b=!!(t!=null&&t.analysisCompletedAt),N=b&&!!(t!=null&&t.capturePid),C=!b,E=x,w=d||[],{lastLine:k}=St(s,E);te(()=>{if(!t)return;const I=[t.analyzerPid,t.capturePid].filter(P=>!!P);if(I.length===0)return;let O=!0;const z=async()=>{try{const q=await(await fetch(`/api/process-status?pids=${I.join(",")}`)).json();if(q.processes&&O){const H={};q.processes.forEach(W=>{H[W.pid]={isRunning:W.isRunning,processName:W.processName}}),h(H)}}catch(P){O&&console.error("Failed to fetch process statuses:",P)}};z();const L=setInterval(()=>void z(),5e3);return()=>{O=!1,clearInterval(L)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[S,A]=M(!1),[$,_]=M(!1);te(()=>{v.length<=3&&S&&A(!1)},[v.length,S]),te(()=>{i.length<=3&&$&&_(!1)},[i.length,$]);const j=S?v:v.slice(0,3),D=v.length>3;return c("div",{className:"flex flex-col gap-[45px]",children:[E?c("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[c("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(ct,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:N?"Capturing...":"Analyzing..."})]}),j.map(I=>c("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)"},children:[c("div",{className:"flex items-center gap-3",children:[n("div",{children:n(Xe,{type:I.entityType||"other",size:"large"})}),c("div",{className:"flex flex-col gap-[1px]",children:[c("div",{className:"flex items-center gap-[14px]",children:[n(de,{to:`/entity/${I.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:I.name}),I.entityType&&n(ya,{type:I.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:I.filePath,children:I.filePath})]})]}),n("button",{onClick:o,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]},I.sha)),D&&!S&&c("button",{onClick:()=>A(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",v.length-3," more"," ",v.length-3===1?"entity":"entities"]}),S&&D&&n("button",{onClick:()=>A(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"}),N&&w&&w.length>0&&m&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:w.map(I=>{var W,Z,B,F;if(!I.id)return null;const O=(Z=(W=I.metadata)==null?void 0:W.screenshotPaths)==null?void 0:Z[0],z=(B=I.metadata)==null?void 0:B.noScreenshotSaved,L=O&&!z,P=(F=u==null?void 0:u.scenarios)==null?void 0:F.find(J=>J.name===I.name),H=P&&P.screenshotStartedAt&&!P.screenshotFinishedAt||!L&&!z;return n(de,{to:`/entity/${m.sha}/scenarios/${I.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:H?"#f9f9f9":void 0,borderColor:H?"#efefef":"#ccc"},children:L?n(Ge,{screenshotPath:O,alt:I.name,className:"w-full h-full object-contain bg-gray-100"}):H?n("div",{className:"w-full h-full flex items-center justify-center",children:n(xa,{size:"medium"})}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},I.id)})}),k&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:k}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-2",children:[c("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(Xn,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(C||((R=p[t.analyzerPid])==null?void 0:R.isRunning))&&n(Xn,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(Xn,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(N||((T=p[t.capturePid])==null?void 0:T.isRunning))&&n(Xn,{variant:"running"})]}),(((U=p[t==null?void 0:t.analyzerPid])==null?void 0:U.isRunning)||((V=p[t==null?void 0:t.capturePid])==null?void 0:V.isRunning))&&n("button",{onClick:()=>{const I=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(L=>{var P;return!!L&&((P=p[L])==null?void 0:P.isRunning)});if(I.length===0)return;const O=I.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${O})?`))return;y({isKilling:!0,current:1,total:I.length}),(async()=>{for(let L=0;L<I.length;L++){const P=I[L];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:P,commitSha:a||""})})}catch(q){console.error(`Failed to kill process ${P}:`,q)}L<I.length-1&&y({isKilling:!0,current:L+2,total:I.length})}y({isKilling:!1,current:0,total:0}),g.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):c("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[c("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(di,{size:24,style:{color:"#005C75"}})}),c("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),c("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(de,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(de,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),c(de,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&c("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),c("div",{className:"flex flex-col gap-4",children:[($?i:i.slice(0,3)).map(I=>{var L;const O=(L=I.analyses)==null?void 0:L[0],z=(O==null?void 0:O.scenarios)||[];return O==null||O.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:c("div",{className:"flex flex-col gap-[15px]",children:[c("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(Xe,{type:I.entityType||"other",size:"large"})}),c("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[c("div",{className:"flex items-center gap-[5px]",children:[n(de,{to:`/entity/${I.sha}`,className:"hover:underline cursor-pointer",title:I.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:I.name}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:"#e8ffe6",color:"#00925d",fontSize:"12px",lineHeight:"16px",fontWeight:400},children:I.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:I.filePath,children:I.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:o,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:P=>{P.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:P=>{P.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),z.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:z.map(P=>{var Z,B,F;if(!P.id)return null;const q=(B=(Z=P.metadata)==null?void 0:Z.screenshotPaths)==null?void 0:B[0],H=(F=P.metadata)==null?void 0:F.noScreenshotSaved,W=q&&!H;return c("div",{className:"shrink-0 flex flex-col gap-2",children:[n(de,{to:`/entity/${I.sha}/scenarios/${P.id}`,className:"block cursor-pointer",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:W?"#f3f4f6":"#FAFAFA",borderColor:W?"#d1d5db":"#BCCDD3",borderStyle:W?"solid":"dashed"},onMouseEnter:J=>{W&&(J.currentTarget.style.borderColor="#005C75",J.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:J=>{J.currentTarget.style.borderColor=W?"#d1d5db":"#BCCDD3",J.currentTarget.style.boxShadow="none"},children:W?n(Ge,{screenshotPath:q,alt:P.name,className:"max-w-full max-h-full object-contain"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})})}),n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:P.name})]},P.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},I.sha)}),i.length>3&&!$&&c("button",{onClick:()=>_(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),$&&i.length>3&&n("button",{onClick:()=>_(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})]})}function tx({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return c("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[c("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Uc,{size:24,style:{color:"#005C75"}})}),c("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),c(de,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[s,a]=M(null),[o,i]=M(null),[l,d]=M(null),[m,u]=M(!1),[p,h]=M(!1),[f,y]=M(new Set),g=mt();te(()=>{e.length<=3&&p&&h(!1)},[e.length,p]);const x=w=>{a(w)},v=(w,k)=>{w.preventDefault(),i(k)},b=async(w,k)=>{if(w.preventDefault(),!s){i(null);return}const S=e.findIndex(_=>_.id===s);if(S===-1){a(null),i(null);return}if(S===k){a(null),i(null);return}const A=S<k?"down":"up",$=Math.abs(k-S);u(!0);try{for(let _=0;_<$;_++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:s,direction:A})});g.revalidate()}catch(_){console.error("Failed to reorder job:",_)}finally{u(!1),a(null),i(null)}},N=()=>{m||(a(null),i(null))},C=async w=>{if(confirm("Are you sure you want to cancel this job?"))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",jobId:w})}),window.location.reload()}catch(k){console.error("Failed to cancel job:",k)}},E=async()=>{if(confirm(`Are you sure you want to cancel all ${e.length} queued jobs?`))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}),window.location.reload()}catch(w){console.error("Failed to cancel jobs:",w)}};return c("div",{children:[c("div",{className:"flex items-center justify-between mb-4",children:[c("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void E(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),c("div",{className:"flex flex-col gap-3",children:[(p?e:e.slice(0,3)).map(w=>{var D,R,T,U;const k=e.findIndex(V=>V.id===w.id),S=l===k,A=s===w.id,$=o===k,_=f.has(w.id),j=((D=w.entities)==null?void 0:D.length)>0?_?w.entities:w.entities.slice(0,3):[];return c("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:A||m?.5:1,transform:$&&s!==null&&!A?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:m?"not-allowed":A?"grabbing":"grab"},onMouseEnter:()=>d(k),onMouseLeave:()=>d(null),draggable:!m,onDragStart:V=>{x(w.id),V.dataTransfer.effectAllowed="move"},onDragOver:V=>v(V,k),onDrop:V=>void b(V,k),onDragEnd:N,children:[c("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(Wc,{size:16,style:{color:"#005C75"}}),c("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",k+1]})]}),c("div",{className:"flex flex-col gap-2 mt-8",children:[j.length>0?c(ue,{children:[j.map(V=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(Xe,{type:V.entityType||"other",size:"large"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(de,{to:`/entity/${V.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:V.name}),V.entityType&&n(ya,{type:V.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:V.filePath})]})]})})},V.sha)),((R=w.entities)==null?void 0:R.length)>3&&n("button",{onClick:()=>{y(V=>{const I=new Set(V);return I.has(w.id)?I.delete(w.id):I.add(w.id),I})},className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"40px",fontSize:"12px",color:"#646464",fontWeight:500},children:_?"Show less":`+${w.entities.length-3} more ${w.entities.length-3===1?"entity":"entities"}`})]}):n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(mr,{size:18,style:{color:"#8e8e8e"}})}),c("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((T=w.entityNames)==null?void 0:T[0])||(w.type==="analysis"?"Analysis Job":w.type==="recapture"?"Recapture Job":w.type==="debug-setup"?"Debug Setup":w.type.charAt(0).toUpperCase()+w.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((U=w.filePaths)==null?void 0:U[0])||(w.filePaths&&w.filePaths.length>1?`${w.filePaths.length} files`:w.entityShas&&w.entityShas.length>0?`${w.entityShas.length} ${w.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),c("div",{className:"flex items-center justify-end gap-2 mt-1",children:[S&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(Jc,{size:20})}),n("button",{onClick:()=>void C(w.id),className:"transition-colors cursor-pointer hover:bg-red-100 rounded flex items-center justify-center",style:{fontSize:"10px",fontWeight:600,lineHeight:"22px",color:"#ef4444",backgroundColor:"#fef6f6",padding:"0 10px",height:"22px"},children:"Cancel"})]})]})]},w.id)}),e.length>3&&!p&&c("button",{onClick:()=>h(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),p&&e.length>3&&n("button",{onClick:()=>h(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function nx({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:s,tab:a,onShowLogs:o}){if(t===0)return c("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[c("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Hc,{size:24,style:{color:"#005C75"}})}),c("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),c(de,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,l]=M(!1),d=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(p=>{d.push({...p,runCreatedAt:u.createdAt})})});const m=i?d:d.slice(0,3);return c("div",{className:"flex flex-col gap-4",children:[m.map(u=>{var y;const p=(y=u.analyses)==null?void 0:y[0],h=(p==null?void 0:p.scenarios)||[],f=!u.isUncommitted;return c("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[c("div",{className:"flex items-start justify-between mb-3",children:[c("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(Xe,{type:u.entityType||"other",size:"large"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(de,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),h.length>0&&c("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[h.slice(0,8).map(g=>{var N,C,E;if(!g.id)return null;const x=(C=(N=g.metadata)==null?void 0:N.screenshotPaths)==null?void 0:C[0],v=(E=g.metadata)==null?void 0:E.noScreenshotSaved,b=x&&!v;return n(de,{to:`/entity/${u.sha}/scenarios/${g.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:b?"#ccc":"#BCCDD3",borderStyle:b?"solid":"dashed"},children:b?n(Ge,{screenshotPath:x,alt:g.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},g.id)}),h.length>8&&c("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",h.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),d.length>3&&!i&&c("button",{onClick:()=>l(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",d.length-3," more"," ",d.length-3===1?"entity":"entities"]}),i&&d.length>3&&n("button",{onClick:()=>l(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const rx=We(function(){const t=Ve(),r=ii(),[s,a]=M(!1);ht({source:"activity-page"});const o=r.tab||"current";return t?c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(Xy,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(ex,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>a(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),o==="queued"&&n(tx,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(nx,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>a(!0)}),s&&t.projectSlug&&n($t,{projectSlug:t.projectSlug,onClose:()=>a(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),sx=Object.freeze(Object.defineProperty({__proto__:null,default:rx,loader:Zy,meta:Qy},Symbol.toStringTag,{value:"Module"}));async function Ol(e,t,r){var C,E;await Be();const s=await Et({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=me();if(!a)throw new Error("Project root not found");const o=Y.join(a,".codeyam","config.json"),i=JSON.parse(K.readFileSync(o,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const d=Lr(l);try{K.writeFileSync(d,"","utf8")}catch{}const{project:m}=await Re(l),u=((C=m.metadata)==null?void 0:C.packageManager)||"npm",p=3112,h=ut(l),f=((E=m.metadata)==null?void 0:E.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const y=i.environmentVariables||[],g=xu({filePath:s.filePath,webapps:f,environmentVariables:y,port:p,packageManager:u});await pn(e,w=>{if(w&&(w.readyToBeCaptured=!0,w.scenarios))for(const k of w.scenarios)(!t||k.name===t)&&(delete k.screenshotStartedAt,delete k.screenshotFinishedAt,delete k.interactiveStartedAt,delete k.interactiveFinishedAt,delete k.error,delete k.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:s.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),v=g.startCommand,b={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:h}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${h}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:v,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${p}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:h,projectSlug:l,port:p,packageManager:u,framework:g.framework,instructions:b}}async function ax({request:e,context:t}){const r=new URL(e.url),s=r.searchParams.get("analysisId"),a=r.searchParams.get("scenarioId")||void 0;if(!s)return Q({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let o=t.analysisQueue;if(o||(o=await Pt()),!o)return Q({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:s,scenarioId:a});try{const i=await Ol(s,a,o);return Q({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),Q({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function ox({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Pt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a)return Q({error:"Missing required field: analysisId"},{status:400});const i=await Ol(a,o,r);return Q({...i,success:!0,message:"Debug setup queued"})}catch(s){console.error("[Debug Setup API] Error during debug setup:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Debug Setup API] Error stack:",o),Q({error:"Failed to setup debug environment",details:a},{status:500})}}const ix=Object.freeze(Object.defineProperty({__proto__:null,action:ox,loader:ax},Symbol.toStringTag,{value:"Module"}));function lx({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return new Response("Missing path parameter",{status:400});const s=me()||process.cwd(),a=Y.resolve(s,r);if(!a.startsWith(s+Y.sep)&&a!==s)return new Response("Path outside project root",{status:403});try{const o=K.readFileSync(a,"utf8");return new Response(o,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch{return new Response("File not found",{status:404})}}const cx=Object.freeze(Object.defineProperty({__proto__:null,loader:lx},Symbol.toStringTag,{value:"Module"})),dx=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function Fl(e){const t=pd("sha256",dx);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function ux(e,t){return t===Fl(e)}async function mx({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return Q({success:!1,error:"Unlock code is required"},{status:400});const s=await Te();return s?ux(s,r)?(await dn({projectSlug:s,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),Q({success:!0})):Q({success:!1,error:"Invalid unlock code"},{status:400}):Q({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),Q({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const px=Object.freeze(Object.defineProperty({__proto__:null,action:mx},Symbol.toStringTag,{value:"Module"}));async function hx({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Pt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("defaultWidth");if(!a||!o)return Q({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return Q({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${a} with width ${i}`);const l=await Gg(a,i,r);return console.log("[API] Recapture queued",l),Q({success:!0,message:"Recapture queued",...l})}catch(s){return console.log("[API] Error during recapture:",s),Q({error:"Failed to recapture screenshots",details:s instanceof Error?s.message:String(s)},{status:500})}}const fx=Object.freeze(Object.defineProperty({__proto__:null,action:hx},Symbol.toStringTag,{value:"Module"}));function gx(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(yx).map(a=>a===""?[]:a.split("/")).reduce((a,o)=>{const i=[];for(let l=0;l<Math.min(a.length,o.length)&&a[l]===o[l];l++)i.push(a[l]);return i}).join("/")}function yx(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const s=r[r.length-1];if(xx(s))r.pop();else break}return r.join("/")}function xx(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function bx({request:e}){const r=new URL(e.url).searchParams.getAll("paths");if(r.length===0)return Response.json({error:"Missing required query parameter: paths"},{status:400});const s=gx(r),a=s?`.claude/rules/${s}/`:".claude/rules/";return Response.json({result:a})}const vx=Object.freeze(Object.defineProperty({__proto__:null,loader:bx},Symbol.toStringTag,{value:"Module"}));function wx(e,t){var i,l,d,m,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,s=e.analyses&&e.analyses.length>0&&e.analyses.some(p=>p.scenarios&&p.scenarios.length>0);if(!r){const p=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),h=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return p||h?s?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:s?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const a=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((m=e.metadata)!=null&&m.previousVersionWithAnalyses)||a){const p=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return s&&!p?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:s?{state:"uncommitted_outdated_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Edited - Simulations Outdated",color:"text-amber-700",bgColor:"bg-amber-50",borderColor:"border-amber-300",icon:"⚠"}}:{state:"uncommitted_outdated_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}else return s?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:{state:"uncommitted_no_previous_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"New",color:"text-purple-700",bgColor:"bg-purple-50",borderColor:"border-purple-200",icon:"+"}}}function Nx(e){return wx(e).hasOutdatedSimulations}function Vr(e,t,r,s,a){var V,I,O,z,L,P,q,H;const o=(V=t==null?void 0:t.scenarios)==null?void 0:V.find(W=>W.name===e.name),i=!!(o!=null&&o.startedAt),l=!!(o!=null&&o.screenshotStartedAt),d=!!(o!=null&&o.screenshotFinishedAt),m=!!(o!=null&&o.finishedAt),u=1800*1e3,p=l&&!d&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,h=!!((O=(I=e.metadata)==null?void 0:I.screenshotPaths)!=null&&O[0])||!!((z=e.metadata)!=null&&z.executionResult),f=l&&!d,y=o==null?void 0:o.error,g=(P=(L=e.metadata)==null?void 0:L.executionResult)==null?void 0:P.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const W of t.errors)x.push({source:`${W.phase} phase`,message:W.message});if(t!=null&&t.steps)for(const W of t.steps)W.error&&x.push({source:W.name,message:W.error});const v=!h&&!y&&!g&&x.length>0,b=!!(y||g||p||v),N=p?"Capture timed out after 30 minutes":(typeof y=="string"?y:null)||(g==null?void 0:g.message)||(v?`Analysis error: ${x[0].message}`:null),C=p?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(o==null?void 0:o.errorStack)||(g==null?void 0:g.stack)||null,w=(s&&a?a.jobs.some(W=>{var Z;return((Z=W.entityShas)==null?void 0:Z.includes(s))||W.type==="analysis"&&W.entityShas&&W.entityShas.length===0})||((H=(q=a.currentlyExecuting)==null?void 0:q.entityShas)==null?void 0:H.includes(s)):!1)&&!i&&!b||!!(o!=null&&o.analyzing)&&!i&&!b,k=i&&!l&&!m&&!b,S=(w||k||f)&&!b,A=(w||k)&&r===!1&&!h;let $;A?$="crashed":b?$="error":h||m?$="completed":f?$="capturing":k?$="starting":w?$="queued":$="pending";let _="📷",j="pending",D=!1,R=`Not captured: ${e.name}`;const T="border-gray-300",U=b||A?"bg-red-50":"bg-white";return b||A?(_="⚠️",j="error",R=`Error: ${A?"Analysis process crashed":N||"Unknown error"}`):w?(_="⋯",j="queued",R=`Queued: ${e.name}`):k?(_="⋯",j="starting",D=!0,R=`Starting server for ${e.name}...`):f&&!b?(_="⋯",j="capturing",D=!0,R=`Capturing ${e.name}...`):h&&(_="✓",j="completed",R=e.name),{hasError:b||A,errorMessage:A?"Analysis process crashed":N,errorStack:A?"Process terminated unexpectedly before completing analysis":C,isCapturing:f,isCaptured:h,hasCrashed:A,isAnalyzing:S,isQueued:w,isServerStarting:k,status:$,icon:_,iconType:j,shouldSpin:D,title:R,borderColor:T,bgColor:U}}function zl({scenario:e,entitySha:t,size:r="medium",showBorder:s=!0,isOutdated:a=!1}){var C,E,w,k,S,A;const o=Vr(e,void 0,void 0,t,void 0),i=(C=e.metadata)==null?void 0:C.executionResult,l=!!i,m=(((w=(E=e.metadata)==null?void 0:E.data)==null?void 0:w.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,p=((S=(k=i==null?void 0:i.sideEffects)==null?void 0:k.consoleOutput)==null?void 0:S.length)||0,h=((A=i==null?void 0:i.timing)==null?void 0:A.duration)||0;let f=0;m>0&&f++,m>2&&f++,u&&f++,p>0&&f++,f=Math.min(3,f);const y=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:l?a?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},v=s?`border-2 ${x.border}`:"",b=Array.from({length:3},($,_)=>n("div",{className:`w-1 h-1 rounded-full ${_<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},_)),N=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:l?`${e.name}
|
|
287
|
-
${m} args → ${u?"value":"void"}${p>0?` (${p} logs)`:""}
|
|
288
|
-
${h}ms`:`Not executed: ${e.name}`;return c(de,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${y.width} ${y.height} ${v} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:N,onClick:$=>$.stopPropagation(),children:[n("div",{className:`${x.icon} ${y.iconSize} font-mono font-bold`,children:o.hasError?"⚠":l?"ƒ":"○"}),l&&!o.hasError&&c("div",{className:`flex items-center gap-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:m}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),l&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:b}),l&&!o.hasError&&h>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:h>1e3?`${Math.round(h/1e3)}s`:`${h}ms`}),l&&!o.hasError&&p>0&&r==="medium"&&c("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",p]})]})}function Ws({size:e=24,className:t=""}){return c("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function $o({scenario:e,entity:t,analysisStatus:r,queueState:s,processIsRunning:a,size:o="medium",cacheBuster:i,className:l="",viewMode:d}){var g,x;if(t.entityType==="library")return n(zl,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=Vr(e,r,a,t.sha,s),p=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},h=`relative ${p.containerClass} ${l}`,f=()=>{const v=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${v}/${d}`:v};if(u.isCaptured){const v=(x=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return n(de,{to:f(),className:`${h} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(Ge,{screenshotPath:v,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const y=()=>{const v={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},b=n(xa,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return b;switch(u.iconType){case"starting":case"capturing":return b;case"error":return c("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(Ws,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(Vc,{...v});default:return b}};return n(de,{to:f(),className:`${h} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:n("div",{className:p.iconSize,children:y()})})}const an=70;function Cx({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:s,entitySha:a,cacheBuster:o,activeTab:i,entityType:l,entity:d,queueState:m,processIsRunning:u,isEntityAnalyzing:p,areScenariosStale:h,viewMode:f,setViewMode:y,isBreakdownView:g}){var D,R,T,U,V,I;const x=xe(null),[v,b]=M(new Set),[N,C]=M(!1);te(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[s==null?void 0:s.id,i]);const E=O=>`/entity/${a}/scenarios/${O}`,w=O=>{b(z=>{const L=new Set(z);return L.has(O)?L.delete(O):L.add(O),L})},k=(O,z=2)=>{const P=O.split(`
|
|
289
|
-
`).slice(0,z).join(" ").trim();return P.length>an?P.substring(0,an-3):(O.split(`
|
|
290
|
-
`).length>z||O.length>P.length,P)},S=ne(()=>{var z;if(!((z=r==null?void 0:r.metadata)!=null&&z.executionFlows)||!(r!=null&&r.scenarios))return null;const O=r.scenarios.filter(L=>{var P;return!((P=L.metadata)!=null&&P.sameAsDefault)});return ma(r.metadata.executionFlows,O)},[r]),A=(S==null?void 0:S.totalFlows)||0,$=(S==null?void 0:S.coveredFlows)||0,_=(S==null?void 0:S.coveragePercentage)||0;(D=d==null?void 0:d.metadata)!=null&&D.defaultWidth||(R=r==null?void 0:r.metadata)!=null&&R.defaultWidth;const j=(T=r==null?void 0:r.status)!=null&&T.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return c("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&c("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),c("div",{className:"grid grid-cols-2 gap-2",children:[c(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((U=e[0])==null?void 0:U.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[c("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(_),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),c(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((V=e[0])==null?void 0:V.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[c("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[$,"/",A]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),c(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((I=e[0])==null?void 0:I.id)}`:`/entity/${a}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${g?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),g?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),d&&d.filePath&&n("div",{children:n(de,{to:`/entity/${a}/create-scenario`,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] no-underline flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&c("div",{className:"py-3 flex items-center justify-between",children:[c("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),j&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:j})]}),p&&(h||e.length===0)?c("div",{className:"",children:[c("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[c("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((O,z)=>{const L=!g&&(s==null?void 0:s.id)===O.id,P=v.has(O.id||"");return O.id?c(de,{to:E(O.id),ref:L?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${L?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n($o,{scenario:O,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),c("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${P?"":"line-clamp-1"}`,children:O.name}),O.description&&n("div",{className:"mt-2",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[P?O.description:k(O.description),!P&&O.description.length>an&&c(ue,{children:["...",n("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),w(O.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),P&&O.description.length>an&&n("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),w(O.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},z):null})})}),t.length>0&&!(p&&h)&&c("div",{className:"border-t border-[#e1e1e1] pt-3",children:[c("button",{onClick:()=>C(!N),className:"flex items-center gap-1 text-[10px] text-[#626262] font-medium cursor-pointer bg-transparent border-none p-0 hover:text-[#005c75] transition-colors w-full",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${N?"rotate-90":""}`,children:n("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"Hidden Scenarios (",t.length,")"]}),N&&c("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((O,z)=>{const L=!g&&(s==null?void 0:s.id)===O.id,P=v.has(O.id||"");return O.id?c(de,{to:`/entity/${a}/scenarios/${O.id}`,ref:L?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${L?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n($o,{scenario:O,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),c("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${P?"":"line-clamp-1"}`,children:O.name}),O.description&&n("div",{className:"mt-2",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[P?O.description:k(O.description),!P&&O.description.length>an&&c(ue,{children:["...",n("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),w(O.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),P&&O.description.length>an&&n("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),w(O.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},z):null})})]})]})]})}function Sx({scenario:e,entitySha:t,onApply:r,onSave:s,onEditMockData:a,onDelete:o,isApplying:i=!1,isSaving:l=!1,saveMessage:d=null,showDeleteConfirm:m=!1,onShowDeleteConfirm:u,isDeleting:p=!1,deleteError:h=null}){const[f,y]=M(""),g=async()=>{await r(f)},x=async v=>{await s(f,v),v||y("")};return c("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[c("div",{className:"border-b border-[#e1e1e1] pb-3",children:[c("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(de,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),c("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[c("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:v=>y(v.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),c("button",{onClick:()=>void g(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&c("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),c("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:a,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(de,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),c("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void x(!1),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:l?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void x(!0),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),o&&c(ue,{children:[m?c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),c("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:p,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:p?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:p,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),h&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:h})]})]})]})}function kx({scenario:e,analysis:t,entity:r}){var i,l,d;const s=((i=e.metadata)==null?void 0:i.executionResult)||null,a=((d=(l=e.metadata)==null?void 0:l.data)==null?void 0:d.argumentsData)||[],o=m=>{var y,g,x;if(!m)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],p=((y=m.sideEffects)==null?void 0:y.consoleOutput)||[];p.length>0&&(u.push(`Console Output: ${p.length} log ${p.length===1?"entry":"entries"} captured`),p.forEach(v=>{u.push(` [${v.level.toUpperCase()}] ${v.args.join(" ")}`)}));const h=((g=m.sideEffects)==null?void 0:g.fileWrites)||[];h.length>0&&(u.push(`
|
|
291
|
-
File System Operations: ${h.length} ${h.length===1?"operation":"operations"} detected`),h.forEach(v=>{u.push(` ${v.operation}: ${v.path}${v.size?` (${v.size} bytes)`:""}`)}));const f=((x=m.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
|
|
292
|
-
API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(v=>{u.push(` ${v.method} ${v.url}${v.status?` → ${v.status}`:""}${v.duration?` (${v.duration}ms)`:""}`)})),m.error&&u.push(`
|
|
293
|
-
Error: ${m.error.name||"Error"}: ${m.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
|
|
294
|
-
`)};return c("div",{className:"flex w-full h-full gap-0",children:[c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(a,null,2)})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:s?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:s.returnValue!==void 0?JSON.stringify(s.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(s)})})]})]})}const Jt={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function er({scenarioId:e,analysisId:t}){const[r,s]=M(!1),[a,o]=M(!1),[i,l]=M(null),[d,m]=M(!1),u=e||t;if(!u)return null;const p=`/codeyam-diagnose ${u}`,h=async()=>{o(!0);try{const{default:y}=await import("html2canvas-pro"),x=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(x),s(!0)}catch(y){console.error("Screenshot capture failed:",y),s(!0)}finally{o(!1)}},f=()=>{s(!1),l(null)};return c(ue,{children:[c("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:Jt.heading},children:"Claude can help debug this error."}),n("p",{className:"m-0 mb-4 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"18px",color:Jt.subtext},children:"Simply run this command in Claude Code:"}),c("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:Jt.commandBoxBg,borderColor:Jt.commandBoxBorder,maxWidth:"505px",height:"35px",paddingLeft:"13px",paddingRight:"13px",paddingTop:"6px",paddingBottom:"6px"},children:[n("code",{className:"font-mono font-['IBM_Plex_Mono'] flex-1 text-left",style:{fontSize:"12px",lineHeight:"20px",color:Jt.commandBoxText},children:p}),n("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(p),m(!0),setTimeout(()=>m(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:d?"#22c55e":Jt.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n(pt,{size:14}):n(wt,{size:14})})]}),c("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void h(),disabled:a,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:Jt.link},children:a?"capturing...":"please do so here"}),"."]})]}),n(yi,{isOpen:r,onClose:f,context:{source:e?"scenario-page":"entity-page",entitySha:void 0,scenarioId:e,analysisId:t,currentUrl:typeof window<"u"?window.location.pathname:"/"},screenshotDataUrl:i??void 0})]})}const Ro=1440,tr=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],xt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function Bl({selectedScenario:e,analysis:t,entity:r,viewMode:s,cacheBuster:a,hasScenarios:o,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:d=!0,processIsRunning:m,queueState:u}){var G,X,le,ve,oe,pe,Ce,$e,Me,Ie,Fe;const p=De(),[h,f]=M(!1),[y,g]=M(!1),[x,v]=M({name:"Desktop",width:Ro,height:900}),[b,N]=M(Ro),[C,E]=M(1),{customSizes:w,addCustomSize:k,removeCustomSize:S}=Yr(l),A=ne(()=>[...tr,...w],[w]),$=(ke,re)=>{N(ke);const he=A.find(Se=>Se.width===ke&&Se.height===re);v({name:(he==null?void 0:he.name)||"Custom",width:ke,height:re})},_=ke=>{N(ke.width),v({name:ke.name,width:ke.width,height:ke.height})},j=ke=>{k(ke,x.width,x.height??900),g(!1),v(re=>({...re,name:ke}))},D=(ke,re)=>{N(ke);const he=A.find(Se=>Se.width===ke&&Se.height===re);v(Se=>({name:(he==null?void 0:he.name)||"Custom",width:ke,height:Se.height}))},R=(X=(G=e==null?void 0:e.metadata)==null?void 0:G.screenshotPaths)==null?void 0:X[0],T=ne(()=>e?Vr(e,t==null?void 0:t.status,m,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,m,r==null?void 0:r.sha,u]),U=ne(()=>{var re,he;const ke=[];if((re=t==null?void 0:t.status)!=null&&re.errors&&t.status.errors.length>0)for(const Se of t.status.errors)ke.push({source:`${Se.phase} phase`,message:Se.message,stack:Se.stack});if((he=t==null?void 0:t.status)!=null&&he.steps)for(const Se of t.status.steps)Se.error&&ke.push({source:Se.name,message:Se.error,stack:Se.errorStack});return ke},[(le=t==null?void 0:t.status)==null?void 0:le.errors,(ve=t==null?void 0:t.status)==null?void 0:ve.steps]),V=(T==null?void 0:T.errorMessage)||null,I=(T==null?void 0:T.errorStack)||null,{interactiveServerUrl:O,isStarting:z,isLoading:L,showIframe:P,iframeKey:q,onIframeLoad:H}=rn({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:l,enabled:s==="interactive"}),W=ne(()=>O||null,[O]),Z=!i&&o&&e&&!((pe=(oe=e.metadata)==null?void 0:oe.screenshotPaths)!=null&&pe[0])&&(($e=(Ce=t==null?void 0:t.status)==null?void 0:Ce.scenarios)==null?void 0:$e.some(ke=>ke.name===e.name&&ke.screenshotStartedAt&&!ke.screenshotFinishedAt)),{lastLine:B}=St(l,i||s==="interactive"||Z||!1);if(!e){if(i&&r)return c(ue,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:Z?"Capturing screenshots...":"Analyzing..."}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:"This may take a few minutes."}),B&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:B}),l&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),h&&l&&n($t,{projectSlug:l,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(U.length>0){const ke=U.length===1?((Me=U[0])==null?void 0:Me.message)||"An error occurred during analysis.":`${U.length} errors occurred during analysis.`;return c(ue,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:c("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:xt.background,border:`2px solid ${xt.border}`},role:"alert",children:c("div",{className:"flex items-center gap-3",children:[n(Ws,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:c("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:xt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",ke," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:xt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(er,{analysisId:t==null?void 0:t.id})})]})}),h&&l&&n($t,{projectSlug:l,onClose:()=>f(!1)})]})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:c("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{p.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:p.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:p.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return c(ue,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
|
|
295
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
296
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
297
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
298
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
299
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||Z&&!R)&&!V&&s==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:c("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[c("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:Z?`Capturing ${r==null?void 0:r.name}`:`Analyzing ${r==null?void 0:r.name}`}),n("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:Z?`Taking screenshots for ${((Ie=t==null?void 0:t.scenarios)==null?void 0:Ie.length)||0} scenario${((Fe=t==null?void 0:t.scenarios)==null?void 0:Fe.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&c("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),B&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:B,children:B})]})]})}),l&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):s==="screenshot"&&(R||V)||s==="interactive"&&(W||z)||s==="data"?c(ue,{children:[V&&!R&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:c("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:xt.background,border:`2px solid ${xt.border}`,maxHeight:"50vh"},role:"alert",children:c("div",{className:"flex flex-col gap-3",children:[c("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:xt.text},children:[n(Ws,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),c("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:xt.link},children:"See logs"})," ","for details."]}),n("div",{className:"flex-1 min-w-0",children:n("div",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:xt.text},children:V})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(er,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),s==="interactive"?c("div",{className:"flex-1 flex flex-col min-h-0",children:[W&&c("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n(Mp,{presets:[...tr],customSizes:w,currentWidth:x.width,currentHeight:x.height??900,scale:C,onSizeChange:$,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:S}),e&&r&&c(de,{to:`/entity/${r.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${r.sha}/scenarios/${e.id}/interactive`)}`,className:"flex items-center gap-2 px-4 py-2 bg-[#005c75] text-white rounded hover:bg-[#004a5c] transition-colors text-sm font-medium no-underline",title:"Open in fullscreen",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),W&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${tr[tr.length-1].width}px`,width:"100%"},children:n(la,{currentViewportWidth:b,currentPresetName:x.name,onDevicePresetClick:_,devicePresets:A})})}),n(Wr,{scenarioId:e.id,scenarioName:e.name,iframeUrl:W,isStarting:z,isLoading:L,showIframe:P,iframeKey:q,onIframeLoad:H,onScaleChange:E,onDimensionChange:D,projectSlug:l,defaultWidth:x.width,defaultHeight:x.height})]}):s==="data"?n("div",{className:"flex-1 min-h-0",children:n(kx,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${b}px`},children:(R||!V)&&n(Ge,{screenshotPath:R,cacheBuster:a,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!R?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),c("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),c("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),B&&c("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:B})]}),l&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):V?c("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:c("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[c("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),c("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),c("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(de,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),c("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:V})})]}),I&&c("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:I})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(er,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):U.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:U,title:"Analysis Error",description:U.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${U.length} errors occurred during analysis. Screenshot capture was not completed.`}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(er,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):c("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),h&&l&&n($t,{projectSlug:l,onClose:()=>f(!1)}),y&&n(Br,{width:x.width,height:x.height??900,onSave:j,onCancel:()=>g(!1)})]})}function Ex({analysis:e,entitySha:t}){mt();const[r,s]=M(e);te(()=>{s(e)},[e]);const[a,o]=M(null),i=ne(()=>{var p;if(!((p=r==null?void 0:r.metadata)!=null&&p.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(h=>{var f;return!((f=h.metadata)!=null&&f.sameAsDefault)});return ma(r.metadata.executionFlows,u)},[r]),l=ne(()=>i?Dh(i):[],[i]),d=ne(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var p;return!((p=u.metadata)!=null&&p.sameAsDefault)}):[],[r]),m=u=>{var h;const p=((h=u.metadata)==null?void 0:h.coveredFlows)||[];return i?i.executionFlows.filter(f=>p.includes(f.id)):[]};return r?!i||i.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:c("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:c("div",{className:"p-6 space-y-6",children:[c("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),c("div",{className:"grid grid-cols-4 gap-4 text-center",children:[c("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:d.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[c("div",{className:"text-2xl font-bold text-gray-900",children:[i.coveredFlows,"/",i.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[c("div",{className:`text-2xl font-bold ${i.coveragePercentage===100?"text-green-600":i.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[i.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),c("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:c("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",d.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:d.length===0?c("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n(de,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):d.map(u=>{var f,y,g;const p=(y=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0],h=m(u);return c("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(Ge,{screenshotPath:p,alt:u.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:c("div",{children:[n(de,{to:`/entity/${t}/scenarios/${u.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:u.name}),((g=u.metadata)==null?void 0:g.error)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:u.description}),h.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:h.map(x=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${x.isError?"bg-red-50 text-red-700":x.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:x.name},x.id))})]})]},u.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:c(de,{to:`/entity/${t}/create-scenario`,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 no-underline",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),l.length>0&&c("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[c("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[l.length," uncovered execution flow",l.length>1?"s":""," — consider adding scenarios to cover these"]}),c("div",{className:"flex flex-wrap gap-1",children:[l.slice(0,10).map(u=>c("span",{className:`text-xs px-2 py-0.5 rounded ${u.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[u.name,u.impact==="high"&&" (high impact)"]},u.id)),l.length>10&&c("span",{className:"text-xs text-amber-600",children:["+",l.length-10," more"]})]})]}),c("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:c("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",i.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const p=a===u.id,h=u.usedInScenarios.length>0;return c("div",{children:[n("button",{onClick:()=>o(p?null:u.id),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:c("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:p?"▼":"▶"}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:u.name}),h?n("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):n("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),u.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),u.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),u.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),u.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:u.description})]})]})}),p&&c("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[u.requiredValues.length>0&&c("div",{className:"mb-4",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:u.requiredValues.map((f,y)=>c("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:f.attributePath}),n("span",{className:"text-gray-400",children:f.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:f.value})]},y))})]}),h&&c("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children:u.usedInScenarios.map(f=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:f.name},f.id))})]}),u.codeSnippet&&c("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:c("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function Io({hasIndirectBadge:e,onAnalyze:t}){return c(ue,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),c("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function Ax({entity:e,history:t}){const[r,s]=M("entity"),[a,o]=M(new Set),i=t.filter(u=>u.analyses.length>0).length,l=ne(()=>{const u=new Map;return t.forEach(p=>{p.analyses.forEach(h=>{(h.scenarios??[]).filter(y=>{var g;return!((g=y.metadata)!=null&&g.sameAsDefault)}).forEach(y=>{u.has(y.name)||u.set(y.name,[]),u.get(y.name).push({version:p,analysis:h,scenario:y})})})}),Array.from(u.entries()).map(([p,h])=>{var f;return{name:p,description:((f=h[0])==null?void 0:f.scenario.description)||"",versions:h.sort((y,g)=>{const x=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-x})}})},[t]),d=l.length,m=u=>{o(p=>{const h=new Set(p);return h.has(u)?h.delete(u):h.add(u),h})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:c("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:c("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[c("button",{onClick:()=>s("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),c("button",{onClick:()=>s("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:d})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?c("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,p)=>c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[u.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),c(de,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((h,f)=>{var g;const y=(h.scenarios??[]).filter(x=>{var v;return!((v=x.metadata)!=null&&v.sameAsDefault)});return n("div",{children:y.length===0?n(Io,{hasIndirectBadge:h.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):c(ue,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-end gap-2",children:[h.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[y.length," scenario",y.length!==1?"s":""]})]})}),((g=h.metadata)==null?void 0:g.scenarioChangesOverview)&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:c("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[c("span",{className:"font-medium",children:["What Changed:"," "]}),h.metadata.scenarioChangesOverview]})}),y.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:y.map((x,v)=>{var C,E;const b=(E=(C=x.metadata)==null?void 0:C.screenshotPaths)==null?void 0:E[0],N=`${x.name}-${v}`;return c(de,{to:`/entity/${u.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:b?n(Ge,{screenshotPath:b,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},N)})})})]})},h.id||f)})}):n(Io,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:l.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):l.map((u,p)=>{const h=a.has(u.name),f=h?u.versions:u.versions.slice(0,1),y=u.versions.length-1,g=u.versions[0];return g==null||g.version.sha,e==null||e.sha,c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),c("div",{className:"p-5 bg-white",children:[f.map((x,v)=>{var k,S;const{version:b,analysis:N,scenario:C}=x,E=(S=(k=C.metadata)==null?void 0:k.screenshotPaths)==null?void 0:S[0],w=v===0;return c("div",{className:`flex gap-5 items-start ${w?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(de,{to:`/entity/${b.sha}/scenarios/${C.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:E?n(Ge,{screenshotPath:E,alt:C.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),c("div",{className:"flex-1 flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[b.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),w&&u.versions.length>1&&c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),c(de,{to:`/entity/${b.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:b.sha.substring(0,8)})]}),N.createdAt&&c("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(N.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),N.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${b.sha}-${v}`)}),y>0&&c("button",{onClick:()=>m(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${h?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),h?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},u.name)})})]})})}function Do({entity:e,analysisInfo:t,from:r}){const s=De(),a=s.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=l=>{l.preventDefault(),l.stopPropagation(),o&&s.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(de,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:c("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(Ge,{screenshotPath:e.screenshotPath,alt:e.name,className:"max-w-full max-h-full object-contain"})}):n("div",{className:"w-[125px] h-full bg-[#efefef] flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n("span",{className:"text-[40px]",children:n(Xe,{type:e.entityType})})}),c("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(Xe,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&c("div",{className:"flex items-center gap-2 mt-2",children:[c("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?c(ue,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):c(ue,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Lo=e=>{var a,o,i;const t=((a=e.analysisStatus)==null?void 0:a.status)||"not_analyzed",r=((o=e.analysisStatus)==null?void 0:o.scenarioCount)||0,s=(i=e.analysisStatus)==null?void 0:i.timestamp;return t==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:t==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:r>0,scenarioCount:r,timestamp:s}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:s}};function Px({importedEntities:e,importingEntities:t}){const[r]=mn(),s=r.get("from"),a=De(),o=a.state!=="idle",i=e.length>0,l=t.length>0,d=h=>h.filter(f=>f.entityType==="visual"||f.entityType==="library"),m=h=>{const f=d(h);f.length!==0&&a.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},u=d(e).length>0,p=d(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:c("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>m(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(h=>n(Do,{entity:h,analysisInfo:Lo(h),from:s},h.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),p&&n("button",{onClick:()=>m(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),l?n("div",{className:"p-6 space-y-4",children:t.map(h=>n(Do,{entity:h,analysisInfo:Lo(h),from:s},h.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function Mx({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(Px,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function _x({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(Dn,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function Dn({data:e,depth:t,defaultExpanded:r,maxDepth:s,objectKey:a,showInlineToggle:o=!1}){const[i,l]=M(r||t<2);if(te(()=>{l(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return c("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):c("span",{children:[c("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[c("span",{children:[i?"▼":"▶"," ","["]}),!i&&c("span",{children:[e.length,"]"]})]}),i?c(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((m,u)=>n("div",{className:"py-0.5",children:n(Dn,{data:m,depth:t+1,defaultExpanded:r,maxDepth:s})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const m=Object.keys(e);if(m.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=h=>h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,p=h=>Array.isArray(h)&&h.length>0;return c("span",{children:[c("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[c("span",{children:[i?"▼":"▶"," ","{"]}),!i&&c("span",{children:[m.length,"}"]})]}),i?c(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:m.map(h=>{const f=e[h],y=u(f),g=p(f);return n("div",{className:"py-0.5",children:y?n(ba,{propertyKey:h,value:f,depth:t,defaultExpanded:r,maxDepth:s}):g?n(va,{propertyKey:h,value:f,depth:t,defaultExpanded:r,maxDepth:s}):c(ue,{children:[c("span",{className:"text-orange-600",children:[h,": "]}),n(Dn,{data:f,depth:t+1,defaultExpanded:r,maxDepth:s})]})},h)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function ba({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=M(s||r<2),l=Object.keys(t);return te(()=>{i(s||r<2)},[s,r]),c(ue,{children:[c("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&c("span",{className:"text-gray-600",children:[l.length,"}"]})]}),o&&c(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(d=>{const m=t[d],u=m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,p=Array.isArray(m)&&m.length>0;return n("div",{className:"py-0.5",children:u?n(ba,{propertyKey:d,value:m,depth:r+1,defaultExpanded:s,maxDepth:a}):p?n(va,{propertyKey:d,value:m,depth:r+1,defaultExpanded:s,maxDepth:a}):c(ue,{children:[c("span",{className:"text-orange-600",children:[d,": "]}),n(Dn,{data:m,depth:r+2,defaultExpanded:s,maxDepth:a})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function va({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=M(s||r<2);return te(()=>{i(s||r<2)},[s,r]),c(ue,{children:[c("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&c("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&c(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,d)=>{const m=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,u=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:m?n(ba,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):u?n(va,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):n(Dn,{data:l,depth:r+2,defaultExpanded:s,maxDepth:a})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function ws({label:e,count:t,isActive:r,onClick:s,badgeColorActive:a,badgeTextActive:o}){return c("button",{onClick:s,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${a} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function Oo({label:e,isActive:t,onClick:r,disabled:s=!1}){return n("button",{onClick:r,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm cursor-pointer ${t?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:s,children:e})}function Fo({call:e,scenarioName:t}){const[r,s]=M(!1),[a,o]=M("system"),i=h=>new Date(h).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=h=>h?`$${h.toFixed(4)}`:null,d=(h,f)=>{if(!h&&!f)return null;const y=[];return h&&y.push(`${h.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},m=ne(()=>{var h,f,y,g,x;try{const v=JSON.parse(e.response);return(y=(f=(h=v.choices)==null?void 0:h[0])==null?void 0:f.message)!=null&&y.content?v.choices[0].message.content:(x=(g=v.content)==null?void 0:g[0])!=null&&x.text?v.content[0].text:e.response}catch{return e.response}},[e.response]),u=ne(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),p=ne(()=>{var h;if(t)return t;try{const f=JSON.parse(e.props);return((h=f==null?void 0:f.scenario)==null?void 0:h.name)||null}catch{return null}},[e.props,t]);return c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>s(!r),children:c("div",{className:"flex items-start justify-between gap-4",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),p&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:p}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),c("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),c("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&c("div",{className:"border-t border-[#e1e1e1]",children:[c("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),a&&c("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[a==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),a==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),a==="response"&&c("div",{children:[e.error&&c("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:m})]}),a==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!a&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:c("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const zo=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function jx({entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a}){var N,C,E,w,k,S,A,$,_;const[o,i]=M("entity"),[l,d]=M("analysis"),[m,u]=M(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[p,h]=M("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=ne(()=>{if(!a)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const j=[...a.entityCalls,...a.analysisCalls],D=j.filter(T=>T.object_type==="entity"||zo.includes(T.prompt_type)),R=j.filter(T=>T.object_type!=="entity"&&!zo.includes(T.prompt_type));return D.sort((T,U)=>U.created_at-T.created_at),R.sort((T,U)=>U.created_at-T.created_at),{entityLlmCalls:D,scenarioLlmCalls:R,totalLlmCalls:j.length}},[a]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(N=e==null?void 0:e.metadata)==null?void 0:N.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(C=t==null?void 0:t.metadata)==null?void 0:C.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(w=(E=e==null?void 0:e.metadata)==null?void 0:E.isolatedDataStructure)==null?void 0:w.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(k=t==null?void 0:t.metadata)==null?void 0:k.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(S=e==null?void 0:e.metadata)==null?void 0:S.importedExports,"External Dependencies":(A=e==null?void 0:e.metadata)==null?void 0:A.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:($=t==null?void 0:t.metadata)==null?void 0:$.scenariosDataStructure,description:"Structure template used across all scenarios"}],v=x.filter(j=>j.data!==void 0&&j.data!==null).length;let b=null;if(o==="entity"){const j=x.find(D=>D.id===l);j&&j.data!==void 0&&j.data!==null&&(b={title:j.title,description:j.description,data:j.data})}else if(o==="scenarios"&&m){const j=r.find(D=>(D.id||D.name)===m.scenarioId);j&&(b={title:j.name,description:j.description||"Scenario data and configuration",data:j.metadata})}return c("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:c("div",{className:"flex border-b border-gray-200 relative",children:[n(ws,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(ws,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(ws,{label:"LLM Calls",count:g,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((_=t==null?void 0:t.metadata)==null?void 0:_.analyzerVersion)&&c("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?c("div",{className:"flex-1 min-h-0",children:[c("div",{className:"flex gap-4 mb-4",children:[c("button",{onClick:()=>h("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${p==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),c("button",{onClick:()=>h("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${p==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",y.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:p==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(j=>n(Fo,{call:j},j.id)):y.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):y.map(j=>n(Fo,{call:j},j.id))})]}):c("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?c(ue,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),v===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(j=>{const D=j.data!==void 0&&j.data!==null;return n(Oo,{label:j.title,isActive:l===j.id,onClick:()=>d(j.id),disabled:!D},j.id)})})]}):c(ue,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"SCENARIOS"}),r.length===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No scenarios available."}):n("nav",{className:"space-y-1",children:r.map(j=>{const D=j.id||j.name,R=(m==null?void 0:m.scenarioId)===D;return n(Oo,{label:j.name,isActive:R,onClick:()=>u({scenarioId:D})},D)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:b?n(Tx,{title:b.title,description:b.description,data:b.data}):o==="scenarios"&&r.length===0?n(Bo,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:s}):o==="entity"?n(Bo,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:s}):n("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function Bo({title:e,description:t,onAnalyze:r}){return c("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function Tx({title:e,description:t,data:r}){const[s,a]=M(!0);return c(ue,{children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),c("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>a(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>a(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n(At,{content:JSON.stringify(r,null,2),label:"Copy JSON",copiedLabel:"Copied!",className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none transition-colors whitespace-nowrap"})]}),n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"p-6",children:r?n("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:n(_x,{data:r,defaultExpanded:s,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function $x({entity:e,analysis:t,scenarios:r,onAnalyze:s}){const a=De();return te(()=>{if(e!=null&&e.sha&&a.state==="idle"&&!a.data){const o=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;a.load(o)}},[e==null?void 0:e.sha,t==null?void 0:t.id,a.state,a.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(jx,{entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a.data})})}const Rx={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},Ix={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},Dx=2e3,Lx=e=>{var r;if(!e)return"typescript";switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"ts":case"tsx":return"typescript";case"js":case"jsx":return"javascript";case"json":return"json";case"css":return"css";default:return"typescript"}};function Ox({entity:e,entityCode:t}){const r=kr(),s=xe(null);return te(()=>{const a=r.hash;if(!a||!s.current)return;const o=a.match(/^#L(\d+)$/);if(!o)return;const i=parseInt(o[1],10);setTimeout(()=>{if(!s.current)return;const l=s.current.querySelector(`[data-line-number="${i}"]`);if(l&&l instanceof HTMLElement){l.scrollIntoView({behavior:"smooth",block:"center"});const d=l.style.backgroundColor;l.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{l.style.backgroundColor=d},2e3)}},300)},[r.hash,t]),n("div",{ref:s,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:c("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(At,{content:t,label:"Copy Code",duration:Dx,className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] disabled:opacity-75 disabled:cursor-not-allowed"})]}),n("div",{className:"p-0",children:t?n("div",{className:"relative",children:n(Sd,{language:Lx(e==null?void 0:e.filePath),style:kd,showLineNumbers:!0,customStyle:Rx,lineNumberStyle:Ix,wrapLines:!0,lineProps:a=>({"data-line-number":a,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const Fx=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function zx({currentParams:e,nextParams:t,currentUrl:r,nextUrl:s,formMethod:a,defaultShouldRevalidate:o}){return r.pathname===s.pathname&&r.search===s.search?o:!!(e.sha!==t.sha||a)}async function Bx({params:e,request:t,context:r}){const{sha:s}=e;if(!s)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),l=(e["*"]||"").split("/").filter(Boolean),d=l[0]||"scenarios",m=l[1]||null,u=l[2]||null,p=r.analysisQueue,h=p?p.getState():{paused:!1,jobs:[]},[f,y,g,x]=await Promise.all([Xt(s),Te(),hn(),nm(me()||process.cwd())]),v=f?await Rr(f):null,b=f?await $i(f.sha):null;let N={importedEntities:[],importingEntities:[]},C=null,E=[];f&&(N=await Ri(f),C=await Ii(f),E=await Li(f));const w=!!(f&&E.length>0&&E[0].sha!==f.sha),k=E.length>0?E[0].sha:null,S=!!(E.length>0&&E[0].analyses&&E[0].analyses.length>0),A=f?await Di(f):!1;return Q({entity:f??void 0,analysis:v??void 0,currentEntityAnalysis:b??void 0,projectSlug:y,from:o,relatedEntities:N,entityCode:C??void 0,hasNewerVersion:w,newestEntitySha:k,newestVersionHasAnalysis:S,fileModifiedSinceEntity:A,history:E,tab:d,scenarioId:m,viewModeFromUrl:u,currentCommit:g,hasAnApiKey:x,queueState:h})}const Yx=We(function(){var ja,Ta,$a,Ra,Ia,Da,La,Oa,Fa,za,Ba,Ya,Ua,Wa,Ja;const t=Ve(),a=(ii()["*"]||"").split("/").filter(Boolean),o=a[0]||"scenarios",i=a[1]||null,l=a[2]||null,d=t.entity,m=t.analysis,u=t.currentEntityAnalysis,p=u||m,h=t.projectSlug;t.from;const f=t.relatedEntities,y=t.entityCode,g=t.hasNewerVersion,x=t.newestEntitySha,v=t.newestVersionHasAnalysis,b=t.fileModifiedSinceEntity,N=t.history,C=t.currentCommit,E=t.hasAnApiKey,w=t.queueState;(ja=p==null?void 0:p.status)==null||ja.errors;const k=(p==null?void 0:p.scenarios)||[],S=k.filter(ce=>{var Ae;return!((Ae=ce.metadata)!=null&&Ae.sameAsDefault)}),A=k.filter(ce=>{var Ae;return(Ae=ce.metadata)==null?void 0:Ae.sameAsDefault}),$=Ct(),_=xe(null);te(()=>{_.current===null&&(_.current=window.history.length)},[]);const j=()=>{if(typeof window>"u")return;const ce=window.history.state;if(ce===null||(ce==null?void 0:ce.idx)===void 0||(ce==null?void 0:ce.idx)===0)$("/");else{const Ae=window.history.length,Qe=_.current;if(Qe!==null&&Ae>Qe){const ze=Ae-Qe+1;$(-ze)}else $(-1)}},D=!!w.currentlyExecuting,R=o,T=(Ta=C==null?void 0:C.metadata)==null?void 0:Ta.currentRun,U=!!(T!=null&&T.createdAt)&&!(T!=null&&T.analysisCompletedAt),V=!!(d!=null&&d.sha&&(($a=T==null?void 0:T.currentEntityShas)!=null&&$a.includes(d.sha))),I=!!(d!=null&&d.sha&&((Ia=(Ra=w.currentlyExecuting)==null?void 0:Ra.entityShas)!=null&&Ia.includes(d.sha))),O=!!(d!=null&&d.sha&&((Da=w.jobs)!=null&&Da.some(ce=>{var Ae;return(Ae=ce.entityShas)==null?void 0:Ae.includes(d.sha)}))),z=V||I||O,L=z&&((La=p==null?void 0:p.status)==null?void 0:La.finishedAt)!=null&&S.length>0&&p.entitySha!==(d==null?void 0:d.sha),P=ne(()=>{if(R!=="scenarios")return null;if(i){const ce=S.find(Ae=>Ae.id===i);if(ce)return ce}return S.length>0&&!z?S[0]:null},[R,i,S,z]),q=((za=(Fa=(Oa=P==null?void 0:P.metadata)==null?void 0:Oa.executionResult)==null?void 0:Fa.error)==null?void 0:za.message)||((Ua=(Ya=(Ba=p==null?void 0:p.status)==null?void 0:Ba.errors)==null?void 0:Ya[0])==null?void 0:Ua.message);ht({source:P?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:P==null?void 0:P.id,analysisId:p==null?void 0:p.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:P==null?void 0:P.name,errorMessage:q});const[H,W]=M(()=>l&&l!=="edit"?l:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");te(()=>{l&&l!==H&&l!=="edit"&&W(l)},[l]);const Z=l==="edit",[B,F]=M(!1),[J,G]=M(!1),[X,le]=M(null),[ve,oe]=M(!1),[pe,Ce]=M(!1),[$e,Me]=M(null),[Ie,Fe]=M(null),[ke,re]=M(0),{interactiveServerUrl:he,isStarting:Se,isLoading:tt,showIframe:ge,iframeKey:Le,onIframeLoad:Je}=rn({analysisId:p==null?void 0:p.id,scenarioId:P==null?void 0:P.id,scenarioName:P==null?void 0:P.name,projectSlug:h,enabled:Z&&!!P,refreshTrigger:ke}),[nt,Kr]=M(!1),[Qr,_a]=M(""),[zt,Bt]=M(!1),[Un,Yt]=M(Date.now()),[yn,xn]=M(!1),rt=De(),ft=De(),Ye=De(),He=mt(),Zr=w.jobs.some(ce=>{var Ae;return(d==null?void 0:d.sha)&&((Ae=ce.entityShas)==null?void 0:Ae.includes(d.sha))||ce.type==="analysis"&&ce.commitSha===(C==null?void 0:C.sha)&&ce.entityShas&&ce.entityShas.length===0}),ie=z,we=((Wa=d==null?void 0:d.metadata)==null?void 0:Wa.defaultWidth)||((Ja=p==null?void 0:p.metadata)==null?void 0:Ja.defaultWidth)||1440,je=Math.round(we*(900/1440));rt.state==="submitting"||rt.state,ne(()=>{var ce;return!!((ce=P==null?void 0:P.metadata)!=null&&ce.interactiveExamplePath)},[P]);const{isCompleted:Oe}=St(h,zt);te(()=>{rt.state==="idle"&&rt.data&&(rt.data.success?setTimeout(()=>{Yt(Date.now()),He.revalidate(),Bt(!1)},1500):rt.data.error&&(Bt(!1),alert(`Recapture failed: ${rt.data.error}`)))},[rt.state,rt.data,He]),te(()=>{zt&&Oe&&setTimeout(()=>{Yt(Date.now()),He.revalidate(),Bt(!1)},1500)},[zt,Oe,He]),te(()=>{ft.state==="idle"&&ft.data&&(ft.data.success?setTimeout(()=>{Yt(Date.now()),He.revalidate(),Bt(!1)},1500):ft.data.error&&(Bt(!1),alert(`Recapture failed: ${ft.data.error}`)))},[ft.state,ft.data,He]);const gt=()=>{d&&(g&&x&&x!==d.sha?($(`/entity/${x}/scenarios`),setTimeout(()=>{Ye.submit({entitySha:x,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):Ye.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};te(()=>{Ye.state==="idle"&&Ye.data&&(Ye.data.success?He.revalidate():Ye.data.error&&alert(`Analysis failed: ${Ye.data.error}`))},[Ye.state,Ye.data,d==null?void 0:d.sha,He]),te(()=>{const ce=setTimeout(()=>{He.revalidate()},500);return()=>clearTimeout(ce)},[]),te(()=>{if(U||ie){const ce=setInterval(()=>{He.revalidate()},3e3);return()=>clearInterval(ce)}},[U,ie,He]);const bn=(ce,Ae)=>ce==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${ce}`,Xr=(ce,Ae)=>`/entity/${d==null?void 0:d.sha}/scenarios/${ce}/${Ae}`,vn=ce=>{W(ce),P!=null&&P.id&&(ce==="interactive"?$(`/entity/${d==null?void 0:d.sha}/scenarios/${P.id}/fullscreen`,{replace:!0}):$(Xr(P.id,ce),{replace:!0}))},rc=async ce=>{var Ae,Qe;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:ce,hasSelectedScenario:!!P,hasAnalysis:!!p}),!P||!p){const ze="Error: No scenario or analysis available";console.error("[EntityDetail]",ze),le(ze);return}F(!0),le(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:ce,scenarioId:P.id,scenarioName:P.name,currentData:P.data});try{const ze=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:ce,existingScenarios:p.scenarios,scenariosDataStructure:(Ae=p.metadata)==null?void 0:Ae.scenariosDataStructure,editingMockName:P.name,editingMockData:Ie||((Qe=P.metadata)==null?void 0:Qe.data)})}),yt=await ze.json();if(!ze.ok||!yt.success)throw new Error(yt.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",yt.data),Fe(yt.data);const Wn=(p.scenarios||[]).map(Ke=>Ke.id===P.id?{...Ke,metadata:{...Ke.metadata,data:yt.data}}:Ke),wn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:p,scenarios:Wn})}),st=await wn.json();if(!wn.ok||!st.success)throw console.error("[EntityDetail] Temp save failed:",st),new Error(st.error||"Failed to apply preview");if(le("Generating preview. Capturing screenshot..."),he){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:he});const Ke=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:he,scenarioId:P.id,projectId:p.projectId,viewportWidth:1440})}),Nn=await Ke.json();!Ke.ok||!Nn.success?(console.error("[EntityDetail] Direct capture failed:",Nn),le("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),le('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Ke=new FormData;Ke.append("analysisId",p.id||""),Ke.append("scenarioId",P.id||"");const Nn=await fetch("/api/recapture-scenario",{method:"POST",body:Ke}),ts=await Nn.json();!Nn.ok||!ts.success?(console.warn("[EntityDetail] Recapture failed:",ts.error),le("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",ts.jobId),le('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}re(Ke=>Ke+1),He.revalidate()}catch(ze){console.error("Error applying changes:",ze),le(`Error: ${ze instanceof Error?ze.message:String(ze)}`)}finally{F(!1)}},sc=async(ce,Ae)=>{var Qe;if(!P||!p){le("Error: No scenario or analysis available");return}G(!0),le(null),console.log("[EntityDetail] Saving scenario to database",{description:ce,saveAsNew:Ae});try{const ze=Ie||((Qe=P.metadata)==null?void 0:Qe.data);let yt;if(Ae){const st={...P,id:`${P.name}-${Date.now()}`,name:`${P.name} (Copy)`,metadata:{...P.metadata,data:ze},description:ce||P.description};yt=[...p.scenarios||[],st]}else yt=(p.scenarios||[]).map(st=>st.id===P.id?{...st,metadata:{...st.metadata,data:ze},description:ce||st.description}:st);const Wn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:p,scenarios:yt})}),wn=await Wn.json();if(!Wn.ok||!wn.success)throw new Error(wn.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),le(Ae?"New scenario created successfully":"Scenario saved successfully"),Fe(null),He.revalidate()}catch(ze){console.error("Error saving scenario:",ze),le(`Error: ${ze instanceof Error?ze.message:String(ze)}`)}finally{G(!1)}},ac=()=>{P!=null&&P.id&&(d!=null&&d.sha)&&$(`/entity/${d.sha}/scenarios/${P.id}/dev`)},oc=async()=>{var ce;if(!(P!=null&&P.id)){Me("Cannot delete scenario without ID");return}oe(!0),Me(null);try{const Ae=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:P.id,screenshotPaths:((ce=P.metadata)==null?void 0:ce.screenshotPaths)||[]})}),Qe=await Ae.json();if(!Ae.ok||!Qe.success)throw new Error(Qe.error||"Failed to delete scenario");$(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(Ae){console.error("[EntityDetail] Error deleting scenario:",Ae),Me(Ae instanceof Error?Ae.message:"Failed to delete scenario"),Ce(!1)}finally{oe(!1)}},es=p&&d&&p.entitySha!==d.sha,ic=d?Nx(d):!1;return n(Ur,{children:c("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-end h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:j,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:S.length},{id:"related",label:"Related Entities",count:f.importedEntities.length+f.importingEntities.length},{id:"code",label:"Code"},{id:"data",label:"Data Structure"},{id:"history",label:"History"}].map(ce=>n(de,{to:bn(ce.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${R===ce.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:R===ce.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:c("span",{className:"flex items-center gap-2",children:[ce.label,ce.count!==void 0&&ce.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${R===ce.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:ce.count})]})},ce.id))})]})}),(g||es&&!u||b&&ic)&&!z&&!Zr&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:c("div",{className:"flex items-center gap-3",children:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:es&&!g?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),n("span",{className:"text-sm",style:{color:"#714A25"},children:g?"You are viewing an older version. A newer version is available.":es?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&x&&v?n(de,{to:`/entity/${x}/scenarios`,className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono cursor-pointer transition-colors no-underline",style:{backgroundColor:"#C69538"},onMouseEnter:ce=>{ce.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:ce=>{ce.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:gt,disabled:Ye.state!=="idle",className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#C69538"},onMouseEnter:ce=>{Ye.state==="idle"&&(ce.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:ce=>{Ye.state==="idle"&&(ce.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),c("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[R==="scenarios"&&c(ue,{children:[Z&&P?n(Sx,{scenario:P,entitySha:(d==null?void 0:d.sha)||"",onApply:rc,onSave:sc,onEditMockData:ac,onDelete:oc,isApplying:B,isSaving:J,saveMessage:X,showDeleteConfirm:pe,onShowDeleteConfirm:Ce,isDeleting:ve,deleteError:$e}):n(Cx,{scenarios:S,hiddenScenarios:A,analysis:p,selectedScenario:P,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:Un,activeTab:R,entityType:d==null?void 0:d.entityType,entity:d,queueState:w,processIsRunning:D,isEntityAnalyzing:z,areScenariosStale:L,viewMode:H,setViewMode:vn,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(Ex,{analysis:p??null,entitySha:(d==null?void 0:d.sha)||""}):Z&&P?n(Wr,{scenarioId:P.id||P.name,scenarioName:P.name,iframeUrl:he,isStarting:Se,isLoading:tt,showIframe:ge,iframeKey:Le,onIframeLoad:Je,projectSlug:h,defaultWidth:1440,defaultHeight:900}):c("div",{className:"flex flex-col flex-1 min-h-0",children:[P&&c("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:P.name}),c("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[we," × ",je]})]}),c("div",{className:"flex items-center gap-2",children:[n(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${P.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),c("button",{className:"px-3 py-1.5 bg-[#022A35] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#011a21] transition-colors flex items-center gap-1.5",onClick:()=>{alert("Download functionality coming soon")},title:"Download",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),c(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${P.id}/dev`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Dev Mode - Live preview with data editor and code sync",children:[c("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n("polyline",{points:"16 18 22 12 16 6"}),n("polyline",{points:"8 6 2 12 8 18"})]}),"Dev Mode"]}),c(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${P.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:n("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),n(Bl,{selectedScenario:P,analysis:p,entity:d,viewMode:H,cacheBuster:Un,hasScenarios:S.length>0,isAnalyzing:ie,projectSlug:h,hasAnApiKey:E,processIsRunning:D,queueState:w})]})]}),R==="related"&&n(Mx,{relatedEntities:f}),R==="data"&&n($x,{entity:d,analysis:p,scenarios:S,onAnalyze:gt}),R==="code"&&n(Ox,{entity:d,entityCode:y}),R==="history"&&n(Ax,{entity:d,history:N})]}),yn&&h&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>xn(!1),children:c("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:ce=>ce.stopPropagation(),children:[c("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>xn(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n($t,{projectSlug:h,onClose:()=>xn(!1)})})]})})]})})}),Ux=Object.freeze(Object.defineProperty({__proto__:null,default:Yx,loader:Bx,meta:Fx,shouldRevalidate:zx},Symbol.toStringTag,{value:"Module"}));async function Wx(e){const{entityShas:t,filePaths:r,context:s,scenarioCount:a,queue:o}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await Be();const i=me();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=ee.join(i,".codeyam","config.json"),d=JSON.parse(await ye.readFile(l,"utf8")),{projectSlug:m,branchId:u}=d;if(!m||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${m}, Branch: ${u}`);const p=Lr(m);try{await ye.writeFile(p,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:h,branch:f}=await Re(m);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await Ze({shas:t});if(!y||y.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let g=r;if((!g||g.length===0)&&(g=[...new Set(y.map(b=>b.filePath).filter(b=>!!b))],console.log(`[analyzeEntities] Found ${g.length} unique files`)),!g||g.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${g.length} files...`);const x=await Xu(h,f,g);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await Tt({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:b=>{if(!b)return;const N=b.currentRun;if(N&&N.id&&N.archivedAt)return;N&&(N.analysesCompleted&&N.analysesCompleted>0||N.capturesCompleted&&N.capturesCompleted>0)&&dm(b)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:v}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:m,filePaths:g,entityShas:t,entityNames:y.map(b=>b.name),...s?{context:s}:{},...a?{scenarioCount:a}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${v} for ${t.length} entities`),{jobId:v}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function Jx({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Pt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("entitySha"),o=s.get("entityShas"),i=s.get("filePath"),l=s.get("context"),d=s.get("scenarioCount");let m;if(o)m=o.split(",").filter(Boolean);else if(a)m=[a];else return Q({error:"Missing required field: entitySha or entityShas"},{status:400});if(m.length===0)return Q({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${m.length} entity(ies)`);const u=await Ze({shas:m}),h=[...new Set(u.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await Wx({entityShas:m,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),Q({success:!0,message:`Analysis queued for ${m.length} entity(ies)`,entityCount:m.length,fileCount:h,jobId:f})}catch(s){return console.error("[API] Error starting analysis:",s),Q({error:"Failed to start analysis",details:s.message},{status:500})}}const Hx=Object.freeze(Object.defineProperty({__proto__:null,action:Jx},Symbol.toStringTag,{value:"Module"}));function Vx(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function Yl(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const a=t.getHours(),o=t.getMinutes(),i=a>=12?"pm":"am",l=a%12||12,d=o.toString().padStart(2,"0");return`Today, ${l}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function at(e,t=[],r=!1){var u,p;if(t.some(h=>{var f,y;return!!((f=h.entityShas)!=null&&f.includes(e.sha)||(y=h.entities)!=null&&y.some(g=>g.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const a=e.analyses[0];if(!(((u=a.status)==null?void 0:u.scenarios)&&a.status.scenarios.length>0&&a.status.scenarios.some(h=>h.screenshotFinishedAt||h.finishedAt))||a.entitySha!==e.sha)return"not-analyzed";const i=a.createdAt?new Date(a.createdAt).getTime():0,l=(p=e.metadata)!=null&&p.editedAt?new Date(e.metadata.editedAt).getTime():0,d=a.scenarios||[],m=d.some(h=>{var f,y,g;return((y=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=h.metadata)==null?void 0:g.executionResult)});return i>=l?d.length>0&&m?d.every(f=>{var y,g,x;return((g=(y=f.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const Gx=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function qx({request:e,context:t}){try{const r=t.analysisQueue,s=r?r.getState():{paused:!1,jobs:[]},a=await nn();return Q({entities:a||[],queueState:s})}catch(r){return console.error("Failed to load simulations:",r),Q({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const Kx=We(function(){const t=Ve(),r=t.entities,s=t.queueState;ht({source:"simulations-page"});const[a,o]=M(""),[i,l]=M("visual"),d=ne(()=>{const g=[];return r.forEach(x=>{var b;const v=(b=x.analyses)==null?void 0:b[0];if(v!=null&&v.scenarios){const N=v.scenarios.filter(C=>{var E;return!((E=C.metadata)!=null&&E.sameAsDefault)}).map(C=>{var _,j,D,R,T;const E=(j=(_=C.metadata)==null?void 0:_.screenshotPaths)==null?void 0:j[0],w=(D=C.metadata)==null?void 0:D.noScreenshotSaved,k=E&&!w,S=(T=(R=v.status)==null?void 0:R.scenarios)==null?void 0:T.find(U=>U.name===C.name),A=S&&S.screenshotStartedAt&&!S.screenshotFinishedAt;let $;return k?$="completed":A?$="capturing":$="error",{scenarioName:C.name,scenarioDescription:C.description||"",screenshotPath:E||"",scenarioId:C.id,state:$}}).filter(C=>C.state==="completed"||C.state==="capturing");N.length>0&&g.push({entity:x,screenshots:N,createdAt:v.createdAt||""})}}),g.sort((x,v)=>new Date(v.createdAt).getTime()-new Date(x.createdAt).getTime()),g},[r]),m=ne(()=>r.filter(g=>{var b,N;const x=(b=g.analyses)==null?void 0:b[0];return!((N=x==null?void 0:x.scenarios)==null?void 0:N.some(C=>{var E,w;return(w=(E=C.metadata)==null?void 0:E.screenshotPaths)==null?void 0:w[0]}))}),[r]),u=ne(()=>d.filter(({entity:g})=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[d,a,i]),p=ne(()=>m.filter(g=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[m,a,i]),h=se(g=>{o(g.target.value)},[]),f=se(g=>{l(g.target.value)},[]),y=d.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:c("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative",children:[c("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(it,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(Ln,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:a,onChange:h})]})]})]}),y&&u.length>0&&n("div",{className:"mb-2",children:c("div",{className:"flex items-center py-3",children:[c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:u.length})," ",u.length===1?"entity":"entities"]}),c("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:u.reduce((g,{screenshots:x})=>g+x.length,0)})," ","scenarios"]})]})}),c("div",{className:"flex flex-col gap-3",children:[y&&(u.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(ue,{children:u.map(({entity:g,screenshots:x})=>n(Qx,{entity:g,screenshots:x,queueJobs:(s==null?void 0:s.jobs)||[]},g.sha))})),!y&&(p.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):p.map(g=>n(Zx,{entity:g},g.sha)))]})]})})});function Qx({entity:e,screenshots:t,queueJobs:r}){var f,y,g;const s=Ct(),a=De(),[o,i]=M(!1),l=t.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),d=x=>{s(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},m=()=>{i(!0),a.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};te(()=>{a.state==="idle"&&o&&i(!1)},[a.state,o]);const u=at(e,r),p=Vx(u),h=u==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:c("div",{className:"flex flex-col",children:[c("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(Xe,{type:e.entityType||"other",size:"large"})}),c("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[c("div",{className:"flex items-center gap-[5px]",children:[c(de,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",l,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:p.bgColor,color:p.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:p.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),c("div",{className:"flex-shrink-0 flex items-center gap-2",children:[h&&n(ue,{children:o||a.state!=="idle"?c("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(ct,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:m,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void s(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>c("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>d(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:v=>{x.state==="completed"&&(v.currentTarget.style.borderColor="#005C75",v.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:v=>{v.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",v.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(Ge,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(xa,{size:"medium"}):null})}),c("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:c("div",{className:"bg-gray-100 text-gray-800 text-xs rounded-lg px-3 py-2 shadow-lg max-w-xs border border-gray-200",children:[x.scenarioName,x.scenarioDescription&&c(ue,{children:[": ",x.scenarioDescription]}),n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-100 border-l border-t border-gray-200 transform rotate-45"})]})})]})]},x.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function Zx({entity:e}){const t=De(),[r,s]=M(!1),a=()=>{s(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return te(()=>{t.state==="idle"&&r&&s(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:a,children:c("div",{className:"px-5 py-4 flex items-center",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(Xe,{type:e.entityType}),c("div",{className:"min-w-0",children:[c("div",{className:"flex items-center gap-3 mb-0.5",children:[n(de,{to:`/entity/${e.sha}`,className:"text-sm font-medium text-gray-900 no-underline",children:e.name}),n("span",{className:"text-[10px] font-semibold px-1 py-0.5 rounded",style:{color:e.entityType==="visual"?"#7c3aed":e.entityType==="library"?"#0DBFE9":e.entityType==="type"?"#dc2626":e.entityType==="data"?"#2563eb":e.entityType==="index"?"#ea580c":e.entityType==="functionCall"?"#7c3aed":e.entityType==="class"?"#059669":e.entityType==="method"?"#0891b2":"#6b7280",backgroundColor:e.entityType==="visual"?"#f3e8ff":e.entityType==="library"?"#cffafe":e.entityType==="type"?"#fee2e2":e.entityType==="data"?"#dbeafe":e.entityType==="index"?"#ffedd5":e.entityType==="functionCall"?"#f3e8ff":e.entityType==="class"?"#d1fae5":e.entityType==="method"?"#cffafe":"#f3f4f6"},children:e.entityType?e.entityType.toUpperCase():"UNKNOWN"})]}),n("div",{className:"text-xs text-gray-400 truncate",children:e.filePath})]})]}),n("div",{className:"w-32 flex justify-center",children:n("span",{className:"text-[10px] text-gray-500 bg-gray-100 px-2 py-1 rounded",children:"Not analyzed"})}),n("div",{className:"w-32 text-center text-[10px] text-gray-500",children:Yl(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(ct,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:a,className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer",children:"Analyze"})})]})})}const Xx=Object.freeze(Object.defineProperty({__proto__:null,default:Kx,loader:qx,meta:Gx},Symbol.toStringTag,{value:"Module"}));function eb({request:e,context:t}){const r=t.dbNotifier||dt;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const s=new ReadableStream({start(a){const o=new TextEncoder;a.enqueue(o.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
300
|
-
|
|
301
|
-
`)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",d),clearInterval(m);try{a.close()}catch{}}},d=u=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
|
|
302
|
-
|
|
303
|
-
`))}catch{l()}};r.on("change",d);const m=setInterval(()=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
304
|
-
|
|
305
|
-
`))}catch{l()}},3e4);e.signal.addEventListener("abort",l)}});return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const tb=Object.freeze(Object.defineProperty({__proto__:null,loader:eb},Symbol.toStringTag,{value:"Module"}));function nb(){return new Response(JSON.stringify({status:"ok",version:oa,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const rb=Object.freeze(Object.defineProperty({__proto__:null,loader:nb},Symbol.toStringTag,{value:"Module"}));function wa(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const s=r[1],a=r[2],o={},i=s.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/),l=s.match(/paths:\s*\[([^\]]*)\]/);i&&i[1].trim()?o.paths=i[1].split(`
|
|
306
|
-
`).filter(m=>m.trim().startsWith("-")).map(m=>m.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):l&&(o.paths=l[1].split(",").map(m=>m.replace(/['"]/g,"").trim()).filter(Boolean));const d=s.match(/^category:\s*(.+)$/m);return d&&(o.category=d[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:a}}async function Gr(e,t=""){const r=[];try{const s=await ye.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){const i=await Gr(ee.join(e,a.name),o);r.push(...i)}else a.isFile()&&a.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function Yn(e){const t=await Gr(e),r=[];for(const s of t){const a=ee.join(e,s);try{const o=await ye.readFile(a,"utf-8"),{frontmatter:i,body:l}=wa(o);r.push({filePath:s,absolutePath:a,frontmatter:i,body:l})}catch{}}return r}function Ul(e){const t=ee.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function Wl(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(s=>Ps(e,s,{matchBase:!0}));const r=Ul(t);return r?Ps(e,r,{matchBase:!0}):!1}function sb(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!Ul(e)?[]:t.filter(r=>Wl(r,e))}const ab=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function Na(e){const t=[];async function r(s,a){try{const o=await be.readdir(s,{withFileTypes:!0});for(const i of o){const l=Y.join(s,i.name),d=a?`${a}/${i.name}`:i.name;i.isDirectory()&&ab.has(i.name)||(i.isDirectory()?await r(l,d):i.isFile()&&t.push(d))}}catch{}}return await r(e,""),t}const ob="codeyam-rule-state.json",Ns=1;function Jl(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return Fn.createHash("sha256").update(t).digest("hex")}function Hl(e){return ee.join(e,".claude",ob)}async function Vl(e){const t=Hl(e);try{const r=await ye.readFile(t,"utf-8"),s=JSON.parse(r);return s.version!==Ns?(console.warn(`[ruleState] Unknown version ${s.version}, using empty state`),{version:Ns,rules:{}}):s}catch{return{version:Ns,rules:{}}}}async function Gl(e,t){const r=Hl(e),s=ee.dirname(r);await ye.mkdir(s,{recursive:!0}),await ye.writeFile(r,JSON.stringify(t,null,2)+`
|
|
307
|
-
`,"utf-8")}async function Ca(e,t){const r=await Vl(e),s=new Set(t.map(a=>a.filePath));for(const a of Object.keys(r.rules))s.has(a)||delete r.rules[a];for(const a of t){const o=await ye.readFile(a.absolutePath,"utf-8"),i=Jl(o),l=r.rules[a.filePath];l?l.contentHash!==i&&(r.rules[a.filePath]={...l,contentHash:i,reviewed:!1}):r.rules[a.filePath]={contentHash:i,reviewed:!1}}return await Gl(e,r),r}async function Yo(e,t,r,s){const a=await Vl(e);if(r){const o=ee.join(e,".claude","rules"),i=ee.join(o,t),l=await ye.readFile(i,"utf-8"),d=Jl(l);a.rules[t]?(a.rules[t].reviewed=!0,a.rules[t].contentHash=d):a.rules[t]={contentHash:d,reviewed:!0}}else a.rules[t]&&(a.rules[t].reviewed=!1);await Gl(e,a)}function Sa(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function ql(e,t=""){const r=[],s=await ye.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;a.isDirectory()?r.push(...await ql(ee.join(e,a.name),o)):a.name.endsWith(".md")&&r.push(o)}return r}function wr(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
|
|
308
|
-
`).filter(s=>!(!s.startsWith("+")&&!s.startsWith("-")||s.startsWith("+++")||s.startsWith("---"))).map(s=>s.substring(1).trim());if(t.length===0)return!1;const r=/^(category:\s*\w+)$/;return t.every(s=>r.test(s))}async function ib({request:e}){const t=me();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),s=r.searchParams.get("action"),a=ee.join(t,".claude","rules");if(s==="recent-changes")return cb(t,a);if(s==="reviewed-status")return ub(t,a);if(s==="audit")return mb(t,a);if(s==="source-files")return pb(t);if(s==="rule-coverage")return hb(t,a);if(s==="rule-diff"){const o=r.searchParams.get("filePath");return o?db(t,o):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(s==="rules-for-path"){const o=r.searchParams.get("path");return o?fb(a,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await Gr(a),i=[];for(const u of o){const p=ee.join(a,u);try{const h=await ye.readFile(p,"utf-8"),f=await ye.stat(p),{frontmatter:y,body:g}=wa(h);i.push({filePath:u,content:h,frontmatter:y,body:g,lastModified:f.mtime.toISOString()})}catch{}}i.sort((u,p)=>new Date(p.lastModified).getTime()-new Date(u.lastModified).getTime());let l=i.length>0;if(!l)try{await ye.access(ee.join(t,".claude","codeyam-rule-state.json")),l=!0}catch{}const d=await Yn(a),m={};if(d.length>0){const u=await Ca(t,d);for(const p of d)m[p.filePath]=Sa(u,p.filePath)}return Response.json({memories:i,memoryInitialized:l,reviewedStatus:m})}catch(o){return console.error("[API] Error loading memories:",o),Response.json({error:"Failed to load memories",details:o instanceof Error?o.message:String(o),memoryInitialized:!1},{status:500})}}async function lb(e,t){const r=[];try{const s=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const a of s.split(`
|
|
309
|
-
`).filter(Boolean)){const o=a.substring(0,2);let i=a.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const l=o[0],d=o[1];let m=[i];if(i.endsWith("/")&&l==="?"){const u=ee.join(e,i);try{m=(await ql(u)).map(h=>i+h)}catch{continue}}for(const u of m){if(u.endsWith("/"))continue;const p=u.replace(".claude/rules/","");let h="modified";l==="A"||l==="?"?h="added":l==="D"||d==="D"?h="deleted":(l==="M"||d==="M")&&(h="modified");let f="";try{if(h==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(h==="added"&&l==="?"){const y=`${e}/${u}`;try{const g=await ye.readFile(y,"utf-8");f=`diff --git a/${u} b/${u}
|
|
310
|
-
new file mode 100644
|
|
311
|
-
--- /dev/null
|
|
312
|
-
+++ b/${u}
|
|
313
|
-
@@ -0,0 +1,${g.split(`
|
|
314
|
-
`).length} @@
|
|
315
|
-
${g.split(`
|
|
316
|
-
`).map(x=>"+"+x).join(`
|
|
317
|
-
`)}`}catch{f="(content not available)"}}else f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});f.length>5e3&&(f=f.substring(0,5e3)+`
|
|
318
|
-
... (truncated)`)}catch{f="(diff not available)"}h==="modified"&&wr(f)||r.push({filePath:p,changeType:h,diff:f})}}}catch{}return r}async function cb(e,t){try{const{execSync:r}=await import("child_process"),s=[],a=await Yn(t),o={};if(a.length>0){const u=await Ca(e,a);for(const p of a)o[p.filePath]=Sa(u,p.filePath)}const l=(await lb(e,r)).filter(u=>!o[u.filePath]);l.length>0&&s.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:l});const m=r('git log --format="%H|%aI|%s" --since="60 days ago" -- .claude/rules/ 2>/dev/null || true',{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024}).split(`
|
|
319
|
-
`).filter(Boolean).slice(0,20);for(const u of m){const[p,h,...f]=u.split("|"),y=f.join("|");if(!p||!h)continue;const g=r(`git diff-tree --no-commit-id --name-status -r ${p} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),x=[];for(const v of g.split(`
|
|
320
|
-
`).filter(Boolean)){const[b,N]=v.split(" ");if(!N||!N.startsWith(".claude/rules/"))continue;const C=N.replace(".claude/rules/","");let E="modified";if(b==="A"?E="added":b==="D"&&(E="deleted"),o[C])continue;let w="";try{w=r(`git show ${p} --format="" -- "${N}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),w.length>5e3&&(w=w.substring(0,5e3)+`
|
|
321
|
-
... (truncated)`)}catch{w="(diff not available)"}E==="modified"&&wr(w)||x.push({filePath:C,changeType:E,diff:w})}x.length>0&&s.push({commitHash:p.substring(0,8),date:h,message:y,files:x})}return Response.json({changes:s,reviewedStatus:o})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function db(e,t){try{const{execSync:r}=await import("child_process"),s=`.claude/rules/${t}`,a=r(`git rev-list --count HEAD -- "${s}" 2>/dev/null || echo 0`,{cwd:e,encoding:"utf-8"}),o=parseInt(a.trim(),10)||0,i=r(`git diff HEAD -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});if(i.trim()){if(wr(i))return Response.json({diff:null});const g=i.length>5e3?i.substring(0,5e3)+`
|
|
322
|
-
... (truncated)`:i;return Response.json({diff:{diff:g,commitMessage:"Uncommitted changes",date:new Date().toISOString(),isUncommitted:!0,commitCount:o}})}if(r(`git status --porcelain -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim().startsWith("?")){const g=ee.join(e,s);try{const x=await ye.readFile(g,"utf-8"),v=`diff --git a/${s} b/${s}
|
|
323
|
-
new file mode 100644
|
|
324
|
-
--- /dev/null
|
|
325
|
-
+++ b/${s}
|
|
326
|
-
@@ -0,0 +1,${x.split(`
|
|
327
|
-
`).length} @@
|
|
328
|
-
${x.split(`
|
|
329
|
-
`).map(b=>"+"+b).join(`
|
|
330
|
-
`)}`;return Response.json({diff:{diff:v.length>5e3?v.substring(0,5e3)+`
|
|
331
|
-
... (truncated)`:v,commitMessage:"New file (untracked)",date:new Date().toISOString(),isUncommitted:!0,commitCount:0}})}catch{}}const m=r(`git log -1 --format="%H|%aI|%s" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim();if(!m)return Response.json({diff:null});const[u,p,...h]=m.split("|"),f=h.join("|");if(!u||!p)return Response.json({diff:null});let y=r(`git show ${u} --format="" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});return y.trim()?wr(y)?Response.json({diff:null}):(y.length>5e3&&(y=y.substring(0,5e3)+`
|
|
332
|
-
... (truncated)`),Response.json({diff:{diff:y,commitMessage:f,date:p,isUncommitted:!1,commitCount:o}})):Response.json({diff:null})}catch(r){return console.error("[API] Error getting rule diff:",r),Response.json({diff:null})}}async function ub(e,t){try{const r=await Yn(t),s={};if(r.length>0){const a=await Ca(e,r);for(const o of r)s[o.filePath]=Sa(a,o.filePath)}return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function mb(e,t){try{const r=await Yn(t),s=await Na(e),a=[];for(const o of s){const i=r.filter(l=>Wl(o,l));if(i.length>0){const l=i.reduce((d,m)=>d+m.body.length,0);a.push({filePath:o,matchingRules:i.map(d=>({filePath:d.filePath,patterns:d.frontmatter.paths||[],bodyLength:d.body.length})),totalTextLength:l})}}return a.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:a,totalFilesWithCoverage:a.length,allSourceFiles:s})}catch(r){return console.error("[API] Error getting audit data:",r),Response.json({error:"Failed to get audit data",details:r instanceof Error?r.message:String(r)},{status:500})}}async function pb(e){try{const t=await Na(e);return Response.json({files:t})}catch(t){return console.error("[API] Error getting source files:",t),Response.json({error:"Failed to get source files",details:t instanceof Error?t.message:String(t)},{status:500})}}async function hb(e,t){try{const[r,s]=await Promise.all([Yn(t),Na(e)]),a={};for(const o of r)a[o.filePath]=sb(o,s).length;return Response.json({coverage:a})}catch(r){return console.error("[API] Error getting rule coverage:",r),Response.json({error:"Failed to get rule coverage",details:r instanceof Error?r.message:String(r)},{status:500})}}async function fb(e,t){try{const r=await Gr(e),s=[];for(const o of r){const i=ee.join(e,o);try{const l=await ye.readFile(i,"utf-8"),d=await ye.stat(i),{frontmatter:m,body:u}=wa(l);m.paths&&m.paths.some(p=>Ps(t,p,{matchBase:!0}))&&s.push({filePath:o,content:l,frontmatter:m,body:u,lastModified:d.mtime.toISOString()})}catch{}}const a=s.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:s,totalTextLength:a})}catch(r){return console.error("[API] Error getting rules for path:",r),Response.json({error:"Failed to get rules for path",details:r instanceof Error?r.message:String(r)},{status:500})}}async function gb({request:e}){const t=me();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=ee.join(t,".claude","rules");try{const s=await e.json(),{action:a,filePath:o,content:i,lastModified:l}=s;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(a==="mark-reviewed")return await Yo(t,o,!0),console.log(`[API] Rule marked as reviewed: ${o}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:o});if(a==="mark-unreviewed")return await Yo(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const d=ee.normalize(o);if(d.includes("..")||ee.isAbsolute(d))return Response.json({error:"Invalid file path"},{status:400});const m=ee.join(r,d);switch(a){case"create":case"update":return i?(await ye.mkdir(ee.dirname(m),{recursive:!0}),await ye.writeFile(m,i,"utf-8"),console.log(`[API] Memory ${a}d: ${o}`),Response.json({success:!0,message:`Memory ${a}d successfully`,filePath:o})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await ye.unlink(m),console.log(`[API] Memory deleted: ${o}`);const u=ee.dirname(m);try{(await ye.readdir(u)).length===0&&u!==r&&await ye.rmdir(u)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(u){if(u.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw u}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(s){return console.error("[API] Error managing memory:",s),Response.json({error:"Failed to manage memory",details:s instanceof Error?s.message:String(s)},{status:500})}}const yb=Object.freeze(Object.defineProperty({__proto__:null,action:gb,loader:ib},Symbol.toStringTag,{value:"Module"}));async function xb({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await Pt()),!r)return Q({error:"Queue not initialized"},{status:500});const s=new URL(e.url),a=s.searchParams.get("queryType");if(!a)return Q({error:"Missing queryType parameter for GET request"},{status:400});if(a==="job"){const i=s.searchParams.get("jobId");if(!i)return Q({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((o=l.currentlyExecuting)==null?void 0:o.id)===i)return Q({jobId:i,status:"running",job:l.currentlyExecuting});const d=l.jobs.find(u=>u.id===i);if(d){const u=l.jobs.indexOf(d);return Q({jobId:i,status:"queued",position:u,job:d})}const m=r.getJobResult(i);return m?Q({jobId:i,status:m.status==="error"?"failed":"completed",error:m.error}):Q({jobId:i,status:"completed"})}if(a==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async m=>{const u=[];if(m.entityShas&&m.entityShas.length>0){const p=m.entityShas.map(f=>Xt(f)),h=await Promise.all(p);u.push(...h.filter(f=>f!==null))}return{id:m.id,type:m.type,commitSha:m.commitSha,projectSlug:m.projectSlug,queuedAt:m.queuedAt,entities:u,filePaths:m.filePaths}}));let d;if(i.currentlyExecuting){const m=i.currentlyExecuting,u=[];if(m.entityShas&&m.entityShas.length>0){const p=m.entityShas.map(f=>Xt(f)),h=await Promise.all(p);u.push(...h.filter(f=>f!==null))}d={id:m.id,type:m.type,commitSha:m.commitSha,projectSlug:m.projectSlug,queuedAt:m.queuedAt,entities:u,filePaths:m.filePaths}}return Q({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:d}})}return Q({error:"Unknown queryType"},{status:400})}async function bb({request:e,context:t}){console.log("[Queue API] Received request"),console.log("[Queue API] Context keys:",Object.keys(t||{})),console.log("[Queue API] analysisQueue exists:",!!(t!=null&&t.analysisQueue));let r=t.analysisQueue;if(r||(r=await Pt(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),Q({error:"Queue not initialized"},{status:500});const s=await e.json(),{action:a,...o}=s;if(console.log("[Queue API] Action:",a,"Params:",Object.keys(o)),a==="enqueue"){const{jobId:i,completion:l}=r.enqueue(o);return l.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),Q({jobId:i,status:"queued"})}if(a==="resume")return r.resume(),Q({status:"resumed"});if(a==="pause")return r.pause(),Q({status:"paused"});if(a==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?Q({status:"removed",jobId:i}):Q({error:"Job not found in queue"},{status:404}):Q({error:"Missing jobId parameter"},{status:400})}if(a==="clear"){const i=r.clearQueue();return Q({status:"cleared",count:i})}if(a==="reorder"){const{jobId:i,direction:l}=o;return!i||!l?Q({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?Q({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?Q({status:"reordered",jobId:i,direction:l}):Q({error:"Could not reorder job (not found or at boundary)"},{status:400})}return Q({error:"Unknown action"},{status:400})}const vb=Object.freeze(Object.defineProperty({__proto__:null,action:bb,loader:xb},Symbol.toStringTag,{value:"Module"})),wb=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],Nb=We(function(){return De(),n(Ur,{children:c("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-center h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),c("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:c("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(Bl,{selectedScenario:null,analysis:void 0,entity:{sha:"mock-sha",name:"Dashboard",filePath:"codeyam-cli/src/webserver/app/routes/_index.tsx",entityType:"visual"},viewMode:"screenshot",cacheBuster:Date.now(),hasScenarios:!1,isAnalyzing:!1,projectSlug:null,hasAnApiKey:!0})]})]})})}),Cb=Object.freeze(Object.defineProperty({__proto__:null,default:Nb,meta:wb},Symbol.toStringTag,{value:"Module"})),Sb=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function kb({request:e}){var t,r;try{const s=await Ir();if(!s)return Q({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let a=!1;try{const d=await Te();if(d){const{project:m}=await Re(d);a=((r=(t=m.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=me()||process.cwd(),i=await Dr(o),l=Hi(s.projectSlug);return Q({config:s,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:l,simulationsEnabled:a,error:null})}catch(s){return console.error("Failed to load config:",s),Q({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function Eb(e){if(!e||!e.trim())return;const t=e.trim().split(/\s+/);if(t.length===0)return;const r=t[0],s=t.length>1?t.slice(1):void 0;return{command:r,args:s}}async function Ab({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),s=t.get("startCommands"),a=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore"),d=t.get("memorySettings");let m;if(r)try{m=JSON.parse(r)}catch{return Q({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(s)try{u=JSON.parse(s)}catch{return Q({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let p;l&&(p=l.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let h;if(d)try{h=JSON.parse(d)}catch{return Q({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await Ir();x!=null&&x.webapps&&(f=x.webapps.map((v,b)=>{if(u[b]!==void 0){const N=Eb(u[b]);return{...v,startCommand:N}}return v}))}if(!await Oi({universalMocks:m,pathsToIgnore:p,webapps:f,memory:h}))return Q({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let g=!1;if(a!==void 0||o!==void 0||i!==void 0){const x=me()||process.cwd(),v=await Dr(x);g=a!==void 0&&a!==(v.GROQ_API_KEY||"")||o!==void 0&&o!==(v.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(v.OPENAI_API_KEY||""),await tm(x,{...v,GROQ_API_KEY:a||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return Q({success:!0,error:null,requiresRestart:g})}catch(t){return console.log("[Settings Action] Failed to save config:",t),Q({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function Uo(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Wo({mock:e,onSave:t,onCancel:r}){const[s,a]=M(e.entityName),[o,i]=M(e.filePath),[l,d]=M(e.content);return c("div",{className:"space-y-3",children:[c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:s,onChange:u=>a(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange:u=>d(u.target.value),rows:6,className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),c("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!s.trim()||!o.trim()||!l.trim()){alert("All fields are required");return}t({entityName:s,filePath:o,content:l})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function Pb(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const Mb=We(function(){var $e,Me,Ie,Fe,ke;const{config:t,secrets:r,versionInfo:s,simulationsEnabled:a,error:o}=Ve(),i=vc(),l=De(),d=mt(),[m,u]=M(a?"project-metadata":"memory");ht({source:"settings-page"});const[p,h]=M((t==null?void 0:t.universalMocks)||[]),[f,y]=M(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,x]=M(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[v,b]=M((r==null?void 0:r.GROQ_API_KEY)||""),[N,C]=M((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[E,w]=M((r==null?void 0:r.OPENAI_API_KEY)||""),[k,S]=M(!1),[A,$]=M(!1),[_,j]=M(!1),[D,R]=M(!1),[T,U]=M(!1),[V,I]=M(!1),[O,z]=M(null),[L,P]=M(!1),[q,H]=M({}),[W,Z]=M((($e=t==null?void 0:t.memory)==null?void 0:$e.conversationReflection)??!0),[B,F]=M(((Me=t==null?void 0:t.memory)==null?void 0:Me.ruleMaintenance)??!0),[J,G]=M(((Ie=t==null?void 0:t.memory)==null?void 0:Ie.promptModel)??"haiku");te(()=>{var re,he,Se,tt;if(t){h(t.universalMocks||[]);const ge=(t.pathsToIgnore||[]).join(", ");y(ge),x(ge);const Le={};(re=t.webapps)==null||re.forEach((Je,nt)=>{Je.startCommand&&(Le[nt]=Uo(Je.startCommand))}),H(Le),Z(((he=t.memory)==null?void 0:he.conversationReflection)??!0),F(((Se=t.memory)==null?void 0:Se.ruleMaintenance)??!0),G(((tt=t.memory)==null?void 0:tt.promptModel)??"haiku")}r&&(b(r.GROQ_API_KEY||""),C(r.ANTHROPIC_API_KEY||""),w(r.OPENAI_API_KEY||""))},[t,r]),te(()=>{if(i!=null&&i.success){R(!0);const re=setTimeout(()=>R(!1),3e3);return()=>clearTimeout(re)}},[i]),te(()=>{if(l.state==="idle"&&l.data&&!V){console.log("[Settings] Fetcher data:",l.data);const re=l.data;if(re.success){console.log("[Settings] Save successful, revalidating..."),R(!0),I(!0),(f!==g||re.requiresRestart)&&U(!0),d.revalidate();const he=setTimeout(()=>{R(!1),I(!1)},3e3);return()=>clearTimeout(he)}}},[l.state,l.data,V,d,f,g]);const X=re=>{re.preventDefault();const he=new FormData(re.currentTarget);he.set("universalMocks",JSON.stringify(p)),he.set("startCommands",JSON.stringify(q)),he.set("memorySettings",JSON.stringify({conversationReflection:W,ruleMaintenance:B,promptModel:J})),console.log("[Settings] Submitting form data:",{universalMocks:he.get("universalMocks"),startCommands:he.get("startCommands"),openAiApiKey:he.get("openAiApiKey")?"***":"(empty)"}),l.submit(he,{method:"post"})},le=re=>{h([...p,re]),P(!1)},ve=(re,he)=>{const Se=[...p];Se[re]=he,h(Se),z(null)},oe=re=>{h(p.filter((he,Se)=>Se!==re))};if(o)return c("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const pe=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"memory",label:"Memory"},{id:"current-configuration",label:"Current Configuration"}],Ce=a?pe:pe.filter(re=>re.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[c("div",{className:"mb-8 flex justify-between items-start",children:[c("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:l.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:l.state==="submitting"?"Saving...":"Save Settings"})]}),(D||T||(i==null?void 0:i.error)||l.data&&typeof l.data=="object"&&"error"in l.data)&&c("div",{className:"mb-4 space-y-3",children:[D&&n("div",{className:"text-emerald-600 text-sm font-medium bg-emerald-50 border border-emerald-200 rounded px-4 py-2",children:"Settings saved successfully!"}),T&&c("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"Settings changed. Please restart CodeYam for changes to take effect:"}),c("div",{className:"flex items-center gap-2 mt-1",children:[n("code",{className:"bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"}),n(At,{content:"codeyam stop && codeyam",className:"px-2 py-1 text-xs bg-amber-200 hover:bg-amber-300 text-amber-800 rounded border-none transition-colors"})]})]}),(i==null?void 0:i.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:i.error}),(()=>{if(l.data&&typeof l.data=="object"&&"error"in l.data){const re=l.data;return typeof re.error=="string"?n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:re.error}):null}return null})()]}),c("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:Ce.map(re=>n("li",{children:n("button",{type:"button",onClick:()=>u(re.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${m===re.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:re.label})},re.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:c("form",{id:"settings-form",onSubmit:X,className:"space-y-6",children:[m==="project-metadata"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),c("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((re,he)=>{var Se;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:re.path==="."?"Root":re.path})]}),re.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:re.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:re.framework})]}),re.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",c("span",{className:"text-gray-900 font-mono text-xs",children:[re.startCommand.command," ",(Se=re.startCommand.args)==null?void 0:Se.join(" ")]})]})]})},he)})}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),n("p",{className:"mt-2 text-sm text-gray-600",children:"Web applications are detected during initialization. To modify, edit `.codeyam/config.json` or re-run `codeyam init`."})]})]}),m==="ai-provider"&&c("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),c("div",{className:"space-y-6",children:[c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),c("div",{className:"flex flex-wrap gap-2 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:k?"text":"password",id:"groqApiKey",name:"groqApiKey",value:v,onChange:re=>b(re.target.value),placeholder:"gsk_...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>S(!k),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:k?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),c("div",{className:"flex flex-wrap gap-2 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:A?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:N,onChange:re=>C(re.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>$(!A),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:A?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),c("div",{className:"flex flex-wrap gap-2 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:_?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:E,onChange:re=>w(re.target.value),placeholder:"sk-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>j(!_),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:_?"Hide":"Show"})]})]})]})]})]}),m==="commands"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((re,he)=>c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[c("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:re.path==="."?"Root":re.path}),n("div",{className:"text-sm text-gray-600",children:re.framework})]}),c("div",{children:[n("label",{htmlFor:`startCommand-${he}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${he}`,name:`startCommand-${he}`,value:q[he]||"",onChange:Se=>H({...q,[he]:Se.target.value}),placeholder:"e.g., pnpm dev --port $PORT",className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("p",{className:"mt-2 text-xs text-gray-500",children:"Use $PORT as a placeholder for the dynamic port number"})]})]},he))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),m==="paths-to-ignore"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:re=>y(re.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),c("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),m==="universal-mocks"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),p.length===0?c("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>P(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:p.map((re,he)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:O===he?n(Wo,{mock:re,onSave:Se=>ve(he,Se),onCancel:()=>z(null)}):n(ue,{children:c("div",{className:"flex justify-between items-start mb-2",children:[c("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:re.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:re.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:re.content})]}),c("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>z(he),className:"px-3 py-1 bg-teal-600 text-white border-none rounded text-sm cursor-pointer hover:bg-teal-700",children:"Edit"}),n("button",{type:"button",onClick:()=>oe(he),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},he))}),p.length>0&&n("button",{type:"button",onClick:()=>P(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),m==="memory"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),c("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":W,onClick:()=>Z(!W),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${W?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${W?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":B,onClick:()=>F(!B),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${B?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${B?"translate-x-5":"translate-x-0"}`})})]})}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(re=>c("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${J===re.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:re.value,checked:J===re.value,onChange:()=>G(re.value),className:"mt-1 accent-[#005C75]"}),c("div",{children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:re.label}),re.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:re.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:re.description})]})]},re.value))})]})]})]}),m==="current-configuration"&&c("div",{className:"space-y-6",children:[t&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:c("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&c("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((re,he)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:re.path==="."?"Root":re.path})]}),re.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:re.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:re.framework})]}),re.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:Uo(re.startCommand)})]})]})},he))})]})]}),s&&c("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[s.webserverVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:s.webserverVersion.version||"unknown"})]}),s.templateVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:s.templateVersion.version||((Fe=s.templateVersion.gitCommit)==null?void 0:Fe.slice(0,7))||"unknown"}),s.templateVersion.buildTimestamp&&c("span",{className:"text-gray-500 ml-2",children:["(built"," ",Pb(s.templateVersion.buildTimestamp),")"]})]}),s.cachedAnalyzerVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:s.cachedAnalyzerVersion.version||((ke=s.cachedAnalyzerVersion.gitCommit)==null?void 0:ke.slice(0,7))||"unknown"}),s.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!s.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),L&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(Wo,{mock:{entityName:"",filePath:"",content:""},onSave:le,onCancel:()=>P(!1)})]})})]})})}),_b=Object.freeze(Object.defineProperty({__proto__:null,action:Ab,default:Mb,loader:kb,meta:Sb},Symbol.toStringTag,{value:"Module"}));async function jb({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=me();if(!r)return new Response("Project root not found",{status:500});const a=ee.extname(t)!==""?t:`${t}.html`,o=ee.join(r,".codeyam","captures","static",a);try{await ye.access(o);let i=await ye.readFile(o);const l=ee.extname(o).toLowerCase();let d="application/octet-stream";if(l===".html"){d="text/html";let m=i.toString("utf-8");const u=m.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const h=u[1].match(/=\s*(\{[\s\S]*\})/);if(h){const f=JSON.parse(h[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const y=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;m=m.replace(u[0],y)}}catch(p){console.error("[Static] Failed to parse Remix context:",p)}i=Buffer.from(m,"utf-8")}else l===".js"||l===".mjs"?d="application/javascript":l===".css"?d="text/css":l===".json"?d="application/json":l===".png"?d="image/png":l===".jpg"||l===".jpeg"?d="image/jpeg":l===".svg"?d="image/svg+xml":l===".woff"?d="font/woff":l===".woff2"?d="font/woff2":l===".ttf"&&(d="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const Tb=Object.freeze(Object.defineProperty({__proto__:null,loader:jb},Symbol.toStringTag,{value:"Module"}));function $b(e,t,r=10){var d;const s=new Map,a=m=>m.entityType==="visual"||m.entityType==="library";for(const m of e)a(m)&&s.set(m.sha,{entity:m,depth:0});const o=new Map;for(const m of t){const u=(d=m.metadata)==null?void 0:d.importedBy;if(u)for(const p of Object.keys(u))for(const h of Object.keys(u[p])){const{shas:f}=u[p][h];for(const y of f)o.has(m.sha)||o.set(m.sha,new Set),o.get(m.sha).add(y)}}const i=[],l=new Set;for(const m of e)i.push({sha:m.sha,depth:0}),l.add(m.sha);for(;i.length>0;){const{sha:m,depth:u}=i.shift();if(u>=r)continue;const p=o.get(m);if(p)for(const h of p){if(l.has(h))continue;l.add(h);const f=t.find(y=>y.sha===h);if(f){if(a(f)){const y=u+1,g=s.get(h);(!g||y<g.depth)&&s.set(h,{entity:f,depth:y})}i.push({sha:h,depth:u+1})}}}return Array.from(s.values()).sort((m,u)=>m.depth!==u.depth?m.depth-u.depth:m.entity.name.localeCompare(u.entity.name))}function Nr(e){const t=new Map;for(const s of e)t.has(s.name)||t.set(s.name,[]),t.get(s.name).push(s);const r=[];for(const s of t.values())if(s.length===1)r.push(s[0]);else{const a=s.sort((o,i)=>{var m,u;const l=((m=o.metadata)==null?void 0:m.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(l)});r.push(a[0])}return r}function Kl(e,t){const r=new Map,s=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&s.add(a.oldPath);for(const a of e){const o=t.filter(d=>d.filePath===a.path||a.status==="renamed"&&a.oldPath&&d.filePath===a.oldPath),i=o.filter(d=>{var m,u;return s.has(d.filePath)&&((m=d.metadata)==null?void 0:m.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),l=Nr(i);r.set(a.path,{status:a,entities:o,editedEntities:l})}return r}function Rb(e,t,r){const s=new Map;if(!r){for(const o of e)if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const i=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),l=Nr(i);s.set(o.path,{status:o,entities:l})}return s}const a=new Map;for(const o of r.fileComparisons){const i=new Set;for(const l of o.newEntities)i.add(l.name);for(const l of o.modifiedEntities)i.add(l.name);for(const l of o.deletedEntities)i.add(l.name);i.size>0&&a.set(o.filePath,i)}for(const o of e){const i=a.get(o.path);if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const l=i?t.filter(m=>(m.filePath===o.path||o.status==="renamed"&&o.oldPath&&m.filePath===o.oldPath)&&i.has(m.name)):[],d=Nr(l);s.set(o.path,{status:o,entities:d})}}return s}function Ib(e,t){const r=new Map,s=Ql(e,t);for(const a of s){const i=$b([a],t).filter(({depth:l})=>l>0);r.set(a.sha,i)}return r}function Ql(e,t){const r=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&r.add(a.oldPath);const s=t.filter(a=>{var o,i;return r.has(a.filePath)&&((o=a.metadata)==null?void 0:o.isUncommitted)&&!((i=a.metadata)!=null&&i.isSuperseded)});return Nr(s)}function Db({recentSimulations:e}){const t=ne(()=>{const r=new Map;return e.forEach(s=>{const a=s.entitySha,o=r.get(a);o?o.push(s):r.set(a,[s])}),Array.from(r.entries()).map(([s,a])=>({entitySha:s,entityName:a[0].entityName,scenarios:a}))},[e]);return c("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?c(ue,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>c("div",{children:[c("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n($n,{size:16,style:{color:"#8B5CF6"}})}),n(de,{to:`/entity/${r.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:r.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:r.scenarios.map((s,a)=>n(de,{to:s.scenarioId?`/entity/${s.entitySha}/scenarios/${s.scenarioId}`:`/entity/${s.entitySha}`,className:"aspect-4/3 border border-gray-200 rounded-lg overflow-hidden bg-gray-50 transition-all flex items-center justify-center hover:scale-105",onMouseEnter:o=>{o.currentTarget.style.borderColor="#005C75",o.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:o=>{o.currentTarget.style.borderColor="#E5E7EB",o.currentTarget.style.boxShadow="none"},title:s.scenarioName,children:n(Ge,{screenshotPath:s.screenshotPath,alt:s.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},s.scenarioId||`${s.entitySha}-${a}`))})]},r.entitySha))}),n(de,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):c("div",{className:"py-12 px-6 text-center rounded-lg w-full flex flex-col items-center justify-center min-h-50 border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n($n,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),c("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(de,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(de,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const Lb="/assets/codeyam-name-logo-CvKwUgHo.svg",Ob=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function Fb({request:e,context:t}){var r,s,a,o,i;try{const l=await Te();if(l){const{project:D}=await Re(l);if(((r=D.metadata)==null?void 0:r.editorMode)??!1)return qa("/editor");if(!(((a=(s=D.metadata)==null?void 0:s.labs)==null?void 0:a.simulations)??!1))return qa("/memory")}const d=t.analysisQueue,m=d?d.getState():{paused:!1,jobs:[]},[u,p]=await Promise.all([nn(),hn()]),h=Jr(),f=u?Kl(h,u):new Map,y=Array.from(f.entries()).sort((D,R)=>D[0].localeCompare(R[0])),g=(u==null?void 0:u.length)||0,x=(u==null?void 0:u.filter(D=>D.entityType==="visual").length)||0,v=(u==null?void 0:u.filter(D=>D.entityType==="library").length)||0,b=u?Ql(h,u):[],N=b.length,C=(u==null?void 0:u.filter(D=>(D.analyses??[]).filter(R=>R.scenarios&&R.scenarios.length>0).length>0).length)||0,E=(u==null?void 0:u.reduce((D,R)=>{var U,V,I;const T=((I=(V=(U=R.analyses)==null?void 0:U[0])==null?void 0:V.scenarios)==null?void 0:I.length)||0;return D+T},0))||0,w=(u==null?void 0:u.reduce((D,R)=>{var V,I;const U=(((I=(V=R.analyses)==null?void 0:V[0])==null?void 0:I.scenarios)||[]).filter(O=>{var z,L;return(L=(z=O.metadata)==null?void 0:z.screenshotPaths)==null?void 0:L[0]}).length;return D+U},0))||0,k=[];u==null||u.forEach(D=>{var T;const R=(T=D.analyses)==null?void 0:T[0];R!=null&&R.scenarios&&R.scenarios.filter(V=>{var I;return!((I=V.metadata)!=null&&I.sameAsDefault)}).forEach(V=>{var O,z;const I=(z=(O=V.metadata)==null?void 0:O.screenshotPaths)==null?void 0:z[0];I&&k.push({entitySha:D.sha,entityName:D.name,scenarioId:V.id,scenarioName:V.name,screenshotPath:I,createdAt:R.createdAt||""})})}),k.sort((D,R)=>new Date(R.createdAt).getTime()-new Date(D.createdAt).getTime());const S=k.slice(0,16),A=(u==null?void 0:u.filter(D=>D.entityType==="visual").filter(D=>{var U,V;const R=(U=D.analyses)==null?void 0:U[0];return!((V=R==null?void 0:R.scenarios)==null?void 0:V.some(I=>{var O,z;return(z=(O=I.metadata)==null?void 0:O.screenshotPaths)==null?void 0:z[0]}))}).slice(0,8))||[],$=(o=p==null?void 0:p.metadata)==null?void 0:o.currentRun,_=((i=$==null?void 0:$.currentEntityShas)==null?void 0:i.length)||0,j=m.jobs.length||0;return Q({stats:{totalEntities:g,visualEntities:x,libraryEntities:v,uncommittedEntities:N,entitiesWithAnalyses:C,totalScenarios:E,capturedScreenshots:w,currentlyAnalyzing:_,filesOnQueue:j},uncommittedFiles:y,uncommittedEntitiesList:b,recentSimulations:S,visualEntitiesForSimulation:A,projectSlug:l,queueState:m,currentCommit:p})}catch(l){return console.error("Failed to load dashboard data:",l),Q({stats:{totalEntities:0,visualEntities:0,libraryEntities:0,uncommittedEntities:0,entitiesWithAnalyses:0,totalScenarios:0,capturedScreenshots:0,currentlyAnalyzing:0,filesOnQueue:0},uncommittedFiles:[],uncommittedEntitiesList:[],recentSimulations:[],visualEntitiesForSimulation:[],projectSlug:null,queueState:{paused:!1,jobs:[]},currentCommit:null,error:"Failed to load dashboard data"})}}const zb=We(function(){var O,z;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:s,recentSimulations:a,visualEntitiesForSimulation:o,projectSlug:i,queueState:l,currentCommit:d}=Ve(),m=De(),u=mt(),{showToast:p}=ta();ht({source:"dashboard"});const[h,f]=M(new Set),[y,g]=M(null),[x,v]=M(!1),[b,N]=M(!1),{lastLine:C,isCompleted:E}=St(i,!!y),{simulatingEntity:w,scenarios:k,scenarioStatuses:S,allScenariosCaptured:A}=ne(()=>{var F,J;const L={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return L;const P=o==null?void 0:o.find(G=>G.sha===y);if(!P)return L;const q=(F=P.analyses)==null?void 0:F[0],H=(q==null?void 0:q.scenarios)||[],W=((J=q==null?void 0:q.status)==null?void 0:J.scenarios)||[],Z=W.filter(G=>G.screenshotFinishedAt).length,B=H.length>0&&Z===H.length;return{simulatingEntity:P,scenarios:H,scenarioStatuses:W,allScenariosCaptured:B}},[y,o]);te(()=>{(E||A)&&g(null)},[E,A]);const $=(O=d==null?void 0:d.metadata)==null?void 0:O.currentRun,_=new Set(($==null?void 0:$.currentEntityShas)||[]),j=new Set(l.jobs.flatMap(L=>L.entityShas||[])),D=new Set(((z=l.currentlyExecuting)==null?void 0:z.entityShas)||[]),R=s.filter(L=>L.entityType==="visual"||L.entityType==="library"),T=R.filter(L=>!_.has(L.sha)&&!j.has(L.sha)&&!D.has(L.sha)),U=()=>{if(T.length===0){p("All entities are already queued or analyzing","info",3e3);return}const L=T.map(P=>P.sha);N(!0),p(`Starting analysis for ${T.length} entities...`,"info",3e3),m.submit({entityShas:L.join(",")},{method:"post",action:"/api/analyze"})};te(()=>{if(m.state==="idle"&&m.data){const L=m.data;L.success?(console.log("[Analyze All] Success:",L.message),p(`Analysis started for ${L.entityCount} entities in ${L.fileCount} files. Watch the logs for progress.`,"success",6e3),N(!1)):L.error&&(console.error("[Analyze All] Error:",L.error),p(`Error: ${L.error}`,"error",8e3),N(!1))}},[m.state,m.data,p]);const V=L=>{f(P=>{const q=new Set(P);return q.has(L)?q.delete(L):q.add(L),q})},I=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children:c("div",{className:"px-20 pt-8 pb-12",children:[c("header",{className:"mb-8 flex justify-between items-center",children:[c("div",{className:"flex items-center gap-4",children:[n("img",{src:Lb,alt:"CodeYam",className:"h-3.5"}),n("span",{className:"text-gray-400 text-sm",children:"|"}),n("h1",{className:"text-sm font-mono font-normal text-gray-400 m-0",children:i?i.replace(/-/g," ").replace(/\b\w/g,L=>L.toUpperCase()):"Project"})]}),u.state==="loading"&&n("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),n("div",{className:"flex items-center justify-between gap-3",children:I.map((L,P)=>n(de,{to:L.link,className:"flex-1 bg-white rounded-xl border border-gray-200 overflow-hidden flex transition-all hover:shadow-lg no-underline cursor-pointer",style:{borderLeft:`4px solid ${L.color}`},children:c("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[c("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[c("div",{className:"flex items-center gap-1.5 group relative",children:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:L.label}),c("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[L.tooltip,n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:L.color},children:"View All →"})]}),c("div",{className:"flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${L.color}15`},children:[L.iconType==="folder"&&n(Gc,{size:20,style:{color:L.color}}),L.iconType==="check"&&n(Hs,{size:20,style:{color:L.color}}),L.iconType==="image"&&n($n,{size:20,style:{color:L.color}}),L.iconType==="code-xml"&&n(qc,{size:20,style:{color:L.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:L.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:L.color},children:"View All →"})]})]})},P))}),c("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[c("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[c("div",{className:"flex justify-between items-start mb-5",children:[c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${s.length} uncommitted entit${s.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),R.length>0&&n("button",{onClick:U,disabled:m.state!=="idle"||b||T.length===0,className:"px-5 py-2.5 text-white border-none rounded-lg text-sm font-semibold cursor-pointer transition-all hover:-translate-y-px disabled:bg-gray-400 disabled:cursor-not-allowed disabled:translate-y-0",style:{backgroundColor:"#005C75"},onMouseEnter:L=>L.currentTarget.style.backgroundColor="#004560",onMouseLeave:L=>L.currentTarget.style.backgroundColor="#005C75",children:m.state!=="idle"||b?"Starting analysis...":T.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([L,P])=>{const q=h.has(L),H=P.editedEntities||[];return c("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>V(L),role:"button",tabIndex:0,children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:q?"▼":"▶"}),c("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[c("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),c("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:L}),c("span",{className:"text-xs text-gray-500",children:[H.length," entit",H.length!==1?"ies":"y"]})]})]})}),q&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:H.length>0?H.map(W=>{const Z=_.has(W.sha),B=j.has(W.sha)||D.has(W.sha);return c(de,{to:`/entity/${W.sha}`,className:"flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg no-underline transition-all hover:shadow-md hover:-translate-y-0.5",style:{borderColor:"inherit"},onMouseEnter:F=>F.currentTarget.style.borderColor="#005C75",onMouseLeave:F=>F.currentTarget.style.borderColor="inherit",children:[c("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:W.entityType==="visual"?"#8B5CF615":W.entityType==="library"?"#6366F1":"#EC4899"},children:[W.entityType==="visual"&&n($n,{size:16,style:{color:"#8B5CF6"}}),W.entityType==="library"&&n(ci,{size:16,className:"text-white"}),W.entityType==="other"&&n(Kc,{size:16,className:"text-white"})]}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:W.name}),W.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),W.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),W.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),W.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:W.description})]}),c("div",{className:"flex items-center gap-2 shrink-0",children:[Z&&c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(ct,{size:14,className:"animate-spin"}),"Analyzing..."]}),!Z&&B&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!Z&&!B&&n("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),p(`Starting analysis for ${W.name}...`,"info",3e3),m.submit({entityShas:W.sha},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:F=>F.currentTarget.style.backgroundColor="#004560",onMouseLeave:F=>F.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},W.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},L)})}):c("div",{className:"py-12 px-6 text-center flex flex-col items-center rounded-lg min-h-50 justify-center border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:c("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&n(Db,{recentSimulations:a}),y&&c("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:a.length>0?`Latest ${a.length} captured screenshot${a.length!==1?"s":""}`:"No simulations captured yet"})]})}),y&&c("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[w&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(Xe,{type:"visual"})}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",w.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:w.filePath})]})]})}),A?c("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),c("span",{children:["Complete (",k.length," scenario",k.length!==1?"s":"",")"]})]}):C?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(ct,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:C,children:C}),i&&n("button",{onClick:()=>v(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):m.state!=="idle"?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(ct,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(ct,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),k.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:k.slice(0,8).map((L,P)=>{var J,G,X;const q=(J=w==null?void 0:w.analyses)==null?void 0:J[0],H=Vr(L,q==null?void 0:q.status,void 0,y||void 0,void 0),W=(X=(G=L.metadata)==null?void 0:G.screenshotPaths)==null?void 0:X[0],Z=H.isCaptured,B=H.status==="capturing"||H.status==="starting",F=H.hasError;return Z?n(de,{to:`/entity/${y}`,className:"w-20 h-15 border-2 border-gray-200 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center no-underline hover:border-blue-600 hover:scale-105 hover:shadow-md",children:n(Ge,{screenshotPath:W,alt:L.name,title:L.name,className:"max-w-full max-h-full object-contain object-center"})},P):F?n("div",{className:"w-20 h-15 border-2 border-solid border-red-300 rounded bg-red-50 flex flex-col items-center justify-center text-lg",title:H.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},P):n("div",{className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`${B?"Capturing":"Pending"} ${L.name}...`,children:n("span",{className:B?"animate-pulse":"text-gray-400",children:B?"⋯":"⏹️"})},P)})})]})]})]}),x&&i&&n($t,{projectSlug:i,onClose:()=>v(!1)})]})})}),Bb=Object.freeze(Object.defineProperty({__proto__:null,default:zb,loader:Fb,meta:Ob},Symbol.toStringTag,{value:"Module"}));function ka(e){const[t,r]=M(null),[s,a]=M(!1),o=se(()=>{e&&(a(!0),fetch(`/api/editor-test-results?testFile=${encodeURIComponent(e)}`).then(i=>i.json()).then(i=>{r(i),a(!1)}).catch(()=>{r({testFilePath:e,status:"error",testCases:[],errorMessage:"Failed to fetch test results"}),a(!1)}))},[e]);return te(()=>{e&&o()},[e,o]),{results:t,isRunning:s,runTests:o}}function An({imgSrc:e,name:t,isActive:r,onSelect:s}){return c("button",{onClick:s,className:"flex flex-col items-center gap-1 cursor-pointer group",title:t,children:[n("div",{className:`w-32 h-32 rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] ${r?"border-[#005c75] ring-1 ring-[#005c75]":"border-transparent hover:border-[#4d4d4d]"}`,children:e?n("img",{src:e,alt:t,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})})}),n("span",{className:`text-[10px] leading-tight text-center truncate w-32 ${r?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:t})]})}function Cs({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=ka(e);if(s&&!r)return c("div",{className:"px-2 pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!r)return null;if(r.status==="error")return n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-red-400",children:r.errorMessage})});const o=t?r.testCases.filter(d=>d.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return c("div",{className:"px-2 pt-1 space-y-0.5",children:[i.map(d=>{var u;const m=l&&d.fullName.startsWith(l)?d.fullName.slice(l.length):d.fullName;return c("div",{children:[c("div",{className:"flex items-center gap-1.5",children:[d.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):d.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${d.status==="passed"?"text-green-400":d.status==="failed"?"text-red-400":"text-gray-500"}`,children:m})]}),d.status==="failed"&&((u=d.failureMessages)==null?void 0:u.map((p,h)=>n("div",{className:"pl-4 text-[9px] text-red-300/70 truncate max-w-full",title:p,children:p.split(`
|
|
333
|
-
`)[0]},h)))]},d.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#00a0c4] hover:text-[#00c4ee] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}function Ht({filePath:e}){return e?c("div",{className:"flex items-center gap-1 px-2 mt-0.5",children:[c("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(At,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function Yb({scenarios:e,projectRoot:t,activeScenarioId:r,onScenarioSelect:s,zoomComponent:a,onZoomChange:o,analyzedEntities:i=[],glossaryFunctions:l=[],activeAnalyzedScenarioId:d,onAnalyzedScenarioSelect:m,entityImports:u,pageFilePaths:p={}}){const{pageGroups:h,componentGroups:f}=ne(()=>{const w=new Map,k=new Map;for(const A of e)if(A.componentName){const $=k.get(A.componentName)||[];$.push(A),k.set(A.componentName,$)}else{const $=Nt(A.url),_=w.get($)||[];_.push(A),w.set($,_)}const S=new Map([...k.entries()].sort(([A],[$])=>A.localeCompare($)));return{pageGroups:w,componentGroups:S}},[e]),y=ne(()=>{const w=new Set((i||[]).filter(S=>S.entityType==="visual").map(S=>S.name)),k=new Map;for(const[S,A]of f)w.has(S)||k.set(S,A);return k},[f,i]),{visualEntities:g,libraryEntities:x}=ne(()=>{const w=i.filter(S=>S.entityType==="visual").sort((S,A)=>S.name.localeCompare(A.name)),k=i.filter(S=>S.entityType==="library"||S.entityType==="functionCall").sort((S,A)=>S.name.localeCompare(A.name));return{visualEntities:w,libraryEntities:k}},[i]),v=ne(()=>{const w=new Set(x.map(k=>k.name));return l.filter(k=>!w.has(k.name)).sort((k,S)=>k.name.localeCompare(S.name))},[l,x]),b=i.some(w=>w.isAnalyzing),N=xe(null),C=xe(0),E=se(()=>{N.current&&(C.current=N.current.scrollTop)},[]);if(te(()=>{N.current&&C.current>0&&(N.current.scrollTop=C.current)}),e.length===0&&i.length===0&&v.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:c("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No scenarios yet"}),n("p",{className:"text-xs",children:"Scenarios will appear here as Claude creates them alongside your code. Each scenario represents a different state of your app's data."})]})});if(a){const w=f.get(a)||[],k=new Set((u==null?void 0:u[a])||[]),S=k.size>0,A=S?g.filter(_=>k.has(_.name)):[],$=S?x.filter(_=>k.has(_.name)):[];return n("div",{className:"flex-1 overflow-auto",children:c("div",{className:"p-3 space-y-1",children:[c("button",{onClick:()=>o(void 0),className:"w-full flex items-center gap-2 px-3 py-1.5 text-xs text-gray-400 hover:text-white transition-colors cursor-pointer",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M7.5 9L4.5 6L7.5 3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"All scenarios"]}),n("div",{className:"px-3 py-1.5",children:n("span",{className:"text-xs font-semibold text-white uppercase tracking-wider",children:a})}),n("div",{className:"flex flex-wrap gap-2 px-2",children:w.length===0?n("div",{className:"px-3 py-2 text-xs text-gray-500",children:"No scenarios for this component"}):w.map(_=>n(An,{imgSrc:_.screenshotPath?`/api/editor-scenario-image/${_.id}.png`:null,name:_.name,isActive:_.id===r,onSelect:()=>s(_)},_.id))}),A.length>0&&c("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),A.map(_=>c("div",{className:"mt-2",children:[n("div",{className:"flex items-center gap-2 px-2 py-1",children:n("button",{onClick:()=>o(_.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:_.name})}),n(Ht,{filePath:_.filePath,projectRoot:t}),(_.scenarios.length>0||_.pendingScenarios.length>0)&&n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:_.scenarios.map(j=>n(An,{imgSrc:j.screenshotPath?`/api/screenshot/${j.screenshotPath}`:null,name:j.name,isActive:j.id===d,onSelect:()=>m==null?void 0:m({analysisId:_.analysisId,scenarioId:j.id,scenarioName:j.name,entitySha:_.sha,entityName:_.name})},j.id))})]},_.sha))]}),$.length>0&&c("div",{className:"pt-2 mt-1",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),$.map(_=>c("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:_.name})}),n(Ht,{filePath:_.filePath,projectRoot:t}),_.testFile&&n(Cs,{testFile:_.testFile,entityName:_.name})]},_.sha))]})]})})}return n("div",{ref:N,onScroll:E,className:"flex-1 overflow-auto",children:c("div",{className:"p-3 space-y-3",children:[h.size>0&&c("div",{children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),[...h.entries()].sort(([w],[k])=>w==="Home"?-1:k==="Home"?1:w.localeCompare(k)).map(([w,k])=>c("div",{className:"px-2 pt-1",children:[n("div",{className:"py-0.5",children:n("span",{className:"text-[11px] font-medium text-gray-400",children:w})}),p[w]&&n(Ht,{filePath:p[w],projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:k.map(S=>n(An,{imgSrc:S.screenshotPath?`/api/editor-scenario-image/${S.id}.png`:null,name:S.name,isActive:S.id===r&&!d,onSelect:()=>s(S)},S.id))})]},w))]}),y.size>0&&c("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),[...y.entries()].map(([w,k])=>{var S;return c("div",{className:"mt-2",children:[n("div",{className:"flex items-center justify-between px-2 py-1",children:n("button",{onClick:()=>o(w),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:w})}),((S=k[0])==null?void 0:S.componentPath)&&n(Ht,{filePath:k[0].componentPath,projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:k.map(A=>n(An,{imgSrc:A.screenshotPath?`/api/editor-scenario-image/${A.id}.png`:null,name:A.name,isActive:A.id===r&&!d,onSelect:()=>s(A)},A.id))})]},w)})]}),g.length>0&&c("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[c("div",{className:"px-2 py-1",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),b&&e.length===0&&i.every(w=>w.scenarioCount===0)&&n("span",{className:"ml-2 text-[10px] text-gray-500",children:"— Entities are being analyzed..."})]}),g.map(w=>c("div",{className:"mt-2",children:[c("div",{className:"flex items-center gap-2 px-2 py-1",children:[n("button",{onClick:()=>o(w.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:w.name}),w.isAnalyzing&&w.scenarioCount===0&&c("span",{className:"flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(Ht,{filePath:w.filePath,projectRoot:t}),(w.scenarios.length>0||w.pendingScenarios.length>0)&&c("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:[w.scenarios.map(k=>n(An,{imgSrc:k.screenshotPath?`/api/screenshot/${k.screenshotPath}`:null,name:k.name,isActive:k.id===d,onSelect:()=>m==null?void 0:m({analysisId:w.analysisId,scenarioId:k.id,scenarioName:k.name,entitySha:w.sha,entityName:w.name})},k.id)),w.pendingScenarios.map(k=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:k,children:k},k))]})]},w.sha))]}),(x.length>0||v.length>0)&&c("div",{className:`pt-2 mt-1 ${g.length>0?"":"border-t border-[#3d3d3d]"}`,children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),x.map(w=>c("div",{className:"mt-2",children:[c("div",{className:"px-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:w.name}),w.isAnalyzing&&w.scenarioCount===0&&c("span",{className:"ml-2 inline-flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(Ht,{filePath:w.filePath,projectRoot:t}),w.testFile?n(Cs,{testFile:w.testFile,entityName:w.name}):n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},w.sha)),v.map(w=>c("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:w.name})}),n(Ht,{filePath:w.filePath,projectRoot:t}),n(Cs,{testFile:w.testFile,entityName:w.name})]},w.name))]})]})})}const Jo=120;function Zl({text:e,theme:t}){const[r,s]=M(!1),a=e.length>Jo,o=a&&!r?e.slice(0,Jo)+"…":e,i=t==="light";return c("div",{className:`px-4 py-2 ${i?"border-b border-gray-200 bg-gray-50":"border-b border-[#3d3d3d] bg-[#252525]"}`,children:[n("span",{className:"text-[9px] font-semibold uppercase tracking-wider text-gray-500",children:"User Prompt"}),c("p",{className:`text-[11px] mt-0.5 mb-0 leading-relaxed ${i?"text-gray-600":"text-gray-400"}`,children:[o,a&&n("button",{onClick:()=>s(!r),className:`ml-1 text-[11px] font-medium bg-transparent border-none p-0 cursor-pointer ${i?"text-blue-500 hover:text-blue-700":"text-[#00a0c4] hover:text-[#00c0e8]"}`,children:r?"Show less":"Read more…"})]})]})}function Ho({status:e}){const t={new:{label:"New",bg:"bg-green-900/40",text:"text-green-400",border:"border-green-700/50"},edited:{label:"Edited",bg:"bg-blue-900/40",text:"text-blue-400",border:"border-blue-700/50"},impacted:{label:"Impacted",bg:"bg-amber-900/40",text:"text-amber-400",border:"border-amber-700/50"}}[e.status];return n("span",{className:`${t.bg} ${t.text} ${t.border} border text-[8px] font-bold px-1 py-0 rounded-full uppercase tracking-wider`,children:t.label})}function Ub({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=ka(e);if(s&&!r)return c("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#00a0c4] animate-pulse"}),n("span",{className:"text-[10px] text-gray-500",children:"Running tests..."})]});if(!r)return null;if(r.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-400",children:r.errorMessage})});const o=t?r.testCases.filter(d=>d.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return c("div",{className:"pt-1 space-y-0.5",children:[i.map(d=>{var u;const m=l&&d.fullName.startsWith(l)?d.fullName.slice(l.length):d.fullName;return c("div",{children:[c("div",{className:"flex items-center gap-1.5",children:[d.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):d.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${d.status==="passed"?"text-green-400":d.status==="failed"?"text-red-400":"text-gray-500"}`,children:m})]}),d.status==="failed"&&((u=d.failureMessages)==null?void 0:u.map((p,h)=>n("div",{className:"pl-4 text-[9px] text-red-400/70 truncate max-w-full",title:p,children:p.split(`
|
|
334
|
-
`)[0]},h)))]},d.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#00a0c4] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}const Wb={feature:{label:"Feature",color:"bg-[#005c75]"},fix:{label:"Fix",color:"bg-amber-700"},refactor:{label:"Refactor",color:"bg-purple-700"},scaffold:{label:"Scaffold",color:"bg-green-700"},data:{label:"Data",color:"bg-blue-700"},milestone:{label:"Milestone",color:"bg-yellow-600"}};function Jb(e){try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Hb(e){try{return new Date(e+"T00:00:00").toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"})}catch{return e}}function Vb({isActive:e,onScreenshotClick:t,glossaryFunctions:r=[],pageNames:s=[]}){const[a,o]=M([]),[i,l]=M(!0),[d,m]=M(new Set),u=se(f=>{m(y=>{const g=new Set(y);return g.has(f)?g.delete(f):g.add(f),g})},[]),p=se(async()=>{try{const f=await fetch("/api/editor-journal");if(f.ok){const y=await f.json();o(y.entries||[])}}catch{}finally{l(!1)}},[]);if(te(()=>{p()},[p]),te(()=>{e&&p()},[e,p]),te(()=>{const f=new EventSource("/api/events");return f.addEventListener("message",y=>{try{const g=JSON.parse(y.data);g.type==="db-change"&&g.changeType==="journal"&&p()}catch{}}),()=>f.close()},[p]),i)return n("div",{className:"flex-1 flex items-center justify-center",children:n("span",{className:"text-gray-500 text-sm",children:"Loading journal..."})});if(a.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:c("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No journal entries yet"}),n("p",{className:"text-xs",children:"Journal entries will appear as you build. Claude records features, screenshots, and commits as the project evolves."})]})});const h=eg(a);return n("div",{className:"flex-1 overflow-auto",children:n("div",{className:"p-3 space-y-4",children:[...h.entries()].map(([f,y])=>c("div",{children:[n("div",{className:"px-3 py-1.5 sticky top-0 bg-[#1e1e1e] z-10",children:n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:Hb(f)})}),n("div",{className:"space-y-2",children:y.map((g,x)=>{const v=Wb[g.type]||{label:g.type,color:"bg-gray-600"},b=`${g.time}-${x}`,N=d.has(b);return c("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[c("div",{className:`p-3 space-y-2 ${N?"":"max-h-[300px] overflow-y-auto"}`,children:[n("div",{className:"flex items-start gap-2",children:c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white truncate",children:g.title}),n("span",{className:`${v.color} text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:v.label})]}),n("span",{className:"text-[10px] text-gray-500",children:Jb(g.time)}),g.featureName&&n("span",{className:"text-[10px] text-gray-500 italic truncate",title:g.featureName,children:g.featureName})]})}),g.userPrompt&&n(Zl,{text:g.userPrompt,theme:"dark"}),n("p",{className:"text-xs text-gray-400 leading-relaxed",children:g.description}),g.screenshot&&n("button",{type:"button",className:"rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] flex items-center justify-center p-1 cursor-pointer transition-colors w-full",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${g.screenshot.replace("screenshots/","")}`,commitSha:g.commitSha,commitMessage:g.commitMessage,scenarioName:g.title}),children:n("img",{src:`/api/editor-journal-image/${g.screenshot.replace("screenshots/","")}`,alt:g.title,className:"max-w-full max-h-full object-contain",loading:"lazy"})}),g.scenarioScreenshots&&g.scenarioScreenshots.length>0&&(()=>{const C=tg(g.scenarioScreenshots);new Set(s);const E=C.filter(([_])=>_==="App").flatMap(([,_])=>_),w=Is(C.filter(([_])=>_!=="App"),g.entityChangeStatus),k=g.entityChangeStatus,A=k&&Object.keys(k).length>0?s.filter(_=>k[_]):s,$=_=>n("button",{type:"button",className:"w-[4.5rem] h-[4.5rem] rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${_.path.replace("screenshots/","")}`,commitSha:g.commitSha,commitMessage:g.commitMessage,scenarioName:_.name}),children:n("img",{src:`/api/editor-journal-image/${_.path.replace("screenshots/","")}`,alt:_.name,title:_.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},_.path);return c("div",{className:"space-y-2",children:[(A.length>0||E.length>0)&&c("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),A.map(_=>c("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:_}),(k==null?void 0:k[_])&&n(Ho,{status:k[_]})]},_)),E.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:E.map($)})]}),w.length>0&&c("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),w.map(([_,j])=>c("div",{children:[c("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:_}),(k==null?void 0:k[_])&&n(Ho,{status:k[_]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:j.map($)})]},_))]})]})})(),r.length>0&&c("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"}),n("div",{className:"space-y-2",children:r.map(C=>c("div",{children:[n("span",{className:"text-[11px] font-medium text-gray-200",children:C.name}),n("span",{className:"text-[9px] text-gray-500 truncate block",children:C.filePath}),C.testFile?n(Ub,{testFile:C.testFile,entityName:C.name}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},C.name))})]}),g.commitSha&&c("div",{className:"flex items-center gap-1.5 text-[10px]",children:[n("span",{className:"font-mono text-[#00a0c4] bg-[#00a0c4]/10 px-1.5 py-0.5 rounded",children:g.commitSha.slice(0,7)}),n("span",{className:"text-gray-500 truncate",children:g.commitMessage})]})]}),c("button",{onClick:()=>u(b),className:"w-full py-1.5 text-[10px] text-gray-500 hover:text-gray-300 border-t border-[#3d3d3d] transition-colors cursor-pointer",children:["——— ",N?"Collapse":"Expand"," ———"]})]},b)})})]},f))})})}function Vt({imgSrc:e,name:t,isActive:r,onSelect:s}){return c("button",{onClick:s,className:"flex flex-col items-center gap-1 cursor-pointer group",title:t,children:[n("div",{className:`w-24 h-24 rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] ${r?"border-[#005c75] ring-1 ring-[#005c75]":"border-transparent hover:border-[#4d4d4d]"}`,children:e?n("img",{src:e,alt:t,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})})}),n("span",{className:`text-[10px] leading-tight text-center truncate w-24 ${r?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:t})]})}function nr({filePath:e}){return e?c("div",{className:"flex items-center gap-1 mt-0.5",children:[c("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(At,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function Gb({hasProject:e,scenarios:t,analyzedEntities:r,glossaryFunctions:s=[],projectRoot:a,activeScenarioId:o,onScenarioSelect:i,onAnalyzedScenarioSelect:l,onSwitchToBuild:d,zoomComponent:m,onZoomChange:u,entityImports:p,pageFilePaths:h={}}){const{pageGroups:f,componentGroups:y}=ne(()=>{const E=new Map,w=new Map;for(const S of t)if(S.componentName){const A=w.get(S.componentName)||[];A.push(S),w.set(S.componentName,A)}else{const A=Nt(S.url),$=E.get(A)||[];$.push(S),E.set(A,$)}const k=new Map([...w.entries()].sort(([S],[A])=>S.localeCompare(A)));return{pageGroups:E,componentGroups:k}},[t]),g=ne(()=>r.filter(E=>E.entityType==="visual").sort((E,w)=>E.name.localeCompare(w.name)),[r]),x=ne(()=>{const E=new Map;for(const w of s)E.set(w.name,w);return E},[s]),v=xe(null),b=xe(0),N=se(()=>{v.current&&(b.current=v.current.scrollTop)},[]);if(te(()=>{v.current&&b.current>0&&(v.current.scrollTop=b.current)}),!e)return n("div",{className:"flex-1 flex items-center justify-center",children:c("div",{className:"flex flex-col items-center gap-4",children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:"Ready to build something?"}),n("button",{onClick:d,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})});if(!(t.length>0||g.length>0))return n("div",{className:"flex-1 flex items-center justify-center",children:c("div",{className:"flex flex-col items-center gap-4 px-8 text-center",children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:"Your project is ready"}),n("p",{className:"text-sm text-gray-400 m-0 font-['IBM_Plex_Sans'] leading-relaxed max-wpn-70",children:"Describe what you want to build in the Chat and your pages and components will appear here."}),n("button",{onClick:d,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})});if(m){const E=f.get(m)||[],w=y.get(m)||[],k=g.find(I=>I.name===m),S=x.get(m),A=[...E,...w],$=new Set((p==null?void 0:p[m])||[]),_=$.size>0,j=_?[...y.entries()].filter(([I])=>$.has(I)):[],D=_?g.filter(I=>$.has(I.name)&&!j.some(([O])=>O===I.name)):[],R=_?s.filter(I=>$.has(I.name)):[],T=j.length>0||D.length>0,U=R.length>0,V=T||U;return n("div",{className:"flex-1 overflow-auto",children:c("div",{className:"p-4 space-y-3",children:[c("button",{onClick:()=>u(void 0),className:"flex items-center gap-2 text-xs text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M7.5 9L4.5 6L7.5 3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"All"]}),c("div",{children:[n("h2",{className:"text-sm font-semibold text-white m-0 font-['IBM_Plex_Sans'] uppercase tracking-wider",children:m}),S&&n(nr,{filePath:S.filePath,projectRoot:a})]}),A.length>0&&n("div",{className:"flex flex-wrap gap-2",children:A.map(I=>n(Vt,{imgSrc:I.screenshotPath?`/api/editor-scenario-image/${I.id}.png`:null,name:I.name,isActive:I.id===o,onSelect:()=>i(I)},I.id))}),k&&(k.scenarios.length>0||k.pendingScenarios.length>0)&&c("div",{className:"flex flex-wrap gap-2",children:[k.scenarios.map(I=>n(Vt,{imgSrc:I.screenshotPath?`/api/screenshot/${I.screenshotPath}`:null,name:I.name,isActive:!1,onSelect:()=>l({analysisId:k.analysisId,scenarioId:I.id,scenarioName:I.name,entitySha:k.sha,entityName:k.name})},I.id)),k.pendingScenarios.map(I=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:I,children:I},I))]}),S&&c("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] text-gray-500",children:"Tests:"}),n(nr,{filePath:S.testFile,projectRoot:a})]}),A.length===0&&!k&&!S&&n("div",{className:"text-xs text-gray-500",children:"No scenarios for this entity"}),V&&c("div",{className:"pt-3 mt-2 border-t border-[#3d3d3d] space-y-3",children:[T&&c("div",{children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),j.map(([I,O])=>c("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(I),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:I})}),O.length>0&&n("div",{className:"flex flex-wrap gap-2 pt-1",children:O.map(z=>n(Vt,{imgSrc:z.screenshotPath?`/api/editor-scenario-image/${z.id}.png`:null,name:z.name,isActive:z.id===o,onSelect:()=>i(z)},z.id))})]},I)),D.map(I=>c("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(I.name),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:I.name})}),(I.scenarios.length>0||I.pendingScenarios.length>0)&&c("div",{className:"flex flex-wrap gap-2 pt-1",children:[I.scenarios.map(O=>n(Vt,{imgSrc:O.screenshotPath?`/api/screenshot/${O.screenshotPath}`:null,name:O.name,isActive:!1,onSelect:()=>l({analysisId:I.analysisId,scenarioId:O.id,scenarioName:O.name,entitySha:I.sha,entityName:I.name})},O.id)),I.pendingScenarios.map(O=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:O,children:O},O))]})]},I.sha))]}),U&&c("div",{children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"}),R.map(I=>c("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(I.name),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:I.name})}),n(nr,{filePath:I.filePath,projectRoot:a}),I.testFile&&c("div",{className:"flex items-center gap-1.5 mt-0.5",children:[n("span",{className:"text-[9px] text-gray-600",children:"test:"}),n("span",{className:"text-[9px] text-gray-500 truncate",children:I.testFile})]})]},I.name))]})]})]})})}return n("div",{ref:v,onScroll:N,className:"flex-1 overflow-auto",children:c("div",{className:"p-4 space-y-4",children:[n("h2",{className:"text-sm font-medium text-gray-300 m-0 font-['IBM_Plex_Sans']",children:"What do you want to work on next?"}),n("button",{onClick:d,className:"w-full py-3 border-2 border-dashed border-[#4d4d4d] rounded-lg text-sm text-gray-400 hover:border-[#005c75] hover:text-white transition-colors cursor-pointer bg-transparent",children:"+ New Page"}),f.size>0&&c("div",{children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),[...f.entries()].sort(([E],[w])=>E==="Home"?-1:w==="Home"?1:E.localeCompare(w)).map(([E,w])=>c("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(E),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:E})}),h[E]&&n(nr,{filePath:h[E],projectRoot:a}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:w.map(k=>n(Vt,{imgSrc:k.screenshotPath?`/api/editor-scenario-image/${k.id}.png`:null,name:k.name,isActive:k.id===o,onSelect:()=>i(k)},k.id))})]},E))]}),y.size>0&&n("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),[...y.entries()].map(([E,w])=>c("div",{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(E),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:E})}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:w.map(k=>n(Vt,{imgSrc:k.screenshotPath?`/api/editor-scenario-image/${k.id}.png`:null,name:k.name,isActive:k.id===o,onSelect:()=>i(k)},k.id))})]},E)),g.map(E=>c("div",{children:[c("div",{className:"flex items-center gap-2 py-1",children:[n("button",{onClick:()=>u(E.name),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:E.name}),E.isAnalyzing&&E.scenarioCount===0&&c("span",{className:"flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),(E.scenarios.length>0||E.pendingScenarios.length>0)&&c("div",{className:"flex flex-wrap gap-2 pt-1",children:[E.scenarios.map(w=>n(Vt,{imgSrc:w.screenshotPath?`/api/screenshot/${w.screenshotPath}`:null,name:w.name,isActive:!1,onSelect:()=>l({analysisId:E.analysisId,scenarioId:w.id,scenarioName:w.name,entitySha:E.sha,entityName:E.name})},w.id)),E.pendingScenarios.map(w=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:w,children:w},w))]})]},E.sha))]})})}const Vo={new:0,edited:1,impacted:2};function Go({status:e,onClick:t}){const r={new:{label:"New",bg:"bg-green-100",text:"text-green-700",border:"border-green-200"},edited:{label:"Edited",bg:"bg-blue-100",text:"text-blue-700",border:"border-blue-200"},impacted:{label:"Impacted",bg:"bg-amber-100",text:"text-amber-700",border:"border-amber-200"}}[e.status],s=t&&(e.status==="edited"||e.status==="impacted");return n("button",{onClick:s?t:void 0,className:`${r.bg} ${r.text} ${r.border} border text-[9px] font-bold px-1.5 py-0.5 rounded-full uppercase tracking-wider shrink-0 ${s?"cursor-pointer hover:opacity-80 transition-opacity":"cursor-default"}`,children:r.label})}function qo({filePath:e}){const[t,r]=M(null),[s,a]=M(!0),[o,i]=M(null);return te(()=>{import("react-diff-viewer-continued").then(l=>{i(()=>l.default)})},[]),te(()=>{a(!0),fetch(`/api/editor-file-diff?path=${encodeURIComponent(e)}`).then(l=>l.json()).then(l=>{r({oldContent:l.oldContent,newContent:l.newContent})}).catch(()=>{r(null)}).finally(()=>a(!1))},[e]),s?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Loading diff..."}):!t||!o?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Could not load diff"}):n("div",{className:"mt-2 border border-gray-200 rounded-lg overflow-hidden max-h-[300px] overflow-auto text-xs",children:n(o,{oldValue:t.oldContent,newValue:t.newContent,splitView:!1,useDarkTheme:!1,showDiffOnly:!0,styles:{contentText:{fontSize:"11px",lineHeight:"1.4"},line:{padding:"1px 8px",fontSize:"11px"}}})})}function Ko({impactedBy:e,changedEntities:t}){return n("div",{className:"mt-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5",children:e&&e.length>0?c(ue,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Re-captured because these dependencies changed"}),n("ul",{className:"mt-1.5 space-y-1",children:e.map(r=>c("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.changeType==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.changeType==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name}),n("span",{className:"text-[9px] text-amber-500 truncate",children:r.filePath})]},r.filePath))})]}):t&&t.length>0?c(ue,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Unchanged — these entities were modified in this session"}),n("ul",{className:"mt-1.5 space-y-1",children:t.map(r=>c("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.status==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.status==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name})]},r.name))})]}):n("span",{className:"text-[10px] text-amber-600",children:"This component was re-captured because a dependency changed"})})}function Qo({scenarioId:e,name:t,isActive:r,onSelect:s}){const[a,o]=M(!1);return te(()=>{o(!1)},[e]),c("button",{onClick:s,className:"flex flex-col items-center gap-1.5 cursor-pointer group",title:t,children:[n("div",{className:`w-32 h-32 rounded-lg overflow-hidden border-2 transition-all ${r?"border-[#0ea5e9] ring-2 ring-[#0ea5e9]/40 shadow-lg shadow-[#0ea5e9]/20":"border-gray-200 hover:border-gray-400 shadow-sm"}`,children:a?n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center",children:n("span",{className:"text-[9px] text-gray-400",children:"No preview"})}):n("img",{src:`/api/editor-scenario-image/${e}.png`,alt:t,className:"w-full h-full object-contain bg-white",loading:"lazy",onError:()=>o(!0)})}),n("span",{className:`text-[11px] leading-tight text-center truncate w-32 font-medium ${r?"text-gray-900":"text-gray-600 group-hover:text-gray-900"}`,children:t})]})}function qb({filePath:e}){return e?c("div",{className:"flex items-center gap-1 mt-0.5",children:[c("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-400 hover:text-gray-600 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(At,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-400 hover:text-gray-600 transition-colors"})]}):null}function Kb({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=ka(e);if(s&&!r)return c("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0ea5e9] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!r)return null;if(r.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-500",children:r.errorMessage})});const o=t?r.testCases.filter(d=>d.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return c("div",{className:"pt-1 space-y-0.5",children:[i.map(d=>{var u;const m=l&&d.fullName.startsWith(l)?d.fullName.slice(l.length):d.fullName;return c("div",{children:[c("div",{className:"flex items-center gap-1.5",children:[d.status==="passed"?n("span",{className:"text-green-600 text-[10px]",children:"✓"}):d.status==="failed"?n("span",{className:"text-red-500 text-[10px]",children:"✗"}):n("span",{className:"text-gray-400 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${d.status==="passed"?"text-green-600":d.status==="failed"?"text-red-500":"text-gray-400"}`,children:m})]}),d.status==="failed"&&((u=d.failureMessages)==null?void 0:u.map((p,h)=>n("div",{className:"pl-4 text-[9px] text-red-400 truncate max-w-full",title:p,children:p.split(`
|
|
335
|
-
`)[0]},h)))]},d.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#0ea5e9] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}function Zo(e){const t=e.indexOf(" - ");return t!==-1?e.slice(t+3):e}function Xo(e,t){return!t||Object.keys(t).length===0?e:[...e].sort(([r],[s])=>{var l,d;const a=((l=t[r])==null?void 0:l.status)||"impacted",o=((d=t[s])==null?void 0:d.status)||"impacted",i=(Vo[a]??2)-(Vo[o]??2);return i!==0?i:r.localeCompare(s)})}function Qb({scenarios:e,allScenarios:t=[],glossaryFunctions:r=[],projectRoot:s,activeScenarioId:a,onScenarioSelect:o,onClose:i,entityChangeStatus:l={},featureName:d,userPrompt:m}){const u=ne(()=>{if(t.length===0||Object.keys(l).length===0)return e;const w=new Set(e.map(S=>S.id)),k=t.filter(S=>{var $;if(w.has(S.id))return!1;const A=S.componentName||Nt(S.url);return(($=l[A])==null?void 0:$.status)==="impacted"});return k.length===0?e:[...e,...k]},[e,t,l]),p=ne(()=>Object.entries(l).filter(([,w])=>w.status==="new"||w.status==="edited").map(([w,k])=>({name:w,status:k.status})),[l]),[h,f]=M(null),y=se(w=>{f(k=>k===w?null:w)},[]),{pageGroups:g,componentGroups:x}=ne(()=>{const w=new Map,k=new Map;for(const S of u)if(S.componentName){const A=k.get(S.componentName)||[];A.push(S),k.set(S.componentName,A)}else{const A=Nt(S.url),$=w.get(A)||[];$.push(S),w.set(A,$)}return{pageGroups:w,componentGroups:k}},[u]),v=ne(()=>Xo([...g.entries()],l),[g,l]),b=ne(()=>Xo([...x.entries()],l),[x,l]),N=ne(()=>Is(v,l),[v,l]),C=ne(()=>Is(b,l),[b,l]),E=ne(()=>Eh(r,l),[r,l]);return u.length===0&&r.length===0?c("div",{className:"h-full bg-white flex items-center justify-center relative",children:[n("button",{onClick:i,className:"absolute top-2 right-3 text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none",title:"Close results",children:"×"}),n("span",{className:"text-sm text-gray-400",children:"No scenarios registered yet"})]}):c("div",{className:"h-full bg-white flex flex-col overflow-hidden",children:[c("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-gray-200 shrink-0",children:[c("div",{className:"min-w-0",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Working Session Results"}),d&&n("div",{className:"text-[11px] text-gray-400 truncate",title:d,children:d})]}),n("button",{onClick:i,className:"text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none shrink-0",title:"Close results",children:"×"})]}),m&&n(Zl,{text:m,theme:"light"}),n("div",{className:"flex-1 overflow-auto p-4",children:c("div",{className:"space-y-5",children:[N.length>0&&c("div",{children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),n("div",{className:"space-y-3 pl-1",children:N.map(([w,k])=>{var _;const S=l[w],A=h===w,$=(_=k[0])==null?void 0:_.componentPath;return c("div",{children:[c("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:w}),S&&n(Go,{status:S,onClick:()=>y(w)})]}),A&&(S==null?void 0:S.status)==="edited"&&$&&n(qo,{filePath:$}),A&&(S==null?void 0:S.status)==="impacted"&&n(Ko,{impactedBy:S.impactedBy,changedEntities:p}),n("div",{className:"flex flex-wrap gap-3",children:k.map(j=>n(Qo,{scenarioId:j.id,name:Zo(j.name),isActive:j.id===a,onSelect:()=>o(j)},j.id))})]},w)})})]}),C.length>0&&c("div",{className:N.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),n("div",{className:"space-y-3 pl-1",children:C.map(([w,k])=>{var _;const S=l[w],A=h===w,$=(_=k[0])==null?void 0:_.componentPath;return c("div",{children:[c("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:w}),S&&n(Go,{status:S,onClick:()=>y(w)})]}),A&&(S==null?void 0:S.status)==="edited"&&$&&n(qo,{filePath:$}),A&&(S==null?void 0:S.status)==="impacted"&&n(Ko,{impactedBy:S.impactedBy,changedEntities:p}),n("div",{className:"flex flex-wrap gap-3",children:k.map(j=>n(Qo,{scenarioId:j.id,name:Zo(j.name),isActive:j.id===a,onSelect:()=>o(j)},j.id))})]},w)})})]}),E.length>0&&c("div",{className:N.length>0||C.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),n("div",{className:"space-y-2 pl-1",children:E.map(w=>c("div",{children:[n("div",{className:"flex items-center gap-2",children:n("span",{className:"text-[11px] font-medium text-gray-700",children:w.name})}),n(qb,{filePath:w.filePath,projectRoot:s}),w.testFile?n(Kb,{testFile:w.testFile,entityName:w.name}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-400",children:"No test file"})})]},w.name))})]})]})})]})}function Zb({items:e,onNavigate:t}){return e.length===0?null:n("nav",{className:"flex items-center gap-1 text-xs",children:e.map((r,s)=>{const a=s===e.length-1;return c("span",{className:"flex items-center gap-1",children:[s>0&&n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),a?n("span",{className:"text-white font-medium",children:r.name}):n("button",{onClick:()=>t(r.componentName),className:"text-gray-400 hover:text-white transition-colors cursor-pointer",children:r.name})]},r.componentName||"app")})})}const Xb=[{key:"app",label:"App"},{key:"build",label:"Build"},{key:"data",label:"Structure"},{key:"journal",label:"Journal"}];function ev({activeTab:e,onTabChange:t,buildIdle:r,zoomComponent:s,breadcrumbItems:a,onBreadcrumbNavigate:o}){return c("div",{className:"bg-[#3d3d3d] h-10 flex items-center px-3 gap-3 shrink-0 z-20 border-b border-[#2d2d2d]",children:[c("div",{className:"flex items-center gap-2 shrink-0",children:[n("img",{src:_r,alt:"CodeYam",className:"h-5 brightness-0 invert"}),n("span",{className:"text-white font-medium text-xs whitespace-nowrap",children:"Codeyam Editor"}),s&&c(ue,{children:[n("div",{className:"w-px h-3.5 bg-gray-600"}),n(Zb,{items:a,onNavigate:o})]})]}),n("div",{className:"flex-1"}),n("div",{className:"flex items-center gap-0.5 bg-[#4a3232] rounded-lg p-0.5 shrink-0",children:Xb.map(i=>c("button",{onClick:()=>t(i.key),className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors cursor-pointer ${e===i.key?"bg-[#7a4444] text-white":"text-gray-300 hover:text-white"}`,children:[i.label,i.key==="build"&&r&&e!=="build"&&n("span",{className:"ml-1 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"})]},i.key))})]})}function tv({preview:e,onDismiss:t,onLoadCommit:r}){return c("div",{className:"flex flex-col items-center gap-6 max-w-[700px] w-full",children:[c("div",{className:"text-center",children:[n("h2",{className:"text-lg font-semibold text-[#333] m-0 font-['IBM_Plex_Sans']",children:"Journal Screenshot"}),n("p",{className:"text-sm text-[#888] mt-1 m-0 font-['IBM_Plex_Sans']",children:"This is a snapshot from a previous version — not a live preview"})]}),n("div",{className:"rounded-lg overflow-hidden border-2 border-[#ccc] shadow-md max-w-full w-fit",children:n("img",{src:e.screenshotUrl,alt:e.scenarioName,className:"max-w-full h-auto block"})}),c("div",{className:"flex items-center gap-2 text-sm text-[#666]",children:[e.commitSha&&n("span",{className:"font-mono text-xs text-[#00a0c4] bg-[#00a0c4]/15 px-2 py-0.5 rounded",children:e.commitSha.slice(0,7)}),c("span",{className:"truncate",children:[e.scenarioName,e.commitMessage&&` — ${e.commitMessage}`]})]}),c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:t,className:"text-sm text-[#888] hover:text-[#333] transition-colors cursor-pointer px-3 py-1.5 rounded border border-[#ccc] hover:border-[#999] bg-white",children:"Back to live preview"}),e.commitSha&&r&&n(nv,{commitSha:e.commitSha,onLoadCommit:r})]})]})}function nv({commitSha:e,onLoadCommit:t}){const[r,s]=M(!1),[a,o]=M(null);return c(ue,{children:[n("button",{onClick:()=>{s(!0),o(null),t(e).then(i=>{i.success||o(i.error||"Failed to load commit")}).catch(i=>{o(i instanceof Error?i.message:"Network error")}).finally(()=>s(!1))},disabled:r,className:"bg-[#005c75] hover:bg-[#004d63] disabled:opacity-50 text-white text-sm font-medium px-4 py-1.5 rounded transition-colors cursor-pointer",children:r?"Loading...":"Load this version"}),a&&n("div",{className:"bg-red-50 border border-red-200 rounded px-4 py-2 text-sm text-red-600 w-full text-center",children:a})]})}function rv({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,onStateChange:o}){const{interactiveServerUrl:i,isStarting:l,isLoading:d}=rn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:!0});return te(()=>{o(i,l||d)},[i,l,d,o]),null}function sv(e,t){return t.status==="error"?{url:null,proxyUrl:null,isStarting:!1,error:t.errorMessage||"Dev server crashed",canStartServer:e.canStartServer,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.url?{url:t.url,proxyUrl:t.proxyUrl||null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.status==="starting"?{...e,isStarting:!0,error:null,canStartServer:!0,shouldAutoStart:!1}:t.status==="stopped"?e.url?{...e,url:null,isStarting:!1,shouldAutoStart:!1}:e.autoStartAttempted?{...e,isStarting:!1,shouldAutoStart:!1}:{...e,autoStartAttempted:!0,shouldAutoStart:!0}:{...e,shouldAutoStart:!1}}function av(){const[e,t]=M({url:null,proxyUrl:null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:!1}),r=xe(e);r.current=e,te(()=>{let o=!1,i=null;const l=async()=>{try{const d=await fetch("/api/editor-dev-server");if(o)return;const m=await d.json(),u=sv(r.current,m),{shouldAutoStart:p,...h}=u;if(t(h),p)try{const f=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})});if(o)return;f.ok?t(y=>({...y,isStarting:!0})):t(y=>({...y,canStartServer:!1}))}catch{}}catch{}};return l(),i=setInterval(()=>void l(),2e3),()=>{o=!0,i&&clearInterval(i)}},[e.url]);const s=se(()=>{t(o=>({...o,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})}).catch(()=>{})},[]),a=se(()=>{t(o=>({...o,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}).catch(()=>{})},[]);return{devServerUrl:e.url,proxyUrl:e.proxyUrl,isStarting:e.isStarting,error:e.error,canStartServer:e.canStartServer,retryServer:s,startServer:a}}function ov(e){return e.filter(t=>t.testFile&&t.returnType!=="JSX.Element"&&t.returnType!=="React.ReactNode").map(t=>({name:t.name,filePath:t.filePath,description:t.description||"",testFile:t.testFile,feature:t.feature}))}function ei(e,t){var r,s,a,o,i;return t?!!((r=e.metadata)!=null&&r.executionResult):!!((a=(s=e.metadata)==null?void 0:s.screenshotPaths)!=null&&a[0])&&!((o=e.metadata)!=null&&o.noScreenshotSaved)&&!((i=e.metadata)!=null&&i.sameAsDefault)}function iv(e,t){return e.filter(r=>r.analyses&&r.analyses.length>0).map(r=>{var p;const s=r.analyses[0],a=s.scenarios||[],o=!((p=s.status)!=null&&p.finishedAt),i=r.entityType||"visual",l=i==="library"||i==="functionCall",d=a.filter(h=>ei(h,l)),m=a.filter(h=>!ei(h,l)),u=t.find(h=>h.filePath===(r.filePath||""));return{sha:r.sha,name:r.name,entityType:i,filePath:r.filePath||"",analysisId:s.id,isAnalyzing:o,scenarioCount:a.length,scenarios:d.map(h=>{var f,y;return{id:h.id,name:h.name,description:h.description||"",screenshotPath:((y=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||null}}),pendingScenarios:m.map(h=>h.name),testFile:u==null?void 0:u.testFile}})}function lv(e,t){var s;const r={};for(const a of e){const i=(((s=a.metadata)==null?void 0:s.importedExports)||[]).map(l=>l.name).filter(l=>t.has(l));i.length>0&&(r[a.name]=i)}return r}const cv=()=>[{title:"Editor - CodeYam"},{name:"description",content:"CodeYam Code + Data Editor"}];async function dv({request:e}){var x;const t=await Te();let r=!1,s=[],a=[];if(t){const{project:v}=await Re(t);r=((x=v.metadata)==null?void 0:x.editorMode)??!1;try{const b=_e();for(const k of["component_name","component_path","screenshot_path","url"])try{await b.schema.alterTable("editor_scenarios").addColumn(k,"varchar").execute()}catch{}const N=await b.selectFrom("editor_scenarios").selectAll().where("project_id","=",v.id).orderBy("created_at","asc").execute(),C=k=>({id:k.id,name:k.name,description:k.description||"",componentName:k.component_name||null,componentPath:k.component_path||null,screenshotPath:k.screenshot_path||null,url:k.url||null});a=en(N,k=>`${k.name}::${k.url||"/"}`).map(C);const E=me()||process.cwd(),w=gg(E);if(w){const k=ca(w),S=N.filter(A=>A.created_at>=k);s=en(S,A=>`${A.name}::${A.url||"/"}`).map(C)}else s=a}catch{}}const o=[...new Set(a.map(v=>v.componentName).filter(v=>v!==null))];let i=[];try{const v=me()||process.cwd(),b=Y.join(v,".codeyam","glossary.json");if(K.existsSync(b)){const N=K.readFileSync(b,"utf8");i=JSON.parse(N)}}catch{}const l=ov(i);let d=[];try{const v=await nn()||[];d=iv(v,i)}catch{}let m=[];try{if(d.length>0){const v=d.map(b=>b.sha);await Be(),m=await Ze({shas:v})||[]}}catch{}let u={};try{if(m.length>0){const v=new Set([...d.map(b=>b.name),...o,...l.map(b=>b.name)]);u=lv(m,v)}}catch{}let p={};try{const v=me()||process.cwd();p=scanPageFilePaths(v)}catch{}let h={};try{h=(await fa({projectRoot:me()||process.cwd(),scenarioInputs:a,glossaryInputs:l})).entityChangeStatus}catch{}const f=me()||process.cwd(),y=Al(f),g=Pl(f);return Q({projectSlug:t,projectRoot:me(),hasProject:!!t,editorMode:r,scenarios:s,allScenarios:a,components:o,analyzedEntities:d,glossaryFunctions:l,entityImports:u,pageFilePaths:p,entityChangeStatus:h,featureName:y,userPrompt:g})}class uv extends kc{constructor(){super(...arguments);Cn(this,"state",{error:null,errorInfo:null})}static getDerivedStateFromError(r){return{error:r,errorInfo:null}}componentDidCatch(r,s){console.error("[EditorErrorBoundary] Error:",r.message),console.error("[EditorErrorBoundary] Component stack:",s.componentStack),console.error("[EditorErrorBoundary] Loader snapshot:",JSON.stringify(this.props.loaderSnapshot,null,2)),this.setState({errorInfo:s})}render(){var r;return this.state.error?n("div",{className:"fixed inset-0 bg-[#1e1e1e] flex items-center justify-center p-8",children:c("div",{className:"max-w-[600px] w-full space-y-4",children:[n("h2",{className:"text-lg font-semibold text-red-400 font-['IBM_Plex_Sans'] m-0",children:"Something went wrong"}),n("pre",{className:"text-xs text-gray-300 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[120px]",children:this.state.error.message}),((r=this.state.errorInfo)==null?void 0:r.componentStack)&&c("details",{className:"text-xs text-gray-500",children:[n("summary",{className:"cursor-pointer hover:text-gray-300 transition-colors",children:"Component stack"}),n("pre",{className:"mt-2 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[200px] text-yellow-300",children:this.state.errorInfo.componentStack})]}),n("p",{className:"text-xs text-gray-500 m-0",children:"Full diagnostics are in the browser console."}),n("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 bg-[#005c75] text-white text-sm rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Reload"})]})}):this.props.children}}const ti=[{name:"Desktop",width:1440,height:900},{name:"Laptop",width:1024,height:768},{name:"Tablet",width:768,height:1024},{name:"Mobile",width:375,height:667}],mv=We(function(){const{projectSlug:t,projectRoot:r,hasProject:s,scenarios:a,allScenarios:o,analyzedEntities:i,glossaryFunctions:l,entityImports:d,pageFilePaths:m,entityChangeStatus:u,featureName:p,userPrompt:h}=Ve(),f=mt(),[y,g]=mn(),x=xe(null),v=xe(null),b=xe(null),N=y.get("zoom")||void 0,C=y.get("scenario")||void 0;te(()=>{if(!C)return;const ie=a.find(je=>je.id===C);if(!ie)return;const we=vt(ie.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:we,scenarioId:ie.id,scenarioName:ie.name})}).catch(()=>{})},[C,a]),te(()=>{const ie=new BroadcastChannel("codeyam-editor");return ie.onmessage=we=>{var je;if(((je=we.data)==null?void 0:je.type)==="switch-scenario"&&we.data.scenarioId){const Oe=we.data.scenarioId,gt=a.find(vn=>vn.id===Oe);if(!gt)return;const bn=new URLSearchParams(y);bn.set("scenario",Oe),bn.delete("zoom"),g(bn),T(null),V(null),L(null);const Xr=vt(gt.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Xr,scenarioId:Oe})}).then(()=>{nt(vn=>vn+1),D(!1)}).catch(()=>{})}},()=>ie.close()},[y,g,a]),te(()=>{if(y.get("ref")!=="link"||!C)return;const ie=new BroadcastChannel("codeyam-editor");ie.postMessage({type:"switch-scenario",scenarioId:C}),ie.close(),window.close()},[]);const{devServerUrl:E,proxyUrl:w,isStarting:k,error:S,canStartServer:A,retryServer:$,startServer:_}=av(),[j,D]=M(!1),[R,T]=M(null),[U,V]=M(null),[I,O]=M(!1),[z,L]=M(null),P=se(ie=>{L(ie)},[]),q=se(async ie=>{const je=await(await fetch("/api/editor-load-commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commitSha:ie})})).json();return je.success&&(L(null),D(!1)),je},[]),H=se((ie,we)=>{V(je=>(ie&&ie!==je&&D(!1),ie)),!we&&ie&&D(!0),O(we)},[]),W=se(ie=>{L(null),T(je=>(je&&je.analysisId===ie.analysisId||(V(null),nt(gt=>gt+1)),ie)),O(!0),D(!1);const we=new URLSearchParams(y);we.delete("scenario"),we.delete("zoom"),g(we)},[y,g]),[Z,B]=M({name:"Desktop",width:1440,height:900}),[F,J]=M(!1),[G,X]=M("app"),le=se(()=>{X("build"),oe(!0)},[]),[ve,oe]=M(!1),[pe,Ce]=M(!1),$e=se(ie=>{Ce(ie)},[]),[Me,Ie]=M(!1),Fe=se(()=>{Ie(!0),X("build"),oe(!0)},[]),ke=se(()=>{Ie(!1)},[]),[re,he]=M(!1),Se=se(()=>{if(re){he(!1);return}typeof Notification<"u"&&Notification.permission==="default"?Notification.requestPermission().then(ie=>{ie==="granted"&&he(!0)}):he(!0)},[re]);te(()=>{if(G==="build"){Ce(!1);const ie=setTimeout(()=>{var we,je;(we=x.current)==null||we.scrollToBottom(),(je=x.current)==null||je.focus()},50);return()=>clearTimeout(ie)}},[G]);const[tt,ge]=M(null);te(()=>{const ie=b.current;if(!ie)return;const we=new ResizeObserver(je=>{const Oe=je[0];Oe&&ge({width:Oe.contentRect.width,height:Oe.contentRect.height})});return we.observe(ie),()=>we.disconnect()},[]);const Le=ne(()=>tt?xp(tt,Z):1,[tt,Z]),[Je,nt]=M(0),[Kr,Qr]=M(null),_a=se(ie=>{Qr(ie||null),L(null),nt(we=>we+1)},[]),{customSizes:zt,addCustomSize:Bt}=Yr(t);ne(()=>[...ti,...zt],[zt]),te(()=>{const ie=new EventSource("/api/events");let we=null;return ie.addEventListener("message",je=>{try{const Oe=JSON.parse(je.data);(Oe.type==="db-change"||Oe.type==="unknown")&&(we&&clearTimeout(we),we=setTimeout(()=>{f.revalidate()},2e3))}catch{}}),()=>{we&&clearTimeout(we),ie.close()}},[f]);const Un=ne(()=>{const ie=[{name:"App"}];return N&&ie.push({name:N,componentName:N}),ie},[N]),Yt=se(ie=>{const we=new URLSearchParams(y);if(ie){we.set("zoom",ie);const je=a.find(Oe=>Oe.componentName===ie||Oe.componentName===null&&ie==="Home");if(je){we.set("scenario",je.id);const Oe=vt(je.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Oe,scenarioId:je.id})}).catch(()=>{}),nt(gt=>gt+1),D(!1)}else we.delete("scenario")}else we.delete("zoom"),we.delete("scenario");g(we)},[y,g,a]),yn=se(ie=>{T(null),V(null),L(null);const we=new URLSearchParams(y);we.set("scenario",ie.id),g(we);const je=vt(ie.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:je,scenarioId:ie.id})}).catch(()=>{}),nt(Oe=>Oe+1),D(!1)},[y,g]),xn=ie=>{B({name:ie.name,width:ie.width,height:ie.height})},rt=ie=>{Bt(ie,Z.width,Z.height??900),J(!1),B(we=>({...we,name:ie}))},ft=()=>{R||D(!0)},Ye=ne(()=>yp({activeAnalyzedScenario:!!R,analyzedPreviewUrl:U,activeScenarioId:C||null,scenarios:a,proxyUrl:w,devServerUrl:E,zoomComponent:N||null}),[w,E,N,C,a,R,U]),He=ne(()=>Qi(Ye,Kr),[Ye,Kr]),Zr=ne(()=>({projectSlug:t,hasProject:s,scenarioCount:a==null?void 0:a.length,allScenarioCount:o==null?void 0:o.length,analyzedEntityCount:i==null?void 0:i.length,glossaryFunctionCount:l==null?void 0:l.length,entityChangeStatusKeys:u?Object.keys(u):[],featureName:p}),[t,s,a,o,i,l,u,p]);return n(uv,{loaderSnapshot:Zr,children:c("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[R&&n(rv,{analysisId:R.analysisId,scenarioId:R.scenarioId,scenarioName:R.scenarioName,entityName:R.entityName,projectSlug:t,onStateChange:H},R.analysisId),c("div",{className:"flex-1 flex min-h-0",children:[c("div",{className:"flex-1 flex flex-col min-w-0",children:[n("div",{className:"bg-[#2d2d2d] border-b border-[#3d3d3d] shrink-0 z-10 h-10 flex items-center px-4 gap-1",children:c("div",{className:"flex-1 flex items-center justify-center gap-1",children:[ti.map(ie=>c("button",{onClick:()=>xn(ie),className:`p-1.5 rounded transition-colors cursor-pointer ${Z.name===ie.name?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:`${ie.name} (${ie.width}×${ie.height})`,children:[ie.name==="Desktop"&&c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n("path",{d:"M8 21h8M12 17v4"})]}),ie.name==="Laptop"&&c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8H4V6z"}),n("path",{d:"M2 18h20"})]}),ie.name==="Tablet"&&c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]}),ie.name==="Mobile"&&c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"7",y:"2",width:"10",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]})]},ie.name)),n("button",{onClick:()=>J(!0),className:`p-1.5 rounded transition-colors cursor-pointer ${Z.name==="Custom"?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:"Custom dimensions",children:n("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),n("div",{className:"w-px h-4 bg-[#3d3d3d] mx-1"}),c("span",{className:"text-gray-400 text-xs font-mono",children:[Z.width," × ",Z.height??900]}),n("div",{className:"w-px h-4 bg-[#3d3d3d] mx-1"}),n("button",{onClick:()=>{const ie=He||Ye;ie&&window.open(ie,"_blank")},className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer",title:"Open preview in new window",children:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n("polyline",{points:"15 3 21 3 21 9"}),n("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})})]})}),n("div",{ref:b,className:"flex-1 flex items-center justify-center overflow-hidden p-8",style:{backgroundImage:`
|
|
336
|
-
linear-gradient(45deg, #333 25%, transparent 25%),
|
|
337
|
-
linear-gradient(-45deg, #333 25%, transparent 25%),
|
|
338
|
-
linear-gradient(45deg, transparent 75%, #333 75%),
|
|
339
|
-
linear-gradient(-45deg, transparent 75%, #333 75%)
|
|
340
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#2d2d2d"},children:z?n(tv,{preview:z,onDismiss:()=>L(null),onLoadCommit:q}):Ye?n("div",{style:{width:`${Z.width*Le}px`,height:`${(Z.height??900)*Le}px`},children:c("div",{className:"relative bg-white origin-top-left",style:{width:`${Z.width}px`,height:`${Z.height??900}px`,transform:Le<1?`scale(${Le})`:void 0},children:[!j&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-[#2a2a2a] rounded-lg p-8 w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(It,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),n("iframe",{ref:v,src:He||Ye,className:"w-full h-full border-none",title:"Editor preview",onLoad:ft,style:{opacity:j?1:0}},Je)]})}):n("div",{className:"bg-[#2a2a2a] rounded-lg flex flex-col items-center justify-center",style:{width:`${Z.width*Le}px`,height:`${(Z.height??900)*Le}px`},children:S?c("div",{className:"flex flex-col gap-4 text-center px-8 max-w-[600px]",children:[n("h2",{className:"text-xl font-medium text-red-400 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Dev Server Failed"}),n("pre",{className:"text-xs text-left bg-[#1e1e1e] text-gray-300 p-4 rounded overflow-auto max-h-[300px] w-full font-mono whitespace-pre-wrap",children:S}),n("button",{onClick:$,className:"mx-auto px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Retry"})]}):k||I?c(ue,{children:[n("div",{className:"mb-4",children:n(It,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:I?"Starting Interactive Mode":"Starting Dev Server"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:I?"Loading component preview...":"Your dev server is starting up..."})]})]}):c("div",{className:"flex flex-col gap-3 text-center px-8",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Live Preview"}),n("p",{className:"text-sm text-gray-500 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Describe what you want to build in the Build tab"})]})})})]}),c("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-r border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden order-first",children:[n(ev,{activeTab:G,onTabChange:ie=>{X(ie),ie==="build"&&oe(!0)},buildIdle:pe,zoomComponent:N,breadcrumbItems:Un,onBreadcrumbNavigate:Yt}),c("div",{className:"flex-1 overflow-hidden relative",children:[ve&&c("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:G==="build"?"visible":"hidden"},children:[n("div",{className:Me?"flex-1 min-h-0":"flex-1",style:Me?{flex:"1 1 50%"}:void 0,children:n(Ki,{ref:x,entityName:"Editor",projectSlug:t,entityFilePath:null,scenarioName:null,onRefreshPreview:_a,onShowResults:Fe,onHideResults:ke,editorMode:!0,onIdleChange:$e,notificationsEnabled:re})}),Me&&n("div",{style:{flex:"1 1 50%"},className:"min-h-0 border-t-2 border-gray-300",children:n(Qb,{scenarios:a,allScenarios:o,glossaryFunctions:l,projectRoot:r,activeScenarioId:C,onScenarioSelect:yn,onClose:ke,entityChangeStatus:u,featureName:p,userPrompt:h})})]}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:G==="app"?"visible":"hidden"},children:n(Gb,{hasProject:s,scenarios:o,analyzedEntities:i,glossaryFunctions:l,projectRoot:r,activeScenarioId:C,onScenarioSelect:yn,onAnalyzedScenarioSelect:W,onSwitchToBuild:le,zoomComponent:N,onZoomChange:Yt,entityImports:d,pageFilePaths:m})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:G==="data"?"visible":"hidden"},children:n(Yb,{scenarios:o,projectRoot:r,activeScenarioId:C,onScenarioSelect:yn,zoomComponent:N,onZoomChange:Yt,analyzedEntities:[],glossaryFunctions:l,activeAnalyzedScenarioId:R==null?void 0:R.scenarioId,onAnalyzedScenarioSelect:W,entityImports:d,pageFilePaths:m})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:G==="journal"?"visible":"hidden"},children:n(Vb,{isActive:G==="journal",onScreenshotClick:P,glossaryFunctions:l,pageNames:Object.keys(m)})})]}),n(qi,{serverUrl:E,isStarting:k,projectSlug:t,devServerError:S,onStartServer:A?_:void 0,notificationsEnabled:re,onToggleNotifications:Se})]})]}),F&&n(Br,{width:Z.width,height:Z.height??900,onSave:rt,onCancel:()=>J(!1)})]})})}),pv=Object.freeze(Object.defineProperty({__proto__:null,default:mv,loader:dv,meta:cv},Symbol.toStringTag,{value:"Module"}));function Xl({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(Ad,{remarkPlugins:[Pd],components:{h1:({children:s})=>n("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:s}),h2:({children:s})=>n("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:s}),h3:({children:s})=>n("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:s}),p:({children:s})=>n("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:s}),ul:({children:s})=>n("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),ol:({children:s})=>n("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),li:({children:s})=>n("li",{className:"leading-relaxed",children:s}),code:({children:s,className:a})=>(a==null?void 0:a.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:n("code",{children:s})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:s}),pre:({children:s})=>n(ue,{children:s}),strong:({children:s})=>n("strong",{className:"font-semibold text-gray-900",children:s}),blockquote:({children:s})=>n("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:s}),table:({children:s})=>n("div",{className:"overflow-x-auto mb-3",children:n("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:s})}),thead:({children:s})=>n("thead",{className:"bg-gray-50",children:s}),th:({children:s})=>n("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:s}),td:({children:s})=>n("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:s}),a:({children:s,href:a})=>n("a",{href:a,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:s})},children:r})}function ec(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const s=r.filePath.split("/");s.pop();let a=t,o="";for(const i of s)o=o?`${o}/${i}`:i,a.children.has(i)||a.children.set(i,{name:i,path:o,memories:[],children:new Map}),a=a.children.get(i);s.length===0?t.memories.push(r):a.memories.push(r)}return t}function tc(e){let t=e.memories.length;for(const r of e.children.values())t+=tc(r);return t}function qr(e,t){var s;const r=e.match(/^#+ (.+)$/m);return r?r[1]:((s=t.split("/").pop())==null?void 0:s.replace(".md",""))||t}function Tn(e){return Math.round(e/3.5)}function on(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const d=r.getTime()-t.getTime(),m=Math.floor(d/(1e3*60)),u=Math.floor(d/(1e3*60*60));return m<3?"Just now":m<60?`${m}min ago`:u===1?"1h ago":`${u}h ago`}const a=t.toLocaleDateString("en-US",{month:"short"}),o=t.getDate(),i=t.getFullYear(),l=r.getFullYear();return i===l?`${a} ${o}`:`${a} ${o}, ${i}`}function hv({rule:e,onEdit:t,onDelete:r,onView:s,isReviewed:a,onToggleReviewed:o,changeType:i,isUncommitted:l,changeDate:d,diff:m,isFadingOut:u,showLeftBorder:p}){const[h,f]=M(!1),[y,g]=M(!1),x=ne(()=>qr(e.body,e.filePath),[e.body,e.filePath]),v=Tn(e.body.length),b=h?"#3e3e3e":l?"#d97706":"#c7c7c7",N=`rounded-lg border overflow-hidden transition-all ease-in-out ${l?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,C={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return c("div",{className:N,style:C,children:[n("div",{className:`p-4 cursor-pointer ${l?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>s?s(e):f(!h),children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:h?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:b})})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:l?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),l&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),c("span",{className:"text-xs text-gray-400",children:["~",v.toLocaleString()," tokens"]})]}),n("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&c(ue,{children:[e.frontmatter.paths.slice(0,2).map((E,w)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:E},w)),e.frontmatter.paths.length>2&&c("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),c("div",{className:"flex items-center gap-3 flex-shrink-0",children:[d&&n("span",{className:"text-xs text-gray-400",children:on(d)}),o&&n("button",{onClick:E=>{E.stopPropagation(),o(e.filePath,e.lastModified,a??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${a?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:a?"Mark as unreviewed":"Mark as reviewed",children:a&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),h&&c("div",{className:`border-t ${l?"border-amber-200":"border-gray-100"}`,children:[c("div",{className:`px-4 py-3 flex items-center justify-between ${l?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&m&&c("button",{onClick:E=>{E.stopPropagation(),g(!y)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${y?l?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(ur,{className:"w-3 h-3"}),y?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&c("div",{className:"flex items-center gap-2",children:[c("button",{onClick:E=>{E.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(Qc,{className:"w-3 h-3"}),"Edit"]}),c("button",{onClick:E=>{E.stopPropagation(),r(e)},className:"flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer text-red-600 hover:text-red-800 hover:bg-red-100",children:[n(Zc,{className:"w-3 h-3"}),"Delete"]})]})]}),y&&m&&n("pre",{className:"mx-4 mb-4 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:m.split(`
|
|
341
|
-
`).map((E,w)=>{let k="";return E.startsWith("+")&&!E.startsWith("+++")?k="text-green-400":E.startsWith("-")&&!E.startsWith("---")?k="text-red-400":E.startsWith("@@")&&(k="text-cyan-400"),n("div",{className:k,children:E},w)})}),c("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),c("div",{className:"flex items-center gap-2",children:[c("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(At,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&c("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((E,w)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:E},w))})]}),!y&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(Xl,{content:e.body})})]})]})}function fv(){return new Date().toISOString().split(".")[0]+"",`---
|
|
342
|
-
paths:
|
|
343
|
-
- '**/*.ts'
|
|
344
|
-
---
|
|
345
|
-
|
|
346
|
-
## Title
|
|
347
|
-
|
|
348
|
-
Description here.
|
|
349
|
-
`}function gv({rule:e,onSave:t,onCancel:r}){const[s,a]=M(e?`.claude/rules/${e.filePath}`:""),[o,i]=M((e==null?void 0:e.content)||fv()),[l,d]=M(!!e),[m,u]=M(!1),p=!e;return c("div",{className:"p-6",children:[c("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(On,{className:"w-5 h-5"})})]}),p&&c("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:c("div",{className:"flex items-start gap-3",children:[n(ur,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),c("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),c("div",{className:"relative",children:[n("code",{className:"block bg-white px-3 py-2 pr-9 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam-new-rule"}),n("button",{onClick:()=>{navigator.clipboard.writeText("/codeyam-new-rule"),u(!0),setTimeout(()=>u(!1),2e3)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[#0284c7] hover:text-[#0c4a6e] cursor-pointer transition-colors",title:"Copy command",children:m?n(pt,{className:"w-4 h-4 text-green-500"}):n(wt,{className:"w-4 h-4"})})]})]})]})}),c("button",{onClick:()=>d(!l),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:l?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:l?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(l||!p)&&c("div",{className:"space-y-4",children:[c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),c("div",{className:"relative",children:[n("input",{type:"text",value:s,onChange:h=>a(h.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e}),n("button",{onClick:()=>{navigator.clipboard.writeText(s)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy path",children:n(wt,{className:"w-4 h-4"})})]})]}),e&&c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),c("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${s}\``,readOnly:!0,className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md bg-gray-50 font-mono text-sm text-gray-600"}),n("button",{onClick:()=>{navigator.clipboard.writeText(`Claude, can you help me edit the rule: \`${s}\``)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy prompt",children:n(wt,{className:"w-4 h-4"})})]})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:h=>i(h.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),c("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(s.replace(/^\.claude\/rules\//,""),o),disabled:!s.trim()||!o.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function yv({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:s,onToggleFolder:a}){const o=ne(()=>ec(e),[e]),i=(m,u,p)=>{if(m.target.closest(".chevron-toggle")){p&&a(u||"root");return}const f=u||null;r(t===f?null:f),p&&!s.has(u||"root")&&a(u||"root")},l=m=>{r(t===m?null:m)},d=(m,u=0)=>{const p=s.has(m.path||"root"),h=tc(m),f=m.children.size>0,y=m.name==="root"?"(root)":m.name,g=m.memories.length>0||f,x=m.path||"",v=t===x||t===null&&x==="";return c("div",{children:[c("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${v?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:b=>i(b,m.path,g),children:[g&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:b=>{b.stopPropagation(),a(m.path||"root")},children:n(Dt,{className:`w-3 h-3 text-gray-500 transition-transform ${p?"rotate-90":""}`})}),!g&&n("div",{className:"w-3"}),n(ui,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${v?"text-[#005C75]":""}`,style:{color:"#005C75"},children:y}),c("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[h," rules"]})]}),p&&c("div",{className:"relative",children:[(m.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),m.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:m.memories.map(b=>{var C;const N=t===b.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${N?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>l(b.filePath),children:n("span",{className:"text-xs",children:(C=b.filePath.split("/").pop())==null?void 0:C.replace(".md","")})},b.filePath)})}),f&&n("div",{children:Array.from(m.children.values()).sort((b,N)=>b.name.localeCompare(N.name)).map(b=>d(b,u+1))})]})]},m.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:d(o)})}function xv({memories:e,onEdit:t,onDelete:r,expandedFolders:s,onToggleFolder:a,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:l,onViewRule:d}){const[m,u]=M({});te(()=>{u({})},[o]);const p=ne(()=>({...o,...m}),[o,m]),h=ne(()=>ec(e),[e]),f=(g,x,v)=>{u(b=>({...b,[g]:!v})),v?l(g):i(g,x)},y=(g,x=0)=>{const v=s.has(g.path||"root"),b=g.children.size>0,N=g.name==="root"?"root":g.name,C=g.memories.length>0||b;return c("div",{children:[c("div",{className:"flex items-center gap-2 py-2 cursor-pointer hover:bg-gray-50 rounded px-2 mb-2",style:{backgroundColor:"rgba(224, 233, 236, 0.5)"},onClick:()=>C&&a(g.path||"root"),children:[C&&n(Dt,{className:`w-4 h-4 text-gray-500 transition-transform ${v?"rotate-90":""}`}),!C&&n("div",{className:"w-4"}),n(ui,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:N})]}),v&&c("div",{className:"ml-10 space-y-4 relative",children:[(g.memories.length>0||b)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),g.memories.length>0&&n("div",{className:"space-y-2",children:g.memories.map(E=>n(hv,{rule:E,onEdit:t,onDelete:r,onView:d,isReviewed:p[E.filePath]??!1,onToggleReviewed:f},E.filePath))}),b&&n("div",{className:"space-y-4",children:Array.from(g.children.values()).sort((E,w)=>E.name.localeCompare(w.name)).map(E=>y(E,x+1))})]})]},g.path||"root")};return n("div",{children:y(h)})}function bv({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:s}){const[a,o]=M("unreviewed"),[i,l]=M("by-date"),[d,m]=M(null),[u,p]=M(!0),[h,f]=M(new Map),y=xe(t),g=xe([]);te(()=>()=>{g.current.forEach(clearTimeout)},[]),te(()=>{(async()=>{p(!0);try{const w=await(await fetch("/api/memory?action=rule-coverage")).json();m(w.coverage??null)}catch{m(null)}finally{p(!1)}})()},[s]),te(()=>{const C=y.current,E=[];for(const[w,k]of Object.entries(t))k&&!C[w]&&E.push(w);y.current=t,E.length!==0&&(f(w=>{const k=new Map(w);return E.forEach(S=>k.set(S,"approved")),k}),g.current.push(setTimeout(()=>{f(w=>{const k=new Map(w);return E.forEach(S=>k.set(S,"fading")),k})},1500)),g.current.push(setTimeout(()=>{f(w=>{const k=new Map(w);return E.forEach(S=>k.delete(S)),k})},2500)))},[t]);const x=ne(()=>{const C=[...e];return i==="by-impact"&&d!==null?C.sort((E,w)=>{const k=d[E.filePath]??0,S=d[w.filePath]??0;return S!==k?S-k:new Date(w.lastModified).getTime()-new Date(E.lastModified).getTime()}):C.sort((E,w)=>new Date(w.lastModified).getTime()-new Date(E.lastModified).getTime()),C},[e,i,d]),v=ne(()=>x.filter(C=>!t[C.filePath]).length,[x,t]),b=ne(()=>a==="unreviewed"?x.filter(C=>!t[C.filePath]||h.has(C.filePath)):x,[x,a,t,h]),N=!u&&d!==null;return c("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[c("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),c("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),c("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",v,")"]})]}),c("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),c("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:["All (",x.length,")"]})]})]}),c("div",{className:"grid grid-cols-[1fr_90px_80px_100px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Rule"}),c("button",{onClick:()=>N&&l("by-impact"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none p-0 ${N?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(it,{className:"w-3 h-3"})]}),c("button",{onClick:()=>l("by-date"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none cursor-pointer p-0 hover:text-gray-600 ${i==="by-date"?"text-[#005C75]":"text-gray-400"}`,children:["Changed At",i==="by-date"&&n(it,{className:"w-3 h-3"})]}),c("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",c("span",{className:"relative group",children:[n(ks,{className:"w-3 h-3 text-gray-300 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Showing which rules have been reviewed and approved. Click a rule to view it and approve it"})]})]})]}),n("div",{className:"flex-1 overflow-y-auto max-h-[400px]",children:b.map(C=>{const E=t[C.filePath]??!1,w=h.get(C.filePath),k=qr(C.body,C.filePath),S=(d==null?void 0:d[C.filePath])??0;return n("div",{className:`border-b border-gray-50 transition-all ${w==="fading"?"duration-1000":"duration-300"}`,style:{opacity:w==="fading"?0:1},children:c("div",{className:`grid grid-cols-[1fr_90px_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${w==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(C),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:k})}),n("span",{className:"text-xs text-center",children:u?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):d!==null?n("span",{className:S>0?"text-gray-700 font-medium":"text-gray-300",children:S}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:on(C.lastModified)}),n("div",{className:"flex justify-center",children:n("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors duration-300 ${E?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:E&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})},C.filePath)})}),b.length===0&&a==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"})]})}function vv(e,t){const r=t.map(s=>`- \`${s}\``).join(`
|
|
350
|
-
`);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
|
|
351
|
-
|
|
352
|
-
${r}
|
|
353
|
-
|
|
354
|
-
Please review these rules in conjunction with one another as they all apply to this file.
|
|
355
|
-
|
|
356
|
-
Review each rule with the other rules in mind:
|
|
357
|
-
- Necessary: Is this rule really necessary to avoid confusion in future work sessions?
|
|
358
|
-
- Efficiency: Are the rules concise and well-structured?
|
|
359
|
-
- Effectiveness: Does the rules provide clear, actionable guidance?
|
|
360
|
-
- Context window impact: Can the rules be shortened without losing important information?
|
|
361
|
-
- Overlap: Is there any redundant information across the rules that can be consolidated?
|
|
362
|
-
- Duplication: Are there any rules that are nearly identical that can be merged or removed?
|
|
363
|
-
|
|
364
|
-
Remember that documenting past confusion isn't helpul unless that confusion will likely happen again.
|
|
365
|
-
|
|
366
|
-
Note: Each rule may apply to multiple files, not just the file listed above. Consider this when suggesting changes — modifications should not negatively impact the rule's usefulness for other files it covers.`}function wv({filePath:e,rulePaths:t,onClose:r}){const[s,a]=M(!1),o=vv(e,t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:c("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:l=>l.stopPropagation(),children:[n("button",{onClick:r,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(On,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-1",children:"Audit Rules For File"}),n("p",{className:"font-mono text-sm text-gray-500 mb-4 truncate",title:e,children:e}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can audit these rules to try and make them as efficient and effective as possible, reducing the impact on the context window."}),n("textarea",{readOnly:!0,value:o,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-4",children:n("button",{onClick:()=>{navigator.clipboard.writeText(o),a(!0),setTimeout(()=>a(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:s?c(ue,{children:[n(pt,{className:"w-4 h-4"}),"Copied!"]}):c(ue,{children:[n(wt,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function Nv({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:s}){const[a,o]=M("unreviewed"),[i,l]=M(null),[d,m]=M(""),[u,p]=M(0),[h,f]=M(!1),[y,g]=M(null),[x,v]=M(null),b=xe(null),N=xe(null),[C,E]=M({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[w,k]=M(!0);te(()=>{(async()=>{k(!0);try{const V=await(await fetch("/api/memory?action=audit")).json();E({topPaths:V.topPaths||[],totalFilesWithCoverage:V.totalFilesWithCoverage||0,allSourceFiles:V.allSourceFiles||[]})}catch(U){console.error("Failed to load audit data:",U)}finally{k(!1)}})()},[e]);const S=ne(()=>a==="all"?C.topPaths:C.topPaths.filter(T=>T.matchingRules.some(U=>!t[U.filePath])),[C.topPaths,a,t]);ne(()=>C.topPaths.filter(T=>T.matchingRules.some(U=>!t[U.filePath])).length,[C.topPaths,t]);const A=T=>T.split("/").pop()||T,$=ne(()=>{const T=new Map;for(const U of C.topPaths)T.set(U.filePath,U);return T},[C.topPaths]),_=ne(()=>{if(!d.trim())return[];const T=d.toLowerCase(),U=[],V=[];for(const I of C.allSourceFiles){const O=I.toLowerCase();if(!O.includes(T))continue;const z=$.get(I)||{filePath:I,matchingRules:[],totalTextLength:0};O.startsWith(T)?U.push(z):V.push(z)}return U.sort((I,O)=>I.filePath.localeCompare(O.filePath)),V.sort((I,O)=>I.filePath.localeCompare(O.filePath)),[...U,...V].slice(0,8)},[d,C.allSourceFiles,$]),j=se(T=>{var U;g(T),l(T.filePath),m(T.filePath),f(!1),(U=b.current)==null||U.blur()},[]),D=se(()=>{var T;m(""),g(null),l(null),(T=b.current)==null||T.focus()},[]),R=se(T=>{var U;!h||_.length===0||(T.key==="ArrowDown"?(T.preventDefault(),p(V=>Math.min(V+1,_.length-1))):T.key==="ArrowUp"?(T.preventDefault(),p(V=>Math.max(V-1,0))):T.key==="Enter"?(T.preventDefault(),j(_[u])):T.key==="Escape"&&(f(!1),(U=b.current)==null||U.blur()))},[h,_,u,j]);return te(()=>{p(0)},[_]),c("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[c("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),c("div",{className:"relative flex-1 max-w-[300px]",children:[n(Ln,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:b,type:"text",value:d,onChange:T=>{m(T.target.value),f(!0)},onFocus:()=>{d.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:R,placeholder:"Search files...",className:`w-full pl-8 ${d?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),d&&n("button",{type:"button",onMouseDown:T=>{T.preventDefault(),D()},className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer",children:n("svg",{viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-3 h-3",children:n("path",{d:"M1 1l12 12M13 1L1 13"})})}),h&&_.length>0&&n("div",{ref:N,className:"absolute left-0 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-75 overflow-y-auto min-w-75 max-w-120",children:_.map((T,U)=>c("div",{onMouseDown:V=>{V.preventDefault(),j(T)},onMouseEnter:()=>p(U),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${U===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(mr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:T.filePath,children:(()=>{const V=T.filePath.toLowerCase().indexOf(d.toLowerCase());if(V===-1)return T.filePath;const I=T.filePath.slice(0,V),O=T.filePath.slice(V,V+d.length),z=T.filePath.slice(V+d.length);return c(ue,{children:[I,n("span",{className:"font-semibold text-[#005C75]",children:O}),z]})})()}),c("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[T.matchingRules.length," rule",T.matchingRules.length!==1?"s":""]})]},T.filePath))})]}),n("div",{className:"flex-1"}),c("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),c("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:"All"})]})]}),c("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),c("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",c("span",{className:"relative group",children:[n(ks,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),c("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",c("span",{className:"relative group",children:[n(ks,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Estimated tokens from unreviewed rules / Total number of tokens from all rules that apply to this file"})]})]})]}),w&&n("div",{className:"px-5 py-6",children:c("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!w&&(S.length>0||y)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(y?[y,...S.filter(U=>U.filePath!==y.filePath)].slice(0,8):S.slice(0,8)).map((T,U)=>{const V=T.matchingRules.length,I=T.matchingRules.filter(H=>!t[H.filePath]),O=I.length,z=I.reduce((H,W)=>H+W.bodyLength,0),L=O>0,P=i===T.filePath,q=(y==null?void 0:y.filePath)===T.filePath;return c("div",{children:[c("div",{onClick:()=>l(P?null:T.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${q?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[c("div",{className:"flex items-center gap-2 min-w-0",children:[P?n(it,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(Dt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(mr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:T.filePath,children:q?T.filePath:A(T.filePath)})]}),c("span",{className:"text-sm text-center",children:[n("span",{className:L?"font-semibold text-[#1A5276]":"text-gray-400",children:O}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:V})]}),c("span",{className:"text-sm text-center",children:[n("span",{className:L?"font-semibold text-[#1A5276]":"text-gray-400",children:Tn(z).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:Tn(T.totalTextLength).toLocaleString()})]})]}),P&&c("div",{className:"bg-gray-50 border-b border-gray-100",children:[T.matchingRules.map(H=>{const W=r.find(B=>B.filePath===H.filePath),Z=t[H.filePath]??!1;return c("div",{onClick:B=>{B.stopPropagation(),W&&s(W)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(dr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-700 truncate flex-1",children:W?qr(W.body,W.filePath):H.filePath}),c("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[Tn(H.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${Z?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:Z&&n("svg",{width:"8",height:"6",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]},H.filePath)}),c("div",{className:"flex items-center justify-center gap-3 px-5 py-2 border-t border-gray-200",children:[n("span",{className:"text-xs text-gray-400",children:"Have Claude audit these rules"}),n("button",{onClick:H=>{H.stopPropagation(),v({filePath:T.filePath,rulePaths:T.matchingRules.map(W=>W.filePath)})},className:"px-3 py-1 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer",children:"Prompt"})]})]})]},T.filePath)})}),!w&&S.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:a==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"}),x&&n(wv,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>v(null)})]})}function Cv({rule:e,changeInfo:t,isReviewed:r,onApprove:s,onEdit:a,onDelete:o,onClose:i}){const l=qr(e.body,e.filePath),d=Tn(e.body.length),m=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[p,h]=M(null),f=(t==null?void 0:t.changeType)==="added"||p!=null&&p.commitCount!=null&&p.commitCount<=1&&!(p.commitCount===1&&p.isUncommitted);return te(()=>{h(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(y=>y.json()).then(y=>{y.diff&&h(y.diff)}).catch(()=>{})},[e.filePath]),te(()=>{const y=g=>{g.key==="Escape"&&i()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]),n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:i,children:c("div",{className:"rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",style:{backgroundColor:"#F8F7F6"},onClick:y=>y.stopPropagation(),children:[n("div",{className:"px-6 pt-5 pb-4",children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"min-w-0 flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:l}),t&&c(ue,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:on(t.date)}),n("span",{className:`flex-shrink-0 text-[11px] uppercase font-semibold tracking-wider ${t.changeType==="added"?"text-green-600":t.changeType==="modified"?"text-orange-600":"text-red-600"}`,children:t.changeType})]})]}),m&&c("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:m})]}),c("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:u}),n(At,{content:u,icon:!0,iconSize:12,className:"p-0.5 rounded text-gray-400 hover:text-gray-600 transition-colors",ariaLabel:"Copy file path"})]}),c("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",d.toLocaleString()]})]}),c("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[c("button",{onClick:s,className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer transition-colors ${r?"bg-green-600 text-white":"border border-green-600 text-green-700 hover:bg-green-50"}`,children:[n(pt,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:a,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors",children:"Edit"}),n("button",{onClick:o,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-red-300 text-red-600 hover:bg-red-50 transition-colors",children:"Delete"}),n("button",{onClick:i,className:"p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-200 cursor-pointer transition-colors ml-1",children:n(On,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&c("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((y,g)=>{const x=y.split("/"),v=x.pop()||y,b=x.length>0?x.join("/")+"/":"";return c("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(mr,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),c("span",{children:[b&&n("span",{className:"text-gray-500",children:b}),n("span",{className:"font-bold text-gray-900",children:v})]})]},g)})})]}),f?n("div",{className:"px-6 pb-4",children:c("div",{className:"text-[13px] text-gray-500",children:["Created"," ",t!=null&&t.date?on(t.date):p!=null&&p.date?on(p.date):"recently"]})}):p&&n("div",{className:"px-6 pb-4",children:c("details",{children:[c("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",p.commitMessage," —"," ",on(p.date)]}),n("pre",{className:"mt-2 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:p.diff.split(`
|
|
367
|
-
`).map((y,g)=>{let x="";return y.startsWith("+")&&!y.startsWith("+++")?x="text-green-400":y.startsWith("-")&&!y.startsWith("---")?x="text-red-400":y.startsWith("@@")&&(x="text-cyan-400"),n("div",{className:x,children:y},g)})})]})}),c("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n(Xl,{content:e.body})})]})]})})}function Sv(){return c("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function kv(){return c("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function Ev(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[c("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),c("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),c("ol",{className:"space-y-5",children:[c("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),c("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),c("div",{children:[c("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(ni,{value:"/codeyam-memory"}),n("span",{className:"text-[14px] font-medium text-gray-900",children:"in the Claude Code session"})]}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"This kicks off analysis of your git history to find confusion patterns."})]})]}),c("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),c("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Return to this dashboard page to review the new rules"}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"You can review, edit, and approve the rules Claude creates."})]})]})]})]}),c("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),c("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),c("div",{className:"space-y-6",children:[c("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),c("div",{children:[c("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),c("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),c("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),c("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),c("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),c("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(ni,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function ni({value:e}){const[t,r]=M(!1);return c("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n(pt,{className:"w-3.5 h-3.5 text-green-400"}):c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function rr({label:e,count:t,icon:r,bgColor:s,iconBgColor:a,textColor:o}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:s,border:"1px solid #EFEFEF"},children:c("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:a},children:r}),c("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o},children:e})]})]})})}function Av({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:s,reviewCounts:a}){return c("div",{className:"mb-8",children:[c("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[c("div",{children:[c("div",{className:"flex items-center gap-3 mb-2",children:[n(Sv,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),c("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:s,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),c("div",{className:"flex items-center gap-3",children:[c("div",{className:"relative",children:[n(Ln,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),c("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Vs,{className:"w-4 h-4"}),"New Rule"]})]})]}),c("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(rr,{label:"Total Rules",count:a.total,icon:n(kv,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(rr,{label:"Unreviewed",count:a.unreviewed,icon:n(Xc,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(rr,{label:"Reviewed",count:a.reviewed,icon:n(pt,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(rr,{label:"Stale",count:a.stale,icon:n(di,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function Pv({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:c("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(On,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),c("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[c("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:c("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Vs,{className:"w-4 h-4"}),"New Rule"]})})]})})}function Mv({rule:e,onConfirm:t,onCancel:r}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:c("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[n("h3",{className:"text-lg font-semibold mb-2",children:"Delete Memory?"}),c("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),c("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const ri="Can you help me perform an interactive rules audit? Please look at all of the rules in `.claude/rules`. Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts `folder1/folder2/file1` and `folder1/folder2/folder3/file2` then the rule should be in `.claude/rules/folder1/folder2`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rule is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. Too often rules reflect past confusion that has been resolved and is unlikely to happen again. Content and rules like this should be removed. If you have any questions please ask!",si="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function ai({text:e}){const[t,r]=M(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?c(ue,{children:[n(pt,{className:"w-4 h-4"}),"Copied!"]}):c(ue,{children:[n(wt,{className:"w-4 h-4"}),"Copy Prompt"]})})}function _v({onClose:e}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:c("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:t=>t.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(On,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit All Rules"}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can review all rules to look for information that is inconsistent, inappropriate, duplicative, inefficient, etc."}),n("textarea",{readOnly:!0,value:ri,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(ai,{text:ri})}),c("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:si,className:"w-full h-16 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(ai,{text:si})})]})]})})}function jv(){const[e,t]=M(!1);return c(ue,{children:[c("div",{className:"border border-gray-200 rounded-lg px-5 py-4 mb-8 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit All Rules"}),n("p",{className:"text-sm text-gray-500",children:"Ask Claude to review, audit, and improve all rules."}),n("button",{onClick:()=>t(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),e&&n(_v,{onClose:()=>t(!1)})]})}const Tv=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function $v({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?Q({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?Q({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):Q({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),Q({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const Rv=We(function(){const{memories:t,reviewedStatus:r,memoryInitialized:s,error:a}=Ve(),o=De(),i=mt(),[l,d]=M(""),[m,u]=M(null),[p,h]=M(new Set(["root"])),[f,y]=M(null),[g,x]=M(!1),[v,b]=M(null),[N,C]=M(0),[E,w]=M(!1),[k,S]=M(null),[A,$]=M(null),[_,j]=M({}),D=B=>{h(F=>{const J=new Set(F);return J.has(B)?J.delete(B):J.add(B),J})};ht({source:"memory-page"});const R=ne(()=>({...r,..._}),[r,_]),T=xe(o.state);te(()=>{const B=T.current==="loading"||T.current==="submitting",F=o.state==="idle";B&&F&&o.data&&(i.revalidate(),y(null),x(!1),C(J=>J+1)),T.current=o.state},[o.state,o.data,i]),te(()=>{j(B=>{const F={};for(const[J,G]of Object.entries(B))r[J]!==G&&(F[J]=G);return Object.keys(F).length===Object.keys(B).length?B:F})},[r]);const U=(B,F)=>{j(J=>({...J,[B]:!0})),o.submit({action:"mark-reviewed",filePath:B,lastModified:F},{method:"POST",action:"/api/memory",encType:"application/json"})},V=B=>{j(F=>({...F,[B]:!1})),o.submit({action:"mark-unreviewed",filePath:B},{method:"POST",action:"/api/memory",encType:"application/json"})},I=(B,F)=>{S(B),$(F??null)},O=ne(()=>{let B=t;if(l.trim()){const F=l.toLowerCase();B=B.filter(J=>{var X;return(((X=J.filePath.split("/").pop())==null?void 0:X.replace(".md",""))||"").toLowerCase().includes(F)||J.body.toLowerCase().includes(F)})}return B},[t,l]),z=ne(()=>m?O.some(F=>F.filePath===m)?O.filter(F=>F.filePath===m):O.filter(F=>F.filePath.startsWith(m+"/")||F.filePath===m):O,[O,m]),L=(B,F)=>{const J=f?"update":"create";o.submit({action:J,filePath:B,content:F},{method:"POST",action:"/api/memory",encType:"application/json"})},P=B=>{o.submit({action:"delete",filePath:B.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),b(null)},q=ne(()=>{const B=t.filter(F=>R[F.filePath]).length;return{total:t.length,reviewed:B,unreviewed:t.length-B,stale:0}},[t,R]),H=ne(()=>{const B=new Set(["root"]);for(const F of O){const J=F.filePath.split("/");J.pop();let G="";for(const X of J)G=G?`${G}/${X}`:X,B.add(G)}return B},[O]),W=H.size===p.size&&[...H].every(B=>p.has(B)),Z=()=>{h(W?new Set(["root"]):new Set(H))};return a?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:a})]})}):s?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(Av,{searchFilter:l,onSearchChange:d,onCreateNew:()=>x(!0),onLearnMore:()=>w(!0),reviewCounts:q}),(g||f)&&n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>{x(!1),y(null)},children:n("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:B=>B.stopPropagation(),children:n(gv,{rule:f,onSave:L,onCancel:()=>{x(!1),y(null)}})})}),c("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(bv,{memories:O,reviewedStatus:R,onViewRule:I,refreshKey:N}),n(Nv,{onEditRule:y,onDeleteRule:b,refreshKey:N,reviewedStatus:R,onMarkReviewed:U,onMarkUnreviewed:V,memories:t,onViewRule:I})]}),n(jv,{}),c("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:H.size>1&&n("button",{onClick:Z,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:W?"Collapse All":"Expand All"})})]}),c("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(yv,{memories:O,selectedPath:m,onSelectPath:u,expandedFolders:p,onToggleFolder:D})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?c("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(ed,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),c("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),c("button",{onClick:()=>x(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(Vs,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):c("div",{children:[m&&c("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:m||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(xv,{memories:z,onEdit:y,onDelete:b,expandedFolders:p,onToggleFolder:D,reviewedStatus:R,onMarkReviewed:U,onMarkUnreviewed:V,onViewRule:I})]})})]}),n("div",{className:"mt-8 mb-8",children:n(de,{to:"/agent-transcripts",className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#005C75] hover:shadow-sm transition-all group",children:c("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),c("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),k&&!f&&(()=>{const B=t.find(F=>F.filePath===k.filePath)??k;return n(Cv,{rule:B,changeInfo:A??void 0,isReviewed:R[B.filePath]??!1,onApprove:()=>{R[B.filePath]??!1?V(B.filePath):U(B.filePath,B.lastModified),S(null)},onEdit:()=>{y(B)},onDelete:()=>{b(B),S(null)},onClose:()=>S(null)})})(),E&&n(Pv,{onClose:()=>w(!1),onCreateNew:()=>{w(!1),x(!0)}}),v&&n(Mv,{rule:v,onConfirm:P,onCancel:()=>b(null)})]})}):n(Ev,{})}),Iv=Object.freeze(Object.defineProperty({__proto__:null,default:Rv,loader:$v,meta:Tv},Symbol.toStringTag,{value:"Module"}));function Ss(e){return`${e.filePath||""}::${e.name}`}function nc(e,t){const r=De(),{showToast:s}=ta(),[a,o]=M(new Map);te(()=>{if(r.state==="idle"&&r.data){const h=r.data;h!=null&&h.error&&s(`Error: ${h.error}`,"error",6e3)}},[r.state,r.data,s]),te(()=>{var f;if(a.size===0)return;const h=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(x=>{a.forEach((v,b)=>{v===x&&h.add(b)})})}),e==null||e.forEach(y=>{a.forEach((g,x)=>{g===y&&h.add(x)})}),h.size>0&&o(y=>{const g=new Map(y);return h.forEach(x=>g.delete(x)),g})},[t,e,a]);const i=se(h=>{console.log("Generate analysis clicked for entity:",h.sha,h.name);const f=Ss(h);o(g=>new Map(g).set(f,h.sha));const y=new FormData;y.append("entitySha",h.sha),y.append("filePath",h.filePath||""),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),l=se(h=>{const f=h.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const v=new Map(x);return f.forEach(b=>v.set(Ss(b),b.sha)),v});const y=f.map(x=>x.sha).join(","),g=new FormData;g.append("entityShas",y),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),d=se(h=>(e==null?void 0:e.includes(h))??!1,[e]),m=se(h=>{const f=Ss(h);return a.has(f)},[a]),u=se(h=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(y=>{var g;return(g=y.entityShas)==null?void 0:g.includes(h)}))??!1},[t]),p=ne(()=>Array.from(a.keys()),[a]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:d,isEntityPending:m,isEntityInQueue:u,pendingEntityKeys:p}}function Ea({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:s,analyzeAllDisabled:a=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:c("div",{className:"flex justify-between items-center px-3 py-2",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"STATE"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),c("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),c("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:s&&n("button",{onClick:s,disabled:a,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:a?o:"Analyze all entities",children:o})})]})]})]})})}function Dv({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},s={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const o=s[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:o.textColor},children:o.label})})}const a=r[e]||{label:"?",bgColor:"bg-gray-500"};return c("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${a.bgColor}`,title:e,children:a.label}),a.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function Aa({filePath:e,isExpanded:t,onToggle:r,fileStatus:s,simulationPreviews:a,entityCount:o,state:i,lastModified:l,actionButton:d,uncommittedCount:m,children:u,isNotAnalyzable:p=!1,isUncommitted:h=!1}){return c("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[c("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${p?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(bi,{filePath:e}),s&&n(Dv,{status:typeof s=="string"?s:s.status,variant:"full"}),h&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(h||i==="out-of-date")&&c("div",{className:"flex gap-1.5 items-center",children:[h&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!h&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:a}),c("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:c("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:Yl(l)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function Pa({entities:e,maxPreviews:t=3}){var s,a,o,i,l;const r=[];for(const d of e){if(r.length>=t)break;const m=((a=(s=d.analyses)==null?void 0:s[0])==null?void 0:a.scenarios)||[];if(d.entityType==="library"){const u=m.find(p=>{var h,f;return((h=p.metadata)==null?void 0:h.executionResult)||((f=p.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=m.find(p=>{var h,f;return(f=(h=p.metadata)==null?void 0:h.screenshotPaths)==null?void 0:f[0]});if(u){const p=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],h=!!((l=u.metadata)!=null&&l.error);p&&r.push({type:"screenshot",screenshot:p,hasError:h,scenario:u,entitySha:d.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(ue,{children:r.map((d,m)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return c(de,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:p=>p.stopPropagation(),children:[n(Ge,{screenshotPath:d.screenshot,alt:`Preview ${m+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(cr,{size:12,color:"white"})})]},`screenshot-${m}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(zl,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${m}`):null})})}function Ma({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:s}){var u,p;const a=t||r?[{entityShas:[e.sha]}]:[],o=at(e,a,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,m=(((p=(u=e.analyses)==null?void 0:u[0])==null?void 0:p.scenarios)||[]).filter(h=>{var f,y;return(y=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return c("div",{className:"bg-white rounded-lg",children:[c(de,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(Xe,{type:"type"})})}):n(Xe,{type:e.entityType||"other"}),n("span",{className:`font-['IBM_Plex_Sans'] text-[14px] leading-[18px] text-black ${i?"font-medium":"font-normal"}`,children:e.name}),n(ya,{type:e.entityType||"other"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),c("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="analyzing"?c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:h=>{h.preventDefault(),h.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):l&&n("button",{onClick:h=>{h.preventDefault(),h.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),m.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:m.map((h,f)=>{var g,x;const y=(x=(g=h.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return y?n(de,{to:`/entity/${e.sha}?scenario=${h.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:v=>v.stopPropagation(),children:n(Ge,{screenshotPath:y,alt:h.name,className:"max-w-full max-h-full object-contain object-center"})},h.id):null})})]})}function Lv({entities:e,page:t,itemsPerPage:r=50,currentRun:s,filter:a,entityType:o,queueState:i,isEntityPending:l,pendingEntityKeys:d,onGenerateSimulation:m,onGenerateAllSimulations:u,totalFilesCount:p,totalEntitiesCount:h,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[x,v]=mn(),[b,N]=M(new Set),[C,E]=M(""),[w,k]=M(!1),[S,A]=M("all"),[$,_]=M("desc"),j=o||"all",D=ne(()=>{let P=e;return j!=="all"&&(P=P.filter(q=>q.entityType===j)),a==="analyzed"&&(P=P.filter(q=>q.analyses&&q.analyses.length>0)),P},[e,j,a]),R=ne(()=>{const P=new Map,q=new Map,H=new Map;D.forEach(F=>{var X,le;const J=`${F.filePath}::${F.name}`,G=q.get(J);if(!G)q.set(J,F),H.set(J,[]);else{const ve=((X=G.metadata)==null?void 0:X.editedAt)||G.createdAt||"",oe=((le=F.metadata)==null?void 0:le.editedAt)||F.createdAt||"";let pe=!1;if(oe>ve)pe=!0;else if(oe===ve){const Ce=G.createdAt||"";pe=(F.createdAt||"")>Ce}pe?(H.get(J).push(G),q.set(J,F)):H.get(J).push(F)}}),q.forEach((F,J)=>{var X;if(!(F.analyses&&F.analyses.length>0)&&((X=F.metadata)!=null&&X.previousVersionWithAnalyses)){const ve=(H.get(J)||[]).find(oe=>{var pe;return oe.sha===((pe=F.metadata)==null?void 0:pe.previousVersionWithAnalyses)});ve&&ve.analyses&&ve.analyses.length>0&&(F.analyses=ve.analyses)}}),Array.from(q.values()).sort((F,J)=>{var le,ve,oe,pe;const G=!((le=F.metadata)!=null&&le.notExported)&&!((ve=F.metadata)!=null&&ve.namedExport),X=!((oe=J.metadata)!=null&&oe.notExported)&&!((pe=J.metadata)!=null&&pe.namedExport);return G&&!X?-1:!G&&X?1:0}).forEach(F=>{var ve,oe,pe,Ce,$e;const J=F.filePath??"No File Path";P.has(J)||P.set(J,{filePath:J,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const G=P.get(J);G.entities.push(F),G.totalCount++,(ve=F.metadata)!=null&&ve.isUncommitted&&G.uncommittedCount++;const X=((Ce=(pe=(oe=F.analyses)==null?void 0:oe[0])==null?void 0:pe.scenarios)==null?void 0:Ce.length)||0;G.simulationCount+=X;const le=(($e=F.metadata)==null?void 0:$e.editedAt)||F.updatedAt;le&&(!G.lastUpdated||new Date(le)>new Date(G.lastUpdated))&&(G.lastUpdated=le)});const W=(i==null?void 0:i.jobs)||[],Z=F=>{const J=`${F.filePath||""}::${F.name}`;return(d==null?void 0:d.includes(J))||!1};P.forEach(F=>{const J=F.entities.map(G=>Z(G)?"queued":at(G,W));J.includes("analyzing")||J.includes("queued")?F.state="analyzing":J.includes("incomplete")?F.state="incomplete":J.includes("out-of-date")?F.state="out-of-date":J.includes("not-analyzed")?F.state="not-analyzed":F.state="up-to-date"}),P.forEach(F=>{var J,G,X,le,ve;for(const oe of F.entities){if(F.previewScreenshots.length+F.previewLibraryScenarios.length>=3)break;const Ce=((G=(J=oe.analyses)==null?void 0:J[0])==null?void 0:G.scenarios)||[];if(oe.entityType==="library"){const $e=Ce.find(Me=>{var Ie,Fe;return((Ie=Me.metadata)==null?void 0:Ie.executionResult)||((Fe=Me.metadata)==null?void 0:Fe.error)});$e&&F.previewLibraryScenarios.push({scenario:$e,entitySha:oe.sha})}else{const $e=Ce.find(Me=>{var Ie,Fe;return(Fe=(Ie=Me.metadata)==null?void 0:Ie.screenshotPaths)==null?void 0:Fe[0]});if($e){const Me=(le=(X=$e.metadata)==null?void 0:X.screenshotPaths)==null?void 0:le[0],Ie=!!((ve=$e.metadata)!=null&&ve.error);Me&&!F.previewScreenshots.includes(Me)&&(F.previewScreenshots.push(Me),F.previewScreenshotErrors.push(Ie))}}}});const B=Array.from(P.values());return B.sort((F,J)=>{if(a==="analyzed"){const le=Math.max(...F.entities.filter(oe=>{var pe,Ce;return(Ce=(pe=oe.analyses)==null?void 0:pe[0])==null?void 0:Ce.createdAt}).map(oe=>new Date(oe.analyses[0].createdAt).getTime()),0),ve=Math.max(...J.entities.filter(oe=>{var pe,Ce;return(Ce=(pe=oe.analyses)==null?void 0:pe[0])==null?void 0:Ce.createdAt}).map(oe=>new Date(oe.analyses[0].createdAt).getTime()),0);return $==="desc"?ve-le:le-ve}if(F.uncommittedCount>0&&J.uncommittedCount===0)return-1;if(F.uncommittedCount===0&&J.uncommittedCount>0)return 1;const G=F.lastUpdated?new Date(F.lastUpdated).getTime():0,X=J.lastUpdated?new Date(J.lastUpdated).getTime():0;return $==="desc"?X-G:G-X}),B},[D,a,$,i,d]),T=ne(()=>{let P=R;if(S!=="all"&&(P=P.filter(q=>q.state===S)),C.trim()){const q=C.toLowerCase();P=P.filter(H=>H.filePath.toLowerCase().includes(q))}return P},[R,C,S]),U=(t-1)*r,V=U+r,I=T.slice(U,V),O=Math.ceil(T.length/r),z=P=>{N(q=>{const H=new Set(q);return H.has(P)?H.delete(P):H.add(P),H})},L=()=>{_(P=>P==="desc"?"asc":"desc")};return c("div",{children:[c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative w-[130px]",children:[c("select",{value:j,onChange:P=>{const q=P.target.value,H=new URLSearchParams(x);q==="all"?H.delete("entityType"):H.set("entityType",q),H.set("page","1"),v(H)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(it,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"relative w-[130px]",children:[c("select",{value:S,onChange:P=>A(P.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All States"}),n("option",{value:"analyzing",children:"Analyzing..."}),n("option",{value:"up-to-date",children:"Up to date"}),n("option",{value:"incomplete",children:"Incomplete"}),n("option",{value:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(it,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(Ln,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",value:C,onChange:P=>E(P.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),p!==void 0&&h!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center",children:[c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:T.length})," ",T.length===1?"file":"files"]}),c("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:T.reduce((P,q)=>P+q.totalCount,0)})," ",T.reduce((P,q)=>P+q.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),y?c("button",{onClick:g,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[T.filter(P=>P.uncommittedCount>0).length," ","uncommitted"," ",T.filter(P=>P.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):c("button",{onClick:g,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),I.length>0&&c("div",{className:"flex gap-6",children:[c("button",{onClick:()=>{N(new Set(I.map(P=>P.filePath))),k(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(mi,{className:"w-3.5 h-3.5"}),"Expand All"]}),c("button",{onClick:()=>{N(new Set),k(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(pi,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(Ea,{showActions:!0,sortOrder:$,onSortChange:L}),n("div",{className:"flex flex-col gap-[3px]",children:I.map(P=>{const q=b.has(P.filePath),W=P.entities.filter(J=>(J.entityType==="visual"||J.entityType==="library")&&(at(J,(i==null?void 0:i.jobs)||[])==="not-analyzed"||at(J,(i==null?void 0:i.jobs)||[])==="out-of-date"||at(J,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,Z=J=>{var G;return((G=s==null?void 0:s.currentEntityShas)==null?void 0:G.includes(J))||!1},B=J=>{var G;return l!=null&&l(J)?!0:((G=i==null?void 0:i.jobs)==null?void 0:G.some(X=>{var le;return(le=X.entityShas)==null?void 0:le.includes(J.sha)}))||!1},F=J=>{m==null||m(J)};return n(Aa,{filePath:P.filePath,isExpanded:q,onToggle:()=>z(P.filePath),simulationPreviews:n(Pa,{entities:P.entities,maxPreviews:1}),entityCount:P.totalCount,state:P.state,lastModified:P.lastUpdated,uncommittedCount:P.uncommittedCount,isUncommitted:P.uncommittedCount>0,actionButton:W?n("button",{onClick:J=>{J.stopPropagation();const G=P.entities.filter(X=>(X.entityType==="visual"||X.entityType==="library")&&(at(X,(i==null?void 0:i.jobs)||[])==="not-analyzed"||at(X,(i==null?void 0:i.jobs)||[])==="out-of-date"||at(X,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(G)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:P.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:P.entities.sort((J,G)=>{var pe,Ce,$e,Me;const X=!((pe=J.metadata)!=null&&pe.notExported)&&!((Ce=J.metadata)!=null&&Ce.namedExport),le=!(($e=G.metadata)!=null&&$e.notExported)&&!((Me=G.metadata)!=null&&Me.namedExport);if(X&&!le)return-1;if(!X&&le)return 1;const ve=J.entityType==="visual"||J.entityType==="library",oe=G.entityType==="visual"||G.entityType==="library";return ve&&!oe?-1:!ve&&oe?1:J.name.localeCompare(G.name)}).map(J=>n(Ma,{entity:J,isActivelyAnalyzing:Z(J.sha),isQueued:B(J),onGenerateSimulation:F},J.sha))},P.filePath)})}),O>1&&c("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),c("span",{children:["Page ",t," of ",O]}),t<O&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const Ov=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function Fv({request:e,context:t}){try{const r=new URL(e.url),s=parseInt(r.searchParams.get("page")||"1"),a=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[d,m]=await Promise.all([nn(),hn()]);return Q({entities:d,currentCommit:m,page:s,filter:a,entityType:o,queueState:l})}catch(r){return console.error("Failed to load entities:",r),Q({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const zv=We(function(){var C,E,w;const{entities:t,currentCommit:r,page:s,filter:a,entityType:o,queueState:i,error:l}=Ve();mt();const[d,m]=mn(),[u,p]=M(!1);ht({source:"files-page"});const{handleGenerateSimulation:h,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=nc((E=(C=r==null?void 0:r.metadata)==null?void 0:C.currentRun)==null?void 0:E.currentEntityShas,i),x=t||[],v=ne(()=>{const k=new Set([]);for(const S of x)k.add(S.filePath??"No File Path");return Array.from(k)},[x]),b=ne(()=>{let k=x;return u&&(k=k.filter(S=>{var A;return(A=S.metadata)==null?void 0:A.isUncommitted})),k.sort((S,A)=>{var $,_,j,D,R,T;return($=S.metadata)!=null&&$.isUncommitted&&!((_=A.metadata)!=null&&_.isUncommitted)?-1:!((j=S.metadata)!=null&&j.isUncommitted)&&((D=A.metadata)!=null&&D.isUncommitted)?1:new Date(((R=A.metadata)==null?void 0:R.editedAt)||0).getTime()-new Date(((T=S.metadata)==null?void 0:T.editedAt)||0).getTime()})},[x,u]),N=ne(()=>{var S;const k=new Set([]);for(const A of x)(S=A.metadata)!=null&&S.isUncommitted&&k.add(A.filePath??"No File Path");return Array.from(k)},[x]);return l?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:l})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:c("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),c("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(Lv,{entities:b,page:s,itemsPerPage:50,currentRun:(w=r==null?void 0:r.metadata)==null?void 0:w.currentRun,filter:a,entityType:o,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:h,onGenerateAllSimulations:f,totalFilesCount:v.length,totalEntitiesCount:x.length,uncommittedFilesCount:N.length,showOnlyUncommitted:u,onToggleUncommitted:()=>p(!u)})]})})}),Bv=Object.freeze(Object.defineProperty({__proto__:null,default:zv,loader:Fv,meta:Ov},Symbol.toStringTag,{value:"Module"})),Yv=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function Uv({request:e}){var t;try{const r=await Te();if(!r)return Q({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:s}=await Re(r),a=me()||process.cwd(),o=Il(a)||"";let i="";try{const d=await Ir();if(d!=null&&d.webapps&&Array.isArray(d.webapps)){const m=d.webapps.map(u=>u.framework).filter(Boolean);m.length>0&&(i=m.join(", "))}}catch{}const l=Fl(r);return Q({labs:((t=s.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:o,detectedTechStack:i,unlockCode:l,error:null})}catch(r){return console.error("Failed to load labs config:",r),Q({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function Wv({request:e}){try{const t=await e.formData(),r=t.get("feature"),s=t.get("enabled")==="true";if(!r)return Q({success:!1,error:"Missing feature name"},{status:400});const a=await Te();return a?(r==="clearAccess"?await dn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await dn({projectSlug:a,metadataUpdate:{labs:{[r]:s}}}),Q({success:!0,error:null})):Q({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),Q({success:!1,error:"Failed to save labs configuration"},{status:500})}}const Jv=[{id:"simulations",name:"Simulations",description:"Enable entity analysis, visual simulations, git impact analysis, file browsing, and activity monitoring. When disabled, only Memory, Labs, and Settings are accessible.",defaultEnabled:!0},{id:"enhancedClaudeTesting",name:"Enhanced Claude Testing",description:"Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!0},{id:"gitIntegration",name:"Git Integration Showing Impacted Files",description:"Lorem Ipsum Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!1}],oi="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",Hv=[{title:"CodeYam Simulations",status:"apply for early access",desc:"CodeYam Simulations are the core of the CodeYam development experience. They leverage static code analysis and AI to generate robust data scenarios that are used to hydrate code. This creates a whole new dimension to the software development experience"},{title:"The Full CodeYam Experience",status:"more to come",desc:"CodeYam is completely rethinking the software development experience in the AI era. Focused on navigating the challenges of iteration speed, complexity, and communication, CodeYam will provide a powerful software development experience."}];function Vv({onClose:e}){const t=xe(null),r=xe(0);return te(()=>{const s=t.current;if(!s)return;const a=100,o=2e3,i=500;let l=null,d=!1;const m=()=>{r.current=Date.now(),!l&&!d&&(l=setInterval(()=>{const u=Date.now()-r.current,p=s.scrollTop>a,h=u>o;p&&h&&(s.scrollTo({top:0,behavior:"smooth"}),d=!0,l&&(clearInterval(l),l=null))},i))};return s.addEventListener("scroll",m,{passive:!0}),()=>{s.removeEventListener("scroll",m),l&&clearInterval(l)}},[]),c("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:s=>{s.target===s.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),c("div",{className:"relative bg-white rounded-xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-hidden",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),c("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[c("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${oi}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:c("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),c("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:oi,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function Gv({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:s}){var i,l;const a=(i=s.data)==null?void 0:i.error,o=(l=s.data)==null?void 0:l.success;return c("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:d=>{d.target===d.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),c("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),c(s.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:d=>r(d.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||s.state==="submitting",className:"w-full py-3 text-white border-none rounded-lg text-sm font-mono font-semibold uppercase tracking-wider cursor-pointer transition-all bg-primary-200 hover:bg-primary-100 disabled:bg-gray-400 disabled:cursor-not-allowed",children:s.state==="submitting"?"Validating...":"Unlock"}),a&&n("p",{className:"text-red-600 text-sm mt-2",children:a}),o&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const qv=We(function(){const{labs:t,unlockCode:r,error:s}=Ve(),a=De(),o=De(),i=De(),[l,d]=M(""),[m,u]=M(!1),[p,h]=M(!1);ht({source:"labs-page"});const f=(t==null?void 0:t.accessGranted)===!0||(t==null?void 0:t.simulations)===!0;return s?n("div",{className:"bg-cygray-10 min-h-screen",children:c("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:s})})]})}):f?c("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),c("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:Jv.map(y=>{var v;const g=(t==null?void 0:t[y.id])??y.defaultEnabled,x=o.state==="submitting"&&((v=o.formData)==null?void 0:v.get("feature"))===y.id;return n("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:c("div",{className:"flex items-center justify-between gap-4",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:y.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${g?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:g?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:y.description})]}),c(o.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:y.id}),n("input",{type:"hidden",name:"enabled",value:String(!g)}),n("button",{type:"submit",disabled:x,className:`relative inline-flex h-8 w-14 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${g?"bg-primary-100":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-7 w-7 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${g?"translate-x-6":"translate-x-0"}`})})]})]})},y.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:c("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),c("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),c(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):c("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[m&&n(Vv,{onClose:()=>u(!1)}),p&&n(Gv,{onClose:()=>h(!1),unlockCodeInput:l,setUnlockCodeInput:d,unlockFetcher:a}),c("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),c("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>h(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),c("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),c("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),c("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:Hv.map(y=>c("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[c("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[y.title," ",c("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",y.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:y.desc})]},y.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:c("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded border border-white bg-white text-cyblack-100 cursor-pointer transition-colors hover:bg-white/90 mb-4",children:"Apply for Early Access"}),n("p",{className:"text-xs text-white/60 m-0",children:"Takes about 2 minutes. Your answers help us determine eligibility and prioritize access."})]})})]})}),Kv=Object.freeze(Object.defineProperty({__proto__:null,action:Wv,default:qv,loader:Uv,meta:Yv},Symbol.toStringTag,{value:"Module"}));function Qv(e,t,r){const[s,a]=M(()=>new Set),[o,i]=M(()=>new Set),l=xe([]),d=xe([]);return te(()=>{(t.length!==l.current.length||t.some((g,x)=>g!==l.current[x]))&&(l.current=t,a(g=>{const x=new Set;return t.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[t]),te(()=>{(r.length!==d.current.length||r.some((g,x)=>g!==d.current[x]))&&(d.current=r,i(g=>{const x=new Set;return r.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[r]),{expandedUncommitted:s,expandedBranch:o,setExpandedUncommitted:a,setExpandedBranch:i,toggleFile:(y,g,x)=>{x(v=>{const b=new Set(v);return b.has(y)?b.delete(y):b.add(y),b})},expandAllUncommitted:()=>{a(new Set(t))},collapseAllUncommitted:()=>{a(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function Zv(e,t,r){const[s,a]=M(null),[o,i]=M(null),l=De();te(()=>{var p,h;((p=l.data)==null?void 0:p.oldContent)!==void 0&&((h=l.data)==null?void 0:h.newContent)!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const d=p=>{a({type:"file",path:p}),i(null);const h=new FormData;h.append("actionType","getDiff"),h.append("filePath",p),h.append("diffType","branch"),h.append("baseBranch",e),h.append("currentBranch",t||""),l.submit(h,{method:"post"})},m=(p,h)=>{a({type:"entity",path:p,entitySha:h}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",p),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",h),l.submit(f,{method:"post"})},u=()=>{a(null),i(null)};return{diffView:s,diffContent:o,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:m,handleCloseDiff:u}}function Xv({diffView:e,diffContent:t,isLoading:r,entities:s,onClose:a}){var m;const[o,i]=M(!1),[l,d]=M(!1);return te(()=>{d(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:c("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[c("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[c("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&c("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((m=s.find(u=>u.sha===e.entitySha))==null?void 0:m.name)||e.entitySha]})]}),c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:a,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(Md,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!o,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:a,className:"px-4 py-2 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",children:"Close"})})]})})}function ew({files:e,currentBranch:t,defaultBranch:r,baseBranch:s,allBranches:a,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:d,onToggleFile:m,onBranchChange:u,onGenerateSimulation:p,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=e.flatMap(([N,{entities:C}])=>{const E=C.filter(w=>i(w.sha)||l(w)).map(w=>w.sha);return E.length>0?[{entityShas:E}]:[]}),v=N=>{const C=N.map(E=>at(E,x));return C.includes("analyzing")||C.includes("queued")?"analyzing":C.includes("out-of-date")?"out-of-date":C.includes("not-analyzed")?"not-analyzed":"up-to-date"},b=ne(()=>[...e].sort((N,C)=>{const E=N[1].entities.reduce((A,$)=>{var j;const _=((j=$.metadata)==null?void 0:j.editedAt)||$.updatedAt;return _?A?new Date(_)>new Date(A)?_:A:_:A},null),w=C[1].entities.reduce((A,$)=>{var j;const _=((j=$.metadata)==null?void 0:j.editedAt)||$.updatedAt;return _?A?new Date(_)>new Date(A)?_:A:_:A},null);if(!E&&!w)return 0;if(!E)return 1;if(!w)return-1;const k=new Date(E).getTime(),S=new Date(w).getTime();return d==="desc"?S-k:k-S}),[e,d]);return n("div",{children:e.length>0?c("div",{children:[n(Ea,{showActions:!0,sortOrder:d,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([N,{status:C,entities:E,isUncommitted:w}])=>{const k=o.has(N),S=v(E),A=E.reduce((D,R)=>{var U;const T=((U=R.metadata)==null?void 0:U.editedAt)||R.updatedAt;return T?D?new Date(T)>new Date(D)?T:D:T:D},null),_=E.filter(D=>D.entityType==="visual"||D.entityType==="library").length===0;let j;return _?j=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):S==="analyzing"?j=c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):S==="up-to-date"?j=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):S==="out-of-date"?j=n("button",{onClick:D=>{D.stopPropagation(),E.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!i(R.sha)&&!l(R)).forEach(R=>p(R))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):S==="not-analyzed"&&(j=n("button",{onClick:D=>{D.stopPropagation(),E.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!i(R.sha)&&!l(R)).forEach(R=>p(R))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Aa,{filePath:N,isExpanded:k,onToggle:()=>m(N),fileStatus:C,isUncommitted:w,simulationPreviews:n(Pa,{entities:E,maxPreviews:1}),entityCount:E.length,state:S,lastModified:A,isNotAnalyzable:_,actionButton:j,children:E.sort((D,R)=>{const T=D.entityType==="visual"||D.entityType==="library",U=R.entityType==="visual"||R.entityType==="library";return T&&!U?-1:!T&&U?1:0}).map(D=>n(Ma,{entity:D,isActivelyAnalyzing:i(D.sha),isQueued:l(D),onGenerateSimulation:p},D.sha))},N)})})]}):c("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function tw({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:s,isEntityQueued:a,projectSlug:o,baseBranch:i,currentBranch:l,sortOrder:d,onToggleFile:m,onShowFileDiff:u,onGenerateSimulation:p,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=ne(()=>{const N=[];return e.forEach(([C,{editedEntities:E}])=>{const w=E.filter(k=>s(k.sha)||a(k)).map(k=>k.sha);w.length>0&&N.push({entityShas:w})}),N},[e,s,a]),v=ne(()=>{const N=new Map;return e.forEach(([C,{editedEntities:E}])=>{const w=E.map($=>at($,x));let k;w.includes("analyzing")||w.includes("queued")?k="analyzing":w.includes("out-of-date")?k="out-of-date":w.includes("not-analyzed")?k="not-analyzed":k="up-to-date";const S=E.reduce(($,_)=>{var D;const j=((D=_.metadata)==null?void 0:D.editedAt)||_.updatedAt;return j&&(!$||new Date(j)>new Date($))?j:$},null),A=E.filter($=>$.entityType==="visual"||$.entityType==="library").length;N.set(C,{state:k,lastModified:S,analyzableCount:A})}),N},[e,x]),b=ne(()=>[...e].sort((N,C)=>{const E=v.get(N[0]),w=v.get(C[0]),k=E==null?void 0:E.lastModified,S=w==null?void 0:w.lastModified;if(!k&&!S)return 0;if(!k)return 1;if(!S)return-1;const A=new Date(k).getTime(),$=new Date(S).getTime();return d==="desc"?$-A:A-$}),[e,v,d]);return e.length===0?c("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):c("div",{children:[n(Ea,{showActions:!0,sortOrder:d,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([N,{status:C,editedEntities:E}])=>{const w=r.has(N),k=v.get(N),{state:S,lastModified:A,analyzableCount:$}=k,_=$===0;let j;return _?j=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):S==="analyzing"?j=c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):S==="up-to-date"?j=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):S==="out-of-date"?j=n("button",{onClick:D=>{D.stopPropagation(),E.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!s(R.sha)&&!a(R)).forEach(R=>p(R))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):S==="not-analyzed"&&(j=n("button",{onClick:D=>{D.stopPropagation(),E.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!s(R.sha)&&!a(R)).forEach(R=>p(R))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Aa,{filePath:N,isExpanded:w,onToggle:()=>m(N),fileStatus:C,simulationPreviews:n(Pa,{entities:E,maxPreviews:1}),entityCount:E.length,state:S,lastModified:A,isNotAnalyzable:_,isUncommitted:!0,actionButton:j,children:E.sort((D,R)=>{const T=D.entityType==="visual"||D.entityType==="library",U=R.entityType==="visual"||R.entityType==="library";return T&&!U?-1:!T&&U?1:0}).map(D=>n(Ma,{entity:D,isActivelyAnalyzing:s(D.sha),isQueued:a(D),onGenerateSimulation:p},D.sha))},N)})})]})}function nw({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:s}){return n("div",{className:"border-b border-gray-200",children:c("nav",{className:"flex gap-8 items-center",children:[c("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[c("span",{className:"flex items-center gap-2",children:["Branch Changes",s>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:s})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),c("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[c("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const rw=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function sw({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const s=t.get("filePath"),a=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),l=t.get("entitySha");let d;return a==="branch"?d=ar(s,o,i):d=Ch(s),Q({...d,entitySha:l})}return Q({error:"Unknown action"},{status:400})}async function aw({request:e,context:t}){try{const r=new URL(e.url),s=r.searchParams.get("compare"),a=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[l,d,m]=await Promise.all([nn(),hn(),Te()]),u=Jr(),p=bh(),h=vh(),f=wh(),y=a||p,g=s||h;let x=[];return y&&y!==g&&(x=yl(g,y)),Q({entities:l||[],gitStatus:u,currentBranch:y,actualCurrentBranch:p,defaultBranch:h,allBranches:f,baseBranch:g,branchDiff:x,currentCommit:d,projectSlug:m,queueState:i})}catch(r){return console.error("Failed to load git data:",r),Q({entities:[],gitStatus:[],currentBranch:null,actualCurrentBranch:null,defaultBranch:"main",allBranches:[],baseBranch:"main",branchDiff:[],currentCommit:null,projectSlug:null,queueState:{paused:!1,jobs:[]},error:"Failed to load git data"})}}const ow=We(function(){var Se,tt;const{entities:t,gitStatus:r,currentBranch:s,actualCurrentBranch:a,defaultBranch:o,allBranches:i,baseBranch:l,branchDiff:d,currentCommit:m,projectSlug:u,queueState:p}=Ve();ht({source:"git-page"});const[h,f]=mn(),[y,g]=M(null),[x,v]=M("desc"),[b,N]=M("branch"),C=h.get("expanded")==="true",E=()=>{v(ge=>ge==="desc"?"asc":"desc")},w=De(),k=w.data;te(()=>{s&&l&&s!==l&&w.state==="idle"&&!k&&w.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(s)}`)},[s,l,w,k]);const S=ne(()=>{const ge=Kl(r,t);return Array.from(ge.entries()).sort((Le,Je)=>Le[0].localeCompare(Je[0]))},[r,t]),A=ne(()=>{const ge=Rb(d,t,k);return Array.from(ge.entries()).sort((Le,Je)=>Le[0].localeCompare(Je[0]))},[d,t,k]),$=ne(()=>Ib(r,t),[r,t]),_=ne(()=>b==="uncommitted"?S:A,[b,S,A]),j=ne(()=>_.map(([ge])=>ge),[_]),{expandedUncommitted:D,setExpandedUncommitted:R,toggleFile:T,expandAllUncommitted:U,collapseAllUncommitted:V}=Qv(C,j,[]),{diffView:I,diffContent:O,isLoading:z,handleShowFileDiff:L,handleCloseDiff:P}=Zv(l,s),q=(Se=m==null?void 0:m.metadata)==null?void 0:Se.currentRun,H=new Set((q==null?void 0:q.currentEntityShas)||[]),W=new Set(p.jobs.flatMap(ge=>ge.entityShas||[])),Z=new Set(((tt=p.currentlyExecuting)==null?void 0:tt.entityShas)||[]),{isAnalyzing:B,handleGenerateSimulation:F,handleGenerateAllSimulations:J,isEntityBeingAnalyzed:G,isEntityPending:X}=nc(q==null?void 0:q.currentEntityShas,p),le=ge=>X(ge)||W.has(ge.sha)||Z.has(ge.sha),ve=ge=>{ge===(a||s)?h.delete("viewBranch"):h.set("viewBranch",ge),f(h)},oe=ge=>{ge===o?h.delete("compare"):h.set("compare",ge),f(h)},pe=()=>{const Le=_.flatMap(([Je,nt])=>nt.editedEntities||nt.entities||[]).filter(Je=>!H.has(Je.sha)&&!W.has(Je.sha)&&!Z.has(Je.sha)&&!X(Je));J(Le)},Ce=S.length,$e=A.length,Me=_.flatMap(([ge,Le])=>Le.editedEntities||Le.entities||[]),Ie=Me.filter(ge=>ge.entityType==="visual"||ge.entityType==="library"),Fe=Ie.length>0&&Ie.every(ge=>H.has(ge.sha)),ke=Ie.length>0&&!Fe&&Ie.every(ge=>W.has(ge.sha)||Z.has(ge.sha)),re=B||Fe||ke,he=Fe?"Analyzing...":ke?"Queued...":B?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),c("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(nw,{activeTab:b,onTabChange:N,uncommittedCount:Ce,branchCount:$e})}),s&&b==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:s===o?c("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):c("div",{className:"flex gap-6 items-center",children:[c("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?c("div",{className:"relative w-50",children:[n("select",{value:s,onChange:ge=>ve(ge.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-2.5 pr-6 text-[13px] h-9.75 w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.map(ge=>n("option",{value:ge,children:ge},ge))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:s})]}),c("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),c("div",{className:"relative w-[200px]",children:[n("select",{value:l,onChange:ge=>oe(ge.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.filter(ge=>ge!==s).map(ge=>n("option",{value:ge,children:ge},ge))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:c("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center",children:[c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:_.length})," ","modified ",_.length===1?"file":"files"]}),c("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:Me.length})," ",Me.length===1?"entity":"entities"]})]}),_.length>0&&c("div",{className:"flex gap-6",children:[c("button",{onClick:U,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(mi,{className:"w-3.5 h-3.5"}),"Expand All"]}),c("button",{onClick:V,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(pi,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),c("div",{className:"overflow-hidden",children:[b==="branch"&&s&&n(ew,{files:A,currentBranch:s,defaultBranch:o,baseBranch:l,allBranches:i,expandedFiles:D,isEntityBeingAnalyzed:G,isEntityQueued:le,sortOrder:x,onToggleFile:ge=>T(ge,D,R),onBranchChange:oe,onGenerateSimulation:F,onSortChange:E,onAnalyzeAll:pe,analyzeAllDisabled:re,analyzeAllText:he}),b==="uncommitted"&&n(tw,{files:S,entityImpactMap:$,expandedFiles:D,isEntityBeingAnalyzed:G,isEntityQueued:le,projectSlug:u,baseBranch:l,currentBranch:s,sortOrder:x,onToggleFile:ge=>T(ge,D,R),onShowFileDiff:L,onGenerateSimulation:F,onSortChange:E,onAnalyzeAll:pe,analyzeAllDisabled:re,analyzeAllText:he})]}),I&&n(Xv,{diffView:I,diffContent:O,isLoading:z,entities:t,onClose:P}),y&&u&&n($t,{projectSlug:u,onClose:()=>g(null)})]})})}),iw=Object.freeze(Object.defineProperty({__proto__:null,action:sw,default:ow,loader:aw,meta:rw},Symbol.toStringTag,{value:"Module"})),rN={entry:{module:"/assets/entry.client-DTvKq3TY.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/index-10oVnAAH.js"],css:[]},routes:{root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/root-3ciuWk-c.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/index-10oVnAAH.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/useReportContext-O-jkvSPx.js","/assets/loader-circle-BAXYRVEO.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/book-open-D_nMCFmP.js","/assets/useToast-9FIWuYfK.js","/assets/useLastLogLine-C14nCb1q.js","/assets/LogViewer-ceAyBX-H.js","/assets/EntityTypeIcon-CobE682z.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/chevron-down-BH2h1Ea2.js","/assets/circle-check-DyIKORY6.js","/assets/CopyButton-DmJveP3T.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-CF164ouH.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.dev-CCa2trIL.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/editorPreview-GNwaLSmC.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/preload-helper-ckwbz45p.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-BMvVHNXU.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/Spinner-Bb5uFQ5V.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C14nCb1q.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-register-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-p9hhkjJM.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/Spinner-Bb5uFQ5V.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C14nCb1q.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-capture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-update-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-client-errors-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-entity-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-entry-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-test-results-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-load-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-dev-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.dev-mode-events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-refresh-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/agent-transcripts-D9hemwl6.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/terminal-BG4heKCG.js","/assets/search-fKo7v0Zo.js","/assets/chevron-down-BH2h1Ea2.js","/assets/book-open-D_nMCFmP.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-audit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-BpKzcsJz.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/LogViewer-ceAyBX-H.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/loader-circle-BAXYRVEO.js","/assets/pause-DTAcYxBt.js","/assets/createLucideIcon-CMT1jU2q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.rule-path-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha._-DItJnD8s.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useLastLogLine-C14nCb1q.js","/assets/Spinner-Bb5uFQ5V.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/LoadingDots-BU_OAEMP.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-ZlRKbhrq.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-CobE682z.js","/assets/CopyButton-DmJveP3T.js","/assets/LogViewer-ceAyBX-H.js","/assets/useReportContext-O-jkvSPx.js","/assets/preload-helper-ckwbz45p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/circle-check-DyIKORY6.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.analyze-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/simulations-B3aOzpCZ.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/EntityTypeIcon-CobE682z.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/loader-circle-BAXYRVEO.js","/assets/createLucideIcon-CMT1jU2q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/dev.empty-CltMNppm.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/ScenarioViewer-ZlRKbhrq.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.js","/assets/LogViewer-ceAyBX-H.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/useLastLogLine-C14nCb1q.js","/assets/Spinner-Bb5uFQ5V.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/circle-check-DyIKORY6.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/settings-DfuTtcJP.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/CopyButton-DmJveP3T.js","/assets/copy-NDbZjXao.js","/assets/createLucideIcon-CMT1jU2q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/static._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/_index-C96V0n15.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useToast-9FIWuYfK.js","/assets/useReportContext-O-jkvSPx.js","/assets/LogViewer-ceAyBX-H.js","/assets/EntityTypeIcon-CobE682z.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/circle-check-DyIKORY6.js","/assets/loader-circle-BAXYRVEO.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/editor":{id:"routes/editor",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/editor-Rfq_y0VR.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useCustomSizes-CrAK28Bc.js","/assets/editorPreview-GNwaLSmC.js","/assets/CopyButton-DmJveP3T.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/Spinner-Bb5uFQ5V.js","/assets/copy-NDbZjXao.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/useLastLogLine-C14nCb1q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/memory-Dg0mvYrI.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/terminal-BG4heKCG.js","/assets/copy-NDbZjXao.js","/assets/CopyButton-DmJveP3T.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/pause-DTAcYxBt.js","/assets/book-open-D_nMCFmP.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/files-DO4CZ16O.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-C76mRRiF.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/useToast-9FIWuYfK.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DtSmdtM4.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/labs-Zk7ryIM1.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/git-CdN8sCqs.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-C76mRRiF.js","/assets/LogViewer-ceAyBX-H.js","/assets/index-yHOVb4rc.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/useToast-9FIWuYfK.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DtSmdtM4.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-9ab0aba3.js",version:"9ab0aba3",sri:void 0},sN="build/client",aN="/",oN={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},iN=!0,lN=!1,cN=[],dN={mode:"lazy",manifestPath:"/__manifest"},uN="/",mN={module:jd},pN={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:ip},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,module:mp},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,module:wp},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,module:Cp},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,module:Jp},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,module:Rh},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,module:Bh},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,module:Wh},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,module:Hh},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,module:Gh},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,module:Kh},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,module:Xf},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,module:cg},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,module:ug},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,module:pg},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,module:xg},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,module:vg},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,module:Cg},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,module:Ag},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,module:Rg},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:Dg},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,module:Vg},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:Qg},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:u0},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,module:f0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:x0},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,module:v0},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,module:N0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:k0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:P0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:_0},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,module:$0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:W0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,module:H0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,module:X0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:sy},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:ly},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:my},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:hy},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:_y},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,module:Ty},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,module:Oy},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:zy},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:Hy},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:Gy},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:sx},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:ix},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,module:cx},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:px},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:fx},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:vx},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:Ux},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:Hx},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:Xx},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:tb},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:rb},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:yb},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:vb},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:Cb},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:_b},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:Tb},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:Bb},"routes/editor":{id:"routes/editor",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,module:pv},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:Iv},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Bv},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:Kv},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:iw}},hN=!1;export{zu as A,Lu as B,_e as C,cu as D,du as E,tn as F,Qd as G,wi as H,Ni as I,eu as J,Ci as K,ru as L,au as M,sN as N,aN as O,qd as P,oN as Q,iN as R,hr as S,lN as T,cN as U,dN as V,uN as W,mN as X,pN as Y,hN as Z,rN as _,Wd as a,cn as b,Qt as c,kt as d,zn as e,na as f,ra as g,vi as h,Yd as i,vu as j,wu as k,Rt as l,Et as m,Ei as n,Mu as o,gr as p,Ze as q,Ai as r,Pi as s,Ru as t,Tt as u,Mi as v,pn as w,dn as x,ao as y,Uu as z};
|