From dc10266a4e5b954fbddae3ec26c4e1430aa19297 Mon Sep 17 00:00:00 2001 From: Yash Date: Sat, 12 Sep 2026 18:06:52 +0530 Subject: [PATCH 1/4] feat: initialized prettier and eslint in the project --- .prettierignore | 10 + .prettierrc.json | 6 + eslint.config.js | 56 +++ package.json | 12 +- pnpm-lock.yaml | 963 ++++++++++++++++++++++++++++++++++++++++++++--- 5 files changed, 1003 insertions(+), 44 deletions(-) create mode 100644 .prettierignore create mode 100644 .prettierrc.json create mode 100644 eslint.config.js diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..02fc8e30 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,10 @@ +node_modules +dist +coverage +.git +.turbo +src-tauri/target +src-tauri/gen +src-tauri/resources +*.lock +pnpm-lock.yaml \ No newline at end of file diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..bccee911 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,6 @@ +{ + "semi": true, + "singleQuote": false, + "trailingComma": "all", + "printWidth": 100 +} diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 00000000..802c58e8 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,56 @@ +import eslint from "@eslint/js"; +import prettier from "eslint-config-prettier"; +import globals from "globals"; +import tseslint from "typescript-eslint"; + +export default tseslint.config( + { + ignores: [ + "**/node_modules/**", + "**/dist/**", + "**/coverage/**", + "**/.turbo/**", + "src-tauri/target/**", + "src-tauri/gen/**", + ], + }, + + eslint.configs.recommended, + ...tseslint.configs.recommended, + + { + files: ["**/*.{js,mjs,cjs,ts,tsx}"], + + languageOptions: { + globals: { + ...globals.browser, + ...globals.node, + }, + }, + + rules: { + "no-unused-vars": "off", + + "no-empty": ["warn", { allowEmptyCatch: true }], + "no-useless-catch": "error", + "prefer-const": "error", + + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/ban-ts-comment": "off", + "@typescript-eslint/no-empty-object-type": "off", + "@typescript-eslint/no-require-imports": "off", + "@typescript-eslint/no-unused-expressions": "off", + "@typescript-eslint/no-wrapper-object-types": "off", + + "@typescript-eslint/no-unused-vars": [ + "warn", + { + argsIgnorePattern: "^_", + varsIgnorePattern: "^_", + }, + ], + }, + }, + + prettier, +); diff --git a/package.json b/package.json index 120c7128..e9cecd95 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,10 @@ "build:tauri-assets": "npm run bridge:package && npm run build", "preview": "vite preview", "tauri": "tauri", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "format": "prettier . --write", + "format:check": "prettier . --check", "bridge:copy-native": "npm --prefix bridge run copy:native", "bridge:package": "node scripts/package-bridge.mjs" }, @@ -65,6 +69,7 @@ "tldraw": "^4.4.1" }, "devDependencies": { + "@eslint/js": "^9.39.1", "@tauri-apps/cli": "2.10.1", "@types/node": "^24.10.1", "@types/react": "^19.1.8", @@ -72,8 +77,13 @@ "@vitejs/plugin-react": "^4.6.0", "baseline-browser-mapping": "^2.9.19", "concurrently": "^9.2.1", + "eslint": "^9.39.1", + "eslint-config-prettier": "^10.1.8", + "globals": "^16.5.0", + "prettier": "^3.6.2", + "typescript-eslint": "^8.46.4", "tw-animate-css": "^1.4.0", "typescript": "~5.8.3", "vite": "^7.0.4" } -} \ No newline at end of file +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 64d08875..dd0ca540 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -133,7 +133,7 @@ importers: version: 19.2.3(react@19.2.3) react-markdown: specifier: ^10.1.0 - version: 10.1.0(@types/react@19.2.8)(react@19.2.3) + version: 10.1.0(@types/react@19.2.8)(react@19.2.3)(supports-color@8.1.1) react-router-dom: specifier: ^7.9.6 version: 7.9.6(react-dom@19.2.3(react@19.2.3))(react@19.2.3) @@ -159,6 +159,9 @@ importers: specifier: ^4.4.1 version: 4.4.1(@floating-ui/dom@1.7.6)(@types/react-dom@19.2.3(@types/react@19.2.8))(@types/react@19.2.8)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) devDependencies: + '@eslint/js': + specifier: ^9.39.1 + version: 9.39.5 '@tauri-apps/cli': specifier: 2.10.1 version: 2.10.1 @@ -173,19 +176,34 @@ importers: version: 19.2.3(@types/react@19.2.8) '@vitejs/plugin-react': specifier: ^4.6.0 - version: 4.7.0(vite@7.3.1(@types/node@24.12.0)(jiti@2.6.1)(lightningcss@1.31.1)) + version: 4.7.0(supports-color@8.1.1)(vite@7.3.1(@types/node@24.12.0)(jiti@2.6.1)(lightningcss@1.31.1)) baseline-browser-mapping: specifier: ^2.9.19 version: 2.9.19 concurrently: specifier: ^9.2.1 version: 9.2.1 + eslint: + specifier: ^9.39.1 + version: 9.39.5(jiti@2.6.1)(supports-color@8.1.1) + eslint-config-prettier: + specifier: ^10.1.8 + version: 10.1.8(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1)) + globals: + specifier: ^16.5.0 + version: 16.5.0 + prettier: + specifier: ^3.6.2 + version: 3.9.6 tw-animate-css: specifier: ^1.4.0 version: 1.4.0 typescript: specifier: ~5.8.3 version: 5.8.3 + typescript-eslint: + specifier: ^8.46.4 + version: 8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3) vite: specifier: ^7.0.4 version: 7.3.1(@types/node@24.12.0)(jiti@2.6.1)(lightningcss@1.31.1) @@ -193,7 +211,7 @@ importers: packages: '@aptabase/tauri@https://codeload.github.com/aptabase/tauri-plugin-aptabase/tar.gz/de6df6b8671568aad53eabaf4b49207a3d6c5622': - resolution: {tarball: https://codeload.github.com/aptabase/tauri-plugin-aptabase/tar.gz/de6df6b8671568aad53eabaf4b49207a3d6c5622} + resolution: {gitHosted: true, tarball: https://codeload.github.com/aptabase/tauri-plugin-aptabase/tar.gz/de6df6b8671568aad53eabaf4b49207a3d6c5622} version: 0.4.2 '@babel/code-frame@7.27.1': @@ -497,6 +515,44 @@ packages: cpu: [x64] os: [win32] + '@eslint-community/eslint-utils@4.10.1': + resolution: {integrity: sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + + '@eslint-community/regexpp@4.12.2': + resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + '@eslint/config-array@0.21.2': + resolution: {integrity: sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/config-helpers@0.4.2': + resolution: {integrity: sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/core@0.17.0': + resolution: {integrity: sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/eslintrc@3.3.7': + resolution: {integrity: sha512-F42g89Qd5oAWtp0k0nnSrjziAKza7w8SVT4mStc18LZMaRb4J1HQAHLCalEtDCxrTuksx7NU9qsmeLwpOfPqWw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/js@9.39.5': + resolution: {integrity: sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/object-schema@2.1.7': + resolution: {integrity: sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/plugin-kit@0.4.1': + resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@floating-ui/core@1.7.5': resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==} @@ -512,6 +568,26 @@ packages: '@floating-ui/utils@0.2.11': resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==} + '@humanfs/core@0.19.2': + resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} + engines: {node: '>=18.18.0'} + + '@humanfs/node@0.16.8': + resolution: {integrity: sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==} + engines: {node: '>=18.18.0'} + + '@humanfs/types@0.15.0': + resolution: {integrity: sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==} + engines: {node: '>=18.18.0'} + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/retry@0.4.3': + resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} + engines: {node: '>=18.18'} + '@jridgewell/gen-mapping@0.3.13': resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} @@ -1363,66 +1439,79 @@ packages: resolution: {integrity: sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==} cpu: [arm] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.59.0': resolution: {integrity: sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==} cpu: [arm] os: [linux] + libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.59.0': resolution: {integrity: sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==} cpu: [arm64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.59.0': resolution: {integrity: sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==} cpu: [arm64] os: [linux] + libc: [musl] '@rollup/rollup-linux-loong64-gnu@4.59.0': resolution: {integrity: sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==} cpu: [loong64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-loong64-musl@4.59.0': resolution: {integrity: sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==} cpu: [loong64] os: [linux] + libc: [musl] '@rollup/rollup-linux-ppc64-gnu@4.59.0': resolution: {integrity: sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==} cpu: [ppc64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-ppc64-musl@4.59.0': resolution: {integrity: sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==} cpu: [ppc64] os: [linux] + libc: [musl] '@rollup/rollup-linux-riscv64-gnu@4.59.0': resolution: {integrity: sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==} cpu: [riscv64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-riscv64-musl@4.59.0': resolution: {integrity: sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==} cpu: [riscv64] os: [linux] + libc: [musl] '@rollup/rollup-linux-s390x-gnu@4.59.0': resolution: {integrity: sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==} cpu: [s390x] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.59.0': resolution: {integrity: sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==} cpu: [x64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-musl@4.59.0': resolution: {integrity: sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==} cpu: [x64] os: [linux] + libc: [musl] '@rollup/rollup-openbsd-x64@4.59.0': resolution: {integrity: sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==} @@ -1492,24 +1581,28 @@ packages: engines: {node: '>= 20'} cpu: [arm64] os: [linux] + libc: [glibc] '@tailwindcss/oxide-linux-arm64-musl@4.2.1': resolution: {integrity: sha512-WZA0CHRL/SP1TRbA5mp9htsppSEkWuQ4KsSUumYQnyl8ZdT39ntwqmz4IUHGN6p4XdSlYfJwM4rRzZLShHsGAQ==} engines: {node: '>= 20'} cpu: [arm64] os: [linux] + libc: [musl] '@tailwindcss/oxide-linux-x64-gnu@4.2.1': resolution: {integrity: sha512-qMFzxI2YlBOLW5PhblzuSWlWfwLHaneBE0xHzLrBgNtqN6mWfs+qYbhryGSXQjFYB1Dzf5w+LN5qbUTPhW7Y5g==} engines: {node: '>= 20'} cpu: [x64] os: [linux] + libc: [glibc] '@tailwindcss/oxide-linux-x64-musl@4.2.1': resolution: {integrity: sha512-5r1X2FKnCMUPlXTWRYpHdPYUY6a1Ar/t7P24OuiEdEOmms5lyqjDRvVY1yy9Rmioh+AunQ0rWiOTPE8F9A3v5g==} engines: {node: '>= 20'} cpu: [x64] os: [linux] + libc: [musl] '@tailwindcss/oxide-wasm32-wasi@4.2.1': resolution: {integrity: sha512-MGFB5cVPvshR85MTJkEvqDUnuNoysrsRxd6vnk1Lf2tbiqNlXpHYZqkqOQalydienEWOHHFyyuTSYRsLfxFJ2Q==} @@ -1578,30 +1671,35 @@ packages: engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [glibc] '@tauri-apps/cli-linux-arm64-musl@2.10.1': resolution: {integrity: sha512-MIj78PDDGjkg3NqGptDOGgfXks7SYJwhiMh8SBoZS+vfdz7yP5jN18bNaLnDhsVIPARcAhE1TlsZe/8Yxo2zqg==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [musl] '@tauri-apps/cli-linux-riscv64-gnu@2.10.1': resolution: {integrity: sha512-X0lvOVUg8PCVaoEtEAnpxmnkwlE1gcMDTqfhbefICKDnOTJ5Est3qL0SrWxizDackIOKBcvtpejrSiVpuJI1kw==} engines: {node: '>= 10'} cpu: [riscv64] os: [linux] + libc: [glibc] '@tauri-apps/cli-linux-x64-gnu@2.10.1': resolution: {integrity: sha512-2/12bEzsJS9fAKybxgicCDFxYD1WEI9kO+tlDwX5znWG2GwMBaiWcmhGlZ8fi+DMe9CXlcVarMTYc0L3REIRxw==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [glibc] '@tauri-apps/cli-linux-x64-musl@2.10.1': resolution: {integrity: sha512-Y8J0ZzswPz50UcGOFuXGEMrxbjwKSPgXftx5qnkuMs2rmwQB5ssvLb6tn54wDSYxe7S6vlLob9vt0VKuNOaCIQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [musl] '@tauri-apps/cli-win32-arm64-msvc@2.10.1': resolution: {integrity: sha512-iSt5B86jHYAPJa/IlYw++SXtFPGnWtFJriHn7X0NFBVunF6zu9+/zOn8OgqIWSl8RgzhLGXQEEtGBdR4wzpVgg==} @@ -1947,6 +2045,9 @@ packages: '@types/hast@3.0.4': resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==} + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + '@types/linkify-it@5.0.0': resolution: {integrity: sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==} @@ -1985,6 +2086,65 @@ packages: '@types/use-sync-external-store@0.0.6': resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==} + '@typescript-eslint/eslint-plugin@8.70.0': + resolution: {integrity: sha512-/v8HZt6RlyIZxB3ntehELOcUcfxKPVGWXnQdJuHRmzrqgF8nQypcC/oxGW+Ot4VGKDq81XugPKxx0n5PBtf9PA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + '@typescript-eslint/parser': ^8.70.0 + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/parser@8.70.0': + resolution: {integrity: sha512-zYvrmj9Yxd63UGaXw+kdt6A0F0s0qveJyuatIM77bYC2DE4pgmg7a50u8LR7PRtXd0x+h+Tl3eXabGm06SWd3Q==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/project-service@8.70.0': + resolution: {integrity: sha512-hFHbTNqhU9G+2eKFXCBVb1tjFT/LceiJ4+HfLO4pTpDI0KHi6iajpcFFkaSQ9gXmCh7n82A0PthaayEdN6mspQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/scope-manager@8.70.0': + resolution: {integrity: sha512-8nP3Kwh5hlgZ4FicGvmznAmJe8UL4sdU8tLukrPaMuQmDuk4Y8xYfzu/aYZW4xT2JCgc7H/TpDI5cGlxcWJSqQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/tsconfig-utils@8.70.0': + resolution: {integrity: sha512-adnkeeNq9Sq1sUf4+FRVc0KdgYghzsgFpZSQVZVvY0LCuUuN0FnQgyGzCJeC4fW1cdXseBAjU2EOqUIjbNcZUw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/type-utils@8.70.0': + resolution: {integrity: sha512-NUMKIhYVaVIVLnRL9CRt+VVcuLgSHUCpXn4/+K8wql+vdInUzvx8BjUO1oJ7cG9shjFJKtF8F8Hh2kCh3/KBVw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/types@8.70.0': + resolution: {integrity: sha512-asTOIYhDg4zdzOScCyaytrsV3cR6B4ecPQlXw/dJIm7J/MZTtCtfVII9JD8Geh4jTCrK/Xe6cg5UevoleMcoJQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/typescript-estree@8.70.0': + resolution: {integrity: sha512-d9NmHMPEKQ7QCLLm1jI3zmoQBwT5KwFYjXBJ9ymZfKCUU+5rmTRykKAFvH5Qn/ZCds3CEAFS9OC9M/jkl0X2bA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/utils@8.70.0': + resolution: {integrity: sha512-oZmtKJz/4fufZ2p3+Cn3ijEojcdfR+1zYDH2xKYrEly0dR/Q/1xUPRCOlKGxod78nWlU2UnDe09GZ3TaknBFGA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/visitor-keys@8.70.0': + resolution: {integrity: sha512-BoC8PiO4Hkdo0TVJh9Ntxr5MxPDI7/oFsrygN5ADelFSeXG/qgNuucIGA+L5Z6JpPTE/uRfcTWtscjbUaufepQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@uiw/codemirror-extensions-basic-setup@4.25.4': resolution: {integrity: sha512-YzNwkm0AbPv1EXhCHYR5v0nqfemG2jEB0Z3Att4rBYqKrlG7AA9Rhjc3IyBaOzsBu18wtrp9/+uhTyu7TXSRng==} peerDependencies: @@ -2024,6 +2184,19 @@ packages: peerDependencies: vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn@8.18.0: + resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==} + engines: {node: '>=0.4.0'} + hasBin: true + + ajv@6.15.0: + resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + ansi-regex@5.0.1: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} @@ -2042,15 +2215,33 @@ packages: bail@2.0.2: resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==} + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + baseline-browser-mapping@2.9.19: resolution: {integrity: sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg==} hasBin: true + brace-expansion@1.1.18: + resolution: {integrity: sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==} + + brace-expansion@5.0.9: + resolution: {integrity: sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==} + engines: {node: 20 || >=22} + browserslist@4.28.0: resolution: {integrity: sha512-tbydkR/CxfMwelN0vwdP/pLkDwyAASZ+VfWm4EOwlB6SWhx1sYnWLqo8N5j0rAzPfzfRaxt0mM/4wPU/Su84RQ==} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true + callsites@3.1.0: + resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} + engines: {node: '>=6'} + camelize@1.0.1: resolution: {integrity: sha512-dU+Tx2fsypxTgtLoE36npi3UqcjSSMNYfkqgmoEhtZrraP5VWq0K7FkWVTYa8eMPtnU/G2txVsfdCJTn9uzpuQ==} @@ -2112,6 +2303,9 @@ packages: comma-separated-tokens@2.0.3: resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} + concat-map@0.0.1: + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + concurrently@9.2.1: resolution: {integrity: sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==} engines: {node: '>=18'} @@ -2127,6 +2321,10 @@ packages: crelt@1.0.6: resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==} + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + css-color-keywords@1.0.0: resolution: {integrity: sha512-FyyrDHZKEjXDpNJYvVsV960FiqQyXc/LlYmsxl2BcdMb2WPx0OGRVgTg55rPSyLSNMqP52R9r8geSp7apN3Ofg==} engines: {node: '>=4'} @@ -2227,6 +2425,9 @@ packages: decode-named-character-reference@1.3.0: resolution: {integrity: sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==} + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + dequal@2.0.3: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} @@ -2271,19 +2472,81 @@ packages: resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} engines: {node: '>=10'} + eslint-config-prettier@10.1.8: + resolution: {integrity: sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==} + hasBin: true + peerDependencies: + eslint: '>=7.0.0' + + eslint-scope@8.4.0: + resolution: {integrity: sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@4.2.1: + resolution: {integrity: sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + eslint-visitor-keys@5.0.1: + resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint@9.39.5: + resolution: {integrity: sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options. + hasBin: true + peerDependencies: + jiti: '*' + peerDependenciesMeta: + jiti: + optional: true + + espree@10.4.0: + resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + esquery@1.7.0: + resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + estree-util-is-identifier-name@3.0.0: resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==} + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + eventemitter3@4.0.7: resolution: {integrity: sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==} extend@3.0.2: resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + fast-equals@5.4.0: resolution: {integrity: sha512-jt2DW/aNFNwke7AUd+Z+e6pz39KO5rzdbbFCg2sGafS4mk13MI7Z8O5z9cADNn5lhGODIgLwug6TZO2ctf7kcw==} engines: {node: '>=6.0.0'} + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} @@ -2293,6 +2556,21 @@ packages: picomatch: optional: true + file-entry-cache@8.0.0: + resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} + engines: {node: '>=16.0.0'} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@4.0.1: + resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} + engines: {node: '>=16'} + + flatted@3.4.4: + resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} + fractional-indexing@3.2.0: resolution: {integrity: sha512-PcOxmqwYCW7O2ovKRU8OoQQj2yqTfEB/yeTYk4gPid6dN5ODRfU1hXd9tTVZzax/0NkO7AxpHykvZnT1aYp/BQ==} engines: {node: ^14.13.1 || >=16.0.0} @@ -2314,6 +2592,18 @@ packages: resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==} engines: {node: '>=6'} + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + + globals@14.0.0: + resolution: {integrity: sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==} + engines: {node: '>=18'} + + globals@16.5.0: + resolution: {integrity: sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==} + engines: {node: '>=18'} + graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} @@ -2342,6 +2632,22 @@ packages: idb@7.1.1: resolution: {integrity: sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==} + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + ignore@7.0.9: + resolution: {integrity: sha512-brTTsvFRt5C1gGHtPst/281UjPD5t9fBqbgoMPlVWy11ZLTPfu7HxK4ZYqO9H7o/yC9rSTCI85EaQ4OoY12qYw==} + engines: {node: '>= 4'} + + import-fresh@3.3.1: + resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==} + engines: {node: '>=6'} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + inline-style-parser@0.2.7: resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==} @@ -2358,10 +2664,18 @@ packages: is-decimal@2.0.1: resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==} + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + is-fullwidth-code-point@3.0.0: resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} engines: {node: '>=8'} + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + is-hexadecimal@2.0.1: resolution: {integrity: sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==} @@ -2373,6 +2687,9 @@ packages: resolution: {integrity: sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==} engines: {node: '>=0.10.0'} + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + jiti@2.6.1: resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} hasBin: true @@ -2384,16 +2701,36 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + js-yaml@4.3.2: + resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==} + hasBin: true + jsesc@3.1.0: resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} engines: {node: '>=6'} hasBin: true + json-buffer@3.0.1: + resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + json5@2.2.3: resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} engines: {node: '>=6'} hasBin: true + keyv@4.5.4: + resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + lightningcss-android-arm64@1.31.1: resolution: {integrity: sha512-HXJF3x8w9nQ4jbXRiNppBCqeZPIAfUo8zE/kOEGbW5NZvGc/K7nMxbhIr+YlFlHW5mpbg/YFPdbnCh1wAXCKFg==} engines: {node: '>= 12.0.0'} @@ -2429,24 +2766,28 @@ packages: engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [glibc] lightningcss-linux-arm64-musl@1.31.1: resolution: {integrity: sha512-mVZ7Pg2zIbe3XlNbZJdjs86YViQFoJSpc41CbVmKBPiGmC4YrfeOyz65ms2qpAobVd7WQsbW4PdsSJEMymyIMg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [musl] lightningcss-linux-x64-gnu@1.31.1: resolution: {integrity: sha512-xGlFWRMl+0KvUhgySdIaReQdB4FNudfUTARn7q0hh/V67PVGCs3ADFjw+6++kG1RNd0zdGRlEKa+T13/tQjPMA==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [glibc] lightningcss-linux-x64-musl@1.31.1: resolution: {integrity: sha512-eowF8PrKHw9LpoZii5tdZwnBcYDxRw2rRCyvAXLi34iyeYfqCQNA9rmUM0ce62NlPhCvof1+9ivRaTY6pSKDaA==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [musl] lightningcss-win32-arm64-msvc@1.31.1: resolution: {integrity: sha512-aJReEbSEQzx1uBlQizAOBSjcmr9dCdL3XuC/6HLXAxmtErsj2ICo5yYggg1qOODQMtnjNQv2UHb9NpOuFtYe4w==} @@ -2470,6 +2811,10 @@ packages: linkifyjs@4.3.2: resolution: {integrity: sha512-NT1CJtq3hHIreOianA8aSXn6Cw0JzYOuDQbOrSPe7gqFnCpKP++MQe3ODgO3oh2GJFORkAAdqredOa60z63GbA==} + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + lodash.isequal@4.5.0: resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==} deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead. @@ -2477,6 +2822,9 @@ packages: lodash.isequalwith@4.4.0: resolution: {integrity: sha512-dcZON0IalGBpRmJBmMkaoV7d3I80R2O+FrzsZyHdNSFrANq/cgDqKQNmAHE8UEj4+QYWwwhkQOVdLHiAopzlsQ==} + lodash.merge@4.6.2: + resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} + lodash.throttle@4.1.1: resolution: {integrity: sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ==} @@ -2602,6 +2950,13 @@ packages: micromark@4.0.2: resolution: {integrity: sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==} + minimatch@10.2.6: + resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} + engines: {node: 18 || 20 || >=22} + + minimatch@3.1.5: + resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} @@ -2610,6 +2965,9 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true + natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + next-themes@0.4.6: resolution: {integrity: sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA==} peerDependencies: @@ -2623,12 +2981,36 @@ packages: resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} engines: {node: '>=0.10.0'} + optionator@0.9.4: + resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} + engines: {node: '>= 0.8.0'} + orderedmap@2.1.1: resolution: {integrity: sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==} + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + + parent-module@1.0.1: + resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} + engines: {node: '>=6'} + parse-entities@4.0.2: resolution: {integrity: sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==} + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -2647,6 +3029,15 @@ packages: resolution: {integrity: sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==} engines: {node: ^10 || ^12 || >=14} + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + + prettier@3.9.6: + resolution: {integrity: sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==} + engines: {node: '>=14'} + hasBin: true + prop-types@15.8.1: resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==} @@ -2715,6 +3106,10 @@ packages: resolution: {integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==} engines: {node: '>=6'} + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + quickselect@2.0.0: resolution: {integrity: sha512-RKJ22hX8mHe3Y6wH/N3wCM6BWtjaxIyyUIkpHOvfFnxdI4yD4tBXEBKSbriGujF6jnSVkJrffuo6vxACiSSxIw==} @@ -2830,6 +3225,7 @@ packages: recharts@2.15.4: resolution: {integrity: sha512-UT/q6fwS3c1dHbXv2uFgYJ9BMFHu3fwnd7AYZaEQhXuYQ4hgsxLvsUXzGdKeZrW5xopzDCvuA2N41WJ88I7zIw==} engines: {node: '>=14'} + deprecated: 1.x and 2.x branches are no longer active. Bump to Recharts v3 to receive latest features and bugfixes. See https://github.com/recharts/recharts/wiki/3.0-migration-guide peerDependencies: react: ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 react-dom: ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 @@ -2844,6 +3240,10 @@ packages: resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} engines: {node: '>=0.10.0'} + resolve-from@4.0.0: + resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} + engines: {node: '>=4'} + rollup@4.59.0: resolution: {integrity: sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==} engines: {node: '>=18.0.0', npm: '>=8.0.0'} @@ -2862,12 +3262,25 @@ packages: resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} hasBin: true + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + set-cookie-parser@2.7.2: resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==} shallowequal@1.1.0: resolution: {integrity: sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==} + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + shell-quote@1.8.3: resolution: {integrity: sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==} engines: {node: '>= 0.4'} @@ -2896,6 +3309,10 @@ packages: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} + strip-json-comments@3.1.1: + resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} + engines: {node: '>=8'} + style-mod@4.1.3: resolution: {integrity: sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==} @@ -2956,6 +3373,12 @@ packages: trough@2.2.0: resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==} + ts-api-utils@2.5.0: + resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} + engines: {node: '>=18.12'} + peerDependencies: + typescript: '>=4.8.4' + tslib@2.6.2: resolution: {integrity: sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==} @@ -2965,6 +3388,17 @@ packages: tw-animate-css@1.4.0: resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + + typescript-eslint@8.70.0: + resolution: {integrity: sha512-P/W5cz70/cQAuKfY3xwQMWWTV7BvJ0mAQmi+9mBcsVPaBUpd6Ohpa+fECv9rBFrQcig86jAiNBFNWUqnTjr4pw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + typescript@5.8.3: resolution: {integrity: sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==} engines: {node: '>=14.17'} @@ -3000,6 +3434,9 @@ packages: peerDependencies: browserslist: '>= 4.21.0' + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + use-callback-ref@1.3.3: resolution: {integrity: sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==} engines: {node: '>=10'} @@ -3077,6 +3514,15 @@ packages: w3c-keyname@2.2.8: resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==} + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + wrap-ansi@7.0.0: resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} engines: {node: '>=10'} @@ -3096,6 +3542,10 @@ packages: resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} engines: {node: '>=12'} + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + zustand@4.5.7: resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==} engines: {node: '>=12.7.0'} @@ -3129,20 +3579,20 @@ snapshots: '@babel/compat-data@7.28.5': {} - '@babel/core@7.28.5': + '@babel/core@7.28.5(supports-color@8.1.1)': dependencies: '@babel/code-frame': 7.27.1 '@babel/generator': 7.28.5 '@babel/helper-compilation-targets': 7.27.2 - '@babel/helper-module-transforms': 7.28.3(@babel/core@7.28.5) + '@babel/helper-module-transforms': 7.28.3(@babel/core@7.28.5(supports-color@8.1.1))(supports-color@8.1.1) '@babel/helpers': 7.28.4 '@babel/parser': 7.28.5 '@babel/template': 7.27.2 - '@babel/traverse': 7.28.5 + '@babel/traverse': 7.28.5(supports-color@8.1.1) '@babel/types': 7.28.5 '@jridgewell/remapping': 2.3.5 convert-source-map: 2.0.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) gensync: 1.0.0-beta.2 json5: 2.2.3 semver: 6.3.1 @@ -3167,19 +3617,19 @@ snapshots: '@babel/helper-globals@7.28.0': {} - '@babel/helper-module-imports@7.27.1': + '@babel/helper-module-imports@7.27.1(supports-color@8.1.1)': dependencies: - '@babel/traverse': 7.28.5 + '@babel/traverse': 7.28.5(supports-color@8.1.1) '@babel/types': 7.28.5 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.28.3(@babel/core@7.28.5)': + '@babel/helper-module-transforms@7.28.3(@babel/core@7.28.5(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.28.5 - '@babel/helper-module-imports': 7.27.1 + '@babel/core': 7.28.5(supports-color@8.1.1) + '@babel/helper-module-imports': 7.27.1(supports-color@8.1.1) '@babel/helper-validator-identifier': 7.28.5 - '@babel/traverse': 7.28.5 + '@babel/traverse': 7.28.5(supports-color@8.1.1) transitivePeerDependencies: - supports-color @@ -3200,14 +3650,14 @@ snapshots: dependencies: '@babel/types': 7.28.5 - '@babel/plugin-transform-react-jsx-self@7.27.1(@babel/core@7.28.5)': + '@babel/plugin-transform-react-jsx-self@7.27.1(@babel/core@7.28.5(supports-color@8.1.1))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-react-jsx-source@7.27.1(@babel/core@7.28.5)': + '@babel/plugin-transform-react-jsx-source@7.27.1(@babel/core@7.28.5(supports-color@8.1.1))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/runtime@7.28.4': {} @@ -3218,7 +3668,7 @@ snapshots: '@babel/parser': 7.28.5 '@babel/types': 7.28.5 - '@babel/traverse@7.28.5': + '@babel/traverse@7.28.5(supports-color@8.1.1)': dependencies: '@babel/code-frame': 7.27.1 '@babel/generator': 7.28.5 @@ -3226,7 +3676,7 @@ snapshots: '@babel/parser': 7.28.5 '@babel/template': 7.27.2 '@babel/types': 7.28.5 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) transitivePeerDependencies: - supports-color @@ -3408,6 +3858,52 @@ snapshots: '@esbuild/win32-x64@0.27.4': optional: true + '@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))': + dependencies: + eslint: 9.39.5(jiti@2.6.1)(supports-color@8.1.1) + eslint-visitor-keys: 3.4.3 + + '@eslint-community/regexpp@4.12.2': {} + + '@eslint/config-array@0.21.2(supports-color@8.1.1)': + dependencies: + '@eslint/object-schema': 2.1.7 + debug: 4.4.3(supports-color@8.1.1) + minimatch: 3.1.5 + transitivePeerDependencies: + - supports-color + + '@eslint/config-helpers@0.4.2': + dependencies: + '@eslint/core': 0.17.0 + + '@eslint/core@0.17.0': + dependencies: + '@types/json-schema': 7.0.15 + + '@eslint/eslintrc@3.3.7(supports-color@8.1.1)': + dependencies: + ajv: 6.15.0 + debug: 4.4.3(supports-color@8.1.1) + espree: 10.4.0 + globals: 14.0.0 + ignore: 5.3.2 + import-fresh: 3.3.1 + js-yaml: 4.3.2 + minimatch: 3.1.5 + strip-json-comments: 3.1.1 + transitivePeerDependencies: + - supports-color + + '@eslint/js@9.39.5': {} + + '@eslint/object-schema@2.1.7': {} + + '@eslint/plugin-kit@0.4.1': + dependencies: + '@eslint/core': 0.17.0 + levn: 0.4.1 + '@floating-ui/core@1.7.5': dependencies: '@floating-ui/utils': 0.2.11 @@ -3425,6 +3921,22 @@ snapshots: '@floating-ui/utils@0.2.11': {} + '@humanfs/core@0.19.2': + dependencies: + '@humanfs/types': 0.15.0 + + '@humanfs/node@0.16.8': + dependencies: + '@humanfs/core': 0.19.2 + '@humanfs/types': 0.15.0 + '@humanwhocodes/retry': 0.4.3 + + '@humanfs/types@0.15.0': {} + + '@humanwhocodes/module-importer@1.0.1': {} + + '@humanwhocodes/retry@0.4.3': {} + '@jridgewell/gen-mapping@0.3.13': dependencies: '@jridgewell/sourcemap-codec': 1.5.5 @@ -4940,6 +5452,8 @@ snapshots: dependencies: '@types/unist': 3.0.3 + '@types/json-schema@7.0.15': {} + '@types/linkify-it@5.0.0': {} '@types/markdown-it@14.1.2': @@ -4975,6 +5489,97 @@ snapshots: '@types/use-sync-external-store@0.0.6': {} + '@typescript-eslint/eslint-plugin@8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3))(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3)': + dependencies: + '@eslint-community/regexpp': 4.12.2 + '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3) + '@typescript-eslint/scope-manager': 8.70.0 + '@typescript-eslint/type-utils': 8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3) + '@typescript-eslint/visitor-keys': 8.70.0 + eslint: 9.39.5(jiti@2.6.1)(supports-color@8.1.1) + ignore: 7.0.9 + natural-compare: 1.4.0 + ts-api-utils: 2.5.0(typescript@5.8.3) + typescript: 5.8.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3)': + dependencies: + '@typescript-eslint/scope-manager': 8.70.0 + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@8.1.1)(typescript@5.8.3) + '@typescript-eslint/visitor-keys': 8.70.0 + debug: 4.4.3(supports-color@8.1.1) + eslint: 9.39.5(jiti@2.6.1)(supports-color@8.1.1) + typescript: 5.8.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/project-service@8.70.0(supports-color@8.1.1)(typescript@5.8.3)': + dependencies: + '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.8.3) + '@typescript-eslint/types': 8.70.0 + debug: 4.4.3(supports-color@8.1.1) + typescript: 5.8.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/scope-manager@8.70.0': + dependencies: + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/visitor-keys': 8.70.0 + + '@typescript-eslint/tsconfig-utils@8.70.0(typescript@5.8.3)': + dependencies: + typescript: 5.8.3 + + '@typescript-eslint/type-utils@8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3)': + dependencies: + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@8.1.1)(typescript@5.8.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3) + debug: 4.4.3(supports-color@8.1.1) + eslint: 9.39.5(jiti@2.6.1)(supports-color@8.1.1) + ts-api-utils: 2.5.0(typescript@5.8.3) + typescript: 5.8.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/types@8.70.0': {} + + '@typescript-eslint/typescript-estree@8.70.0(supports-color@8.1.1)(typescript@5.8.3)': + dependencies: + '@typescript-eslint/project-service': 8.70.0(supports-color@8.1.1)(typescript@5.8.3) + '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.8.3) + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/visitor-keys': 8.70.0 + debug: 4.4.3(supports-color@8.1.1) + minimatch: 10.2.6 + semver: 7.8.5 + tinyglobby: 0.2.15 + ts-api-utils: 2.5.0(typescript@5.8.3) + typescript: 5.8.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/utils@8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3)': + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1)) + '@typescript-eslint/scope-manager': 8.70.0 + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@8.1.1)(typescript@5.8.3) + eslint: 9.39.5(jiti@2.6.1)(supports-color@8.1.1) + typescript: 5.8.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/visitor-keys@8.70.0': + dependencies: + '@typescript-eslint/types': 8.70.0 + eslint-visitor-keys: 5.0.1 + '@uiw/codemirror-extensions-basic-setup@4.25.4(@codemirror/autocomplete@6.20.1)(@codemirror/commands@6.10.2)(@codemirror/language@6.12.2)(@codemirror/lint@6.9.5)(@codemirror/search@6.6.0)(@codemirror/state@6.5.4)(@codemirror/view@6.39.16)': dependencies: '@codemirror/autocomplete': 6.20.1 @@ -5011,11 +5616,11 @@ snapshots: '@use-gesture/core': 10.3.1 react: 19.2.3 - '@vitejs/plugin-react@4.7.0(vite@7.3.1(@types/node@24.12.0)(jiti@2.6.1)(lightningcss@1.31.1))': + '@vitejs/plugin-react@4.7.0(supports-color@8.1.1)(vite@7.3.1(@types/node@24.12.0)(jiti@2.6.1)(lightningcss@1.31.1))': dependencies: - '@babel/core': 7.28.5 - '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.5) - '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/core@7.28.5) + '@babel/core': 7.28.5(supports-color@8.1.1) + '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.5(supports-color@8.1.1)) + '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/core@7.28.5(supports-color@8.1.1)) '@rolldown/pluginutils': 1.0.0-beta.27 '@types/babel__core': 7.20.5 react-refresh: 0.17.0 @@ -5023,6 +5628,19 @@ snapshots: transitivePeerDependencies: - supports-color + acorn-jsx@5.3.2(acorn@8.18.0): + dependencies: + acorn: 8.18.0 + + acorn@8.18.0: {} + + ajv@6.15.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + ansi-regex@5.0.1: {} ansi-styles@4.3.0: @@ -5037,8 +5655,21 @@ snapshots: bail@2.0.2: {} + balanced-match@1.0.2: {} + + balanced-match@4.0.4: {} + baseline-browser-mapping@2.9.19: {} + brace-expansion@1.1.18: + dependencies: + balanced-match: 1.0.2 + concat-map: 0.0.1 + + brace-expansion@5.0.9: + dependencies: + balanced-match: 4.0.4 + browserslist@4.28.0: dependencies: baseline-browser-mapping: 2.9.19 @@ -5047,6 +5678,8 @@ snapshots: node-releases: 2.0.27 update-browserslist-db: 1.1.4(browserslist@4.28.0) + callsites@3.1.0: {} + camelize@1.0.1: {} caniuse-lite@1.0.30001756: {} @@ -5112,6 +5745,8 @@ snapshots: comma-separated-tokens@2.0.3: {} + concat-map@0.0.1: {} + concurrently@9.2.1: dependencies: chalk: 4.1.2 @@ -5127,6 +5762,12 @@ snapshots: crelt@1.0.6: {} + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + css-color-keywords@1.0.0: {} css-to-react-native@3.2.0: @@ -5210,9 +5851,11 @@ snapshots: date-fns@4.2.1: {} - debug@4.4.3: + debug@4.4.3(supports-color@8.1.1): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 8.1.1 decimal.js-light@2.5.1: {} @@ -5220,6 +5863,8 @@ snapshots: dependencies: character-entities: 2.0.2 + deep-is@0.1.4: {} + dequal@2.0.3: {} detect-libc@2.1.2: {} @@ -5279,18 +5924,114 @@ snapshots: escape-string-regexp@4.0.0: {} + eslint-config-prettier@10.1.8(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1)): + dependencies: + eslint: 9.39.5(jiti@2.6.1)(supports-color@8.1.1) + + eslint-scope@8.4.0: + dependencies: + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-visitor-keys@3.4.3: {} + + eslint-visitor-keys@4.2.1: {} + + eslint-visitor-keys@5.0.1: {} + + eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1): + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1)) + '@eslint-community/regexpp': 4.12.2 + '@eslint/config-array': 0.21.2(supports-color@8.1.1) + '@eslint/config-helpers': 0.4.2 + '@eslint/core': 0.17.0 + '@eslint/eslintrc': 3.3.7(supports-color@8.1.1) + '@eslint/js': 9.39.5 + '@eslint/plugin-kit': 0.4.1 + '@humanfs/node': 0.16.8 + '@humanwhocodes/module-importer': 1.0.1 + '@humanwhocodes/retry': 0.4.3 + '@types/estree': 1.0.8 + ajv: 6.15.0 + chalk: 4.1.2 + cross-spawn: 7.0.6 + debug: 4.4.3(supports-color@8.1.1) + escape-string-regexp: 4.0.0 + eslint-scope: 8.4.0 + eslint-visitor-keys: 4.2.1 + espree: 10.4.0 + esquery: 1.7.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 8.0.0 + find-up: 5.0.0 + glob-parent: 6.0.2 + ignore: 5.3.2 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + json-stable-stringify-without-jsonify: 1.0.1 + lodash.merge: 4.6.2 + minimatch: 3.1.5 + natural-compare: 1.4.0 + optionator: 0.9.4 + optionalDependencies: + jiti: 2.6.1 + transitivePeerDependencies: + - supports-color + + espree@10.4.0: + dependencies: + acorn: 8.18.0 + acorn-jsx: 5.3.2(acorn@8.18.0) + eslint-visitor-keys: 4.2.1 + + esquery@1.7.0: + dependencies: + estraverse: 5.3.0 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@5.3.0: {} + estree-util-is-identifier-name@3.0.0: {} + esutils@2.0.3: {} + eventemitter3@4.0.7: {} extend@3.0.2: {} + fast-deep-equal@3.1.3: {} + fast-equals@5.4.0: {} + fast-json-stable-stringify@2.1.0: {} + + fast-levenshtein@2.0.6: {} + fdir@6.5.0(picomatch@4.0.3): optionalDependencies: picomatch: 4.0.3 + file-entry-cache@8.0.0: + dependencies: + flat-cache: 4.0.1 + + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flat-cache@4.0.1: + dependencies: + flatted: 3.4.4 + keyv: 4.5.4 + + flatted@3.4.4: {} + fractional-indexing@3.2.0: {} fsevents@2.3.3: @@ -5302,6 +6043,14 @@ snapshots: get-nonce@1.0.1: {} + glob-parent@6.0.2: + dependencies: + is-glob: 4.0.3 + + globals@14.0.0: {} + + globals@16.5.0: {} + graceful-fs@4.2.11: {} graphlib@2.1.8: @@ -5310,7 +6059,7 @@ snapshots: has-flag@4.0.0: {} - hast-util-to-jsx-runtime@2.3.6: + hast-util-to-jsx-runtime@2.3.6(supports-color@8.1.1): dependencies: '@types/estree': 1.0.8 '@types/hast': 3.0.4 @@ -5319,9 +6068,9 @@ snapshots: devlop: 1.1.0 estree-util-is-identifier-name: 3.0.0 hast-util-whitespace: 3.0.0 - mdast-util-mdx-expression: 2.0.1 - mdast-util-mdx-jsx: 3.2.0 - mdast-util-mdxjs-esm: 2.0.1 + mdast-util-mdx-expression: 2.0.1(supports-color@8.1.1) + mdast-util-mdx-jsx: 3.2.0(supports-color@8.1.1) + mdast-util-mdxjs-esm: 2.0.1(supports-color@8.1.1) property-information: 7.2.0 space-separated-tokens: 2.0.2 style-to-js: 1.1.21 @@ -5342,6 +6091,17 @@ snapshots: idb@7.1.1: {} + ignore@5.3.2: {} + + ignore@7.0.9: {} + + import-fresh@3.3.1: + dependencies: + parent-module: 1.0.1 + resolve-from: 4.0.0 + + imurmurhash@0.1.4: {} + inline-style-parser@0.2.7: {} internmap@2.0.3: {} @@ -5355,14 +6115,22 @@ snapshots: is-decimal@2.0.1: {} + is-extglob@2.1.1: {} + is-fullwidth-code-point@3.0.0: {} + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + is-hexadecimal@2.0.1: {} is-plain-obj@4.1.0: {} is-plain-object@5.0.0: {} + isexe@2.0.0: {} + jiti@2.6.1: {} jittered-fractional-indexing@1.0.1: @@ -5371,10 +6139,29 @@ snapshots: js-tokens@4.0.0: {} + js-yaml@4.3.2: + dependencies: + argparse: 2.0.1 + jsesc@3.1.0: {} + json-buffer@3.0.1: {} + + json-schema-traverse@0.4.1: {} + + json-stable-stringify-without-jsonify@1.0.1: {} + json5@2.2.3: {} + keyv@4.5.4: + dependencies: + json-buffer: 3.0.1 + + levn@0.4.1: + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + lightningcss-android-arm64@1.31.1: optional: true @@ -5430,10 +6217,16 @@ snapshots: linkifyjs@4.3.2: {} + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + lodash.isequal@4.5.0: {} lodash.isequalwith@4.4.0: {} + lodash.merge@4.6.2: {} + lodash.throttle@4.1.1: {} lodash.uniq@4.5.0: {} @@ -5469,14 +6262,14 @@ snapshots: punycode.js: 2.3.1 uc.micro: 2.1.0 - mdast-util-from-markdown@2.0.3: + mdast-util-from-markdown@2.0.3(supports-color@8.1.1): dependencies: '@types/mdast': 4.0.4 '@types/unist': 3.0.3 decode-named-character-reference: 1.3.0 devlop: 1.1.0 mdast-util-to-string: 4.0.0 - micromark: 4.0.2 + micromark: 4.0.2(supports-color@8.1.1) micromark-util-decode-numeric-character-reference: 2.0.2 micromark-util-decode-string: 2.0.1 micromark-util-normalize-identifier: 2.0.1 @@ -5486,18 +6279,18 @@ snapshots: transitivePeerDependencies: - supports-color - mdast-util-mdx-expression@2.0.1: + mdast-util-mdx-expression@2.0.1(supports-color@8.1.1): dependencies: '@types/estree-jsx': 1.0.5 '@types/hast': 3.0.4 '@types/mdast': 4.0.4 devlop: 1.1.0 - mdast-util-from-markdown: 2.0.3 + mdast-util-from-markdown: 2.0.3(supports-color@8.1.1) mdast-util-to-markdown: 2.1.2 transitivePeerDependencies: - supports-color - mdast-util-mdx-jsx@3.2.0: + mdast-util-mdx-jsx@3.2.0(supports-color@8.1.1): dependencies: '@types/estree-jsx': 1.0.5 '@types/hast': 3.0.4 @@ -5505,7 +6298,7 @@ snapshots: '@types/unist': 3.0.3 ccount: 2.0.1 devlop: 1.1.0 - mdast-util-from-markdown: 2.0.3 + mdast-util-from-markdown: 2.0.3(supports-color@8.1.1) mdast-util-to-markdown: 2.1.2 parse-entities: 4.0.2 stringify-entities: 4.0.4 @@ -5514,13 +6307,13 @@ snapshots: transitivePeerDependencies: - supports-color - mdast-util-mdxjs-esm@2.0.1: + mdast-util-mdxjs-esm@2.0.1(supports-color@8.1.1): dependencies: '@types/estree-jsx': 1.0.5 '@types/hast': 3.0.4 '@types/mdast': 4.0.4 devlop: 1.1.0 - mdast-util-from-markdown: 2.0.3 + mdast-util-from-markdown: 2.0.3(supports-color@8.1.1) mdast-util-to-markdown: 2.1.2 transitivePeerDependencies: - supports-color @@ -5671,10 +6464,10 @@ snapshots: micromark-util-types@2.0.2: {} - micromark@4.0.2: + micromark@4.0.2(supports-color@8.1.1): dependencies: '@types/debug': 4.1.13 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) decode-named-character-reference: 1.3.0 devlop: 1.1.0 micromark-core-commonmark: 2.0.3 @@ -5693,10 +6486,20 @@ snapshots: transitivePeerDependencies: - supports-color + minimatch@10.2.6: + dependencies: + brace-expansion: 5.0.9 + + minimatch@3.1.5: + dependencies: + brace-expansion: 1.1.18 + ms@2.1.3: {} nanoid@3.3.11: {} + natural-compare@1.4.0: {} + next-themes@0.4.6(react-dom@19.2.3(react@19.2.3))(react@19.2.3): dependencies: react: 19.2.3 @@ -5706,8 +6509,29 @@ snapshots: object-assign@4.1.1: {} + optionator@0.9.4: + dependencies: + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + word-wrap: 1.2.5 + orderedmap@2.1.1: {} + p-limit@3.1.0: + dependencies: + yocto-queue: 0.1.0 + + p-locate@5.0.0: + dependencies: + p-limit: 3.1.0 + + parent-module@1.0.1: + dependencies: + callsites: 3.1.0 + parse-entities@4.0.2: dependencies: '@types/unist': 2.0.11 @@ -5718,6 +6542,10 @@ snapshots: is-decimal: 2.0.1 is-hexadecimal: 2.0.1 + path-exists@4.0.0: {} + + path-key@3.1.1: {} + picocolors@1.1.1: {} picomatch@4.0.3: {} @@ -5736,6 +6564,10 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 + prelude-ls@1.2.1: {} + + prettier@3.9.6: {} + prop-types@15.8.1: dependencies: loose-envify: 1.4.0 @@ -5849,6 +6681,8 @@ snapshots: punycode.js@2.3.1: {} + punycode@2.3.1: {} + quickselect@2.0.0: {} radix-ui@1.4.3(@types/react-dom@19.2.3(@types/react@19.2.8))(@types/react@19.2.8)(react-dom@19.2.3(react@19.2.3))(react@19.2.3): @@ -5927,17 +6761,17 @@ snapshots: react-is@18.3.1: {} - react-markdown@10.1.0(@types/react@19.2.8)(react@19.2.3): + react-markdown@10.1.0(@types/react@19.2.8)(react@19.2.3)(supports-color@8.1.1): dependencies: '@types/hast': 3.0.4 '@types/mdast': 4.0.4 '@types/react': 19.2.8 devlop: 1.1.0 - hast-util-to-jsx-runtime: 2.3.6 + hast-util-to-jsx-runtime: 2.3.6(supports-color@8.1.1) html-url-attributes: 3.0.1 mdast-util-to-hast: 13.2.1 react: 19.2.3 - remark-parse: 11.0.0 + remark-parse: 11.0.0(supports-color@8.1.1) remark-rehype: 11.1.2 unified: 11.0.5 unist-util-visit: 5.1.0 @@ -6038,10 +6872,10 @@ snapshots: tiny-invariant: 1.3.3 victory-vendor: 36.9.2 - remark-parse@11.0.0: + remark-parse@11.0.0(supports-color@8.1.1): dependencies: '@types/mdast': 4.0.4 - mdast-util-from-markdown: 2.0.3 + mdast-util-from-markdown: 2.0.3(supports-color@8.1.1) micromark-util-types: 2.0.2 unified: 11.0.5 transitivePeerDependencies: @@ -6057,6 +6891,8 @@ snapshots: require-directory@2.1.1: {} + resolve-from@4.0.0: {} + rollup@4.59.0: dependencies: '@types/estree': 1.0.8 @@ -6098,10 +6934,18 @@ snapshots: semver@6.3.1: {} + semver@7.8.5: {} + set-cookie-parser@2.7.2: {} shallowequal@1.1.0: {} + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + shell-quote@1.8.3: {} sonner@2.0.7(react-dom@19.2.3(react@19.2.3))(react@19.2.3): @@ -6128,6 +6972,8 @@ snapshots: dependencies: ansi-regex: 5.0.1 + strip-json-comments@3.1.1: {} + style-mod@4.1.3: {} style-to-js@1.1.21: @@ -6204,12 +7050,31 @@ snapshots: trough@2.2.0: {} + ts-api-utils@2.5.0(typescript@5.8.3): + dependencies: + typescript: 5.8.3 + tslib@2.6.2: {} tslib@2.8.1: {} tw-animate-css@1.4.0: {} + type-check@0.4.0: + dependencies: + prelude-ls: 1.2.1 + + typescript-eslint@8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3): + dependencies: + '@typescript-eslint/eslint-plugin': 8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3))(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3) + '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@8.1.1)(typescript@5.8.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.6.1)(supports-color@8.1.1))(supports-color@8.1.1)(typescript@5.8.3) + eslint: 9.39.5(jiti@2.6.1)(supports-color@8.1.1) + typescript: 5.8.3 + transitivePeerDependencies: + - supports-color + typescript@5.8.3: {} uc.micro@2.1.0: {} @@ -6255,6 +7120,10 @@ snapshots: escalade: 3.2.0 picocolors: 1.1.1 + uri-js@4.4.1: + dependencies: + punycode: 2.3.1 + use-callback-ref@1.3.3(@types/react@19.2.8)(react@19.2.3): dependencies: react: 19.2.3 @@ -6317,6 +7186,12 @@ snapshots: w3c-keyname@2.2.8: {} + which@2.0.2: + dependencies: + isexe: 2.0.0 + + word-wrap@1.2.5: {} + wrap-ansi@7.0.0: dependencies: ansi-styles: 4.3.0 @@ -6339,6 +7214,8 @@ snapshots: y18n: 5.0.8 yargs-parser: 21.1.1 + yocto-queue@0.1.0: {} + zustand@4.5.7(@types/react@19.2.8)(react@19.2.3): dependencies: use-sync-external-store: 1.6.0(react@19.2.3) From 70bed7dc535ade6458a193a0e0aa58dcc0e170e0 Mon Sep 17 00:00:00 2001 From: Yash Date: Sat, 12 Sep 2026 18:14:58 +0530 Subject: [PATCH 2/4] refac: formatted the complete codebase --- .github/workflows/test.yml | 5 +- AGENTS.md | 3 + ARCHITECTURE.md | 101 +- CLAUDE.md | 6 +- DECISIONS.md | 16 +- FEATURES.md | 135 +- bridge/__tests__/connectionBuilder.test.ts | 28 +- .../connectors/mariadb.cache.test.ts | 604 ++-- bridge/__tests__/connectors/mariadb.test.ts | 139 +- .../__tests__/connectors/mysql.cache.test.ts | 26 +- bridge/__tests__/connectors/mysql.test.ts | 6 +- .../connectors/postgres.cache.test.ts | 394 ++- bridge/__tests__/connectors/postgres.test.ts | 18 +- .../__tests__/connectors/sqlite.cache.test.ts | 104 +- bridge/__tests__/connectors/sqlite.test.ts | 123 +- bridge/__tests__/databaseService.test.ts | 34 +- bridge/__tests__/dbStore.test.ts | 25 +- bridge/__tests__/discoveryService.test.ts | 648 ++-- bridge/__tests__/gitAdvancedHandlers.test.ts | 482 ++- bridge/__tests__/gitHandlers.test.ts | 714 ++--- bridge/__tests__/gitService.test.ts | 944 +++--- bridge/__tests__/importProject.test.ts | 1734 ++++++----- bridge/__tests__/monitoringHandlers.test.ts | 159 +- .../monitoringWebSocketServer.test.ts | 270 +- bridge/__tests__/projectStore.test.ts | 1258 ++++---- bridge/__tests__/schemaContext.test.ts | 144 +- bridge/__tests__/sqlValidator.test.ts | 36 +- .../sshTunnelService.integration.test.ts | 202 +- bridge/__tests__/sshTunnelService.test.ts | 8 +- bridge/package.json | 2 +- bridge/scripts/build-pkg.js | 4 +- bridge/scripts/copy-native.js | 15 +- bridge/src/ai/README.md | 5 + bridge/src/ai/prompts/chart-recommendation.ts | 6 +- bridge/src/ai/prompts/nl-sql-interpreter.ts | 6 +- bridge/src/ai/prompts/nl-sql.ts | 16 +- bridge/src/ai/prompts/query-explanation.ts | 17 +- bridge/src/ai/prompts/schema-analysis.ts | 2 +- bridge/src/ai/providers/anthropic.provider.ts | 5 +- bridge/src/ai/providers/gemini.provider.ts | 5 +- bridge/src/ai/providers/groq.provider.ts | 5 +- bridge/src/ai/providers/mistral.provider.ts | 5 +- bridge/src/ai/providers/ollama.provider.ts | 5 +- bridge/src/ai/providers/openai.provider.ts | 5 +- bridge/src/ai/providers/types.ts | 21 +- bridge/src/ai/utils/schemaContext.ts | 16 +- bridge/src/ai/utils/sqlValidator.ts | 14 +- bridge/src/connectors/README.md | 4 + bridge/src/connectors/mariadb.ts | 2689 ++++++++-------- bridge/src/connectors/mysql.ts | 275 +- bridge/src/connectors/postgres.ts | 311 +- bridge/src/connectors/sqlite.ts | 323 +- bridge/src/handlers/README.md | 4 + bridge/src/handlers/aiHandlers.ts | 52 +- bridge/src/handlers/databaseHandlers.ts | 14 +- bridge/src/handlers/gitAdvancedHandlers.ts | 320 +- bridge/src/handlers/gitHandlers.ts | 472 ++- bridge/src/handlers/migrationHandlers.ts | 1000 +++--- bridge/src/handlers/monitoringHandlers.ts | 2 +- bridge/src/handlers/projectHandlers.ts | 1862 +++++------ bridge/src/handlers/queryHandlers.ts | 114 +- bridge/src/handlers/sessionHandlers.ts | 89 +- bridge/src/handlers/statsHandlers.ts | 8 +- bridge/src/index.ts | 4 +- bridge/src/jsonRpc.ts | 241 +- bridge/src/jsonRpcHandler.ts | 299 +- bridge/src/queries/README.md | 4 + bridge/src/queries/index.ts | 8 +- bridge/src/queries/mysql/crud.ts | 32 +- bridge/src/queries/mysql/index.ts | 14 +- bridge/src/queries/postgres/crud.ts | 26 +- bridge/src/queries/postgres/index.ts | 12 +- bridge/src/queries/sqlite/constraints.ts | 2 +- bridge/src/queries/sqlite/crud.ts | 25 +- bridge/src/queries/sqlite/index.ts | 12 +- bridge/src/queries/sqlite/tables.ts | 4 +- bridge/src/services/README.md | 4 + bridge/src/services/ai.impl.ts | 12 +- bridge/src/services/aiCacheService.ts | 13 +- bridge/src/services/aiHistoryStore.ts | 17 +- bridge/src/services/connectionBuilder.ts | 16 +- bridge/src/services/databaseService.ts | 17 +- bridge/src/services/dbStore.ts | 47 +- bridge/src/services/discoveryService.ts | 103 +- bridge/src/services/gitService.ts | 2363 +++++++------- bridge/src/services/logger.ts | 2 +- bridge/src/services/migrationLock.ts | 62 +- bridge/src/services/monitoringService.ts | 31 +- .../src/services/monitoringWebSocketServer.ts | 27 +- bridge/src/services/nlSqlService.ts | 140 +- bridge/src/services/projectStore.ts | 2732 ++++++++--------- bridge/src/services/queryExecutor.ts | 4 +- bridge/src/services/sshTunnelService.ts | 4 +- bridge/src/sessionManager.ts | 14 +- bridge/src/types/README.md | 4 + bridge/src/types/ai.ts | 8 +- bridge/src/types/cache.ts | 6 +- bridge/src/types/common.ts | 134 +- bridge/src/types/index.ts | 56 +- bridge/src/types/mysql.ts | 78 +- bridge/src/types/postgres.ts | 82 +- bridge/src/types/sqlite.ts | 44 +- bridge/src/utils/README.md | 4 + bridge/src/utils/baselineMigration.ts | 242 +- bridge/src/utils/config.ts | 10 +- bridge/src/utils/dbTypeDetector.ts | 2 +- bridge/src/utils/lruCache.ts | 2 +- bridge/src/utils/migrationFileReader.ts | 89 +- bridge/src/utils/migrationGenerator.ts | 495 ++- scripts/package-bridge.mjs | 11 +- src-tauri/capabilities/default.json | 6 +- src-tauri/tauri.conf.json | 20 +- src/App.css | 56 +- src/components/dev/DeveloperContextMenu.tsx | 94 +- src/components/dev/RemoteConfigDialog.tsx | 451 ++- src/components/feedback/BridgeFailed.tsx | 38 +- src/components/feedback/BridgeLoader.tsx | 20 +- src/components/layout/BridgeStatus.tsx | 29 +- src/components/layout/CommandPalette.tsx | 116 +- src/components/layout/SlideOutPanel.tsx | 97 +- src/components/layout/TitleBar.tsx | 152 +- src/components/layout/VerticalIconBar.tsx | 233 +- src/components/providers/ThemeProvider.tsx | 165 +- src/components/shared/CommandPalette.tsx | 210 +- src/components/shared/ConfirmDialog.tsx | 96 +- src/components/shared/DataTable.tsx | 65 +- .../shared/FloatingActionButton.tsx | 66 +- src/components/shared/InputDialog.tsx | 6 +- src/components/shared/ShortcutsHelp.tsx | 15 +- src/components/shared/ShortcutsTrigger.tsx | 10 +- src/components/shared/UpdateNotification.tsx | 10 +- src/components/shared/WhatsNewDialog.tsx | 36 +- src/components/ui/SQLPreviewSheet.tsx | 2 +- src/components/ui/alert-dialog.tsx | 70 +- src/components/ui/alert.tsx | 7 +- src/components/ui/badge.tsx | 33 +- src/components/ui/button.tsx | 26 +- src/components/ui/card.tsx | 43 +- src/components/ui/chart.tsx | 185 +- src/components/ui/checkbox.tsx | 19 +- src/components/ui/collapsible.tsx | 24 +- src/components/ui/context-menu.tsx | 102 +- src/components/ui/dialog.tsx | 62 +- src/components/ui/dropdown-menu.tsx | 101 +- src/components/ui/empty.tsx | 40 +- src/components/ui/input.tsx | 18 +- src/components/ui/label.tsx | 17 +- src/components/ui/pagination.tsx | 61 +- src/components/ui/progress.tsx | 19 +- src/components/ui/radio-group.tsx | 16 +- src/components/ui/scroll-area.tsx | 20 +- src/components/ui/select.tsx | 69 +- src/components/ui/separator.tsx | 12 +- src/components/ui/sheet.tsx | 55 +- src/components/ui/skeleton.tsx | 6 +- src/components/ui/sonner.tsx | 20 +- src/components/ui/spinner.tsx | 8 +- src/components/ui/switch.tsx | 19 +- src/components/ui/table.tsx | 60 +- src/components/ui/tabs.tsx | 40 +- src/components/ui/textarea.tsx | 17 +- src/components/ui/tooltip.tsx | 26 +- .../ai/components/AIHistoryDetailDialog.tsx | 96 +- src/features/ai/components/AIHistoryPanel.tsx | 40 +- src/features/ai/components/AIResultDialog.tsx | 80 +- .../chart/components/ChartConfigPanel.tsx | 248 +- .../chart/components/ChartRenderer.tsx | 419 ++- .../chart/components/ChartVisualization.tsx | 70 +- src/features/chart/components/index.ts | 6 +- .../chart/hooks/useChartVisualization.ts | 294 +- .../database/components/AIWorkspacePanel.tsx | 27 +- .../components/ContentViewerPanel.tsx | 405 ++- .../database/components/DataViewPanel.tsx | 435 +-- .../database/components/DatabaseErrorView.tsx | 66 +- .../database/components/EditRowDialog.tsx | 236 +- .../components/ExpandableBottomPanel.tsx | 89 +- .../database/components/InsertDataDialog.tsx | 369 ++- .../database/components/MigrationsPanel.tsx | 501 +-- .../MigrationsPanelLoadingState.tsx | 109 +- .../components/TablesExplorerPanel.tsx | 364 +-- src/features/database/components/index.ts | 2 +- src/features/database/hooks/useCachedData.ts | 25 +- .../database/hooks/useDatabaseDetailPage.ts | 56 +- .../database/hooks/useDatabaseDetails.ts | 670 ++-- .../database/hooks/useDatabaseStats.ts | 104 +- .../database/hooks/useDiscoveredDatabases.ts | 60 +- src/features/database/hooks/useEditDialog.ts | 234 +- src/features/database/hooks/useExport.ts | 20 +- .../database/hooks/useInsertDataDialog.ts | 445 +-- .../database/hooks/useMigrationsPanel.ts | 233 +- .../database/hooks/useRowOperations.ts | 345 ++- .../database/hooks/useSelectedDbStats.ts | 48 +- .../database/hooks/useTableExplorerPanel.ts | 110 +- .../database/hooks/useWelcomeMessage.ts | 70 +- src/features/database/types.ts | 398 +-- .../er-diagram/components/AnnotationLayer.tsx | 156 +- .../components/ERDiagramContent.tsx | 1325 ++++---- .../components/ERDiagramLoadingState.tsx | 112 +- .../er-diagram/components/ERDiagramPanel.tsx | 18 +- .../er-diagram/components/TableNode.tsx | 370 +-- src/features/er-diagram/components/index.ts | 4 +- .../er-diagram/hooks/useERDiagramData.ts | 253 +- src/features/er-diagram/types.ts | 28 +- .../git/components/GitHistoryGraph.tsx | 815 ++--- src/features/git/components/GitStatusBar.tsx | 919 +++--- .../git/components/GitStatusPanel.tsx | 979 +++--- .../components/GitStatusPanelLoadingState.tsx | 155 +- src/features/git/hooks/useGitAdvanced.ts | 177 +- src/features/git/hooks/useGitQueries.ts | 209 +- src/features/git/types.ts | 108 +- .../home/components/AddConnectionDialog.tsx | 314 +- .../home/components/ConnectionDetails.tsx | 88 +- .../home/components/ConnectionList.tsx | 815 ++--- .../home/components/DatabaseOverviewPanel.tsx | 316 +- .../home/components/DatabasePreview.tsx | 321 +- .../components/DeleteConnectionDialog.tsx | 340 +- src/features/home/components/DeleteDialog.tsx | 10 +- .../components/DiscoveredDatabasesCard.tsx | 302 +- .../home/components/MigrationStatusCard.tsx | 23 +- src/features/home/components/WelcomeView.tsx | 121 +- .../home/hooks/useConnectionGroups.ts | 150 +- src/features/home/hooks/useCountUp.ts | 10 +- .../home/hooks/useDeleteConnection.ts | 171 +- src/features/home/hooks/useIndexPage.ts | 632 ++-- src/features/home/types.ts | 170 +- .../monitoring/components/MetricCard.tsx | 72 +- .../components/MonitoringDashboard.tsx | 313 +- .../components/MonitoringLoadingState.tsx | 123 +- .../monitoring/components/MonitoringPanel.tsx | 219 +- .../monitoring/hooks/useMonitoringStream.ts | 184 +- .../components/ImportProjectDialog.tsx | 59 +- .../components/MigrationSyncDialog.tsx | 106 +- .../project/components/SchemaDriftSheet.tsx | 47 +- .../components/UnlinkedProjectItem.tsx | 156 +- src/features/project/hooks/useDbQueries.ts | 18 +- .../project/hooks/useImportAnalysis.ts | 56 +- .../project/hooks/useProjectQueries.ts | 31 +- src/features/project/hooks/useProjectSync.ts | 201 +- src/features/project/types.ts | 2 +- .../components/BuilderHeader.tsx | 103 +- .../components/BuilderSidebar.tsx | 828 +++-- .../components/BuilderStatusBar.tsx | 54 +- .../components/DiagramCanvas.tsx | 208 +- .../components/QueryBuilderPanel.tsx | 801 +++-- .../QueryBuilderPanelLoadingState.tsx | 150 +- .../components/SQLResultsPanel.tsx | 100 +- .../query-builder/components/index.ts | 34 +- .../query-builder/hooks/useQueryHistory.ts | 102 +- src/features/query-builder/types.ts | 144 +- .../components/AddIndexesDialog.tsx | 249 +- .../components/AlterTableDialog.tsx | 837 ++--- .../components/AnalyzeSchemaButton.tsx | 2 +- .../components/CreateTableDialog.tsx | 184 +- .../components/DropTableDialog.tsx | 265 +- .../components/ForeignKeyRow.tsx | 306 +- .../schema-explorer/components/IndexRow.tsx | 248 +- .../components/MetaDataPanel.tsx | 126 +- .../components/SchemaExplorerHeader.tsx | 281 +- .../components/SchemaExplorerPanel.tsx | 304 +- .../SchemaExplorerPanelLoadingState.tsx | 188 +- .../components/TableDesignerForm.tsx | 452 +-- .../schema-explorer/components/index.ts | 36 +- .../components/metadata/ColumnDetails.tsx | 260 +- .../components/metadata/DatabaseDetails.tsx | 154 +- .../components/metadata/OtherDetails.tsx | 120 +- .../components/metadata/SchemaDetails.tsx | 228 +- .../components/metadata/TableDetails.tsx | 697 ++--- .../components/metadata/index.ts | 10 +- .../hooks/useAddIndexDialog.ts | 282 +- .../hooks/useAlterTableDialog.ts | 258 +- .../hooks/useCreateTableDialog.ts | 386 +-- .../hooks/useDropTableDialog.ts | 154 +- .../hooks/useSchemaExplorerData.ts | 251 +- .../hooks/useSchemaExplorerPanel.ts | 238 +- .../hooks/useTableDesignerForm.ts | 139 +- src/features/schema-explorer/types.ts | 36 +- .../settings/components/AISettings.tsx | 195 +- .../settings/components/AnalyticsSettings.tsx | 135 +- .../settings/components/CheckForUpdates.tsx | 224 +- .../settings/components/ColorVariant.tsx | 110 +- .../settings/components/DeveloperMode.tsx | 73 +- src/features/settings/components/Header.tsx | 26 +- .../settings/components/SettingsDialog.tsx | 65 +- .../settings/components/ThemeMode.tsx | 60 +- src/features/settings/components/Version.tsx | 41 +- src/features/settings/components/index.tsx | 18 +- src/features/settings/hooks/useDevMode.ts | 20 +- .../settings/hooks/useDevModeKeyboard.ts | 42 +- .../settings/hooks/useDeveloperMode.ts | 44 +- .../settings/hooks/useThemeVariant.ts | 225 +- src/features/settings/hooks/useUpdater.ts | 26 +- .../settings/hooks/useWebviewActions.ts | 80 +- src/features/tree/ColumnTreeItem.tsx | 176 +- src/features/tree/SchemaExtras.tsx | 169 +- src/features/tree/TableTreeItem.tsx | 223 +- src/features/tree/TreeViewPanel.tsx | 285 +- src/features/tree/index.ts | 2 +- .../components/ExplainQueryButton.tsx | 10 +- .../workspace/components/NLQueryDialog.tsx | 18 +- .../workspace/components/QueryTabBar.tsx | 127 +- .../workspace/components/ResultsPanel.tsx | 127 +- .../components/SQLWorkspacePanel.tsx | 480 +-- .../SQLWorkspacePanelLoadingState.tsx | 111 +- .../workspace/components/SqlEditor.tsx | 6 +- .../workspace/components/StatusBar.tsx | 44 +- .../workspace/components/WorkspaceHeader.tsx | 146 +- .../workspace/components/WorkspaceSidebar.tsx | 297 +- src/features/workspace/components/index.ts | 14 +- src/features/workspace/types.ts | 28 +- src/lib/bytesToMB.ts | 2 +- src/lib/dataExport.ts | 12 +- src/lib/parseConnectionUrl.ts | 214 +- src/lib/schemaConverters.ts | 98 +- src/lib/schemaTransformer.ts | 38 +- src/lib/themes.ts | 703 ++--- src/lib/utils.ts | 27 +- src/main.tsx | 46 +- src/pages/DatabaseDetails.tsx | 63 +- src/pages/Index.tsx | 326 +- src/pages/NotFound.tsx | 24 +- src/services/analytics.ts | 156 +- src/services/bridge/ai.ts | 16 +- src/services/bridge/bridge.ts | 61 +- src/services/bridge/bridgeClient.ts | 140 +- src/services/bridge/database.ts | 1113 +++---- src/services/bridge/git.ts | 421 +-- src/services/bridge/migration.ts | 201 +- src/services/bridge/project.ts | 993 +++--- src/services/bridge/query.ts | 108 +- src/services/bridge/session.ts | 74 +- src/services/bridge/useBridgeInit.ts | 2 +- 331 files changed, 31497 insertions(+), 30680 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0ebd8da6..ca5ba518 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -108,12 +108,12 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v4 with: - version: 10 # aligned with release workflow + version: 10 # aligned with release workflow - name: Setup Node uses: actions/setup-node@v6 with: - node-version: 22 # aligned with release workflow, not lts/* + node-version: 22 # aligned with release workflow, not lts/* cache: "pnpm" - name: Install bridge dependencies @@ -137,4 +137,3 @@ jobs: run: | cd bridge pnpm test - \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index 36475f55..627a286c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,6 +13,7 @@ RelWave uses a **Bridge Architecture** to balance performance, security, and dev ## 🛠️ Tech Stack ### Frontend + - **Framework:** React 19 - **Build Tool:** Vite - **Styling:** Tailwind CSS 4, shadcn/ui (Radix UI) @@ -21,6 +22,7 @@ RelWave uses a **Bridge Architecture** to balance performance, security, and dev - **Editor:** CodeMirror 6 (SQL editing) ### Bridge (Node.js) + - **Runtime:** Node.js (bundled via `pkg`) - **Database Drivers:** `pg` (PostgreSQL), `mysql2` (MySQL/MariaDB), `better-sqlite3` (SQLite) - **Version Control:** `simple-git` @@ -28,6 +30,7 @@ RelWave uses a **Bridge Architecture** to balance performance, security, and dev - **Security:** `@napi-rs/keyring` for encrypted credential storage ### Desktop Layer + - **Framework:** Tauri 2 (Rust) ## 📂 Key Directories diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 35e26dbe..9803df9c 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -6,9 +6,9 @@ RelWave is a cross-platform desktop database visualizer built with a high-perfor RelWave consists of three distinct layers that communicate over a JSON-RPC protocol: -* **Frontend (React/TypeScript):** A modern, responsive UI built with Vite, Tailwind CSS (optional), and Lucide icons. It manages state using TanStack Query and coordinates with the bridge via a service layer. -* **Bridge (Node.js):** A standalone backend bundled with `pkg`. It handles all heavy-lifting tasks: database connectivity (PostgreSQL, MySQL, MariaDB, SQLite), Git version control, and file system operations. -* **Tauri (Rust):** The native shell that hosts the web view and manages the bridge as a sidecar process. It acts as a secure pipe, forwarding standard I/O between the Frontend and the Bridge. +- **Frontend (React/TypeScript):** A modern, responsive UI built with Vite, Tailwind CSS (optional), and Lucide icons. It manages state using TanStack Query and coordinates with the bridge via a service layer. +- **Bridge (Node.js):** A standalone backend bundled with `pkg`. It handles all heavy-lifting tasks: database connectivity (PostgreSQL, MySQL, MariaDB, SQLite), Git version control, and file system operations. +- **Tauri (Rust):** The native shell that hosts the web view and manages the bridge as a sidecar process. It acts as a secure pipe, forwarding standard I/O between the Frontend and the Bridge. ### Data Flow Diagram @@ -29,31 +29,40 @@ Databases / Git / Filesystem The bridge is the core engine of RelWave, designed to be fast, extensible, and isolated from the UI. ### JSON-RPC Dispatcher + The communication follows a standard JSON-RPC 2.0 pattern over `stdin` and `stdout`. + 1. **Entry Point (`bridge/src/index.ts`):** Initializes the `JsonStdio` instance and registers all handlers. 2. **Protocol (`bridge/src/jsonRpc.ts`):** `JsonStdio` handles framing (newline-delimited JSON) and provides `sendResponse`, `sendError`, and `sendNotification`. 3. **Dispatcher (`bridge/src/jsonRpcHandler.ts`):** The `JsonRpcHandler` maps incoming method names (e.g., `db.list`) to specific handler functions. ### Adding a New Command + To add a new command, follow these steps: + 1. Define the request/response types in `bridge/src/types/`. 2. Implement the logic in a relevant handler (e.g., `bridge/src/handlers/databaseHandlers.ts`) or create a new handler in `bridge/src/handlers/`. 3. Register the new handler/method in `bridge/src/jsonRpcHandler.ts` inside the `registerDbHandlers` function. 4. Add a corresponding method to the frontend service layer in `src/services/bridge/`. ### Session Management (`bridge/src/sessionManager.ts`) + The `SessionManager` tracks active operations, particularly long-running queries. -* Each query runs in a `Session`. -* Sessions store a `cancel` callback and a `connectionId`. -* A background sweep timer removes stale sessions (default 30 min idle). + +- Each query runs in a `Session`. +- Sessions store a `cancel` callback and a `connectionId`. +- A background sweep timer removes stale sessions (default 30 min idle). ### Connection Pooling (`bridge/src/services/connectionPool.ts`) + The `ConnectionPool` manages engine-specific connections. -* Connections are keyed by `dbId`. -* The `ConnectionPool` uses the `ConnectorRegistry` to obtain the correct connector (Postgres, MySQL, etc.). -* Idle connections are automatically swept after 10 minutes. + +- Connections are keyed by `dbId`. +- The `ConnectionPool` uses the `ConnectorRegistry` to obtain the correct connector (Postgres, MySQL, etc.). +- Idle connections are automatically swept after 10 minutes. ### Connector Registry (`bridge/src/services/connectorRegistry.ts`) + A mapping of `DBType` to engine implementations. This decoupling allows adding new database support by simply implementing the `Connector` interface. --- @@ -63,31 +72,37 @@ A mapping of `DBType` to engine implementations. This decoupling allows adding n The frontend is designed for speed and reliability, using a "local-first" philosophy where possible. ### Feature Structure + Features are modularly organized under `src/features/[feature-name]/`: -* `types.ts`: TypeScript definitions for the feature. -* `hooks/`: Feature-specific hooks (often wrapping TanStack Query). -* `components/`: UI components. -* `index.ts`: Public API for the feature. + +- `types.ts`: TypeScript definitions for the feature. +- `hooks/`: Feature-specific hooks (often wrapping TanStack Query). +- `components/`: UI components. +- `index.ts`: Public API for the feature. ### Bridge Service Layer + The frontend talks to the bridge through specialized services in `src/services/bridge/`: -* `bridgeClient.ts`: Low-level wrapper for `invoke('bridge_write')` and `listen('bridge-stdout')`. -* `database.ts`, `query.ts`, `git.ts`, etc.: High-level methods that wrap `bridgeRequest`. + +- `bridgeClient.ts`: Low-level wrapper for `invoke('bridge_write')` and `listen('bridge-stdout')`. +- `database.ts`, `query.ts`, `git.ts`, etc.: High-level methods that wrap `bridgeRequest`. ### State Management -* **TanStack Query:** Used for almost all bridge-related state. It handles caching, loading states, and automatic refetching. -* **React Context:** Used for global UI state (themes, active connection). + +- **TanStack Query:** Used for almost all bridge-related state. It handles caching, loading states, and automatic refetching. +- **React Context:** Used for global UI state (themes, active connection). --- ## 4. Database Query Organization Queries are organized by engine under `bridge/src/queries/`: -* **`constraints.ts`:** Introspection for PKs, FKs, and indexes. -* **`schema.ts`:** Listing tables, schemas, and databases. -* **`stats.ts`:** Database size, row counts, and performance metrics. -* **`crud.ts`:** Row-level operations (Insert, Update, Delete, Search). -* **`migrations.ts`:** Schema migration management. + +- **`constraints.ts`:** Introspection for PKs, FKs, and indexes. +- **`schema.ts`:** Listing tables, schemas, and databases. +- **`stats.ts`:** Database size, row counts, and performance metrics. +- **`crud.ts`:** Row-level operations (Insert, Update, Delete, Search). +- **`migrations.ts`:** Schema migration management. This engine-specific organization avoids the "leaky abstraction" problem of generic ORMs and allows RelWave to use powerful native features (like Postgres' `pg_query_stream` or MySQL's `KILL QUERY`). @@ -96,22 +111,23 @@ This engine-specific organization avoids the "leaky abstraction" problem of gene ## 5. Adding a New Feature (End-to-End Checklist) 1. **Bridge Logic:** - * [ ] Add types to `bridge/src/types/`. - * [ ] (If needed) Add SQL queries to `bridge/src/queries/[engine]/`. - * [ ] Add method to a service in `bridge/src/services/`. - * [ ] Implement RPC method in `bridge/src/handlers/`. - * [ ] Register in `bridge/src/jsonRpcHandler.ts`. + - [ ] Add types to `bridge/src/types/`. + - [ ] (If needed) Add SQL queries to `bridge/src/queries/[engine]/`. + - [ ] Add method to a service in `bridge/src/services/`. + - [ ] Implement RPC method in `bridge/src/handlers/`. + - [ ] Register in `bridge/src/jsonRpcHandler.ts`. 2. **Frontend Logic:** - * [ ] Add bridge call to `src/services/bridge/[service].ts`. - * [ ] Create a hook in `src/features/[feature]/hooks/` using `useQuery` or `useMutation`. - * [ ] Implement UI components in `src/features/[feature]/components/`. - * [ ] Integrate into a page or the main layout. + - [ ] Add bridge call to `src/services/bridge/[service].ts`. + - [ ] Create a hook in `src/features/[feature]/hooks/` using `useQuery` or `useMutation`. + - [ ] Implement UI components in `src/features/[feature]/components/`. + - [ ] Integrate into a page or the main layout. --- ## 6. Key Data Flows ### Connect to a Database + 1. **UI:** User enters credentials and clicks "Connect". 2. **Frontend:** `databaseService.addDatabase` calls `bridgeRequest('db.add', params)`. 3. **Bridge:** `DatabaseHandlers.add` calls `DatabaseService.addDatabase`. @@ -119,6 +135,7 @@ This engine-specific organization avoids the "leaky abstraction" problem of gene 5. **Response:** The new `dbId` is returned to the UI. ### Execute a SQL Query and Stream Results + 1. **UI:** User executes SQL in the query editor. 2. **Frontend:** `queryService.runQuery` calls `bridgeRequest('query.run', { sql, sessionId, dbId })`. 3. **Bridge:** `QueryHandlers.run` initializes a `Session`. @@ -127,12 +144,14 @@ This engine-specific organization avoids the "leaky abstraction" problem of gene 6. **Frontend:** `bridgeClient` listens for these events and dispatches them to the UI. ### Run a Migration + 1. **UI:** User selects a pending migration and clicks "Apply". 2. **Frontend:** `migrationService.apply` calls `bridgeRequest('migration.apply', { connectionId, filename })`. 3. **Bridge:** `MigrationHandlers.apply` calls `DatabaseService` to get the connection and then calls `applyMigration` in the engine connector (e.g., `postgres.ts`). 4. **Connector:** Reads the `.sql` file, executes the `+up` section in a transaction, and records the version in `schema_migrations`. ### Monitor a live database metric + 1. **UI:** User opens the "Monitoring" tab for a database. 2. **Frontend:** Opens a WebSocket connection to the bridge via `MonitoringWebSocketServer`. 3. **Bridge:** `MonitoringService` starts a ticker that periodically queries the DB for metrics (health, active queries, throughput). @@ -144,16 +163,20 @@ This engine-specific organization avoids the "leaky abstraction" problem of gene ## 7. Testing ### Organization -* **Bridge Unit Tests:** Located in `bridge/__tests__/`. Focus on services and utils. -* **Bridge Integration Tests:** Located in `bridge/__tests__/connectors/`. Test actual DB connectivity. + +- **Bridge Unit Tests:** Located in `bridge/__tests__/`. Focus on services and utils. +- **Bridge Integration Tests:** Located in `bridge/__tests__/connectors/`. Test actual DB connectivity. ### Running Tests -* `npm test`: Runs all bridge tests. -* `npm run test:watch`: Runs tests in watch mode. + +- `npm test`: Runs all bridge tests. +- `npm run test:watch`: Runs tests in watch mode. ### Docker Compose Test Setup + `bridge/docker-compose.test.yml` provides a standard environment with: -* PostgreSQL 16 -* MySQL 8.0 -* MariaDB 11.2 -Used for end-to-end connector validation. + +- PostgreSQL 16 +- MySQL 8.0 +- MariaDB 11.2 + Used for end-to-end connector validation. diff --git a/CLAUDE.md b/CLAUDE.md index bd754248..52cb9b1b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3,11 +3,12 @@ Welcome, Claude. This document outlines project-specific instructions and preferences to help you provide the best possible assistance. ## 🎯 High-Level Goals + RelWave is a modern, high-performance database management tool. Our priority is a seamless developer experience, visual clarity, and rock-solid reliability. ## 🛠️ Code Style & Preferences -- **React:** +- **React:** - Use functional components with hooks. - Prefer TanStack Query for data fetching and state synchronization. - Use `lucide-react` for icons. @@ -25,6 +26,7 @@ RelWave is a modern, high-performance database management tool. Our priority is ## 🌉 The Bridge Protocol When implementing a new feature that requires the Bridge: + 1. **Define the Interface:** Decide on the JSON-RPC method name and parameters. 2. **Bridge Handler:** Add a handler in `bridge/src/handlers/`. 3. **Bridge Service:** Implement the logic in a service within `bridge/src/services/`. @@ -46,4 +48,4 @@ When implementing a new feature that requires the Bridge: - **No browser-only APIs:** Remember this runs in a desktop environment. - **No heavy logic in handlers:** Handlers should just route requests to services. -- **No direct DB calls from Frontend:** All database interaction *must* go through the bridge. +- **No direct DB calls from Frontend:** All database interaction _must_ go through the bridge. diff --git a/DECISIONS.md b/DECISIONS.md index 3bb66ea0..3b341c33 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -5,61 +5,73 @@ This document records the non-obvious architectural decisions in the RelWave cod --- ## 1. Node.js sidecar over native Tauri Rust commands for DB access + **What:** Using a standalone Node.js process (the "Bridge") to handle database drivers instead of writing them in Rust. **Why:** The JavaScript ecosystem has extremely mature, well-tested, and performant database drivers (e.g., `pg`, `mysql2`, `better-sqlite3`). Re-implementing these or integrating their Rust counterparts would have significantly increased complexity and slowed development. **Trade-off:** Higher memory overhead due to a separate Node.js runtime and the need for a serialization layer (JSON-RPC) between the UI and the driver. ## 2. JSON-RPC over stdin/stdout as the bridge protocol + **What:** Choosing standard input/output streams with newline-delimited JSON-RPC 2.0 as the communication channel. **Why:** It is a language-agnostic, lightweight, and reliable way to communicate between the Tauri host and the Node.js sidecar without the overhead of a network socket or the security risks of an open port. **Trade-off:** Limited to string-based communication; binary data must be base64-encoded, which increases payload size. ## 3. better-sqlite3 (synchronous) over async SQLite drivers + **What:** Using the `better-sqlite3` library which executes queries synchronously. **Why:** `better-sqlite3` is significantly faster than asynchronous alternatives like `sqlite3`. Since the bridge is already a separate process, its synchronous nature does not block the main UI thread. **Trade-off:** The bridge event loop is blocked during heavy SQLite operations, which is why the bridge uses a separate process per query session for other engines (but SQLite is still limited by file locks). ## 4. Per-engine query modules instead of a single abstracted query layer + **What:** Organizing SQL queries into engine-specific files (e.g., `queries/postgres`, `queries/mysql`) rather than using a generic ORM or abstraction layer. **Why:** Every database engine has unique introspection queries, metadata structures, and performance optimizations. A single abstraction layer often results in "lowest common denominator" features or overly complex "leaky" abstractions. **Trade-off:** More boilerplate when adding a new engine, as similar queries must be implemented multiple times. ## 5. Custom AES-256-CBC encryption for credential storage + **What:** Implementing a custom encryption layer for passwords using Node.js `crypto` module, stored in a local `.credentials` file. -**Why:** Provides a consistent, cross-platform way to protect sensitive database passwords without requiring platform-specific native dependencies during initial development. -**Trade-off:** Not as secure as using the system-native keychain (like Windows Credential Manager or macOS Keychain). *Note: `@napi-rs/keyring` is present in package.json for future migration.* +**Why:** Provides a consistent, cross-platform way to protect sensitive database passwords without requiring platform-specific native dependencies during initial development. +**Trade-off:** Not as secure as using the system-native keychain (like Windows Credential Manager or macOS Keychain). _Note: `@napi-rs/keyring` is present in package.json for future migration._ ## 6. Shelling out to the git binary over a library + **What:** Using `child_process.execFile` to run `git` commands directly instead of using a library like `simple-git`. **Why:** Minimizes dependencies and ensures that the user's existing Git configuration and version are respected. It also avoids the performance overhead of a large JS wrapper. **Trade-off:** Requires the user to have Git installed and on their system PATH. ## 7. React Query (TanStack Query) for all bridge call state + **What:** Using TanStack Query as the primary mechanism for managing data fetched from the bridge. **Why:** It provides "out-of-the-box" support for caching, deduplication of concurrent requests, loading/error states, and background refetching, which is essential for a data-heavy application. **Trade-off:** Adds a layer of complexity to the frontend and requires a specific mental model for data management. ## 8. pino for logging in the bridge + **What:** Using the `pino` logger and redirecting its output to `stderr`. **Why:** High-performance, low-overhead logging. By using `stderr` (via `pino.destination(2)`), logs do not interfere with the JSON-RPC messages on `stdout`. **Trade-off:** Log levels must be filtered on the Tauri side to prevent flooding the developer console. ## 9. pkg for bundling the Node.js bridge into a single binary + **What:** Using `@yao-pkg/pkg` to compile the Node.js bridge into a standalone executable. **Why:** Simplifies distribution by ensuring the user does not need to have Node.js installed on their machine. It also protects the source code of the bridge to some extent. **Trade-off:** Increases the size of the final application bundle and can be tricky to configure for native modules like `better-sqlite3`. ## 10. The connector registry pattern + **What:** A centralized registry (`connectorRegistry.ts`) that maps database types to their connector implementations. **Why:** Decouples the RPC handlers from the specific engine logic. This makes it trivial to add support for new databases (like ClickHouse or DuckDB) without modifying the core handler logic. **Trade-off:** Requires a strict interface (`Connector`) that all database engines must adhere to. ## 11. Session-based event filtering for streaming query results + **What:** Tagging streaming notifications (like `query.batch`) with a `sessionId`. **Why:** Allows the frontend to distinguish between results from multiple concurrent queries running in different tabs or windows. **Trade-off:** Requires the frontend to maintain a mapping of active sessions and their corresponding UI components. ## 12. Separate monitoring connection pool + **What:** Using a dedicated connection pool for the `MonitoringService` that is independent of the main query pool. **Why:** Ensures that we can still collect database metrics even if the main connection pool is exhausted or if a query is currently blocking the connection. **Trade-off:** Increases the number of active connections to the database server. diff --git a/FEATURES.md b/FEATURES.md index 2df8aaf8..c39833d2 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -23,12 +23,12 @@ This document provides a comprehensive breakdown of all features and capabilitie ## Supported Databases -| Database | Connection Type | Schema Explorer | ER Diagram | Query Builder | Migrations | CRUD | -| -------- | --------------- | --------------- | ---------- | ------------- | ---------- | ---- | -| PostgreSQL | Host/port + SSL | ✅ | ✅ | ✅ | ✅ | ✅ | -| MySQL | Host/port + SSL | ✅ | ✅ | ✅ | ✅ | ✅ | -| MariaDB | Host/port + SSL | ✅ | ✅ | ✅ | ✅ | ✅ | -| SQLite | Local file path | ✅ | ✅ | ✅ | ✅ | ✅ | +| Database | Connection Type | Schema Explorer | ER Diagram | Query Builder | Migrations | CRUD | +| ---------- | --------------- | --------------- | ---------- | ------------- | ---------- | ---- | +| PostgreSQL | Host/port + SSL | ✅ | ✅ | ✅ | ✅ | ✅ | +| MySQL | Host/port + SSL | ✅ | ✅ | ✅ | ✅ | ✅ | +| MariaDB | Host/port + SSL | ✅ | ✅ | ✅ | ✅ | ✅ | +| SQLite | Local file path | ✅ | ✅ | ✅ | ✅ | ✅ | ### SQLite-Specific Features @@ -99,6 +99,7 @@ The main landing page for managing database connections. Features a clean, IDE-i Detailed view for individual database operations with a split-panel layout. **Layout:** + - Left panel — Tables Explorer with collapsible table list - Right panel — Content Viewer with data table, pagination, and actions - Slide-out panels — Chart visualization and migrations @@ -171,6 +172,7 @@ Detailed view for individual database operations with a split-panel layout. A full IDE-style SQL editor for writing and executing queries. **Layout:** + - Top bar — database breadcrumb, execution status, Run/Stop buttons - Left sidebar — collapsible with Tables and History sections - Main area — split between editor (top) and results (bottom) @@ -214,6 +216,7 @@ A full IDE-style SQL editor for writing and executing queries. Visual SQL query builder with drag-and-drop canvas. **Layout:** + - Top bar — database breadcrumb, Generate and Execute buttons, progress indicator - Left sidebar — collapsible Explorer with Tables, Configuration, and History - Main canvas — ReactFlow diagram for visual table relationships @@ -303,11 +306,11 @@ Interactive entity-relationship diagram visualization. - Automatic table node generation with column and type information - Minimap for large diagrams - Pan, zoom, and fit-to-screen controls -### 7. Settings +### 7. Settings - Light, dark, and system-preference (auto) modes -**Accent Colors** + **Accent Colors** - Multiple color variants: Blue (default), Purple, Green, Pink, Orange, and more - Visual color preview with live UI element updates - Persistent preferences @@ -324,52 +327,52 @@ RelWave includes native Git integration powered by `simple-git`, providing a ful ### Core Operations -| Operation | Description | -| --------- | ----------- | -| `git.status` | Repository status including branch, dirty state, ahead/behind counts | -| `git.init` | Initialize a new repository with configurable default branch | -| `git.changes` | List all changed files with status indicators | -| `git.stage` | Stage specific files for commit | -| `git.stageAll` | Stage all changed files | -| `git.unstage` | Unstage files from the index | -| `git.commit` | Commit staged changes with a message | -| `git.log` | View recent commit history | -| `git.diff` | View file-level diff output | -| `git.discard` | Discard changes to specific files | +| Operation | Description | +| -------------- | -------------------------------------------------------------------- | +| `git.status` | Repository status including branch, dirty state, ahead/behind counts | +| `git.init` | Initialize a new repository with configurable default branch | +| `git.changes` | List all changed files with status indicators | +| `git.stage` | Stage specific files for commit | +| `git.stageAll` | Stage all changed files | +| `git.unstage` | Unstage files from the index | +| `git.commit` | Commit staged changes with a message | +| `git.log` | View recent commit history | +| `git.diff` | View file-level diff output | +| `git.discard` | Discard changes to specific files | ### Branch Management -| Operation | Description | -| --------- | ----------- | -| `git.branches` | List all local branches | +| Operation | Description | +| ------------------ | -------------------------------- | +| `git.branches` | List all local branches | | `git.createBranch` | Create and checkout a new branch | -| `git.checkout` | Switch to an existing branch | +| `git.checkout` | Switch to an existing branch | ### Stash Operations -| Operation | Description | -| --------- | ----------- | -| `git.stash` | Stash current work-in-progress changes | -| `git.stashPop` | Restore the most recent stash | +| Operation | Description | +| -------------- | -------------------------------------- | +| `git.stash` | Stash current work-in-progress changes | +| `git.stashPop` | Restore the most recent stash | ### Remote Management -| Operation | Description | -| --------- | ----------- | -| `git.remoteList` | List all configured remotes | -| `git.remoteAdd` | Add a new remote with name and URL | -| `git.remoteRemove` | Remove an existing remote | -| `git.remoteGetUrl` | Get the URL of a remote | -| `git.remoteSetUrl` | Update the URL of a remote | +| Operation | Description | +| ------------------ | ---------------------------------- | +| `git.remoteList` | List all configured remotes | +| `git.remoteAdd` | Add a new remote with name and URL | +| `git.remoteRemove` | Remove an existing remote | +| `git.remoteGetUrl` | Get the URL of a remote | +| `git.remoteSetUrl` | Update the URL of a remote | ### Sync Operations -| Operation | Description | -| --------- | ----------- | -| `git.push` | Push commits to a remote repository | -| `git.pull` | Pull changes from a remote repository | -| `git.fetch` | Fetch updates from a remote without merging | -| `git.revert` | Revert a specific commit | +| Operation | Description | +| ------------ | ------------------------------------------- | +| `git.push` | Push commits to a remote repository | +| `git.pull` | Pull changes from a remote repository | +| `git.fetch` | Fetch updates from a remote without merging | +| `git.revert` | Revert a specific commit | ### Additional Features @@ -384,7 +387,9 @@ RelWave includes native Git integration powered by `simple-git`, providing a ful RelWave integrates deeply with multiple Large Language Models (LLMs) to provide intelligent database assistance, schema analysis, and query explanations. ### Supported Providers + The application supports a flexible, multi-provider AI architecture: + - **OpenAI** (GPT-4o, GPT-4 Turbo, etc.) - **Anthropic** (Claude 3.5 Sonnet, Opus, etc.) - **Mistral** (Mistral Large, Mistral Small, etc.) @@ -393,13 +398,14 @@ The application supports a flexible, multi-provider AI architecture: - **Google Gemini** (Gemini 1.5 Pro, Flash) ### AI Capabilities -| Feature | Description | -| ------- | ----------- | -| **Schema Analysis** | Analyzes the structure of your database, identifying relationships, potential optimizations, and providing a human-readable summary of complex schemas. Uses a highly optimized, token-efficient dense schema representation. | -| **Query Explanation** | Breaks down complex SQL queries into plain English, explaining joins, filters, performance implications, and the overall intent of the query. | -| **Local AI Support** | Full privacy and zero-cost inference available through local Ollama integration, ensuring sensitive database schemas never leave your machine. | -| **Context Aware** | The AI system automatically receives the dialect (PostgreSQL, MySQL, SQLite) and the relevant database schema context to provide accurate, dialect-specific responses. | -| **High Token Capacity** | Configured with large output windows (up to 4096 tokens) to handle extensive schema analyses and complex query breakdowns without truncation. | + +| Feature | Description | +| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Schema Analysis** | Analyzes the structure of your database, identifying relationships, potential optimizations, and providing a human-readable summary of complex schemas. Uses a highly optimized, token-efficient dense schema representation. | +| **Query Explanation** | Breaks down complex SQL queries into plain English, explaining joins, filters, performance implications, and the overall intent of the query. | +| **Local AI Support** | Full privacy and zero-cost inference available through local Ollama integration, ensuring sensitive database schemas never leave your machine. | +| **Context Aware** | The AI system automatically receives the dialect (PostgreSQL, MySQL, SQLite) and the relevant database schema context to provide accurate, dialect-specific responses. | +| **High Token Capacity** | Configured with large output windows (up to 4096 tokens) to handle extensive schema analyses and complex query breakdowns without truncation. | --- @@ -472,6 +478,7 @@ SELECT 1; - PostgreSQL exposes statistics via `pg_stat_database` and `pg_stat_activity` for live query and transaction counts. Postgres example — total transactions: + ```sql SELECT xact_commit + xact_rollback AS total_transactions FROM pg_stat_database @@ -479,6 +486,7 @@ WHERE datname = 'your_db_name'; ``` MySQL/MariaDB example — queries counter: + ```sql SHOW GLOBAL STATUS LIKE 'Queries'; ``` @@ -486,6 +494,7 @@ SHOW GLOBAL STATUS LIKE 'Queries'; ### 3. Active Connections (Gauge) Postgres: + ```sql SELECT (SELECT count(*) FROM pg_stat_activity) AS active_connections, @@ -493,6 +502,7 @@ SELECT ``` MySQL/MariaDB: + ```sql SHOW GLOBAL STATUS LIKE 'Threads_connected'; SHOW VARIABLES LIKE 'max_connections'; @@ -510,6 +520,7 @@ For Postgres the cache hit ratio is: $$\text{Cache Hit Ratio} = \left( \frac{\text{blks\_hit}}{\text{blks\_read} + \text{blks\_hit}} \right) \times 100$$ SQL example: + ```sql SELECT datname, @@ -535,32 +546,36 @@ $$\text{Buffer Pool Hit Ratio} = \left( 1 - \frac{\text{Innodb\_buffer\_pool\_re ### Layout Components **Title Bar (Tauri)** + - 32px fixed height, draggable area for window movement - Native minimize, maximize, and close buttons - Proper z-index layering -**Vertical Icon Bar** + - Fixed 60px left sidebar with navigation icons - Pages: Home, Settings, SQL Workspace, Query Builder, Schema Explorer, ER Diagram, Monitoring - Active state indicators and tooltip labels **Slide-Out Panels** + - Right-side panels for charts and migrations - Backdrop overlay with click-to-close - Smooth slide animation **Collapsible Sidebars** + - Toggle to collapse/expand with smooth width transition - Persistent state across sessions ### Database Engine Colors -| Engine | Color | -| ------ | ----- | -| PostgreSQL | Blue | -| MySQL | Orange | -| MariaDB | Purple | -| SQLite | Cyan | +| Engine | Color | +| ---------- | ------ | +| PostgreSQL | Blue | +| MySQL | Orange | +| MariaDB | Purple | +| SQLite | Cyan | ### Theming @@ -628,12 +643,12 @@ All database and Git operations use a JSON-RPC protocol over stdin/stdout. The b ### Caching Strategy -| Layer | Purpose | -| ----- | ------- | -| React Query | API response caching | -| localStorage | User preferences and theme settings | -| Session storage | Temporary data and session state | -| Query history | Persistent query log | +| Layer | Purpose | +| --------------- | ----------------------------------- | +| React Query | API response caching | +| localStorage | User preferences and theme settings | +| Session storage | Temporary data and session state | +| Query history | Persistent query log | --- diff --git a/bridge/__tests__/connectionBuilder.test.ts b/bridge/__tests__/connectionBuilder.test.ts index 9734139f..13736f9d 100644 --- a/bridge/__tests__/connectionBuilder.test.ts +++ b/bridge/__tests__/connectionBuilder.test.ts @@ -34,7 +34,7 @@ describe("ConnectionBuilder", () => { const { config } = await ConnectionBuilder.buildConnection( dbInput, password, - DBType.POSTGRES + DBType.POSTGRES, ); // Assert @@ -56,11 +56,7 @@ describe("ConnectionBuilder", () => { }; // Act - const { config } = await ConnectionBuilder.buildConnection( - dbInput, - password, - DBType.MYSQL - ); + const { config } = await ConnectionBuilder.buildConnection(dbInput, password, DBType.MYSQL); // Assert expect(config).toEqual(expected); @@ -84,7 +80,7 @@ describe("ConnectionBuilder", () => { const { config } = await ConnectionBuilder.buildConnection( dbInput, password, - DBType.POSTGRES + DBType.POSTGRES, ); // Assert @@ -98,11 +94,7 @@ describe("ConnectionBuilder", () => { const password = "any_pwd"; // Act - const { config } = await ConnectionBuilder.buildConnection( - dbInput, - password, - DBType.MYSQL - ); + const { config } = await ConnectionBuilder.buildConnection(dbInput, password, DBType.MYSQL); // Assert expect((config as DatabaseConfig).port).toBe(3306); @@ -115,10 +107,7 @@ describe("ConnectionBuilder", () => { // Test Case 5: Ensure buildPostgresConnection calls buildConnection correctly test("should delegate to buildConnection with DBType.POSTGRES and use default port", async () => { // Act - const { config } = await ConnectionBuilder.buildPostgresConnection( - mockDbInput, - "test" - ); + const { config } = await ConnectionBuilder.buildPostgresConnection(mockDbInput, "test"); // Assert expect((config as DatabaseConfig).port).toBe(5432); @@ -130,10 +119,7 @@ describe("ConnectionBuilder", () => { // Test Case 6: Ensure buildMySQLConnection calls buildConnection correctly test("should delegate to buildConnection with DBType.MYSQL and use default port", async () => { // Act - const { config } = await ConnectionBuilder.buildMySQLConnection( - mockDbInput, - "test" - ); + const { config } = await ConnectionBuilder.buildMySQLConnection(mockDbInput, "test"); // Assert expect((config as DatabaseConfig).port).toBe(3306); @@ -183,7 +169,7 @@ describe("ConnectionBuilder", () => { test("should reject Windows drive roots for SQLite", async () => { const dbInput = { database: "D:/" }; await expect(ConnectionBuilder.buildSQLiteConnection(dbInput)).rejects.toThrow( - 'Invalid SQLite path "D:/"' + 'Invalid SQLite path "D:/"', ); }); diff --git a/bridge/__tests__/connectors/mariadb.cache.test.ts b/bridge/__tests__/connectors/mariadb.cache.test.ts index 8f99d4d4..3bae2e2c 100644 --- a/bridge/__tests__/connectors/mariadb.cache.test.ts +++ b/bridge/__tests__/connectors/mariadb.cache.test.ts @@ -3,343 +3,369 @@ import { mariadbCache } from "../../src/connectors/mariadb"; // Mock MariaDB config for testing const mockConfig = { - host: "localhost", - port: 3306, - user: "testuser", - password: "testpass", - database: "testdb", + host: "localhost", + port: 3306, + user: "testuser", + password: "testpass", + database: "testdb", }; const mockConfig2 = { - host: "localhost", - port: 3306, - user: "testuser", - password: "testpass", - database: "otherdb", + host: "localhost", + port: 3306, + user: "testuser", + password: "testpass", + database: "otherdb", }; describe("MariaDB Cache Manager", () => { - beforeEach(() => { - // Clear all caches before each test - mariadbCache.clearAll(); + beforeEach(() => { + // Clear all caches before each test + mariadbCache.clearAll(); + }); + + describe("Table List Cache", () => { + test("should return null for uncached table list", () => { + const result = mariadbCache.getTableList(mockConfig); + expect(result).toBeNull(); }); - describe("Table List Cache", () => { - test("should return null for uncached table list", () => { - const result = mariadbCache.getTableList(mockConfig); - expect(result).toBeNull(); - }); + test("should cache and retrieve table list", () => { + const tableData = [ + { schema: "testdb", name: "users", type: "BASE TABLE" }, + { schema: "testdb", name: "orders", type: "BASE TABLE" }, + ]; - test("should cache and retrieve table list", () => { - const tableData = [ - { schema: "testdb", name: "users", type: "BASE TABLE" }, - { schema: "testdb", name: "orders", type: "BASE TABLE" }, - ]; + mariadbCache.setTableList(mockConfig, tableData); + const cached = mariadbCache.getTableList(mockConfig); - mariadbCache.setTableList(mockConfig, tableData); - const cached = mariadbCache.getTableList(mockConfig); + expect(cached).toEqual(tableData); + }); - expect(cached).toEqual(tableData); - }); + test("should cache table list with schema", () => { + const tableData = [{ schema: "myschema", name: "products", type: "BASE TABLE" }]; - test("should cache table list with schema", () => { - const tableData = [ - { schema: "myschema", name: "products", type: "BASE TABLE" }, - ]; + mariadbCache.setTableList(mockConfig, tableData, "myschema"); + const cached = mariadbCache.getTableList(mockConfig, "myschema"); - mariadbCache.setTableList(mockConfig, tableData, "myschema"); - const cached = mariadbCache.getTableList(mockConfig, "myschema"); + expect(cached).toEqual(tableData); + }); - expect(cached).toEqual(tableData); - }); + test("should separate caches for different schemas", () => { + const schema1Data = [{ schema: "schema1", name: "table1", type: "BASE TABLE" }]; + const schema2Data = [{ schema: "schema2", name: "table2", type: "BASE TABLE" }]; - test("should separate caches for different schemas", () => { - const schema1Data = [{ schema: "schema1", name: "table1", type: "BASE TABLE" }]; - const schema2Data = [{ schema: "schema2", name: "table2", type: "BASE TABLE" }]; + mariadbCache.setTableList(mockConfig, schema1Data, "schema1"); + mariadbCache.setTableList(mockConfig, schema2Data, "schema2"); - mariadbCache.setTableList(mockConfig, schema1Data, "schema1"); - mariadbCache.setTableList(mockConfig, schema2Data, "schema2"); + expect(mariadbCache.getTableList(mockConfig, "schema1")).toEqual(schema1Data); + expect(mariadbCache.getTableList(mockConfig, "schema2")).toEqual(schema2Data); + }); + }); - expect(mariadbCache.getTableList(mockConfig, "schema1")).toEqual(schema1Data); - expect(mariadbCache.getTableList(mockConfig, "schema2")).toEqual(schema2Data); - }); + describe("Columns Cache", () => { + test("should return null for uncached columns", () => { + const result = mariadbCache.getColumns(mockConfig, "testdb", "users"); + expect(result).toBeNull(); }); - describe("Columns Cache", () => { - test("should return null for uncached columns", () => { - const result = mariadbCache.getColumns(mockConfig, "testdb", "users"); - expect(result).toBeNull(); - }); + test("should cache and retrieve columns", () => { + const columnData = [ + { column_name: "id", data_type: "int" }, + { column_name: "name", data_type: "varchar" }, + ]; - test("should cache and retrieve columns", () => { - const columnData = [ - { column_name: "id", data_type: "int" }, - { column_name: "name", data_type: "varchar" }, - ]; + mariadbCache.setColumns(mockConfig, "testdb", "users", columnData as any); + const cached = mariadbCache.getColumns(mockConfig, "testdb", "users"); - mariadbCache.setColumns(mockConfig, "testdb", "users", columnData as any); - const cached = mariadbCache.getColumns(mockConfig, "testdb", "users"); + expect(cached).toEqual(columnData); + }); - expect(cached).toEqual(columnData); - }); + test("should separate caches for different tables", () => { + const usersColumns = [{ column_name: "id", data_type: "int" }]; + const ordersColumns = [{ column_name: "order_id", data_type: "int" }]; - test("should separate caches for different tables", () => { - const usersColumns = [{ column_name: "id", data_type: "int" }]; - const ordersColumns = [{ column_name: "order_id", data_type: "int" }]; + mariadbCache.setColumns(mockConfig, "testdb", "users", usersColumns as any); + mariadbCache.setColumns(mockConfig, "testdb", "orders", ordersColumns as any); - mariadbCache.setColumns(mockConfig, "testdb", "users", usersColumns as any); - mariadbCache.setColumns(mockConfig, "testdb", "orders", ordersColumns as any); + expect(mariadbCache.getColumns(mockConfig, "testdb", "users")).toEqual(usersColumns); + expect(mariadbCache.getColumns(mockConfig, "testdb", "orders")).toEqual(ordersColumns); + }); + }); - expect(mariadbCache.getColumns(mockConfig, "testdb", "users")).toEqual(usersColumns); - expect(mariadbCache.getColumns(mockConfig, "testdb", "orders")).toEqual(ordersColumns); - }); + describe("Primary Keys Cache", () => { + test("should return null for uncached primary keys", () => { + const result = mariadbCache.getPrimaryKeys(mockConfig, "testdb", "users"); + expect(result).toBeNull(); }); - describe("Primary Keys Cache", () => { - test("should return null for uncached primary keys", () => { - const result = mariadbCache.getPrimaryKeys(mockConfig, "testdb", "users"); - expect(result).toBeNull(); - }); + test("should cache and retrieve primary keys", () => { + const pkData = ["id", "tenant_id"]; - test("should cache and retrieve primary keys", () => { - const pkData = ["id", "tenant_id"]; + mariadbCache.setPrimaryKeys(mockConfig, "testdb", "users", pkData); + const cached = mariadbCache.getPrimaryKeys(mockConfig, "testdb", "users"); - mariadbCache.setPrimaryKeys(mockConfig, "testdb", "users", pkData); - const cached = mariadbCache.getPrimaryKeys(mockConfig, "testdb", "users"); + expect(cached).toEqual(pkData); + }); + }); - expect(cached).toEqual(pkData); - }); + describe("DB Stats Cache", () => { + test("should return null for uncached stats", () => { + const result = mariadbCache.getDBStats(mockConfig); + expect(result).toBeNull(); }); - describe("DB Stats Cache", () => { - test("should return null for uncached stats", () => { - const result = mariadbCache.getDBStats(mockConfig); - expect(result).toBeNull(); - }); + test("should cache and retrieve DB stats", () => { + const statsData = { + total_tables: 25, + total_db_size_mb: 150.5, + total_rows: 100000, + }; - test("should cache and retrieve DB stats", () => { - const statsData = { - total_tables: 25, - total_db_size_mb: 150.5, - total_rows: 100000, - }; + mariadbCache.setDBStats(mockConfig, statsData); + const cached = mariadbCache.getDBStats(mockConfig); - mariadbCache.setDBStats(mockConfig, statsData); - const cached = mariadbCache.getDBStats(mockConfig); + expect(cached).toEqual(statsData); + }); - expect(cached).toEqual(statsData); - }); + test("should separate stats for different databases", () => { + const stats1 = { total_tables: 10, total_db_size_mb: 50, total_rows: 1000 }; + const stats2 = { total_tables: 20, total_db_size_mb: 100, total_rows: 5000 }; - test("should separate stats for different databases", () => { - const stats1 = { total_tables: 10, total_db_size_mb: 50, total_rows: 1000 }; - const stats2 = { total_tables: 20, total_db_size_mb: 100, total_rows: 5000 }; + mariadbCache.setDBStats(mockConfig, stats1); + mariadbCache.setDBStats(mockConfig2, stats2); - mariadbCache.setDBStats(mockConfig, stats1); - mariadbCache.setDBStats(mockConfig2, stats2); + expect(mariadbCache.getDBStats(mockConfig)).toEqual(stats1); + expect(mariadbCache.getDBStats(mockConfig2)).toEqual(stats2); + }); + }); - expect(mariadbCache.getDBStats(mockConfig)).toEqual(stats1); - expect(mariadbCache.getDBStats(mockConfig2)).toEqual(stats2); - }); + describe("Schemas Cache", () => { + test("should return null for uncached schemas", () => { + const result = mariadbCache.getSchemas(mockConfig); + expect(result).toBeNull(); }); - describe("Schemas Cache", () => { - test("should return null for uncached schemas", () => { - const result = mariadbCache.getSchemas(mockConfig); - expect(result).toBeNull(); - }); + test("should cache and retrieve schemas", () => { + const schemaData = [{ name: "testdb" }, { name: "production" }, { name: "staging" }]; + + mariadbCache.setSchemas(mockConfig, schemaData); + const cached = mariadbCache.getSchemas(mockConfig); - test("should cache and retrieve schemas", () => { - const schemaData = [ - { name: "testdb" }, - { name: "production" }, - { name: "staging" }, - ]; + expect(cached).toEqual(schemaData); + }); + }); - mariadbCache.setSchemas(mockConfig, schemaData); - const cached = mariadbCache.getSchemas(mockConfig); + describe("Table Details Cache", () => { + test("should return null for uncached table details", () => { + const result = mariadbCache.getTableDetails(mockConfig, "testdb", "users"); + expect(result).toBeNull(); + }); - expect(cached).toEqual(schemaData); - }); + test("should cache and retrieve table details", () => { + const detailsData = [ + { + name: "id", + type: "int", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }, + { + name: "email", + type: "varchar", + not_nullable: true, + default_value: null, + is_primary_key: false, + is_foreign_key: false, + }, + ]; + + mariadbCache.setTableDetails(mockConfig, "testdb", "users", detailsData); + const cached = mariadbCache.getTableDetails(mockConfig, "testdb", "users"); + + expect(cached).toEqual(detailsData); + }); + }); + + describe("Cache Management", () => { + test("should clear all caches for a connection", () => { + // Set up various caches + mariadbCache.setTableList(mockConfig, [{ schema: "testdb", name: "t1", type: "BASE TABLE" }]); + mariadbCache.setColumns(mockConfig, "testdb", "t1", [ + { column_name: "id", data_type: "int" }, + ] as any); + mariadbCache.setPrimaryKeys(mockConfig, "testdb", "t1", ["id"]); + mariadbCache.setDBStats(mockConfig, { + total_tables: 1, + total_db_size_mb: 1, + total_rows: 100, + }); + mariadbCache.setSchemas(mockConfig, [{ name: "testdb" }]); + mariadbCache.setTableDetails(mockConfig, "testdb", "t1", []); + + // Clear for this connection + mariadbCache.clearForConnection(mockConfig); + + // All should be null + expect(mariadbCache.getTableList(mockConfig)).toBeNull(); + expect(mariadbCache.getColumns(mockConfig, "testdb", "t1")).toBeNull(); + expect(mariadbCache.getPrimaryKeys(mockConfig, "testdb", "t1")).toBeNull(); + expect(mariadbCache.getDBStats(mockConfig)).toBeNull(); + expect(mariadbCache.getSchemas(mockConfig)).toBeNull(); + expect(mariadbCache.getTableDetails(mockConfig, "testdb", "t1")).toBeNull(); }); - describe("Table Details Cache", () => { - test("should return null for uncached table details", () => { - const result = mariadbCache.getTableDetails(mockConfig, "testdb", "users"); - expect(result).toBeNull(); - }); - - test("should cache and retrieve table details", () => { - const detailsData = [ - { - name: "id", - type: "int", - not_nullable: true, - default_value: null, - is_primary_key: true, - is_foreign_key: false, - }, - { - name: "email", - type: "varchar", - not_nullable: true, - default_value: null, - is_primary_key: false, - is_foreign_key: false, - }, - ]; - - mariadbCache.setTableDetails(mockConfig, "testdb", "users", detailsData); - const cached = mariadbCache.getTableDetails(mockConfig, "testdb", "users"); - - expect(cached).toEqual(detailsData); - }); + test("should not affect other connections when clearing", () => { + // Set up caches for both configs + mariadbCache.setDBStats(mockConfig, { + total_tables: 1, + total_db_size_mb: 1, + total_rows: 100, + }); + mariadbCache.setDBStats(mockConfig2, { + total_tables: 2, + total_db_size_mb: 2, + total_rows: 200, + }); + + // Clear only first connection + mariadbCache.clearForConnection(mockConfig); + + // First should be null, second should still exist + expect(mariadbCache.getDBStats(mockConfig)).toBeNull(); + expect(mariadbCache.getDBStats(mockConfig2)).toEqual({ + total_tables: 2, + total_db_size_mb: 2, + total_rows: 200, + }); }); - describe("Cache Management", () => { - test("should clear all caches for a connection", () => { - // Set up various caches - mariadbCache.setTableList(mockConfig, [{ schema: "testdb", name: "t1", type: "BASE TABLE" }]); - mariadbCache.setColumns(mockConfig, "testdb", "t1", [{ column_name: "id", data_type: "int" }] as any); - mariadbCache.setPrimaryKeys(mockConfig, "testdb", "t1", ["id"]); - mariadbCache.setDBStats(mockConfig, { total_tables: 1, total_db_size_mb: 1, total_rows: 100 }); - mariadbCache.setSchemas(mockConfig, [{ name: "testdb" }]); - mariadbCache.setTableDetails(mockConfig, "testdb", "t1", []); - - // Clear for this connection - mariadbCache.clearForConnection(mockConfig); - - // All should be null - expect(mariadbCache.getTableList(mockConfig)).toBeNull(); - expect(mariadbCache.getColumns(mockConfig, "testdb", "t1")).toBeNull(); - expect(mariadbCache.getPrimaryKeys(mockConfig, "testdb", "t1")).toBeNull(); - expect(mariadbCache.getDBStats(mockConfig)).toBeNull(); - expect(mariadbCache.getSchemas(mockConfig)).toBeNull(); - expect(mariadbCache.getTableDetails(mockConfig, "testdb", "t1")).toBeNull(); - }); - - test("should not affect other connections when clearing", () => { - // Set up caches for both configs - mariadbCache.setDBStats(mockConfig, { total_tables: 1, total_db_size_mb: 1, total_rows: 100 }); - mariadbCache.setDBStats(mockConfig2, { total_tables: 2, total_db_size_mb: 2, total_rows: 200 }); - - // Clear only first connection - mariadbCache.clearForConnection(mockConfig); - - // First should be null, second should still exist - expect(mariadbCache.getDBStats(mockConfig)).toBeNull(); - expect(mariadbCache.getDBStats(mockConfig2)).toEqual({ - total_tables: 2, - total_db_size_mb: 2, - total_rows: 200, - }); - }); - - test("should clear table-specific cache", () => { - mariadbCache.setColumns(mockConfig, "testdb", "users", [{ column_name: "id", data_type: "int" }] as any); - mariadbCache.setColumns(mockConfig, "testdb", "orders", [{ column_name: "order_id", data_type: "int" }] as any); - mariadbCache.setPrimaryKeys(mockConfig, "testdb", "users", ["id"]); - mariadbCache.setTableDetails(mockConfig, "testdb", "users", []); - - // Clear only users table cache - mariadbCache.clearTableCache(mockConfig, "testdb", "users"); - - // Users cache should be cleared - expect(mariadbCache.getColumns(mockConfig, "testdb", "users")).toBeNull(); - expect(mariadbCache.getPrimaryKeys(mockConfig, "testdb", "users")).toBeNull(); - expect(mariadbCache.getTableDetails(mockConfig, "testdb", "users")).toBeNull(); - - // Orders cache should still exist - expect(mariadbCache.getColumns(mockConfig, "testdb", "orders")).toEqual([ - { column_name: "order_id", data_type: "int" }, - ]); - }); - - test("should clear all caches globally", () => { - mariadbCache.setDBStats(mockConfig, { total_tables: 1, total_db_size_mb: 1, total_rows: 100 }); - mariadbCache.setDBStats(mockConfig2, { total_tables: 2, total_db_size_mb: 2, total_rows: 200 }); - mariadbCache.setSchemas(mockConfig, [{ name: "testdb" }]); - - mariadbCache.clearAll(); - - expect(mariadbCache.getDBStats(mockConfig)).toBeNull(); - expect(mariadbCache.getDBStats(mockConfig2)).toBeNull(); - expect(mariadbCache.getSchemas(mockConfig)).toBeNull(); - }); - - test("should return correct cache statistics", () => { - mariadbCache.setTableList(mockConfig, []); - mariadbCache.setColumns(mockConfig, "testdb", "t1", [] as any); - mariadbCache.setColumns(mockConfig, "testdb", "t2", [] as any); - mariadbCache.setPrimaryKeys(mockConfig, "testdb", "t1", []); - mariadbCache.setDBStats(mockConfig, { total_tables: 0, total_db_size_mb: 0, total_rows: 0 }); - mariadbCache.setSchemas(mockConfig, []); - mariadbCache.setTableDetails(mockConfig, "testdb", "t1", []); - - const stats = mariadbCache.getStats(); - - expect(stats.tableLists).toBe(1); - expect(stats.columns).toBe(2); - expect(stats.primaryKeys).toBe(1); - expect(stats.dbStats).toBe(1); - expect(stats.schemas).toBe(1); - expect(stats.tableDetails).toBe(1); - }); + test("should clear table-specific cache", () => { + mariadbCache.setColumns(mockConfig, "testdb", "users", [ + { column_name: "id", data_type: "int" }, + ] as any); + mariadbCache.setColumns(mockConfig, "testdb", "orders", [ + { column_name: "order_id", data_type: "int" }, + ] as any); + mariadbCache.setPrimaryKeys(mockConfig, "testdb", "users", ["id"]); + mariadbCache.setTableDetails(mockConfig, "testdb", "users", []); + + // Clear only users table cache + mariadbCache.clearTableCache(mockConfig, "testdb", "users"); + + // Users cache should be cleared + expect(mariadbCache.getColumns(mockConfig, "testdb", "users")).toBeNull(); + expect(mariadbCache.getPrimaryKeys(mockConfig, "testdb", "users")).toBeNull(); + expect(mariadbCache.getTableDetails(mockConfig, "testdb", "users")).toBeNull(); + + // Orders cache should still exist + expect(mariadbCache.getColumns(mockConfig, "testdb", "orders")).toEqual([ + { column_name: "order_id", data_type: "int" }, + ]); + }); + + test("should clear all caches globally", () => { + mariadbCache.setDBStats(mockConfig, { + total_tables: 1, + total_db_size_mb: 1, + total_rows: 100, + }); + mariadbCache.setDBStats(mockConfig2, { + total_tables: 2, + total_db_size_mb: 2, + total_rows: 200, + }); + mariadbCache.setSchemas(mockConfig, [{ name: "testdb" }]); + + mariadbCache.clearAll(); + + expect(mariadbCache.getDBStats(mockConfig)).toBeNull(); + expect(mariadbCache.getDBStats(mockConfig2)).toBeNull(); + expect(mariadbCache.getSchemas(mockConfig)).toBeNull(); + }); + + test("should return correct cache statistics", () => { + mariadbCache.setTableList(mockConfig, []); + mariadbCache.setColumns(mockConfig, "testdb", "t1", [] as any); + mariadbCache.setColumns(mockConfig, "testdb", "t2", [] as any); + mariadbCache.setPrimaryKeys(mockConfig, "testdb", "t1", []); + mariadbCache.setDBStats(mockConfig, { total_tables: 0, total_db_size_mb: 0, total_rows: 0 }); + mariadbCache.setSchemas(mockConfig, []); + mariadbCache.setTableDetails(mockConfig, "testdb", "t1", []); + + const stats = mariadbCache.getStats(); + + expect(stats.tableLists).toBe(1); + expect(stats.columns).toBe(2); + expect(stats.primaryKeys).toBe(1); + expect(stats.dbStats).toBe(1); + expect(stats.schemas).toBe(1); + expect(stats.tableDetails).toBe(1); + }); + }); + + describe("Cache Performance", () => { + test("cached retrieval should be faster than simulated DB call", () => { + const statsData = { + total_tables: 100, + total_db_size_mb: 500.5, + total_rows: 1000000, + }; + + // Set cache + mariadbCache.setDBStats(mockConfig, statsData); + + // Measure cached retrievals + const iterations = 1000; + const start = performance.now(); + + for (let i = 0; i < iterations; i++) { + mariadbCache.getDBStats(mockConfig); + } + + const elapsed = performance.now() - start; + const avgTime = elapsed / iterations; + + // Cached calls should be fast (allowing for console.log overhead) + // In production without logging, this would be sub-millisecond + expect(avgTime).toBeLessThan(10); }); - describe("Cache Performance", () => { - test("cached retrieval should be faster than simulated DB call", () => { - const statsData = { - total_tables: 100, - total_db_size_mb: 500.5, - total_rows: 1000000, - }; - - // Set cache - mariadbCache.setDBStats(mockConfig, statsData); - - // Measure cached retrievals - const iterations = 1000; - const start = performance.now(); - - for (let i = 0; i < iterations; i++) { - mariadbCache.getDBStats(mockConfig); - } - - const elapsed = performance.now() - start; - const avgTime = elapsed / iterations; - - // Cached calls should be fast (allowing for console.log overhead) - // In production without logging, this would be sub-millisecond - expect(avgTime).toBeLessThan(10); - }); - - test("multiple cache types should be retrievable quickly", () => { - // Set up various caches - mariadbCache.setDBStats(mockConfig, { total_tables: 1, total_db_size_mb: 1, total_rows: 100 }); - mariadbCache.setSchemas(mockConfig, [{ name: "testdb" }]); - mariadbCache.setTableList(mockConfig, [{ schema: "testdb", name: "users", type: "BASE TABLE" }]); - mariadbCache.setColumns(mockConfig, "testdb", "users", [] as any); - mariadbCache.setPrimaryKeys(mockConfig, "testdb", "users", ["id"]); - mariadbCache.setTableDetails(mockConfig, "testdb", "users", []); - - const iterations = 100; - const start = performance.now(); - - for (let i = 0; i < iterations; i++) { - mariadbCache.getDBStats(mockConfig); - mariadbCache.getSchemas(mockConfig); - mariadbCache.getTableList(mockConfig); - mariadbCache.getColumns(mockConfig, "testdb", "users"); - mariadbCache.getPrimaryKeys(mockConfig, "testdb", "users"); - mariadbCache.getTableDetails(mockConfig, "testdb", "users"); - } - - const elapsed = performance.now() - start; - const avgTimePerIteration = elapsed / iterations; - - // All 6 cache reads per iteration should be reasonable - // (console.log statements add overhead - in production this would be much faster) - expect(avgTimePerIteration).toBeLessThan(50); - }); + test("multiple cache types should be retrievable quickly", () => { + // Set up various caches + mariadbCache.setDBStats(mockConfig, { + total_tables: 1, + total_db_size_mb: 1, + total_rows: 100, + }); + mariadbCache.setSchemas(mockConfig, [{ name: "testdb" }]); + mariadbCache.setTableList(mockConfig, [ + { schema: "testdb", name: "users", type: "BASE TABLE" }, + ]); + mariadbCache.setColumns(mockConfig, "testdb", "users", [] as any); + mariadbCache.setPrimaryKeys(mockConfig, "testdb", "users", ["id"]); + mariadbCache.setTableDetails(mockConfig, "testdb", "users", []); + + const iterations = 100; + const start = performance.now(); + + for (let i = 0; i < iterations; i++) { + mariadbCache.getDBStats(mockConfig); + mariadbCache.getSchemas(mockConfig); + mariadbCache.getTableList(mockConfig); + mariadbCache.getColumns(mockConfig, "testdb", "users"); + mariadbCache.getPrimaryKeys(mockConfig, "testdb", "users"); + mariadbCache.getTableDetails(mockConfig, "testdb", "users"); + } + + const elapsed = performance.now() - start; + const avgTimePerIteration = elapsed / iterations; + + // All 6 cache reads per iteration should be reasonable + // (console.log statements add overhead - in production this would be much faster) + expect(avgTimePerIteration).toBeLessThan(50); }); + }); }); diff --git a/bridge/__tests__/connectors/mariadb.test.ts b/bridge/__tests__/connectors/mariadb.test.ts index 46f25b64..c26d0489 100644 --- a/bridge/__tests__/connectors/mariadb.test.ts +++ b/bridge/__tests__/connectors/mariadb.test.ts @@ -2,85 +2,92 @@ import { describe, it, expect, test } from "@jest/globals"; import * as mariadbConnector from "../../src/connectors/mariadb"; const invalidConfig: mariadbConnector.MariaDBConfig = { - host: process.env.MARIADB_HOST!, - user: process.env.MARIADB_USER!, - password: process.env.MARIADB_PASSWORD!, - database: process.env.MARIADB_DATABASE!, - ssl: true, - port: Number(process.env.MARIADB_PORT || 3306), + host: process.env.MARIADB_HOST!, + user: process.env.MARIADB_USER!, + password: process.env.MARIADB_PASSWORD!, + database: process.env.MARIADB_DATABASE!, + ssl: true, + port: Number(process.env.MARIADB_PORT || 3306), }; const validConfig: mariadbConnector.MariaDBConfig = { - host: process.env.REAL_MARIADB_HOST!, - user: process.env.REAL_MARIADB_USER!, - password: process.env.REAL_MARIADB_PASSWORD!, - database: process.env.REAL_MARIADB_DATABASE!, - ssl: process.env.REAL_MARIADB_SSL === "true", - port: Number(process.env.REAL_MARIADB_PORT || 3306), + host: process.env.REAL_MARIADB_HOST!, + user: process.env.REAL_MARIADB_USER!, + password: process.env.REAL_MARIADB_PASSWORD!, + database: process.env.REAL_MARIADB_DATABASE!, + ssl: process.env.REAL_MARIADB_SSL === "true", + port: Number(process.env.REAL_MARIADB_PORT || 3306), }; describe("MariaDB Connector", () => { - test("Should Fail to Connect to MariaDB Database", async () => { - const connection = await mariadbConnector.testConnection(invalidConfig); - expect(connection.ok).toBe(false); - expect(connection.status).toBe('disconnected'); - }); + test("Should Fail to Connect to MariaDB Database", async () => { + const connection = await mariadbConnector.testConnection(invalidConfig); + expect(connection.ok).toBe(false); + expect(connection.status).toBe("disconnected"); + }); - test("Should Connect to MariaDB Database", async () => { - const connection = await mariadbConnector.testConnection(validConfig); - expect(connection).toStrictEqual({ ok: true, status: 'connected', message: 'Connection successful' }); + test("Should Connect to MariaDB Database", async () => { + const connection = await mariadbConnector.testConnection(validConfig); + expect(connection).toStrictEqual({ + ok: true, + status: "connected", + message: "Connection successful", }); + }); - test("Should Create a Table Schema", async () => { - const rows: any[] = []; - let doneCalled = false; + test("Should Create a Table Schema", async () => { + const rows: any[] = []; + let doneCalled = false; - const { promise } = mariadbConnector.streamQueryCancelable( - validConfig, - "CREATE TABLE IF NOT EXISTS TestTable (id INT PRIMARY KEY, name VARCHAR(50));", - 1000, - (batch) => { - rows.push(...batch); - }, - () => { - doneCalled = true; - } - ); + const { promise } = mariadbConnector.streamQueryCancelable( + validConfig, + "CREATE TABLE IF NOT EXISTS TestTable (id INT PRIMARY KEY, name VARCHAR(50));", + 1000, + (batch) => { + rows.push(...batch); + }, + () => { + doneCalled = true; + }, + ); - await promise; + await promise; - expect(doneCalled).toBe(true); - expect(rows.length).toBeGreaterThanOrEqual(0); - }); + expect(doneCalled).toBe(true); + expect(rows.length).toBeGreaterThanOrEqual(0); + }); - test("Should Fetch the Table Data", async () => { - const result = await mariadbConnector.fetchTableData( - validConfig, - process.env.REAL_MARIADB_DATABASE!, - "TestTable", - 10, - 1 - ); - expect(result).toHaveProperty('rows'); - expect(result).toHaveProperty('total'); - expect(Array.isArray(result.rows)).toBe(true); - }); + test("Should Fetch the Table Data", async () => { + const result = await mariadbConnector.fetchTableData( + validConfig, + process.env.REAL_MARIADB_DATABASE!, + "TestTable", + 10, + 1, + ); + expect(result).toHaveProperty("rows"); + expect(result).toHaveProperty("total"); + expect(Array.isArray(result.rows)).toBe(true); + }); - test("Should Fetch the Tables List", async () => { - const result = await mariadbConnector.listTables(validConfig, process.env.REAL_MARIADB_DATABASE!); - expect(Array.isArray(result)).toBe(true); - expect(result.length).toBeGreaterThan(0); - expect(result[0]).toHaveProperty("name"); - }); + test("Should Fetch the Tables List", async () => { + const result = await mariadbConnector.listTables( + validConfig, + process.env.REAL_MARIADB_DATABASE!, + ); + expect(Array.isArray(result)).toBe(true); + expect(result.length).toBeGreaterThan(0); + expect(result[0]).toHaveProperty("name"); + }); - test("Should Fetch the Table Schema", async () => { - const result = await mariadbConnector.getTableDetails( - validConfig, - process.env.REAL_MARIADB_DATABASE!, - "TestTable" - ); - expect(Array.isArray(result)).toBe(true); - expect(result.length).toBeGreaterThan(0); - expect(result[0]).toHaveProperty("name"); - }); + test("Should Fetch the Table Schema", async () => { + const result = await mariadbConnector.getTableDetails( + validConfig, + process.env.REAL_MARIADB_DATABASE!, + "TestTable", + ); + expect(Array.isArray(result)).toBe(true); + expect(result.length).toBeGreaterThan(0); + expect(result[0]).toHaveProperty("name"); + }); }); diff --git a/bridge/__tests__/connectors/mysql.cache.test.ts b/bridge/__tests__/connectors/mysql.cache.test.ts index 86b39583..5ac8def0 100644 --- a/bridge/__tests__/connectors/mysql.cache.test.ts +++ b/bridge/__tests__/connectors/mysql.cache.test.ts @@ -43,9 +43,7 @@ describe("MySQL Cache Manager", () => { }); test("should cache table list with schema", () => { - const tableData = [ - { schema: "myschema", name: "products", type: "BASE TABLE" }, - ]; + const tableData = [{ schema: "myschema", name: "products", type: "BASE TABLE" }]; mysqlCache.setTableList(mockConfig, tableData, "myschema"); const cached = mysqlCache.getTableList(mockConfig, "myschema"); @@ -149,11 +147,7 @@ describe("MySQL Cache Manager", () => { }); test("should cache and retrieve schemas", () => { - const schemaData = [ - { name: "testdb" }, - { name: "production" }, - { name: "staging" }, - ]; + const schemaData = [{ name: "testdb" }, { name: "production" }, { name: "staging" }]; mysqlCache.setSchemas(mockConfig, schemaData); const cached = mysqlCache.getSchemas(mockConfig); @@ -199,7 +193,9 @@ describe("MySQL Cache Manager", () => { test("should clear all caches for a connection", () => { // Set up various caches mysqlCache.setTableList(mockConfig, [{ schema: "testdb", name: "t1", type: "BASE TABLE" }]); - mysqlCache.setColumns(mockConfig, "testdb", "t1", [{ column_name: "id", data_type: "int" }] as any); + mysqlCache.setColumns(mockConfig, "testdb", "t1", [ + { column_name: "id", data_type: "int" }, + ] as any); mysqlCache.setPrimaryKeys(mockConfig, "testdb", "t1", ["id"]); mysqlCache.setDBStats(mockConfig, { total_tables: 1, total_db_size_mb: 1, total_rows: 100 }); mysqlCache.setSchemas(mockConfig, [{ name: "testdb" }]); @@ -235,8 +231,12 @@ describe("MySQL Cache Manager", () => { }); test("should clear table-specific cache", () => { - mysqlCache.setColumns(mockConfig, "testdb", "users", [{ column_name: "id", data_type: "int" }] as any); - mysqlCache.setColumns(mockConfig, "testdb", "orders", [{ column_name: "order_id", data_type: "int" }] as any); + mysqlCache.setColumns(mockConfig, "testdb", "users", [ + { column_name: "id", data_type: "int" }, + ] as any); + mysqlCache.setColumns(mockConfig, "testdb", "orders", [ + { column_name: "order_id", data_type: "int" }, + ] as any); mysqlCache.setPrimaryKeys(mockConfig, "testdb", "users", ["id"]); mysqlCache.setTableDetails(mockConfig, "testdb", "users", []); @@ -317,7 +317,9 @@ describe("MySQL Cache Manager", () => { // Set up various caches mysqlCache.setDBStats(mockConfig, { total_tables: 1, total_db_size_mb: 1, total_rows: 100 }); mysqlCache.setSchemas(mockConfig, [{ name: "testdb" }]); - mysqlCache.setTableList(mockConfig, [{ schema: "testdb", name: "users", type: "BASE TABLE" }]); + mysqlCache.setTableList(mockConfig, [ + { schema: "testdb", name: "users", type: "BASE TABLE" }, + ]); mysqlCache.setColumns(mockConfig, "testdb", "users", [] as any); mysqlCache.setPrimaryKeys(mockConfig, "testdb", "users", ["id"]); mysqlCache.setTableDetails(mockConfig, "testdb", "users", []); diff --git a/bridge/__tests__/connectors/mysql.test.ts b/bridge/__tests__/connectors/mysql.test.ts index c9c0de0a..b55236a7 100644 --- a/bridge/__tests__/connectors/mysql.test.ts +++ b/bridge/__tests__/connectors/mysql.test.ts @@ -46,7 +46,7 @@ describe("MySQL Connector", () => { }, () => { doneCalled = true; - } + }, ); await promise; @@ -61,7 +61,7 @@ describe("MySQL Connector", () => { process.env.REAL_MYSQL_DATABASE!, "TestTable", 100, - 10 + 10, ); expect(Array.isArray(result.rows)).toBe(true); expect(result.rows.length).toBeGreaterThanOrEqual(0); @@ -78,7 +78,7 @@ describe("MySQL Connector", () => { const result = await mysqlConnector.getTableDetails( validConfig, process.env.REAL_MYSQL_DATABASE!, - "TestTable" + "TestTable", ); expect(Array.isArray(result)).toBe(true); expect(result.length).toBeGreaterThan(0); diff --git a/bridge/__tests__/connectors/postgres.cache.test.ts b/bridge/__tests__/connectors/postgres.cache.test.ts index 6106e6bf..93d174c2 100644 --- a/bridge/__tests__/connectors/postgres.cache.test.ts +++ b/bridge/__tests__/connectors/postgres.cache.test.ts @@ -1,259 +1,334 @@ -import { postgresCache, PostgresCacheManager } from '../../src/connectors/postgres'; +import { postgresCache, PostgresCacheManager } from "../../src/connectors/postgres"; import { describe, it, expect, test, beforeEach } from "@jest/globals"; // Mock PGConfig for testing const mockConnection = { - host: 'localhost', + host: "localhost", port: 5432, - user: 'testuser', - password: 'testpass', - database: 'testdb' + user: "testuser", + password: "testpass", + database: "testdb", }; const mockConnection2 = { - host: 'localhost', + host: "localhost", port: 5432, - user: 'testuser', - password: 'testpass', - database: 'otherdb' + user: "testuser", + password: "testpass", + database: "otherdb", }; -describe('PostgresCacheManager', () => { +describe("PostgresCacheManager", () => { beforeEach(() => { // Clear all caches before each test postgresCache.clearAll(); }); - describe('Connection Key Generation', () => { - it('should generate consistent keys for same connection', () => { - const tables1 = [{ schema: 'public', name: 'users', type: 'BASE TABLE' }]; - + describe("Connection Key Generation", () => { + it("should generate consistent keys for same connection", () => { + const tables1 = [{ schema: "public", name: "users", type: "BASE TABLE" }]; + postgresCache.setTableList(mockConnection, tables1); const cached = postgresCache.getTableList(mockConnection); - + expect(cached).toEqual(tables1); }); - it('should generate different keys for different databases', () => { - const tables1 = [{ schema: 'public', name: 'users', type: 'BASE TABLE' }]; - const tables2 = [{ schema: 'public', name: 'orders', type: 'BASE TABLE' }]; - + it("should generate different keys for different databases", () => { + const tables1 = [{ schema: "public", name: "users", type: "BASE TABLE" }]; + const tables2 = [{ schema: "public", name: "orders", type: "BASE TABLE" }]; + postgresCache.setTableList(mockConnection, tables1); postgresCache.setTableList(mockConnection2, tables2); - + expect(postgresCache.getTableList(mockConnection)).toEqual(tables1); expect(postgresCache.getTableList(mockConnection2)).toEqual(tables2); }); }); - describe('Table List Cache', () => { + describe("Table List Cache", () => { const mockTables = [ - { schema: 'public', name: 'users', type: 'BASE TABLE' }, - { schema: 'public', name: 'orders', type: 'BASE TABLE' } + { schema: "public", name: "users", type: "BASE TABLE" }, + { schema: "public", name: "orders", type: "BASE TABLE" }, ]; - it('should cache and retrieve table list', () => { + it("should cache and retrieve table list", () => { postgresCache.setTableList(mockConnection, mockTables); const cached = postgresCache.getTableList(mockConnection); - + expect(cached).toEqual(mockTables); }); - it('should return null for uncached table list', () => { + it("should return null for uncached table list", () => { const cached = postgresCache.getTableList(mockConnection); expect(cached).toBeNull(); }); - it('should cache table list per schema', () => { - const publicTables = [{ schema: 'public', name: 'users', type: 'BASE TABLE' }]; - const analyticsTables = [{ schema: 'analytics', name: 'events', type: 'BASE TABLE' }]; - - postgresCache.setTableList(mockConnection, publicTables, 'public'); - postgresCache.setTableList(mockConnection, analyticsTables, 'analytics'); - - expect(postgresCache.getTableList(mockConnection, 'public')).toEqual(publicTables); - expect(postgresCache.getTableList(mockConnection, 'analytics')).toEqual(analyticsTables); + it("should cache table list per schema", () => { + const publicTables = [{ schema: "public", name: "users", type: "BASE TABLE" }]; + const analyticsTables = [{ schema: "analytics", name: "events", type: "BASE TABLE" }]; + + postgresCache.setTableList(mockConnection, publicTables, "public"); + postgresCache.setTableList(mockConnection, analyticsTables, "analytics"); + + expect(postgresCache.getTableList(mockConnection, "public")).toEqual(publicTables); + expect(postgresCache.getTableList(mockConnection, "analytics")).toEqual(analyticsTables); }); - it('should expire table list cache after TTL', async () => { + it("should expire table list cache after TTL", async () => { // Create a cache manager with very short TTL for testing const shortTtlCache = new PostgresCacheManager(); - + // We'll manually test the expiration logic postgresCache.setTableList(mockConnection, mockTables); - + // Immediately should be cached expect(postgresCache.getTableList(mockConnection)).toEqual(mockTables); }); }); - describe('Primary Keys Cache', () => { - const mockPrimaryKeys = [{ column_name: 'id' }]; + describe("Primary Keys Cache", () => { + const mockPrimaryKeys = [{ column_name: "id" }]; + + it("should cache and retrieve primary keys", () => { + postgresCache.setPrimaryKeys(mockConnection, "public", "users", mockPrimaryKeys); + const cached = postgresCache.getPrimaryKeys(mockConnection, "public", "users"); - it('should cache and retrieve primary keys', () => { - postgresCache.setPrimaryKeys(mockConnection, 'public', 'users', mockPrimaryKeys); - const cached = postgresCache.getPrimaryKeys(mockConnection, 'public', 'users'); - expect(cached).toEqual(mockPrimaryKeys); }); - it('should return null for uncached primary keys', () => { - const cached = postgresCache.getPrimaryKeys(mockConnection, 'public', 'users'); + it("should return null for uncached primary keys", () => { + const cached = postgresCache.getPrimaryKeys(mockConnection, "public", "users"); expect(cached).toBeNull(); }); - it('should cache primary keys per table', () => { - const usersPK = [{ column_name: 'id' }]; - const ordersPK = [{ column_name: 'order_id' }]; - - postgresCache.setPrimaryKeys(mockConnection, 'public', 'users', usersPK); - postgresCache.setPrimaryKeys(mockConnection, 'public', 'orders', ordersPK); - - expect(postgresCache.getPrimaryKeys(mockConnection, 'public', 'users')).toEqual(usersPK); - expect(postgresCache.getPrimaryKeys(mockConnection, 'public', 'orders')).toEqual(ordersPK); + it("should cache primary keys per table", () => { + const usersPK = [{ column_name: "id" }]; + const ordersPK = [{ column_name: "order_id" }]; + + postgresCache.setPrimaryKeys(mockConnection, "public", "users", usersPK); + postgresCache.setPrimaryKeys(mockConnection, "public", "orders", ordersPK); + + expect(postgresCache.getPrimaryKeys(mockConnection, "public", "users")).toEqual(usersPK); + expect(postgresCache.getPrimaryKeys(mockConnection, "public", "orders")).toEqual(ordersPK); }); }); - describe('DB Stats Cache', () => { + describe("DB Stats Cache", () => { const mockStats = { total_tables: 10, total_db_size_mb: 256.5, - total_rows: 100000 + total_rows: 100000, }; - it('should cache and retrieve DB stats', () => { + it("should cache and retrieve DB stats", () => { postgresCache.setDBStats(mockConnection, mockStats); const cached = postgresCache.getDBStats(mockConnection); - + expect(cached).toEqual(mockStats); }); - it('should return null for uncached DB stats', () => { + it("should return null for uncached DB stats", () => { const cached = postgresCache.getDBStats(mockConnection); expect(cached).toBeNull(); }); - it('should cache DB stats per connection', () => { + it("should cache DB stats per connection", () => { const stats1 = { total_tables: 10, total_db_size_mb: 256.5, total_rows: 100000 }; const stats2 = { total_tables: 5, total_db_size_mb: 128.0, total_rows: 50000 }; - + postgresCache.setDBStats(mockConnection, stats1); postgresCache.setDBStats(mockConnection2, stats2); - + expect(postgresCache.getDBStats(mockConnection)).toEqual(stats1); expect(postgresCache.getDBStats(mockConnection2)).toEqual(stats2); }); }); - describe('Schemas Cache', () => { - const mockSchemas = [{ name: 'public' }, { name: 'analytics' }]; + describe("Schemas Cache", () => { + const mockSchemas = [{ name: "public" }, { name: "analytics" }]; - it('should cache and retrieve schemas', () => { + it("should cache and retrieve schemas", () => { postgresCache.setSchemas(mockConnection, mockSchemas); const cached = postgresCache.getSchemas(mockConnection); - + expect(cached).toEqual(mockSchemas); }); - it('should return null for uncached schemas', () => { + it("should return null for uncached schemas", () => { const cached = postgresCache.getSchemas(mockConnection); expect(cached).toBeNull(); }); }); - describe('Table Details Cache', () => { + describe("Table Details Cache", () => { const mockDetails = [ - { name: 'id', type: 'integer', not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }, - { name: 'email', type: 'varchar(255)', not_nullable: true, default_value: null, is_primary_key: false, is_foreign_key: false } + { + name: "id", + type: "integer", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }, + { + name: "email", + type: "varchar(255)", + not_nullable: true, + default_value: null, + is_primary_key: false, + is_foreign_key: false, + }, ]; - it('should cache and retrieve table details', () => { - postgresCache.setTableDetails(mockConnection, 'public', 'users', mockDetails); - const cached = postgresCache.getTableDetails(mockConnection, 'public', 'users'); - + it("should cache and retrieve table details", () => { + postgresCache.setTableDetails(mockConnection, "public", "users", mockDetails); + const cached = postgresCache.getTableDetails(mockConnection, "public", "users"); + expect(cached).toEqual(mockDetails); }); - it('should return null for uncached table details', () => { - const cached = postgresCache.getTableDetails(mockConnection, 'public', 'users'); + it("should return null for uncached table details", () => { + const cached = postgresCache.getTableDetails(mockConnection, "public", "users"); expect(cached).toBeNull(); }); - it('should cache table details per schema and table', () => { - const usersDetails = [{ name: 'id', type: 'integer', not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }]; - const ordersDetails = [{ name: 'order_id', type: 'uuid', not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }]; - - postgresCache.setTableDetails(mockConnection, 'public', 'users', usersDetails); - postgresCache.setTableDetails(mockConnection, 'public', 'orders', ordersDetails); - - expect(postgresCache.getTableDetails(mockConnection, 'public', 'users')).toEqual(usersDetails); - expect(postgresCache.getTableDetails(mockConnection, 'public', 'orders')).toEqual(ordersDetails); + it("should cache table details per schema and table", () => { + const usersDetails = [ + { + name: "id", + type: "integer", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }, + ]; + const ordersDetails = [ + { + name: "order_id", + type: "uuid", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }, + ]; + + postgresCache.setTableDetails(mockConnection, "public", "users", usersDetails); + postgresCache.setTableDetails(mockConnection, "public", "orders", ordersDetails); + + expect(postgresCache.getTableDetails(mockConnection, "public", "users")).toEqual( + usersDetails, + ); + expect(postgresCache.getTableDetails(mockConnection, "public", "orders")).toEqual( + ordersDetails, + ); }); }); - describe('Cache Invalidation', () => { - const fullTableInfo = { schema: 'public', name: 'users', type: 'BASE TABLE' }; - const fullColumnDetail = { name: 'id', type: 'integer', not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }; + describe("Cache Invalidation", () => { + const fullTableInfo = { schema: "public", name: "users", type: "BASE TABLE" }; + const fullColumnDetail = { + name: "id", + type: "integer", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }; - it('should clear all caches for a specific connection', () => { + it("should clear all caches for a specific connection", () => { // Setup caches postgresCache.setTableList(mockConnection, [fullTableInfo]); - postgresCache.setDBStats(mockConnection, { total_tables: 10, total_db_size_mb: 100, total_rows: 1000 }); - postgresCache.setSchemas(mockConnection, [{ name: 'public' }]); - postgresCache.setTableDetails(mockConnection, 'public', 'users', [fullColumnDetail]); - postgresCache.setPrimaryKeys(mockConnection, 'public', 'users', [{ column_name: 'id' }]); - + postgresCache.setDBStats(mockConnection, { + total_tables: 10, + total_db_size_mb: 100, + total_rows: 1000, + }); + postgresCache.setSchemas(mockConnection, [{ name: "public" }]); + postgresCache.setTableDetails(mockConnection, "public", "users", [fullColumnDetail]); + postgresCache.setPrimaryKeys(mockConnection, "public", "users", [{ column_name: "id" }]); + // Setup caches for another connection - postgresCache.setTableList(mockConnection2, [{ schema: 'public', name: 'products', type: 'BASE TABLE' }]); - + postgresCache.setTableList(mockConnection2, [ + { schema: "public", name: "products", type: "BASE TABLE" }, + ]); + // Clear caches for first connection postgresCache.clearForConnection(mockConnection); - + // Verify first connection caches are cleared expect(postgresCache.getTableList(mockConnection)).toBeNull(); expect(postgresCache.getDBStats(mockConnection)).toBeNull(); expect(postgresCache.getSchemas(mockConnection)).toBeNull(); - expect(postgresCache.getTableDetails(mockConnection, 'public', 'users')).toBeNull(); - expect(postgresCache.getPrimaryKeys(mockConnection, 'public', 'users')).toBeNull(); - + expect(postgresCache.getTableDetails(mockConnection, "public", "users")).toBeNull(); + expect(postgresCache.getPrimaryKeys(mockConnection, "public", "users")).toBeNull(); + // Verify second connection caches are intact - expect(postgresCache.getTableList(mockConnection2)).toEqual([{ schema: 'public', name: 'products', type: 'BASE TABLE' }]); + expect(postgresCache.getTableList(mockConnection2)).toEqual([ + { schema: "public", name: "products", type: "BASE TABLE" }, + ]); }); - it('should clear table-specific caches', () => { - const usersDetail = { name: 'id', type: 'integer', not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }; - const ordersDetail = { name: 'order_id', type: 'uuid', not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }; - + it("should clear table-specific caches", () => { + const usersDetail = { + name: "id", + type: "integer", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }; + const ordersDetail = { + name: "order_id", + type: "uuid", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }; + // Setup caches - postgresCache.setTableDetails(mockConnection, 'public', 'users', [usersDetail]); - postgresCache.setTableDetails(mockConnection, 'public', 'orders', [ordersDetail]); - postgresCache.setPrimaryKeys(mockConnection, 'public', 'users', [{ column_name: 'id' }]); - postgresCache.setPrimaryKeys(mockConnection, 'public', 'orders', [{ column_name: 'order_id' }]); - + postgresCache.setTableDetails(mockConnection, "public", "users", [usersDetail]); + postgresCache.setTableDetails(mockConnection, "public", "orders", [ordersDetail]); + postgresCache.setPrimaryKeys(mockConnection, "public", "users", [{ column_name: "id" }]); + postgresCache.setPrimaryKeys(mockConnection, "public", "orders", [ + { column_name: "order_id" }, + ]); + // Clear cache for specific table - postgresCache.clearTableCache(mockConnection, 'public', 'users'); - + postgresCache.clearTableCache(mockConnection, "public", "users"); + // Verify specific table caches are cleared - expect(postgresCache.getTableDetails(mockConnection, 'public', 'users')).toBeNull(); - expect(postgresCache.getPrimaryKeys(mockConnection, 'public', 'users')).toBeNull(); - + expect(postgresCache.getTableDetails(mockConnection, "public", "users")).toBeNull(); + expect(postgresCache.getPrimaryKeys(mockConnection, "public", "users")).toBeNull(); + // Verify other table caches are intact - expect(postgresCache.getTableDetails(mockConnection, 'public', 'orders')).toEqual([ordersDetail]); - expect(postgresCache.getPrimaryKeys(mockConnection, 'public', 'orders')).toEqual([{ column_name: 'order_id' }]); + expect(postgresCache.getTableDetails(mockConnection, "public", "orders")).toEqual([ + ordersDetail, + ]); + expect(postgresCache.getPrimaryKeys(mockConnection, "public", "orders")).toEqual([ + { column_name: "order_id" }, + ]); }); - it('should clear all caches', () => { - const table1 = { schema: 'public', name: 'users', type: 'BASE TABLE' }; - const table2 = { schema: 'public', name: 'products', type: 'BASE TABLE' }; - + it("should clear all caches", () => { + const table1 = { schema: "public", name: "users", type: "BASE TABLE" }; + const table2 = { schema: "public", name: "products", type: "BASE TABLE" }; + // Setup caches for multiple connections postgresCache.setTableList(mockConnection, [table1]); postgresCache.setTableList(mockConnection2, [table2]); - postgresCache.setDBStats(mockConnection, { total_tables: 10, total_db_size_mb: 100, total_rows: 1000 }); - + postgresCache.setDBStats(mockConnection, { + total_tables: 10, + total_db_size_mb: 100, + total_rows: 1000, + }); + // Clear all postgresCache.clearAll(); - + // Verify all caches are cleared expect(postgresCache.getTableList(mockConnection)).toBeNull(); expect(postgresCache.getTableList(mockConnection2)).toBeNull(); @@ -261,21 +336,32 @@ describe('PostgresCacheManager', () => { }); }); - describe('Cache Statistics', () => { - const fullTableInfo = { schema: 'public', name: 'users', type: 'BASE TABLE' }; - const fullColumnDetail = { name: 'id', type: 'integer', not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }; + describe("Cache Statistics", () => { + const fullTableInfo = { schema: "public", name: "users", type: "BASE TABLE" }; + const fullColumnDetail = { + name: "id", + type: "integer", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }; - it('should return correct cache statistics', () => { + it("should return correct cache statistics", () => { // Setup various caches postgresCache.setTableList(mockConnection, [fullTableInfo]); - postgresCache.setTableList(mockConnection, [fullTableInfo], 'public'); - postgresCache.setDBStats(mockConnection, { total_tables: 10, total_db_size_mb: 100, total_rows: 1000 }); - postgresCache.setSchemas(mockConnection, [{ name: 'public' }]); - postgresCache.setTableDetails(mockConnection, 'public', 'users', [fullColumnDetail]); - postgresCache.setPrimaryKeys(mockConnection, 'public', 'users', [{ column_name: 'id' }]); - + postgresCache.setTableList(mockConnection, [fullTableInfo], "public"); + postgresCache.setDBStats(mockConnection, { + total_tables: 10, + total_db_size_mb: 100, + total_rows: 1000, + }); + postgresCache.setSchemas(mockConnection, [{ name: "public" }]); + postgresCache.setTableDetails(mockConnection, "public", "users", [fullColumnDetail]); + postgresCache.setPrimaryKeys(mockConnection, "public", "users", [{ column_name: "id" }]); + const stats = postgresCache.getStats(); - + expect(stats.tableLists).toBe(2); expect(stats.primaryKeys).toBe(1); expect(stats.dbStats).toBe(1); @@ -283,9 +369,9 @@ describe('PostgresCacheManager', () => { expect(stats.tableDetails).toBe(1); }); - it('should return zero counts for empty cache', () => { + it("should return zero counts for empty cache", () => { const stats = postgresCache.getStats(); - + expect(stats.tableLists).toBe(0); expect(stats.primaryKeys).toBe(0); expect(stats.dbStats).toBe(0); @@ -294,12 +380,12 @@ describe('PostgresCacheManager', () => { }); }); - describe('Cache Performance', () => { - it('should retrieve cached data faster than setting it', () => { + describe("Cache Performance", () => { + it("should retrieve cached data faster than setting it", () => { const largeDataset = Array.from({ length: 1000 }, (_, i) => ({ - schema: 'public', + schema: "public", name: `table_${i}`, - type: 'BASE TABLE' + type: "BASE TABLE", })); // Time the set operation @@ -318,29 +404,29 @@ describe('PostgresCacheManager', () => { expect(getTime).toBeLessThan(1000); // 100 gets should be under 1s with logging overhead }); - it('should handle concurrent cache access', async () => { + it("should handle concurrent cache access", async () => { const promises = []; - + for (let i = 0; i < 100; i++) { promises.push( Promise.resolve().then(() => { - postgresCache.setDBStats(mockConnection, { - total_tables: i, - total_db_size_mb: i * 10, - total_rows: i * 1000 + postgresCache.setDBStats(mockConnection, { + total_tables: i, + total_db_size_mb: i * 10, + total_rows: i * 1000, }); return postgresCache.getDBStats(mockConnection); - }) + }), ); } const results = await Promise.all(promises); - + // All results should be valid stats objects - results.forEach(result => { - expect(result).toHaveProperty('total_tables'); - expect(result).toHaveProperty('total_db_size_mb'); - expect(result).toHaveProperty('total_rows'); + results.forEach((result) => { + expect(result).toHaveProperty("total_tables"); + expect(result).toHaveProperty("total_db_size_mb"); + expect(result).toHaveProperty("total_rows"); }); }); }); diff --git a/bridge/__tests__/connectors/postgres.test.ts b/bridge/__tests__/connectors/postgres.test.ts index a66eb854..2311b3bf 100644 --- a/bridge/__tests__/connectors/postgres.test.ts +++ b/bridge/__tests__/connectors/postgres.test.ts @@ -64,11 +64,7 @@ describe("Postgres Connector", () => { }); test("Should Get the Table Details", async () => { - const result = await postgresConnector.getTableDetails( - validConfig, - "public", - "student" - ); + const result = await postgresConnector.getTableDetails(validConfig, "public", "student"); expect(Array.isArray(result)).toBe(true); expect(result.length).toBeGreaterThan(0); expect(result[0]).toHaveProperty("name"); @@ -77,13 +73,7 @@ describe("Postgres Connector", () => { }); test("Should Get Table Columns for student Table", async () => { - const columns = await postgresConnector.fetchTableData( - validConfig, - "public", - "student", - 10, - 1 - ); + const columns = await postgresConnector.fetchTableData(validConfig, "public", "student", 10, 1); expect(columns.rows.length).toBeGreaterThan(0); expect(columns.rows[0]).toHaveProperty("id"); expect(columns.rows[0]).toHaveProperty("name"); @@ -105,7 +95,7 @@ describe("Postgres Connector", () => { // onDone callback () => { doneCalled = true; - } + }, ); // wait for streaming to complete @@ -130,7 +120,7 @@ describe("Postgres Connector", () => { 100, (batch) => { rows.push(...batch); - } + }, ); // cancel after small delay diff --git a/bridge/__tests__/connectors/sqlite.cache.test.ts b/bridge/__tests__/connectors/sqlite.cache.test.ts index 2dcf39df..83efc0d9 100644 --- a/bridge/__tests__/connectors/sqlite.cache.test.ts +++ b/bridge/__tests__/connectors/sqlite.cache.test.ts @@ -143,8 +143,22 @@ describe("SQLiteCacheManager", () => { describe("Table Details Cache", () => { const mockDetails = [ - { name: "id", type: "INTEGER", not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }, - { name: "name", type: "TEXT", not_nullable: true, default_value: null, is_primary_key: false, is_foreign_key: false }, + { + name: "id", + type: "INTEGER", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }, + { + name: "name", + type: "TEXT", + not_nullable: true, + default_value: null, + is_primary_key: false, + is_foreign_key: false, + }, ]; it("should cache and retrieve table details", () => { @@ -160,8 +174,26 @@ describe("SQLiteCacheManager", () => { }); it("should cache table details per schema and table", () => { - const usersDetails = [{ name: "id", type: "INTEGER", not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }]; - const ordersDetails = [{ name: "order_id", type: "INTEGER", not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }]; + const usersDetails = [ + { + name: "id", + type: "INTEGER", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }, + ]; + const ordersDetails = [ + { + name: "order_id", + type: "INTEGER", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }, + ]; sqliteCache.setTableDetails(mockConfig, "main", "users", usersDetails); sqliteCache.setTableDetails(mockConfig, "main", "orders", ordersDetails); @@ -276,11 +308,22 @@ describe("SQLiteCacheManager", () => { describe("Cache Invalidation", () => { it("should clear all caches for a specific connection", () => { const table = { schema: "main", name: "users", type: "table" }; - const detail = { name: "id", type: "INTEGER", not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }; + const detail = { + name: "id", + type: "INTEGER", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }; // Setup caches sqliteCache.setTableList(mockConfig, [table]); - sqliteCache.setDBStats(mockConfig, { total_tables: 5, total_db_size_mb: 1.5, total_rows: 500 }); + sqliteCache.setDBStats(mockConfig, { + total_tables: 5, + total_db_size_mb: 1.5, + total_rows: 500, + }); sqliteCache.setSchemas(mockConfig, [{ name: "main" }]); sqliteCache.setTableDetails(mockConfig, "main", "users", [detail]); sqliteCache.setPrimaryKeys(mockConfig, "main", "users", [{ column_name: "id" }]); @@ -299,12 +342,28 @@ describe("SQLiteCacheManager", () => { expect(sqliteCache.getPrimaryKeys(mockConfig, "main", "users")).toBeNull(); // Verify second connection intact - expect(sqliteCache.getTableList(mockConfig2)).toEqual([{ schema: "main", name: "products", type: "table" }]); + expect(sqliteCache.getTableList(mockConfig2)).toEqual([ + { schema: "main", name: "products", type: "table" }, + ]); }); it("should clear table-specific caches", () => { - const usersDetail = { name: "id", type: "INTEGER", not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }; - const ordersDetail = { name: "order_id", type: "INTEGER", not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }; + const usersDetail = { + name: "id", + type: "INTEGER", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }; + const ordersDetail = { + name: "order_id", + type: "INTEGER", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }; // Setup sqliteCache.setTableDetails(mockConfig, "main", "users", [usersDetail]); @@ -321,13 +380,19 @@ describe("SQLiteCacheManager", () => { // Verify other table intact expect(sqliteCache.getTableDetails(mockConfig, "main", "orders")).toEqual([ordersDetail]); - expect(sqliteCache.getPrimaryKeys(mockConfig, "main", "orders")).toEqual([{ column_name: "order_id" }]); + expect(sqliteCache.getPrimaryKeys(mockConfig, "main", "orders")).toEqual([ + { column_name: "order_id" }, + ]); }); it("should clear all caches", () => { sqliteCache.setTableList(mockConfig, [{ schema: "main", name: "users", type: "table" }]); sqliteCache.setTableList(mockConfig2, [{ schema: "main", name: "products", type: "table" }]); - sqliteCache.setDBStats(mockConfig, { total_tables: 5, total_db_size_mb: 1.5, total_rows: 500 }); + sqliteCache.setDBStats(mockConfig, { + total_tables: 5, + total_db_size_mb: 1.5, + total_rows: 500, + }); sqliteCache.clearAll(); @@ -340,11 +405,22 @@ describe("SQLiteCacheManager", () => { describe("Cache Statistics", () => { it("should return correct cache statistics", () => { const table = { schema: "main", name: "users", type: "table" }; - const detail = { name: "id", type: "INTEGER", not_nullable: true, default_value: null, is_primary_key: true, is_foreign_key: false }; + const detail = { + name: "id", + type: "INTEGER", + not_nullable: true, + default_value: null, + is_primary_key: true, + is_foreign_key: false, + }; sqliteCache.setTableList(mockConfig, [table]); sqliteCache.setTableList(mockConfig, [table], "main"); - sqliteCache.setDBStats(mockConfig, { total_tables: 5, total_db_size_mb: 1.5, total_rows: 500 }); + sqliteCache.setDBStats(mockConfig, { + total_tables: 5, + total_db_size_mb: 1.5, + total_rows: 500, + }); sqliteCache.setSchemas(mockConfig, [{ name: "main" }]); sqliteCache.setTableDetails(mockConfig, "main", "users", [detail]); sqliteCache.setPrimaryKeys(mockConfig, "main", "users", [{ column_name: "id" }]); @@ -404,7 +480,7 @@ describe("SQLiteCacheManager", () => { total_rows: i * 100, }); return sqliteCache.getDBStats(mockConfig); - }) + }), ); } diff --git a/bridge/__tests__/connectors/sqlite.test.ts b/bridge/__tests__/connectors/sqlite.test.ts index f6f6136f..76626037 100644 --- a/bridge/__tests__/connectors/sqlite.test.ts +++ b/bridge/__tests__/connectors/sqlite.test.ts @@ -325,7 +325,7 @@ describe("SQLite Connector", () => { }, () => { doneCalled = true; - } + }, ); await promise; @@ -345,7 +345,7 @@ describe("SQLite Connector", () => { (batch) => { batchCount++; expect(batch.length).toBeLessThanOrEqual(1); - } + }, ); await promise; @@ -361,7 +361,7 @@ describe("SQLite Connector", () => { 1, (batch) => { rows.push(...batch); - } + }, ); // Cancel immediately @@ -390,22 +390,17 @@ describe("SQLite Connector", () => { }); test("Should throw on empty data", async () => { - await expect( - sqliteConnector.insertRow(validConfig, "main", "persons", {}) - ).rejects.toThrow("No data provided for insert"); + await expect(sqliteConnector.insertRow(validConfig, "main", "persons", {})).rejects.toThrow( + "No data provided for insert", + ); }); }); describe("updateRow", () => { test("Should update a row and return it", async () => { - const updated = await sqliteConnector.updateRow( - validConfig, - "main", - "persons", - "id", - 1, - { name: "Alice Updated" } - ); + const updated = await sqliteConnector.updateRow(validConfig, "main", "persons", "id", 1, { + name: "Alice Updated", + }); expect(updated.name).toBe("Alice Updated"); expect(updated.id).toBe(1); @@ -413,7 +408,7 @@ describe("SQLite Connector", () => { test("Should throw on empty update data", async () => { await expect( - sqliteConnector.updateRow(validConfig, "main", "persons", "id", 1, {}) + sqliteConnector.updateRow(validConfig, "main", "persons", "id", 1, {}), ).rejects.toThrow("No data provided for update"); }); }); @@ -432,20 +427,14 @@ describe("SQLite Connector", () => { "main", "persons", "id", - inserted.id + inserted.id, ); expect(result).toBe(true); }); test("Should return false when no row matches", async () => { - const result = await sqliteConnector.deleteRow( - validConfig, - "main", - "persons", - "id", - 999999 - ); + const result = await sqliteConnector.deleteRow(validConfig, "main", "persons", "id", 999999); expect(result).toBe(false); }); @@ -456,12 +445,7 @@ describe("SQLite Connector", () => { // =============================== describe("searchTable", () => { test("Should search across all columns", async () => { - const result = await sqliteConnector.searchTable( - validConfig, - "main", - "persons", - "Bob" - ); + const result = await sqliteConnector.searchTable(validConfig, "main", "persons", "Bob"); expect(result.rows.length).toBeGreaterThan(0); expect(result.total).toBeGreaterThan(0); @@ -473,7 +457,7 @@ describe("SQLite Connector", () => { "main", "persons", "bob@test.com", - "email" + "email", ); expect(result.rows.length).toBe(1); @@ -485,7 +469,7 @@ describe("SQLite Connector", () => { validConfig, "main", "persons", - "nonexistent_value_xyz" + "nonexistent_value_xyz", ); expect(result.rows).toEqual([]); @@ -498,15 +482,24 @@ describe("SQLite Connector", () => { // =============================== describe("createTable", () => { test("Should create a new table", async () => { - const result = await sqliteConnector.createTable( - validConfig, - "main", - "test_create_table", - [ - { name: "id", type: "INTEGER", not_nullable: true, is_primary_key: true, is_foreign_key: false, default_value: null }, - { name: "value", type: "TEXT", not_nullable: false, is_primary_key: false, is_foreign_key: false, default_value: null }, - ] - ); + const result = await sqliteConnector.createTable(validConfig, "main", "test_create_table", [ + { + name: "id", + type: "INTEGER", + not_nullable: true, + is_primary_key: true, + is_foreign_key: false, + default_value: null, + }, + { + name: "value", + type: "TEXT", + not_nullable: false, + is_primary_key: false, + is_foreign_key: false, + default_value: null, + }, + ]); expect(result).toBe(true); @@ -524,11 +517,28 @@ describe("SQLite Connector", () => { test("Should add a column to a table", async () => { // Create a temp table first await sqliteConnector.createTable(validConfig, "main", "test_alter", [ - { name: "id", type: "INTEGER", not_nullable: true, is_primary_key: true, is_foreign_key: false, default_value: null }, + { + name: "id", + type: "INTEGER", + not_nullable: true, + is_primary_key: true, + is_foreign_key: false, + default_value: null, + }, ]); const result = await sqliteConnector.alterTable(validConfig, "main", "test_alter", [ - { type: "ADD_COLUMN", column: { name: "new_col", type: "TEXT", not_nullable: false, is_primary_key: false, is_foreign_key: false, default_value: null } }, + { + type: "ADD_COLUMN", + column: { + name: "new_col", + type: "TEXT", + not_nullable: false, + is_primary_key: false, + is_foreign_key: false, + default_value: null, + }, + }, ]); expect(result).toBe(true); @@ -558,7 +568,14 @@ describe("SQLite Connector", () => { describe("dropTable", () => { test("Should drop a table", async () => { await sqliteConnector.createTable(validConfig, "main", "test_drop", [ - { name: "id", type: "INTEGER", not_nullable: true, is_primary_key: true, is_foreign_key: false, default_value: null }, + { + name: "id", + type: "INTEGER", + not_nullable: true, + is_primary_key: true, + is_foreign_key: false, + default_value: null, + }, ]); const result = await sqliteConnector.dropTable(validConfig, "main", "test_drop"); @@ -572,8 +589,22 @@ describe("SQLite Connector", () => { describe("createIndexes", () => { test("Should create indexes on a table", async () => { await sqliteConnector.createTable(validConfig, "main", "test_indexes", [ - { name: "id", type: "INTEGER", not_nullable: true, is_primary_key: true, is_foreign_key: false, default_value: null }, - { name: "value", type: "TEXT", not_nullable: false, is_primary_key: false, is_foreign_key: false, default_value: null }, + { + name: "id", + type: "INTEGER", + not_nullable: true, + is_primary_key: true, + is_foreign_key: false, + default_value: null, + }, + { + name: "value", + type: "TEXT", + not_nullable: false, + is_primary_key: false, + is_foreign_key: false, + default_value: null, + }, ]); const result = await sqliteConnector.createIndexes(validConfig, "main", [ @@ -600,7 +631,7 @@ describe("SQLite Connector", () => { }); // =============================== - // READONLY TESTS + // READONLY TESTS // =============================== describe("readonly mode", () => { test("Should open in readonly mode and allow reads", async () => { diff --git a/bridge/__tests__/databaseService.test.ts b/bridge/__tests__/databaseService.test.ts index b6c326a3..fac51353 100644 --- a/bridge/__tests__/databaseService.test.ts +++ b/bridge/__tests__/databaseService.test.ts @@ -108,9 +108,7 @@ describe("Database Service Method", () => { // Arrange const { host, ...payload } = mockInput; // Act & Assert - await expect(dbService.addDatabase(payload)).rejects.toThrow( - "Missing required field: host" - ); + await expect(dbService.addDatabase(payload)).rejects.toThrow("Missing required field: host"); }); // Test Case 3: Missing required field 'user' @@ -118,9 +116,7 @@ describe("Database Service Method", () => { // Arrange const { user, ...payload } = mockInput; // Act & Assert - await expect(dbService.addDatabase(payload)).rejects.toThrow( - "Missing required field: user" - ); + await expect(dbService.addDatabase(payload)).rejects.toThrow("Missing required field: user"); }); // Test Case 4: Missing required field 'database' @@ -129,7 +125,7 @@ describe("Database Service Method", () => { const { database, ...payload } = mockInput; // Act & Assert await expect(dbService.addDatabase(payload)).rejects.toThrow( - "Missing required field: database" + "Missing required field: database", ); }); @@ -138,9 +134,7 @@ describe("Database Service Method", () => { // Arrange const { type, ...payload } = mockInput; // Act & Assert - await expect(dbService.addDatabase(payload)).rejects.toThrow( - "Missing required field: type" - ); + await expect(dbService.addDatabase(payload)).rejects.toThrow("Missing required field: type"); }); // Test Case 6: Missing required field 'name' @@ -148,9 +142,7 @@ describe("Database Service Method", () => { // Arrange const { name, ...payload } = mockInput; // Act & Assert - await expect(dbService.addDatabase(payload)).rejects.toThrow( - "Missing required field: name" - ); + await expect(dbService.addDatabase(payload)).rejects.toThrow("Missing required field: name"); }); // Test Case 7: Missing required field 'port' @@ -158,9 +150,7 @@ describe("Database Service Method", () => { // Arrange const { port, ...payload } = mockInput; // Act & Assert - await expect(dbService.addDatabase(payload)).rejects.toThrow( - "Missing required field: port" - ); + await expect(dbService.addDatabase(payload)).rejects.toThrow("Missing required field: port"); }); // Test Case 8 : List databases does not expose credentialId @@ -179,9 +169,7 @@ describe("Database Service Method", () => { // Arrange const fakeDbId = "nonexistent-id"; // Act & Assert - await expect(dbService.getDatabaseConnection(fakeDbId)).rejects.toThrow( - "Database not found" - ); + await expect(dbService.getDatabaseConnection(fakeDbId)).rejects.toThrow("Database not found"); }); // Test Case 10: Update database with missing ID @@ -189,9 +177,7 @@ describe("Database Service Method", () => { // Arrange const payload = { name: "UpdatedName" }; // Act & Assert - await expect(dbService.updateDatabase("", payload)).rejects.toThrow( - "Missing id" - ); + await expect(dbService.updateDatabase("", payload)).rejects.toThrow("Missing id"); }); // Test Case 11: Delete database with missing ID @@ -230,8 +216,6 @@ describe("Database Service Method", () => { // Arrange const fakeDbId = "nonexistent-database-id"; // Act & Assert - await expect(dbService.deleteDatabase(fakeDbId)).rejects.toThrow( - "Database not found" - ); + await expect(dbService.deleteDatabase(fakeDbId)).rejects.toThrow("Database not found"); }); }); diff --git a/bridge/__tests__/dbStore.test.ts b/bridge/__tests__/dbStore.test.ts index b626b3d0..cff503f4 100644 --- a/bridge/__tests__/dbStore.test.ts +++ b/bridge/__tests__/dbStore.test.ts @@ -50,7 +50,7 @@ describe("DbStore Cache Tests", () => { TEST_CONFIG_FILE, TEST_CREDENTIALS_FILE, NORMAL_CACHE_TTL, - true // autoPreload + true, // autoPreload ); // Wait for preload to complete await dbStore.waitUntilReady(); @@ -214,7 +214,7 @@ describe("DbStore Cache Tests", () => { TEST_CONFIG_FILE, TEST_CREDENTIALS_FILE, SHORT_CACHE_TTL, - true // autoPreload + true, // autoPreload ); await shortTtlStore.waitUntilReady(); @@ -237,7 +237,7 @@ describe("DbStore Cache Tests", () => { TEST_CONFIG_FILE, TEST_CREDENTIALS_FILE, NORMAL_CACHE_TTL, - true // autoPreload enabled + true, // autoPreload enabled ); // Wait for preload @@ -255,7 +255,7 @@ describe("DbStore Cache Tests", () => { TEST_CONFIG_FILE, TEST_CREDENTIALS_FILE, NORMAL_CACHE_TTL, - false // autoPreload disabled + false, // autoPreload disabled ); // Without preload, cache should not be ready immediately @@ -275,7 +275,7 @@ describe("DbStore Cache Tests", () => { TEST_CONFIG_FILE, TEST_CREDENTIALS_FILE, NORMAL_CACHE_TTL, - true + true, ); await preloadStore.waitUntilReady(); @@ -290,7 +290,7 @@ describe("DbStore Cache Tests", () => { TEST_CONFIG_FILE, TEST_CREDENTIALS_FILE, NORMAL_CACHE_TTL, - false // no preload + false, // no preload ); // First listDBs will read from disk @@ -313,7 +313,7 @@ describe("DbStore Cache Tests", () => { TEST_CONFIG_FILE, TEST_CREDENTIALS_FILE, NORMAL_CACHE_TTL, - true + true, ); await newStore.waitUntilReady(); @@ -338,7 +338,7 @@ describe("DbStore Cache Tests", () => { TEST_CONFIG_FILE, TEST_CREDENTIALS_FILE, NORMAL_CACHE_TTL, - false + false, ); expect(manualStore.isReady()).toBe(false); @@ -375,7 +375,7 @@ describe("DbStore Cache Tests", () => { TEST_CONFIG_FILE, TEST_CREDENTIALS_FILE, NORMAL_CACHE_TTL, - true + true, ); await preloadStore.waitUntilReady(); @@ -410,8 +410,7 @@ describe("DbStore Cache Tests", () => { cachedTimes.push(performance.now() - cachedStart); } - const avgCachedTime = - cachedTimes.reduce((a, b) => a + b, 0) / cachedTimes.length; + const avgCachedTime = cachedTimes.reduce((a, b) => a + b, 0) / cachedTimes.length; // Cached reads should be significantly faster // We expect at least 2x improvement (usually much more) @@ -437,8 +436,7 @@ describe("DbStore Cache Tests", () => { cachedTimes.push(performance.now() - cachedStart); } - const avgCachedTime = - cachedTimes.reduce((a, b) => a + b, 0) / cachedTimes.length; + const avgCachedTime = cachedTimes.reduce((a, b) => a + b, 0) / cachedTimes.length; expect(avgCachedTime).toBeLessThan(uncachedTime); }); @@ -529,4 +527,3 @@ describe("DbStore Cache Tests", () => { }); }); }); - diff --git a/bridge/__tests__/discoveryService.test.ts b/bridge/__tests__/discoveryService.test.ts index 03e992eb..40f9e475 100644 --- a/bridge/__tests__/discoveryService.test.ts +++ b/bridge/__tests__/discoveryService.test.ts @@ -2,359 +2,353 @@ import { describe, expect, test, beforeEach } from "@jest/globals"; import { DiscoveryService, DiscoveredDatabase } from "../src/services/discoveryService"; describe("DiscoveryService", () => { - let service: DiscoveryService; + let service: DiscoveryService; - beforeEach(() => { - service = new DiscoveryService(); + beforeEach(() => { + service = new DiscoveryService(); + }); + + describe("generateFunName", () => { + test("should generate a name in format adjective-noun", () => { + const name = service.generateFunName("postgresql", 5432); + expect(name).toMatch(/^[a-z]+-[a-z]+$/); + }); + + test("should add port suffix for non-default PostgreSQL port", () => { + const name = service.generateFunName("postgresql", 5433); + expect(name).toMatch(/^[a-z]+-[a-z]+-5433$/); }); - describe("generateFunName", () => { - test("should generate a name in format adjective-noun", () => { - const name = service.generateFunName("postgresql", 5432); - expect(name).toMatch(/^[a-z]+-[a-z]+$/); - }); - - test("should add port suffix for non-default PostgreSQL port", () => { - const name = service.generateFunName("postgresql", 5433); - expect(name).toMatch(/^[a-z]+-[a-z]+-5433$/); - }); - - test("should not add port suffix for default PostgreSQL port", () => { - const name = service.generateFunName("postgresql", 5432); - expect(name).not.toContain("-5432"); - }); - - test("should not add port suffix for default MySQL port", () => { - const name = service.generateFunName("mysql", 3306); - expect(name).not.toContain("-3306"); - }); - - test("should not add port suffix for default MariaDB port", () => { - const name = service.generateFunName("mariadb", 3306); - expect(name).not.toContain("-3306"); - }); - - test("should add port suffix for non-default MySQL port", () => { - const name = service.generateFunName("mysql", 3307); - expect(name).toMatch(/^[a-z]+-[a-z]+-3307$/); - }); - - test("should generate different names on multiple calls", () => { - // Given the randomness, most calls should produce different names - const names = new Set(); - for (let i = 0; i < 20; i++) { - names.add(service.generateFunName("postgresql", 5432)); - } - // At least some variety expected (not all same) - expect(names.size).toBeGreaterThan(1); - }); + test("should not add port suffix for default PostgreSQL port", () => { + const name = service.generateFunName("postgresql", 5432); + expect(name).not.toContain("-5432"); }); - describe("extractCredentialsFromEnv (via reflection)", () => { - // Access private method via prototype for testing - const extractCredentials = ( - svc: DiscoveryService, - dbType: "postgresql" | "mysql" | "mariadb", - envVars: Map - ) => { - return (svc as any).extractCredentialsFromEnv(dbType, envVars); - }; - - describe("PostgreSQL", () => { - test("should extract PostgreSQL credentials from env vars", () => { - const envVars = new Map([ - ["POSTGRES_USER", "testuser"], - ["POSTGRES_PASSWORD", "testpass"], - ["POSTGRES_DB", "testdb"], - ]); - - const result = extractCredentials(service, "postgresql", envVars); - - expect(result.user).toBe("testuser"); - expect(result.password).toBe("testpass"); - expect(result.database).toBe("testdb"); - }); - - test("should use defaults when PostgreSQL env vars are missing", () => { - const envVars = new Map(); - - const result = extractCredentials(service, "postgresql", envVars); - - expect(result.user).toBe("postgres"); - expect(result.password).toBe(""); - expect(result.database).toBe("postgres"); - }); - - test("should use POSTGRES_USER as database when POSTGRES_DB is missing", () => { - const envVars = new Map([ - ["POSTGRES_USER", "customuser"], - ]); - - const result = extractCredentials(service, "postgresql", envVars); - - expect(result.user).toBe("customuser"); - expect(result.database).toBe("customuser"); - }); - }); - - describe("MySQL", () => { - test("should extract MySQL credentials with custom user", () => { - const envVars = new Map([ - ["MYSQL_USER", "myuser"], - ["MYSQL_PASSWORD", "mypass"], - ["MYSQL_DATABASE", "mydb"], - ]); - - const result = extractCredentials(service, "mysql", envVars); - - expect(result.user).toBe("myuser"); - expect(result.password).toBe("mypass"); - expect(result.database).toBe("mydb"); - }); - - test("should use root password when user is root", () => { - const envVars = new Map([ - ["MYSQL_ROOT_PASSWORD", "rootpass"], - ["MYSQL_DATABASE", "mydb"], - ]); - - const result = extractCredentials(service, "mysql", envVars); - - expect(result.user).toBe("root"); - expect(result.password).toBe("rootpass"); - expect(result.database).toBe("mydb"); - }); - - test("should use defaults when MySQL env vars are missing", () => { - const envVars = new Map(); - - const result = extractCredentials(service, "mysql", envVars); - - expect(result.user).toBe("root"); - expect(result.password).toBe(""); - expect(result.database).toBe("mysql"); - }); - }); - - describe("MariaDB", () => { - test("should extract MariaDB credentials with MARIADB_ prefix", () => { - const envVars = new Map([ - ["MARIADB_USER", "mariauser"], - ["MARIADB_PASSWORD", "mariapass"], - ["MARIADB_DATABASE", "mariadb"], - ]); - - const result = extractCredentials(service, "mariadb", envVars); - - expect(result.user).toBe("mariauser"); - expect(result.password).toBe("mariapass"); - expect(result.database).toBe("mariadb"); - }); - - test("should fall back to MYSQL_ prefix for MariaDB", () => { - const envVars = new Map([ - ["MYSQL_USER", "fallbackuser"], - ["MYSQL_PASSWORD", "fallbackpass"], - ["MYSQL_DATABASE", "fallbackdb"], - ]); - - const result = extractCredentials(service, "mariadb", envVars); - - expect(result.user).toBe("fallbackuser"); - expect(result.password).toBe("fallbackpass"); - expect(result.database).toBe("fallbackdb"); - }); - - test("should use MARIADB_ROOT_PASSWORD for root user", () => { - const envVars = new Map([ - ["MARIADB_ROOT_PASSWORD", "mariarootpass"], - ]); - - const result = extractCredentials(service, "mariadb", envVars); - - expect(result.user).toBe("root"); - expect(result.password).toBe("mariarootpass"); - }); - - test("should fall back to MYSQL_ROOT_PASSWORD for root user", () => { - const envVars = new Map([ - ["MYSQL_ROOT_PASSWORD", "mysqlrootpass"], - ]); - - const result = extractCredentials(service, "mariadb", envVars); - - expect(result.user).toBe("root"); - expect(result.password).toBe("mysqlrootpass"); - }); - }); + test("should not add port suffix for default MySQL port", () => { + const name = service.generateFunName("mysql", 3306); + expect(name).not.toContain("-3306"); }); - describe("getDefaultPort (private)", () => { - const getDefaultPort = (svc: DiscoveryService, type: string) => { - return (svc as any).getDefaultPort(type); - }; + test("should not add port suffix for default MariaDB port", () => { + const name = service.generateFunName("mariadb", 3306); + expect(name).not.toContain("-3306"); + }); + + test("should add port suffix for non-default MySQL port", () => { + const name = service.generateFunName("mysql", 3307); + expect(name).toMatch(/^[a-z]+-[a-z]+-3307$/); + }); + + test("should generate different names on multiple calls", () => { + // Given the randomness, most calls should produce different names + const names = new Set(); + for (let i = 0; i < 20; i++) { + names.add(service.generateFunName("postgresql", 5432)); + } + // At least some variety expected (not all same) + expect(names.size).toBeGreaterThan(1); + }); + }); + + describe("extractCredentialsFromEnv (via reflection)", () => { + // Access private method via prototype for testing + const extractCredentials = ( + svc: DiscoveryService, + dbType: "postgresql" | "mysql" | "mariadb", + envVars: Map, + ) => { + return (svc as any).extractCredentialsFromEnv(dbType, envVars); + }; + + describe("PostgreSQL", () => { + test("should extract PostgreSQL credentials from env vars", () => { + const envVars = new Map([ + ["POSTGRES_USER", "testuser"], + ["POSTGRES_PASSWORD", "testpass"], + ["POSTGRES_DB", "testdb"], + ]); + + const result = extractCredentials(service, "postgresql", envVars); + + expect(result.user).toBe("testuser"); + expect(result.password).toBe("testpass"); + expect(result.database).toBe("testdb"); + }); + + test("should use defaults when PostgreSQL env vars are missing", () => { + const envVars = new Map(); + + const result = extractCredentials(service, "postgresql", envVars); + + expect(result.user).toBe("postgres"); + expect(result.password).toBe(""); + expect(result.database).toBe("postgres"); + }); + + test("should use POSTGRES_USER as database when POSTGRES_DB is missing", () => { + const envVars = new Map([["POSTGRES_USER", "customuser"]]); + + const result = extractCredentials(service, "postgresql", envVars); + + expect(result.user).toBe("customuser"); + expect(result.database).toBe("customuser"); + }); + }); + + describe("MySQL", () => { + test("should extract MySQL credentials with custom user", () => { + const envVars = new Map([ + ["MYSQL_USER", "myuser"], + ["MYSQL_PASSWORD", "mypass"], + ["MYSQL_DATABASE", "mydb"], + ]); + + const result = extractCredentials(service, "mysql", envVars); - test("should return 5432 for postgresql", () => { - expect(getDefaultPort(service, "postgresql")).toBe(5432); - }); + expect(result.user).toBe("myuser"); + expect(result.password).toBe("mypass"); + expect(result.database).toBe("mydb"); + }); - test("should return 3306 for mysql", () => { - expect(getDefaultPort(service, "mysql")).toBe(3306); - }); + test("should use root password when user is root", () => { + const envVars = new Map([ + ["MYSQL_ROOT_PASSWORD", "rootpass"], + ["MYSQL_DATABASE", "mydb"], + ]); - test("should return 3306 for mariadb", () => { - expect(getDefaultPort(service, "mariadb")).toBe(3306); - }); + const result = extractCredentials(service, "mysql", envVars); - test("should return 0 for unknown type", () => { - expect(getDefaultPort(service, "unknown")).toBe(0); - }); + expect(result.user).toBe("root"); + expect(result.password).toBe("rootpass"); + expect(result.database).toBe("mydb"); + }); + + test("should use defaults when MySQL env vars are missing", () => { + const envVars = new Map(); + + const result = extractCredentials(service, "mysql", envVars); + + expect(result.user).toBe("root"); + expect(result.password).toBe(""); + expect(result.database).toBe("mysql"); + }); }); - describe("getDefaultUser (private)", () => { - const getDefaultUser = (svc: DiscoveryService, type: string) => { - return (svc as any).getDefaultUser(type); - }; + describe("MariaDB", () => { + test("should extract MariaDB credentials with MARIADB_ prefix", () => { + const envVars = new Map([ + ["MARIADB_USER", "mariauser"], + ["MARIADB_PASSWORD", "mariapass"], + ["MARIADB_DATABASE", "mariadb"], + ]); + + const result = extractCredentials(service, "mariadb", envVars); + + expect(result.user).toBe("mariauser"); + expect(result.password).toBe("mariapass"); + expect(result.database).toBe("mariadb"); + }); + + test("should fall back to MYSQL_ prefix for MariaDB", () => { + const envVars = new Map([ + ["MYSQL_USER", "fallbackuser"], + ["MYSQL_PASSWORD", "fallbackpass"], + ["MYSQL_DATABASE", "fallbackdb"], + ]); - test("should return postgres for postgresql", () => { - expect(getDefaultUser(service, "postgresql")).toBe("postgres"); - }); + const result = extractCredentials(service, "mariadb", envVars); - test("should return root for mysql", () => { - expect(getDefaultUser(service, "mysql")).toBe("root"); - }); + expect(result.user).toBe("fallbackuser"); + expect(result.password).toBe("fallbackpass"); + expect(result.database).toBe("fallbackdb"); + }); - test("should return root for mariadb", () => { - expect(getDefaultUser(service, "mariadb")).toBe("root"); - }); + test("should use MARIADB_ROOT_PASSWORD for root user", () => { + const envVars = new Map([["MARIADB_ROOT_PASSWORD", "mariarootpass"]]); - test("should return empty string for unknown type", () => { - expect(getDefaultUser(service, "unknown")).toBe(""); - }); + const result = extractCredentials(service, "mariadb", envVars); + + expect(result.user).toBe("root"); + expect(result.password).toBe("mariarootpass"); + }); + + test("should fall back to MYSQL_ROOT_PASSWORD for root user", () => { + const envVars = new Map([["MYSQL_ROOT_PASSWORD", "mysqlrootpass"]]); + + const result = extractCredentials(service, "mariadb", envVars); + + expect(result.user).toBe("root"); + expect(result.password).toBe("mysqlrootpass"); + }); }); + }); - describe("getDefaultDatabase (private)", () => { - const getDefaultDatabase = (svc: DiscoveryService, type: string) => { - return (svc as any).getDefaultDatabase(type); - }; + describe("getDefaultPort (private)", () => { + const getDefaultPort = (svc: DiscoveryService, type: string) => { + return (svc as any).getDefaultPort(type); + }; - test("should return postgres for postgresql", () => { - expect(getDefaultDatabase(service, "postgresql")).toBe("postgres"); - }); + test("should return 5432 for postgresql", () => { + expect(getDefaultPort(service, "postgresql")).toBe(5432); + }); - test("should return mysql for mysql", () => { - expect(getDefaultDatabase(service, "mysql")).toBe("mysql"); - }); + test("should return 3306 for mysql", () => { + expect(getDefaultPort(service, "mysql")).toBe(3306); + }); + + test("should return 3306 for mariadb", () => { + expect(getDefaultPort(service, "mariadb")).toBe(3306); + }); + + test("should return 0 for unknown type", () => { + expect(getDefaultPort(service, "unknown")).toBe(0); + }); + }); + + describe("getDefaultUser (private)", () => { + const getDefaultUser = (svc: DiscoveryService, type: string) => { + return (svc as any).getDefaultUser(type); + }; - test("should return mysql for mariadb", () => { - expect(getDefaultDatabase(service, "mariadb")).toBe("mysql"); - }); + test("should return postgres for postgresql", () => { + expect(getDefaultUser(service, "postgresql")).toBe("postgres"); + }); + + test("should return root for mysql", () => { + expect(getDefaultUser(service, "mysql")).toBe("root"); + }); + + test("should return root for mariadb", () => { + expect(getDefaultUser(service, "mariadb")).toBe("root"); + }); - test("should return empty string for unknown type", () => { - expect(getDefaultDatabase(service, "unknown")).toBe(""); - }); + test("should return empty string for unknown type", () => { + expect(getDefaultUser(service, "unknown")).toBe(""); + }); + }); + + describe("getDefaultDatabase (private)", () => { + const getDefaultDatabase = (svc: DiscoveryService, type: string) => { + return (svc as any).getDefaultDatabase(type); + }; + + test("should return postgres for postgresql", () => { + expect(getDefaultDatabase(service, "postgresql")).toBe("postgres"); + }); + + test("should return mysql for mysql", () => { + expect(getDefaultDatabase(service, "mysql")).toBe("mysql"); + }); + + test("should return mysql for mariadb", () => { + expect(getDefaultDatabase(service, "mariadb")).toBe("mysql"); + }); + + test("should return empty string for unknown type", () => { + expect(getDefaultDatabase(service, "unknown")).toBe(""); + }); + }); + + describe("DiscoveredDatabase interface", () => { + test("should have all required properties for local source", () => { + const db: DiscoveredDatabase = { + type: "postgresql", + host: "localhost", + port: 5432, + source: "local", + suggestedName: "test-db", + defaultUser: "postgres", + defaultDatabase: "postgres", + }; + + expect(db.type).toBe("postgresql"); + expect(db.host).toBe("localhost"); + expect(db.port).toBe(5432); + expect(db.source).toBe("local"); + expect(db.suggestedName).toBe("test-db"); + expect(db.defaultUser).toBe("postgres"); + expect(db.defaultDatabase).toBe("postgres"); + expect(db.containerName).toBeUndefined(); + expect(db.defaultPassword).toBeUndefined(); }); - describe("DiscoveredDatabase interface", () => { - test("should have all required properties for local source", () => { - const db: DiscoveredDatabase = { - type: "postgresql", - host: "localhost", - port: 5432, - source: "local", - suggestedName: "test-db", - defaultUser: "postgres", - defaultDatabase: "postgres", - }; - - expect(db.type).toBe("postgresql"); - expect(db.host).toBe("localhost"); - expect(db.port).toBe(5432); - expect(db.source).toBe("local"); - expect(db.suggestedName).toBe("test-db"); - expect(db.defaultUser).toBe("postgres"); - expect(db.defaultDatabase).toBe("postgres"); - expect(db.containerName).toBeUndefined(); - expect(db.defaultPassword).toBeUndefined(); - }); - - test("should accept optional properties for Docker containers", () => { - const db: DiscoveredDatabase = { - type: "mysql", - host: "localhost", - port: 3306, - source: "docker", - containerName: "mysql-container", - suggestedName: "test-mysql", - defaultUser: "root", - defaultDatabase: "mydb", - defaultPassword: "secret123", - }; - - expect(db.source).toBe("docker"); - expect(db.containerName).toBe("mysql-container"); - expect(db.defaultPassword).toBe("secret123"); - }); - - test("should accept all database types", () => { - const pgDb: DiscoveredDatabase = { - type: "postgresql", - host: "localhost", - port: 5432, - source: "local", - suggestedName: "pg-db", - defaultUser: "postgres", - defaultDatabase: "postgres", - }; - - const mysqlDb: DiscoveredDatabase = { - type: "mysql", - host: "localhost", - port: 3306, - source: "local", - suggestedName: "mysql-db", - defaultUser: "root", - defaultDatabase: "mysql", - }; - - const mariaDb: DiscoveredDatabase = { - type: "mariadb", - host: "localhost", - port: 3306, - source: "docker", - suggestedName: "maria-db", - defaultUser: "root", - defaultDatabase: "mysql", - }; - - expect(pgDb.type).toBe("postgresql"); - expect(mysqlDb.type).toBe("mysql"); - expect(mariaDb.type).toBe("mariadb"); - }); + test("should accept optional properties for Docker containers", () => { + const db: DiscoveredDatabase = { + type: "mysql", + host: "localhost", + port: 3306, + source: "docker", + containerName: "mysql-container", + suggestedName: "test-mysql", + defaultUser: "root", + defaultDatabase: "mydb", + defaultPassword: "secret123", + }; + + expect(db.source).toBe("docker"); + expect(db.containerName).toBe("mysql-container"); + expect(db.defaultPassword).toBe("secret123"); }); - describe("discoverLocalDatabases", () => { - test("should return an array", async () => { - // This test just verifies the method exists and returns an array - // Actual discovery depends on system state - const result = await service.discoverLocalDatabases(); - expect(Array.isArray(result)).toBe(true); - }, 30000); // Increased timeout for docker commands - - test("each discovered database should have required fields", async () => { - const result = await service.discoverLocalDatabases(); - - for (const db of result) { - expect(db.type).toBeDefined(); - expect(["postgresql", "mysql", "mariadb"]).toContain(db.type); - expect(db.host).toBeDefined(); - expect(typeof db.port).toBe("number"); - expect(db.source).toBeDefined(); - expect(["local", "docker"]).toContain(db.source); - expect(db.suggestedName).toBeDefined(); - expect(db.defaultUser).toBeDefined(); - expect(db.defaultDatabase).toBeDefined(); - } - }, 30000); // Increased timeout for docker commands + test("should accept all database types", () => { + const pgDb: DiscoveredDatabase = { + type: "postgresql", + host: "localhost", + port: 5432, + source: "local", + suggestedName: "pg-db", + defaultUser: "postgres", + defaultDatabase: "postgres", + }; + + const mysqlDb: DiscoveredDatabase = { + type: "mysql", + host: "localhost", + port: 3306, + source: "local", + suggestedName: "mysql-db", + defaultUser: "root", + defaultDatabase: "mysql", + }; + + const mariaDb: DiscoveredDatabase = { + type: "mariadb", + host: "localhost", + port: 3306, + source: "docker", + suggestedName: "maria-db", + defaultUser: "root", + defaultDatabase: "mysql", + }; + + expect(pgDb.type).toBe("postgresql"); + expect(mysqlDb.type).toBe("mysql"); + expect(mariaDb.type).toBe("mariadb"); }); + }); + + describe("discoverLocalDatabases", () => { + test("should return an array", async () => { + // This test just verifies the method exists and returns an array + // Actual discovery depends on system state + const result = await service.discoverLocalDatabases(); + expect(Array.isArray(result)).toBe(true); + }, 30000); // Increased timeout for docker commands + + test("each discovered database should have required fields", async () => { + const result = await service.discoverLocalDatabases(); + + for (const db of result) { + expect(db.type).toBeDefined(); + expect(["postgresql", "mysql", "mariadb"]).toContain(db.type); + expect(db.host).toBeDefined(); + expect(typeof db.port).toBe("number"); + expect(db.source).toBeDefined(); + expect(["local", "docker"]).toContain(db.source); + expect(db.suggestedName).toBeDefined(); + expect(db.defaultUser).toBeDefined(); + expect(db.defaultDatabase).toBeDefined(); + } + }, 30000); // Increased timeout for docker commands + }); }); diff --git a/bridge/__tests__/gitAdvancedHandlers.test.ts b/bridge/__tests__/gitAdvancedHandlers.test.ts index 281daf8a..f8412f83 100644 --- a/bridge/__tests__/gitAdvancedHandlers.test.ts +++ b/bridge/__tests__/gitAdvancedHandlers.test.ts @@ -6,35 +6,35 @@ import type { Rpc } from "../src/types"; // ─── Mock Factory ────────────────────────────────── function createMockRpc(): Rpc & { - _responses: any[]; - _errors: any[]; + _responses: any[]; + _errors: any[]; } { - const responses: any[] = []; - const errors: any[] = []; - return { - sendResponse: jest.fn((id: number | string, payload: any) => { - responses.push({ id, payload }); - }), - sendError: jest.fn((id: number | string, err: any) => { - errors.push({ id, err }); - }), - _responses: responses, - _errors: errors, - }; + const responses: any[] = []; + const errors: any[] = []; + return { + sendResponse: jest.fn((id: number | string, payload: any) => { + responses.push({ id, payload }); + }), + sendError: jest.fn((id: number | string, err: any) => { + errors.push({ id, err }); + }), + _responses: responses, + _errors: errors, + }; } function createMockGitService(): GitService { - return { - remoteList: jest.fn().mockResolvedValue([]), - remoteAdd: jest.fn().mockResolvedValue(undefined), - remoteRemove: jest.fn().mockResolvedValue(undefined), - remoteGetUrl: jest.fn().mockResolvedValue("https://github.com/test/repo.git"), - remoteSetUrl: jest.fn().mockResolvedValue(undefined), - push: jest.fn().mockResolvedValue("Everything up-to-date"), - pull: jest.fn().mockResolvedValue("Already up to date."), - fetch: jest.fn().mockResolvedValue(""), - revert: jest.fn().mockResolvedValue(""), - } as any; + return { + remoteList: jest.fn().mockResolvedValue([]), + remoteAdd: jest.fn().mockResolvedValue(undefined), + remoteRemove: jest.fn().mockResolvedValue(undefined), + remoteGetUrl: jest.fn().mockResolvedValue("https://github.com/test/repo.git"), + remoteSetUrl: jest.fn().mockResolvedValue(undefined), + push: jest.fn().mockResolvedValue("Everything up-to-date"), + pull: jest.fn().mockResolvedValue("Already up to date."), + fetch: jest.fn().mockResolvedValue(""), + revert: jest.fn().mockResolvedValue(""), + } as any; } // ─── Tests ────────────────────────────────────────── @@ -44,9 +44,9 @@ let gitService: GitService; let handlers: GitAdvancedHandlers; beforeEach(() => { - rpc = createMockRpc(); - gitService = createMockGitService(); - handlers = new GitAdvancedHandlers(rpc, undefined, gitService); + rpc = createMockRpc(); + gitService = createMockGitService(); + handlers = new GitAdvancedHandlers(rpc, undefined, gitService); }); // ========================================== @@ -54,42 +54,42 @@ beforeEach(() => { // ========================================== describe("GitAdvancedHandlers — requireDir validation", () => { - const handlerMethods = [ - "handleRemoteList", - "handleRemoteAdd", - "handleRemoteRemove", - "handleRemoteGetUrl", - "handleRemoteSetUrl", - "handlePush", - "handlePull", - "handleFetch", - "handleRevert", - ] as const; - - test("all handlers send BAD_REQUEST when dir is missing", async () => { - for (const method of handlerMethods) { - rpc = createMockRpc(); - gitService = createMockGitService(); - handlers = new GitAdvancedHandlers(rpc, undefined, gitService); - - await (handlers as any)[method]({}, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("dir"), - }); - } - }); - - test("accepts dir, path, or cwd as directory param", async () => { - for (const key of ["dir", "path", "cwd"]) { - rpc = createMockRpc(); - gitService = createMockGitService(); - handlers = new GitAdvancedHandlers(rpc, undefined, gitService); - - await handlers.handleRemoteList({ [key]: "/repo" }, 1); - expect(rpc.sendResponse).toHaveBeenCalled(); - } - }); + const handlerMethods = [ + "handleRemoteList", + "handleRemoteAdd", + "handleRemoteRemove", + "handleRemoteGetUrl", + "handleRemoteSetUrl", + "handlePush", + "handlePull", + "handleFetch", + "handleRevert", + ] as const; + + test("all handlers send BAD_REQUEST when dir is missing", async () => { + for (const method of handlerMethods) { + rpc = createMockRpc(); + gitService = createMockGitService(); + handlers = new GitAdvancedHandlers(rpc, undefined, gitService); + + await (handlers as any)[method]({}, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("dir"), + }); + } + }); + + test("accepts dir, path, or cwd as directory param", async () => { + for (const key of ["dir", "path", "cwd"]) { + rpc = createMockRpc(); + gitService = createMockGitService(); + handlers = new GitAdvancedHandlers(rpc, undefined, gitService); + + await handlers.handleRemoteList({ [key]: "/repo" }, 1); + expect(rpc.sendResponse).toHaveBeenCalled(); + } + }); }); // ========================================== @@ -97,89 +97,81 @@ describe("GitAdvancedHandlers — requireDir validation", () => { // ========================================== describe("GitAdvancedHandlers — Remote Management", () => { - test("handleRemoteList returns remotes", async () => { - const mockRemotes = [ - { name: "origin", fetchUrl: "https://a.git", pushUrl: "https://a.git" }, - ]; - (gitService.remoteList as jest.Mock).mockResolvedValue(mockRemotes); - - await handlers.handleRemoteList({ dir: "/repo" }, 1); - expect(gitService.remoteList).toHaveBeenCalledWith("/repo"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: mockRemotes, - }); + test("handleRemoteList returns remotes", async () => { + const mockRemotes = [{ name: "origin", fetchUrl: "https://a.git", pushUrl: "https://a.git" }]; + (gitService.remoteList as jest.Mock).mockResolvedValue(mockRemotes); + + await handlers.handleRemoteList({ dir: "/repo" }, 1); + expect(gitService.remoteList).toHaveBeenCalledWith("/repo"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: mockRemotes, }); - - test("handleRemoteAdd adds a remote", async () => { - await handlers.handleRemoteAdd( - { dir: "/repo", name: "upstream", url: "https://up.git" }, - 1 - ); - expect(gitService.remoteAdd).toHaveBeenCalledWith("/repo", "upstream", "https://up.git"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); + }); + + test("handleRemoteAdd adds a remote", async () => { + await handlers.handleRemoteAdd({ dir: "/repo", name: "upstream", url: "https://up.git" }, 1); + expect(gitService.remoteAdd).toHaveBeenCalledWith("/repo", "upstream", "https://up.git"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); + }); + + test("handleRemoteAdd returns BAD_REQUEST when name missing", async () => { + await handlers.handleRemoteAdd({ dir: "/repo", url: "https://up.git" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("name"), }); + }); - test("handleRemoteAdd returns BAD_REQUEST when name missing", async () => { - await handlers.handleRemoteAdd({ dir: "/repo", url: "https://up.git" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("name"), - }); + test("handleRemoteAdd returns BAD_REQUEST when url missing", async () => { + await handlers.handleRemoteAdd({ dir: "/repo", name: "origin" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("url"), }); - - test("handleRemoteAdd returns BAD_REQUEST when url missing", async () => { - await handlers.handleRemoteAdd({ dir: "/repo", name: "origin" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("url"), - }); + }); + + test("handleRemoteRemove removes a remote", async () => { + await handlers.handleRemoteRemove({ dir: "/repo", name: "origin" }, 1); + expect(gitService.remoteRemove).toHaveBeenCalledWith("/repo", "origin"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); + }); + + test("handleRemoteRemove returns BAD_REQUEST when name missing", async () => { + await handlers.handleRemoteRemove({ dir: "/repo" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("name"), }); - - test("handleRemoteRemove removes a remote", async () => { - await handlers.handleRemoteRemove({ dir: "/repo", name: "origin" }, 1); - expect(gitService.remoteRemove).toHaveBeenCalledWith("/repo", "origin"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); + }); + + test("handleRemoteGetUrl returns url", async () => { + await handlers.handleRemoteGetUrl({ dir: "/repo", name: "origin" }, 1); + expect(gitService.remoteGetUrl).toHaveBeenCalledWith("/repo", "origin"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: { url: "https://github.com/test/repo.git" }, }); - - test("handleRemoteRemove returns BAD_REQUEST when name missing", async () => { - await handlers.handleRemoteRemove({ dir: "/repo" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("name"), - }); - }); - - test("handleRemoteGetUrl returns url", async () => { - await handlers.handleRemoteGetUrl({ dir: "/repo", name: "origin" }, 1); - expect(gitService.remoteGetUrl).toHaveBeenCalledWith("/repo", "origin"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: { url: "https://github.com/test/repo.git" }, - }); - }); - - test("handleRemoteGetUrl defaults to origin", async () => { - await handlers.handleRemoteGetUrl({ dir: "/repo" }, 1); - expect(gitService.remoteGetUrl).toHaveBeenCalledWith("/repo", "origin"); - }); - - test("handleRemoteSetUrl sets url", async () => { - await handlers.handleRemoteSetUrl( - { dir: "/repo", name: "origin", url: "https://new.git" }, - 1 - ); - expect(gitService.remoteSetUrl).toHaveBeenCalledWith("/repo", "origin", "https://new.git"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); - }); - - test("handleRemoteSetUrl returns BAD_REQUEST when params missing", async () => { - await handlers.handleRemoteSetUrl({ dir: "/repo" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("name"), - }); + }); + + test("handleRemoteGetUrl defaults to origin", async () => { + await handlers.handleRemoteGetUrl({ dir: "/repo" }, 1); + expect(gitService.remoteGetUrl).toHaveBeenCalledWith("/repo", "origin"); + }); + + test("handleRemoteSetUrl sets url", async () => { + await handlers.handleRemoteSetUrl({ dir: "/repo", name: "origin", url: "https://new.git" }, 1); + expect(gitService.remoteSetUrl).toHaveBeenCalledWith("/repo", "origin", "https://new.git"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); + }); + + test("handleRemoteSetUrl returns BAD_REQUEST when params missing", async () => { + await handlers.handleRemoteSetUrl({ dir: "/repo" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("name"), }); + }); }); // ========================================== @@ -187,62 +179,62 @@ describe("GitAdvancedHandlers — Remote Management", () => { // ========================================== describe("GitAdvancedHandlers — Push / Pull / Fetch", () => { - test("handlePush pushes to remote", async () => { - await handlers.handlePush({ dir: "/repo" }, 1); - expect(gitService.push).toHaveBeenCalledWith("/repo", "origin", undefined, { - force: false, - setUpstream: false, - }); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: { output: "Everything up-to-date" }, - }); + test("handlePush pushes to remote", async () => { + await handlers.handlePush({ dir: "/repo" }, 1); + expect(gitService.push).toHaveBeenCalledWith("/repo", "origin", undefined, { + force: false, + setUpstream: false, }); - - test("handlePush passes custom remote and branch", async () => { - await handlers.handlePush( - { dir: "/repo", remote: "upstream", branch: "main", force: true, setUpstream: true }, - 1 - ); - expect(gitService.push).toHaveBeenCalledWith("/repo", "upstream", "main", { - force: true, - setUpstream: true, - }); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: { output: "Everything up-to-date" }, + }); + }); + + test("handlePush passes custom remote and branch", async () => { + await handlers.handlePush( + { dir: "/repo", remote: "upstream", branch: "main", force: true, setUpstream: true }, + 1, + ); + expect(gitService.push).toHaveBeenCalledWith("/repo", "upstream", "main", { + force: true, + setUpstream: true, }); + }); - test("handlePull pulls from remote", async () => { - await handlers.handlePull({ dir: "/repo" }, 1); - expect(gitService.pull).toHaveBeenCalledWith("/repo", "origin", undefined, { - rebase: false, - }); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: { output: "Already up to date." }, - }); + test("handlePull pulls from remote", async () => { + await handlers.handlePull({ dir: "/repo" }, 1); + expect(gitService.pull).toHaveBeenCalledWith("/repo", "origin", undefined, { + rebase: false, + }); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: { output: "Already up to date." }, }); + }); - test("handlePull passes rebase option", async () => { - await handlers.handlePull({ dir: "/repo", rebase: true }, 1); - expect(gitService.pull).toHaveBeenCalledWith("/repo", "origin", undefined, { - rebase: true, - }); + test("handlePull passes rebase option", async () => { + await handlers.handlePull({ dir: "/repo", rebase: true }, 1); + expect(gitService.pull).toHaveBeenCalledWith("/repo", "origin", undefined, { + rebase: true, }); + }); - test("handleFetch fetches from remote", async () => { - await handlers.handleFetch({ dir: "/repo" }, 1); - expect(gitService.fetch).toHaveBeenCalledWith("/repo", undefined, { - prune: false, - all: false, - }); + test("handleFetch fetches from remote", async () => { + await handlers.handleFetch({ dir: "/repo" }, 1); + expect(gitService.fetch).toHaveBeenCalledWith("/repo", undefined, { + prune: false, + all: false, }); + }); - test("handleFetch passes prune and all options", async () => { - await handlers.handleFetch({ dir: "/repo", prune: true, all: true }, 1); - expect(gitService.fetch).toHaveBeenCalledWith("/repo", undefined, { - prune: true, - all: true, - }); + test("handleFetch passes prune and all options", async () => { + await handlers.handleFetch({ dir: "/repo", prune: true, all: true }, 1); + expect(gitService.fetch).toHaveBeenCalledWith("/repo", undefined, { + prune: true, + all: true, }); + }); }); // ========================================== @@ -250,38 +242,38 @@ describe("GitAdvancedHandlers — Push / Pull / Fetch", () => { // ========================================== describe("GitAdvancedHandlers — Revert", () => { - test("handleRevert reverts a commit by hash", async () => { - await handlers.handleRevert({ dir: "/repo", hash: "abc1234" }, 1); - expect(gitService.revert).toHaveBeenCalledWith("/repo", "abc1234", { - noCommit: false, - }); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: { output: "" }, - }); + test("handleRevert reverts a commit by hash", async () => { + await handlers.handleRevert({ dir: "/repo", hash: "abc1234" }, 1); + expect(gitService.revert).toHaveBeenCalledWith("/repo", "abc1234", { + noCommit: false, }); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: { output: "" }, + }); + }); - test("handleRevert accepts commitHash alias", async () => { - await handlers.handleRevert({ dir: "/repo", commitHash: "def5678" }, 1); - expect(gitService.revert).toHaveBeenCalledWith("/repo", "def5678", { - noCommit: false, - }); + test("handleRevert accepts commitHash alias", async () => { + await handlers.handleRevert({ dir: "/repo", commitHash: "def5678" }, 1); + expect(gitService.revert).toHaveBeenCalledWith("/repo", "def5678", { + noCommit: false, }); + }); - test("handleRevert passes noCommit flag", async () => { - await handlers.handleRevert({ dir: "/repo", hash: "abc", noCommit: true }, 1); - expect(gitService.revert).toHaveBeenCalledWith("/repo", "abc", { - noCommit: true, - }); + test("handleRevert passes noCommit flag", async () => { + await handlers.handleRevert({ dir: "/repo", hash: "abc", noCommit: true }, 1); + expect(gitService.revert).toHaveBeenCalledWith("/repo", "abc", { + noCommit: true, }); + }); - test("handleRevert returns BAD_REQUEST when hash missing", async () => { - await handlers.handleRevert({ dir: "/repo" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("hash"), - }); + test("handleRevert returns BAD_REQUEST when hash missing", async () => { + await handlers.handleRevert({ dir: "/repo" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("hash"), }); + }); }); // ========================================== @@ -289,41 +281,35 @@ describe("GitAdvancedHandlers — Revert", () => { // ========================================== describe("GitAdvancedHandlers — Error Forwarding", () => { - test("all handlers forward service errors as GIT_ERROR", async () => { - const err = new Error("network failure"); - for (const key of Object.keys(gitService)) { - const val = (gitService as any)[key]; - if (typeof val?.mockRejectedValue === "function") { - val.mockRejectedValue(err); - } - } - - const testCases: [string, () => Promise][] = [ - ["remoteList", () => handlers.handleRemoteList({ dir: "/r" }, 1)], - [ - "remoteAdd", - () => handlers.handleRemoteAdd({ dir: "/r", name: "o", url: "u" }, 1), - ], - ["remoteRemove", () => handlers.handleRemoteRemove({ dir: "/r", name: "o" }, 1)], - ["remoteGetUrl", () => handlers.handleRemoteGetUrl({ dir: "/r" }, 1)], - [ - "remoteSetUrl", - () => handlers.handleRemoteSetUrl({ dir: "/r", name: "o", url: "u" }, 1), - ], - ["push", () => handlers.handlePush({ dir: "/r" }, 1)], - ["pull", () => handlers.handlePull({ dir: "/r" }, 1)], - ["fetch", () => handlers.handleFetch({ dir: "/r" }, 1)], - ["revert", () => handlers.handleRevert({ dir: "/r", hash: "abc" }, 1)], - ]; - - for (const [name, fn] of testCases) { - rpc = createMockRpc(); - handlers = new GitAdvancedHandlers(rpc, undefined, gitService); - await fn(); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "GIT_ERROR", - message: "network failure", - }); - } - }); + test("all handlers forward service errors as GIT_ERROR", async () => { + const err = new Error("network failure"); + for (const key of Object.keys(gitService)) { + const val = (gitService as any)[key]; + if (typeof val?.mockRejectedValue === "function") { + val.mockRejectedValue(err); + } + } + + const testCases: [string, () => Promise][] = [ + ["remoteList", () => handlers.handleRemoteList({ dir: "/r" }, 1)], + ["remoteAdd", () => handlers.handleRemoteAdd({ dir: "/r", name: "o", url: "u" }, 1)], + ["remoteRemove", () => handlers.handleRemoteRemove({ dir: "/r", name: "o" }, 1)], + ["remoteGetUrl", () => handlers.handleRemoteGetUrl({ dir: "/r" }, 1)], + ["remoteSetUrl", () => handlers.handleRemoteSetUrl({ dir: "/r", name: "o", url: "u" }, 1)], + ["push", () => handlers.handlePush({ dir: "/r" }, 1)], + ["pull", () => handlers.handlePull({ dir: "/r" }, 1)], + ["fetch", () => handlers.handleFetch({ dir: "/r" }, 1)], + ["revert", () => handlers.handleRevert({ dir: "/r", hash: "abc" }, 1)], + ]; + + for (const [name, fn] of testCases) { + rpc = createMockRpc(); + handlers = new GitAdvancedHandlers(rpc, undefined, gitService); + await fn(); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "GIT_ERROR", + message: "network failure", + }); + } + }); }); diff --git a/bridge/__tests__/gitHandlers.test.ts b/bridge/__tests__/gitHandlers.test.ts index f9436b51..62935089 100644 --- a/bridge/__tests__/gitHandlers.test.ts +++ b/bridge/__tests__/gitHandlers.test.ts @@ -6,100 +6,100 @@ import type { Rpc } from "../src/types"; // ─── Mock Factory ────────────────────────────────── function createMockRpc(): Rpc & { - _responses: any[]; - _errors: any[]; + _responses: any[]; + _errors: any[]; } { - const responses: any[] = []; - const errors: any[] = []; - return { - sendResponse: jest.fn((id: number | string, payload: any) => { - responses.push({ id, payload }); - }), - sendError: jest.fn((id: number | string, err: any) => { - errors.push({ id, err }); - }), - _responses: responses, - _errors: errors, - }; + const responses: any[] = []; + const errors: any[] = []; + return { + sendResponse: jest.fn((id: number | string, payload: any) => { + responses.push({ id, payload }); + }), + sendError: jest.fn((id: number | string, err: any) => { + errors.push({ id, err }); + }), + _responses: responses, + _errors: errors, + }; } function createMockLogger(): any { - return { - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - debug: jest.fn(), - child: jest.fn().mockReturnThis(), - }; + return { + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + debug: jest.fn(), + child: jest.fn().mockReturnThis(), + }; } function createMockGitService(): GitService { - return { - isGitInstalled: jest.fn().mockResolvedValue(true), - isRepo: jest.fn().mockResolvedValue(true), - init: jest.fn().mockResolvedValue(undefined), - getRepoRoot: jest.fn().mockResolvedValue("/repo"), - getStatus: jest.fn().mockResolvedValue({ - isGitRepo: true, - branch: "main", - isDirty: false, - stagedCount: 0, - unstagedCount: 0, - untrackedCount: 0, - headCommit: "abc12345", - aheadBehind: { ahead: 0, behind: 0 }, - }), - getChangedFiles: jest.fn().mockResolvedValue([]), - stageFiles: jest.fn().mockResolvedValue(undefined), - stageAll: jest.fn().mockResolvedValue(undefined), - unstageFiles: jest.fn().mockResolvedValue(undefined), - commit: jest.fn().mockResolvedValue("abc1234"), - commitFiles: jest.fn().mockResolvedValue("abc1234"), - log: jest.fn().mockResolvedValue([]), - fileLog: jest.fn().mockResolvedValue([]), - listBranches: jest.fn().mockResolvedValue([]), - createBranch: jest.fn().mockResolvedValue(undefined), - checkoutBranch: jest.fn().mockResolvedValue(undefined), - discardChanges: jest.fn().mockResolvedValue(undefined), - stash: jest.fn().mockResolvedValue(undefined), - stashPop: jest.fn().mockResolvedValue(undefined), - diff: jest.fn().mockResolvedValue("diff output"), - ensureGitignore: jest.fn().mockResolvedValue(true), - generateGitignore: jest.fn().mockReturnValue("# gitignore"), - // Advanced methods (present on GitService but not used by GitHandlers) - resolveRef: jest.fn(), - getFileAtRef: jest.fn(), - show: jest.fn(), - push: jest.fn(), - pull: jest.fn(), - fetch: jest.fn(), - revert: jest.fn(), - remoteList: jest.fn(), - remoteAdd: jest.fn(), - remoteRemove: jest.fn(), - remoteGetUrl: jest.fn(), - remoteSetUrl: jest.fn(), - createTag: jest.fn(), - deleteTag: jest.fn(), - listTags: jest.fn(), - merge: jest.fn(), - abortMerge: jest.fn(), - rebase: jest.fn(), - cherryPick: jest.fn(), - blame: jest.fn(), - stashList: jest.fn(), - stashApply: jest.fn(), - stashDrop: jest.fn(), - stashClear: jest.fn(), - clone: jest.fn(), - dryMerge: jest.fn(), - getMergeState: jest.fn(), - markResolved: jest.fn(), - getProtectedBranches: jest.fn(), - isProtectedBranch: jest.fn(), - deleteBranch: jest.fn(), - renameBranch: jest.fn(), - } as any; + return { + isGitInstalled: jest.fn().mockResolvedValue(true), + isRepo: jest.fn().mockResolvedValue(true), + init: jest.fn().mockResolvedValue(undefined), + getRepoRoot: jest.fn().mockResolvedValue("/repo"), + getStatus: jest.fn().mockResolvedValue({ + isGitRepo: true, + branch: "main", + isDirty: false, + stagedCount: 0, + unstagedCount: 0, + untrackedCount: 0, + headCommit: "abc12345", + aheadBehind: { ahead: 0, behind: 0 }, + }), + getChangedFiles: jest.fn().mockResolvedValue([]), + stageFiles: jest.fn().mockResolvedValue(undefined), + stageAll: jest.fn().mockResolvedValue(undefined), + unstageFiles: jest.fn().mockResolvedValue(undefined), + commit: jest.fn().mockResolvedValue("abc1234"), + commitFiles: jest.fn().mockResolvedValue("abc1234"), + log: jest.fn().mockResolvedValue([]), + fileLog: jest.fn().mockResolvedValue([]), + listBranches: jest.fn().mockResolvedValue([]), + createBranch: jest.fn().mockResolvedValue(undefined), + checkoutBranch: jest.fn().mockResolvedValue(undefined), + discardChanges: jest.fn().mockResolvedValue(undefined), + stash: jest.fn().mockResolvedValue(undefined), + stashPop: jest.fn().mockResolvedValue(undefined), + diff: jest.fn().mockResolvedValue("diff output"), + ensureGitignore: jest.fn().mockResolvedValue(true), + generateGitignore: jest.fn().mockReturnValue("# gitignore"), + // Advanced methods (present on GitService but not used by GitHandlers) + resolveRef: jest.fn(), + getFileAtRef: jest.fn(), + show: jest.fn(), + push: jest.fn(), + pull: jest.fn(), + fetch: jest.fn(), + revert: jest.fn(), + remoteList: jest.fn(), + remoteAdd: jest.fn(), + remoteRemove: jest.fn(), + remoteGetUrl: jest.fn(), + remoteSetUrl: jest.fn(), + createTag: jest.fn(), + deleteTag: jest.fn(), + listTags: jest.fn(), + merge: jest.fn(), + abortMerge: jest.fn(), + rebase: jest.fn(), + cherryPick: jest.fn(), + blame: jest.fn(), + stashList: jest.fn(), + stashApply: jest.fn(), + stashDrop: jest.fn(), + stashClear: jest.fn(), + clone: jest.fn(), + dryMerge: jest.fn(), + getMergeState: jest.fn(), + markResolved: jest.fn(), + getProtectedBranches: jest.fn(), + isProtectedBranch: jest.fn(), + deleteBranch: jest.fn(), + renameBranch: jest.fn(), + } as any; } // ─── Tests ────────────────────────────────────────── @@ -110,10 +110,10 @@ let gitService: GitService; let handlers: GitHandlers; beforeEach(() => { - rpc = createMockRpc(); - logger = createMockLogger(); - gitService = createMockGitService(); - handlers = new GitHandlers(rpc, logger, gitService); + rpc = createMockRpc(); + logger = createMockLogger(); + gitService = createMockGitService(); + handlers = new GitHandlers(rpc, logger, gitService); }); // ========================================== @@ -121,48 +121,48 @@ beforeEach(() => { // ========================================== describe("GitHandlers — requireDir validation", () => { - const handlerNames: [string, (p: any, id: number) => Promise][] = []; - - beforeEach(() => { - handlerNames.length = 0; - handlerNames.push( - ["handleStatus", (p, id) => handlers.handleStatus(p, id)], - ["handleInit", (p, id) => handlers.handleInit(p, id)], - ["handleChanges", (p, id) => handlers.handleChanges(p, id)], - ["handleStageAll", (p, id) => handlers.handleStageAll(p, id)], - ["handleLog", (p, id) => handlers.handleLog(p, id)], - ["handleBranches", (p, id) => handlers.handleBranches(p, id)], - ["handleDiff", (p, id) => handlers.handleDiff(p, id)], - ["handleEnsureIgnore", (p, id) => handlers.handleEnsureIgnore(p, id)], - ["handleStash", (p, id) => handlers.handleStash(p, id)], - ["handleStashPop", (p, id) => handlers.handleStashPop(p, id)] - ); - }); - - test("sends BAD_REQUEST when dir is missing", async () => { - for (const [name, fn] of handlerNames) { - rpc = createMockRpc(); - gitService = createMockGitService(); - handlers = new GitHandlers(rpc, logger, gitService); - - await fn({}, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("dir"), - }); - } - }); - - test("accepts dir, path, or cwd as directory param", async () => { - for (const key of ["dir", "path", "cwd"]) { - rpc = createMockRpc(); - gitService = createMockGitService(); - handlers = new GitHandlers(rpc, logger, gitService); - - await handlers.handleStatus({ [key]: "/repo" }, 1); - expect(rpc.sendResponse).toHaveBeenCalled(); - } - }); + const handlerNames: [string, (p: any, id: number) => Promise][] = []; + + beforeEach(() => { + handlerNames.length = 0; + handlerNames.push( + ["handleStatus", (p, id) => handlers.handleStatus(p, id)], + ["handleInit", (p, id) => handlers.handleInit(p, id)], + ["handleChanges", (p, id) => handlers.handleChanges(p, id)], + ["handleStageAll", (p, id) => handlers.handleStageAll(p, id)], + ["handleLog", (p, id) => handlers.handleLog(p, id)], + ["handleBranches", (p, id) => handlers.handleBranches(p, id)], + ["handleDiff", (p, id) => handlers.handleDiff(p, id)], + ["handleEnsureIgnore", (p, id) => handlers.handleEnsureIgnore(p, id)], + ["handleStash", (p, id) => handlers.handleStash(p, id)], + ["handleStashPop", (p, id) => handlers.handleStashPop(p, id)], + ); + }); + + test("sends BAD_REQUEST when dir is missing", async () => { + for (const [name, fn] of handlerNames) { + rpc = createMockRpc(); + gitService = createMockGitService(); + handlers = new GitHandlers(rpc, logger, gitService); + + await fn({}, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("dir"), + }); + } + }); + + test("accepts dir, path, or cwd as directory param", async () => { + for (const key of ["dir", "path", "cwd"]) { + rpc = createMockRpc(); + gitService = createMockGitService(); + handlers = new GitHandlers(rpc, logger, gitService); + + await handlers.handleStatus({ [key]: "/repo" }, 1); + expect(rpc.sendResponse).toHaveBeenCalled(); + } + }); }); // ========================================== @@ -170,23 +170,23 @@ describe("GitHandlers — requireDir validation", () => { // ========================================== describe("GitHandlers — handleStatus", () => { - test("returns status data on success", async () => { - await handlers.handleStatus({ dir: "/repo" }, 1); - expect(gitService.getStatus).toHaveBeenCalledWith("/repo"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: expect.objectContaining({ isGitRepo: true, branch: "main" }), - }); - }); - - test("returns GIT_ERROR on failure", async () => { - (gitService.getStatus as jest.Mock).mockRejectedValue(new Error("git error")); - await handlers.handleStatus({ dir: "/repo" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "GIT_ERROR", - message: "git error", - }); - }); + test("returns status data on success", async () => { + await handlers.handleStatus({ dir: "/repo" }, 1); + expect(gitService.getStatus).toHaveBeenCalledWith("/repo"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: expect.objectContaining({ isGitRepo: true, branch: "main" }), + }); + }); + + test("returns GIT_ERROR on failure", async () => { + (gitService.getStatus as jest.Mock).mockRejectedValue(new Error("git error")); + await handlers.handleStatus({ dir: "/repo" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "GIT_ERROR", + message: "git error", + }); + }); }); // ========================================== @@ -194,18 +194,18 @@ describe("GitHandlers — handleStatus", () => { // ========================================== describe("GitHandlers — handleInit", () => { - test("initializes repo, sets up gitignore, returns status", async () => { - await handlers.handleInit({ dir: "/repo" }, 1); - expect(gitService.init).toHaveBeenCalledWith("/repo", "main"); - expect(gitService.ensureGitignore).toHaveBeenCalledWith("/repo"); - expect(gitService.getStatus).toHaveBeenCalledWith("/repo"); - expect(rpc.sendResponse).toHaveBeenCalled(); - }); - - test("uses custom default branch", async () => { - await handlers.handleInit({ dir: "/repo", defaultBranch: "develop" }, 1); - expect(gitService.init).toHaveBeenCalledWith("/repo", "develop"); - }); + test("initializes repo, sets up gitignore, returns status", async () => { + await handlers.handleInit({ dir: "/repo" }, 1); + expect(gitService.init).toHaveBeenCalledWith("/repo", "main"); + expect(gitService.ensureGitignore).toHaveBeenCalledWith("/repo"); + expect(gitService.getStatus).toHaveBeenCalledWith("/repo"); + expect(rpc.sendResponse).toHaveBeenCalled(); + }); + + test("uses custom default branch", async () => { + await handlers.handleInit({ dir: "/repo", defaultBranch: "develop" }, 1); + expect(gitService.init).toHaveBeenCalledWith("/repo", "develop"); + }); }); // ========================================== @@ -213,16 +213,16 @@ describe("GitHandlers — handleInit", () => { // ========================================== describe("GitHandlers — handleChanges", () => { - test("returns changed files array", async () => { - const mockChanges = [{ path: "file.txt", status: "M", staged: false }]; - (gitService.getChangedFiles as jest.Mock).mockResolvedValue(mockChanges); - - await handlers.handleChanges({ dir: "/repo" }, 1); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: mockChanges, - }); + test("returns changed files array", async () => { + const mockChanges = [{ path: "file.txt", status: "M", staged: false }]; + (gitService.getChangedFiles as jest.Mock).mockResolvedValue(mockChanges); + + await handlers.handleChanges({ dir: "/repo" }, 1); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: mockChanges, }); + }); }); // ========================================== @@ -230,27 +230,27 @@ describe("GitHandlers — handleChanges", () => { // ========================================== describe("GitHandlers — handleStage", () => { - test("stages specified files", async () => { - await handlers.handleStage({ dir: "/repo", files: ["a.txt", "b.txt"] }, 1); - expect(gitService.stageFiles).toHaveBeenCalledWith("/repo", ["a.txt", "b.txt"]); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); - }); - - test("returns BAD_REQUEST for missing files", async () => { - await handlers.handleStage({ dir: "/repo" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("files"), - }); - }); - - test("returns BAD_REQUEST for empty files array", async () => { - await handlers.handleStage({ dir: "/repo", files: [] }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("files"), - }); - }); + test("stages specified files", async () => { + await handlers.handleStage({ dir: "/repo", files: ["a.txt", "b.txt"] }, 1); + expect(gitService.stageFiles).toHaveBeenCalledWith("/repo", ["a.txt", "b.txt"]); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); + }); + + test("returns BAD_REQUEST for missing files", async () => { + await handlers.handleStage({ dir: "/repo" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("files"), + }); + }); + + test("returns BAD_REQUEST for empty files array", async () => { + await handlers.handleStage({ dir: "/repo", files: [] }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("files"), + }); + }); }); // ========================================== @@ -258,11 +258,11 @@ describe("GitHandlers — handleStage", () => { // ========================================== describe("GitHandlers — handleStageAll", () => { - test("stages all files", async () => { - await handlers.handleStageAll({ dir: "/repo" }, 1); - expect(gitService.stageAll).toHaveBeenCalledWith("/repo"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); - }); + test("stages all files", async () => { + await handlers.handleStageAll({ dir: "/repo" }, 1); + expect(gitService.stageAll).toHaveBeenCalledWith("/repo"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); + }); }); // ========================================== @@ -270,19 +270,19 @@ describe("GitHandlers — handleStageAll", () => { // ========================================== describe("GitHandlers — handleUnstage", () => { - test("unstages specified files", async () => { - await handlers.handleUnstage({ dir: "/repo", files: ["a.txt"] }, 1); - expect(gitService.unstageFiles).toHaveBeenCalledWith("/repo", ["a.txt"]); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); - }); - - test("returns BAD_REQUEST for missing files", async () => { - await handlers.handleUnstage({ dir: "/repo" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("files"), - }); - }); + test("unstages specified files", async () => { + await handlers.handleUnstage({ dir: "/repo", files: ["a.txt"] }, 1); + expect(gitService.unstageFiles).toHaveBeenCalledWith("/repo", ["a.txt"]); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); + }); + + test("returns BAD_REQUEST for missing files", async () => { + await handlers.handleUnstage({ dir: "/repo" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("files"), + }); + }); }); // ========================================== @@ -290,22 +290,22 @@ describe("GitHandlers — handleUnstage", () => { // ========================================== describe("GitHandlers — handleCommit", () => { - test("commits with message and returns hash", async () => { - await handlers.handleCommit({ dir: "/repo", message: "feat: add X" }, 1); - expect(gitService.commit).toHaveBeenCalledWith("/repo", "feat: add X"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: { hash: "abc1234" }, - }); - }); - - test("returns BAD_REQUEST for missing message", async () => { - await handlers.handleCommit({ dir: "/repo" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("message"), - }); - }); + test("commits with message and returns hash", async () => { + await handlers.handleCommit({ dir: "/repo", message: "feat: add X" }, 1); + expect(gitService.commit).toHaveBeenCalledWith("/repo", "feat: add X"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: { hash: "abc1234" }, + }); + }); + + test("returns BAD_REQUEST for missing message", async () => { + await handlers.handleCommit({ dir: "/repo" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("message"), + }); + }); }); // ========================================== @@ -313,19 +313,19 @@ describe("GitHandlers — handleCommit", () => { // ========================================== describe("GitHandlers — handleLog", () => { - test("returns log entries with default count", async () => { - const entries = [{ hash: "abc", subject: "test" }]; - (gitService.log as jest.Mock).mockResolvedValue(entries); - - await handlers.handleLog({ dir: "/repo" }, 1); - expect(gitService.log).toHaveBeenCalledWith("/repo", 20); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: entries }); - }); - - test("respects custom count", async () => { - await handlers.handleLog({ dir: "/repo", count: 5 }, 1); - expect(gitService.log).toHaveBeenCalledWith("/repo", 5); - }); + test("returns log entries with default count", async () => { + const entries = [{ hash: "abc", subject: "test" }]; + (gitService.log as jest.Mock).mockResolvedValue(entries); + + await handlers.handleLog({ dir: "/repo" }, 1); + expect(gitService.log).toHaveBeenCalledWith("/repo", 20); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: entries }); + }); + + test("respects custom count", async () => { + await handlers.handleLog({ dir: "/repo", count: 5 }, 1); + expect(gitService.log).toHaveBeenCalledWith("/repo", 5); + }); }); // ========================================== @@ -333,13 +333,13 @@ describe("GitHandlers — handleLog", () => { // ========================================== describe("GitHandlers — handleBranches", () => { - test("returns branch list", async () => { - const branches = [{ name: "main", current: true }]; - (gitService.listBranches as jest.Mock).mockResolvedValue(branches); + test("returns branch list", async () => { + const branches = [{ name: "main", current: true }]; + (gitService.listBranches as jest.Mock).mockResolvedValue(branches); - await handlers.handleBranches({ dir: "/repo" }, 1); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: branches }); - }); + await handlers.handleBranches({ dir: "/repo" }, 1); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: branches }); + }); }); // ========================================== @@ -347,22 +347,22 @@ describe("GitHandlers — handleBranches", () => { // ========================================== describe("GitHandlers — handleCreateBranch", () => { - test("creates branch and returns name", async () => { - await handlers.handleCreateBranch({ dir: "/repo", name: "feature" }, 1); - expect(gitService.createBranch).toHaveBeenCalledWith("/repo", "feature"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: { branch: "feature" }, - }); - }); - - test("returns BAD_REQUEST for missing name", async () => { - await handlers.handleCreateBranch({ dir: "/repo" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("name"), - }); - }); + test("creates branch and returns name", async () => { + await handlers.handleCreateBranch({ dir: "/repo", name: "feature" }, 1); + expect(gitService.createBranch).toHaveBeenCalledWith("/repo", "feature"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: { branch: "feature" }, + }); + }); + + test("returns BAD_REQUEST for missing name", async () => { + await handlers.handleCreateBranch({ dir: "/repo" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("name"), + }); + }); }); // ========================================== @@ -370,22 +370,22 @@ describe("GitHandlers — handleCreateBranch", () => { // ========================================== describe("GitHandlers — handleCheckout", () => { - test("checks out branch", async () => { - await handlers.handleCheckout({ dir: "/repo", name: "develop" }, 1); - expect(gitService.checkoutBranch).toHaveBeenCalledWith("/repo", "develop"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: { branch: "develop" }, - }); - }); - - test("returns BAD_REQUEST for missing name", async () => { - await handlers.handleCheckout({ dir: "/repo" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("name"), - }); - }); + test("checks out branch", async () => { + await handlers.handleCheckout({ dir: "/repo", name: "develop" }, 1); + expect(gitService.checkoutBranch).toHaveBeenCalledWith("/repo", "develop"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: { branch: "develop" }, + }); + }); + + test("returns BAD_REQUEST for missing name", async () => { + await handlers.handleCheckout({ dir: "/repo" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("name"), + }); + }); }); // ========================================== @@ -393,19 +393,19 @@ describe("GitHandlers — handleCheckout", () => { // ========================================== describe("GitHandlers — handleDiscard", () => { - test("discards changes to specified files", async () => { - await handlers.handleDiscard({ dir: "/repo", files: ["f.txt"] }, 1); - expect(gitService.discardChanges).toHaveBeenCalledWith("/repo", ["f.txt"]); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); - }); - - test("returns BAD_REQUEST for missing files", async () => { - await handlers.handleDiscard({ dir: "/repo" }, 1); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: expect.stringContaining("files"), - }); - }); + test("discards changes to specified files", async () => { + await handlers.handleDiscard({ dir: "/repo", files: ["f.txt"] }, 1); + expect(gitService.discardChanges).toHaveBeenCalledWith("/repo", ["f.txt"]); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); + }); + + test("returns BAD_REQUEST for missing files", async () => { + await handlers.handleDiscard({ dir: "/repo" }, 1); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: expect.stringContaining("files"), + }); + }); }); // ========================================== @@ -413,17 +413,17 @@ describe("GitHandlers — handleDiscard", () => { // ========================================== describe("GitHandlers — handleStash / handleStashPop", () => { - test("stash saves changes", async () => { - await handlers.handleStash({ dir: "/repo", message: "wip" }, 1); - expect(gitService.stash).toHaveBeenCalledWith("/repo", "wip"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); - }); - - test("stashPop restores stash", async () => { - await handlers.handleStashPop({ dir: "/repo" }, 1); - expect(gitService.stashPop).toHaveBeenCalledWith("/repo"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); - }); + test("stash saves changes", async () => { + await handlers.handleStash({ dir: "/repo", message: "wip" }, 1); + expect(gitService.stash).toHaveBeenCalledWith("/repo", "wip"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); + }); + + test("stashPop restores stash", async () => { + await handlers.handleStashPop({ dir: "/repo" }, 1); + expect(gitService.stashPop).toHaveBeenCalledWith("/repo"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { ok: true, data: null }); + }); }); // ========================================== @@ -431,24 +431,24 @@ describe("GitHandlers — handleStash / handleStashPop", () => { // ========================================== describe("GitHandlers — handleDiff", () => { - test("returns diff output", async () => { - await handlers.handleDiff({ dir: "/repo", file: "readme.md" }, 1); - expect(gitService.diff).toHaveBeenCalledWith("/repo", "readme.md", false); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: { diff: "diff output" }, - }); - }); - - test("passes staged flag", async () => { - await handlers.handleDiff({ dir: "/repo", file: "a.ts", staged: true }, 1); - expect(gitService.diff).toHaveBeenCalledWith("/repo", "a.ts", true); - }); - - test("works without file (repo-wide diff)", async () => { - await handlers.handleDiff({ dir: "/repo" }, 1); - expect(gitService.diff).toHaveBeenCalledWith("/repo", undefined, false); - }); + test("returns diff output", async () => { + await handlers.handleDiff({ dir: "/repo", file: "readme.md" }, 1); + expect(gitService.diff).toHaveBeenCalledWith("/repo", "readme.md", false); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: { diff: "diff output" }, + }); + }); + + test("passes staged flag", async () => { + await handlers.handleDiff({ dir: "/repo", file: "a.ts", staged: true }, 1); + expect(gitService.diff).toHaveBeenCalledWith("/repo", "a.ts", true); + }); + + test("works without file (repo-wide diff)", async () => { + await handlers.handleDiff({ dir: "/repo" }, 1); + expect(gitService.diff).toHaveBeenCalledWith("/repo", undefined, false); + }); }); // ========================================== @@ -456,14 +456,14 @@ describe("GitHandlers — handleDiff", () => { // ========================================== describe("GitHandlers — handleEnsureIgnore", () => { - test("returns modified flag", async () => { - await handlers.handleEnsureIgnore({ dir: "/repo" }, 1); - expect(gitService.ensureGitignore).toHaveBeenCalledWith("/repo"); - expect(rpc.sendResponse).toHaveBeenCalledWith(1, { - ok: true, - data: { modified: true }, - }); - }); + test("returns modified flag", async () => { + await handlers.handleEnsureIgnore({ dir: "/repo" }, 1); + expect(gitService.ensureGitignore).toHaveBeenCalledWith("/repo"); + expect(rpc.sendResponse).toHaveBeenCalledWith(1, { + ok: true, + data: { modified: true }, + }); + }); }); // ========================================== @@ -471,34 +471,34 @@ describe("GitHandlers — handleEnsureIgnore", () => { // ========================================== describe("GitHandlers — Error Forwarding", () => { - test("all handlers forward errors as GIT_ERROR", async () => { - const errorMsg = "unexpected git failure"; - // Mock all service methods to reject - for (const key of Object.keys(gitService)) { - const val = (gitService as any)[key]; - if (typeof val?.mockRejectedValue === "function") { - val.mockRejectedValue(new Error(errorMsg)); - } - } - - const testCases: [string, () => Promise][] = [ - ["status", () => handlers.handleStatus({ dir: "/r" }, 1)], - ["changes", () => handlers.handleChanges({ dir: "/r" }, 1)], - ["stageAll", () => handlers.handleStageAll({ dir: "/r" }, 1)], - ["log", () => handlers.handleLog({ dir: "/r" }, 1)], - ["branches", () => handlers.handleBranches({ dir: "/r" }, 1)], - ["stashPop", () => handlers.handleStashPop({ dir: "/r" }, 1)], - ["ensureIgnore", () => handlers.handleEnsureIgnore({ dir: "/r" }, 1)], - ]; - - for (const [name, fn] of testCases) { - rpc = createMockRpc(); - handlers = new GitHandlers(rpc, logger, gitService); - await fn(); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "GIT_ERROR", - message: errorMsg, - }); - } - }); + test("all handlers forward errors as GIT_ERROR", async () => { + const errorMsg = "unexpected git failure"; + // Mock all service methods to reject + for (const key of Object.keys(gitService)) { + const val = (gitService as any)[key]; + if (typeof val?.mockRejectedValue === "function") { + val.mockRejectedValue(new Error(errorMsg)); + } + } + + const testCases: [string, () => Promise][] = [ + ["status", () => handlers.handleStatus({ dir: "/r" }, 1)], + ["changes", () => handlers.handleChanges({ dir: "/r" }, 1)], + ["stageAll", () => handlers.handleStageAll({ dir: "/r" }, 1)], + ["log", () => handlers.handleLog({ dir: "/r" }, 1)], + ["branches", () => handlers.handleBranches({ dir: "/r" }, 1)], + ["stashPop", () => handlers.handleStashPop({ dir: "/r" }, 1)], + ["ensureIgnore", () => handlers.handleEnsureIgnore({ dir: "/r" }, 1)], + ]; + + for (const [name, fn] of testCases) { + rpc = createMockRpc(); + handlers = new GitHandlers(rpc, logger, gitService); + await fn(); + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "GIT_ERROR", + message: errorMsg, + }); + } + }); }); diff --git a/bridge/__tests__/gitService.test.ts b/bridge/__tests__/gitService.test.ts index 119d3dda..283fe073 100644 --- a/bridge/__tests__/gitService.test.ts +++ b/bridge/__tests__/gitService.test.ts @@ -1,4 +1,4 @@ -import { afterAll, beforeEach,beforeAll, describe, expect, test } from "@jest/globals"; +import { afterAll, beforeEach, beforeAll, describe, expect, test } from "@jest/globals"; import { GitService } from "../src/services/gitService"; import fs from "fs/promises"; import fsSync from "fs"; @@ -20,45 +20,45 @@ let testCounter = 0; * Helper: run raw git commands in a directory */ async function rawGit(cwd: string, ...args: string[]): Promise { - const { stdout } = await execFileAsync("git", args, { cwd, windowsHide: true }); - return stdout.trimEnd(); + const { stdout } = await execFileAsync("git", args, { cwd, windowsHide: true }); + return stdout.trimEnd(); } /** * Helper: create a fresh temp repo for each test */ async function createTempRepo(): Promise { - testCounter++; - const dir = path.join(TEST_ROOT, `repo-${testCounter}`); - await fs.mkdir(dir, { recursive: true }); - await rawGit(dir, "init", "-b", "main"); - await rawGit(dir, "config", "user.email", "test@relwave.dev"); - await rawGit(dir, "config", "user.name", "Test User"); - return dir; + testCounter++; + const dir = path.join(TEST_ROOT, `repo-${testCounter}`); + await fs.mkdir(dir, { recursive: true }); + await rawGit(dir, "init", "-b", "main"); + await rawGit(dir, "config", "user.email", "test@relwave.dev"); + await rawGit(dir, "config", "user.name", "Test User"); + return dir; } /** * Helper: create a file and commit it */ async function commitFile(dir: string, filename: string, content: string, message: string) { - await fs.writeFile(path.join(dir, filename), content, "utf-8"); - await rawGit(dir, "add", filename); - await rawGit(dir, "commit", "-m", message); + await fs.writeFile(path.join(dir, filename), content, "utf-8"); + await rawGit(dir, "add", filename); + await rawGit(dir, "commit", "-m", message); } beforeAll(async () => { - await fs.mkdir(TEST_ROOT, { recursive: true }); + await fs.mkdir(TEST_ROOT, { recursive: true }); }); afterAll(async () => { - if (fsSync.existsSync(TEST_ROOT)) { - await fs.rm(TEST_ROOT, { recursive: true, force: true }); - } + if (fsSync.existsSync(TEST_ROOT)) { + await fs.rm(TEST_ROOT, { recursive: true, force: true }); + } }); beforeEach(async () => { - git = new GitService(); - repoDir = await createTempRepo(); + git = new GitService(); + repoDir = await createTempRepo(); }); // ========================================== @@ -66,33 +66,33 @@ beforeEach(async () => { // ========================================== describe("GitService — Basic Operations", () => { - test("isGitInstalled returns true", async () => { - const installed = await git.isGitInstalled(); - expect(installed).toBe(true); - }); - - test("isRepo returns true for initialized repo", async () => { - expect(await git.isRepo(repoDir)).toBe(true); - }); - - test("isRepo returns false for non-repo directory", async () => { - const plain = path.join(TEST_ROOT, "plain-" + Date.now()); - await fs.mkdir(plain, { recursive: true }); - expect(await git.isRepo(plain)).toBe(false); - }); - - test("init creates a new repository", async () => { - const dir = path.join(TEST_ROOT, "new-init-" + Date.now()); - await fs.mkdir(dir, { recursive: true }); - await git.init(dir, "main"); - expect(await git.isRepo(dir)).toBe(true); - }); - - test("getRepoRoot returns the repository root", async () => { - const root = await git.getRepoRoot(repoDir); - // Normalize path separators for cross-platform comparison - expect(path.normalize(root)).toBe(path.normalize(repoDir)); - }); + test("isGitInstalled returns true", async () => { + const installed = await git.isGitInstalled(); + expect(installed).toBe(true); + }); + + test("isRepo returns true for initialized repo", async () => { + expect(await git.isRepo(repoDir)).toBe(true); + }); + + test("isRepo returns false for non-repo directory", async () => { + const plain = path.join(TEST_ROOT, "plain-" + Date.now()); + await fs.mkdir(plain, { recursive: true }); + expect(await git.isRepo(plain)).toBe(false); + }); + + test("init creates a new repository", async () => { + const dir = path.join(TEST_ROOT, "new-init-" + Date.now()); + await fs.mkdir(dir, { recursive: true }); + await git.init(dir, "main"); + expect(await git.isRepo(dir)).toBe(true); + }); + + test("getRepoRoot returns the repository root", async () => { + const root = await git.getRepoRoot(repoDir); + // Normalize path separators for cross-platform comparison + expect(path.normalize(root)).toBe(path.normalize(repoDir)); + }); }); // ========================================== @@ -100,61 +100,61 @@ describe("GitService — Basic Operations", () => { // ========================================== describe("GitService — Status", () => { - test("returns clean status for empty repo", async () => { - const status = await git.getStatus(repoDir); - expect(status.isGitRepo).toBe(true); - expect(status.isDirty).toBe(false); - expect(status.stagedCount).toBe(0); - expect(status.unstagedCount).toBe(0); - expect(status.untrackedCount).toBe(0); - }); - - test("returns not-a-repo status for plain directory", async () => { - const dir = path.join(TEST_ROOT, "not-a-repo-" + Date.now()); - await fs.mkdir(dir, { recursive: true }); - - const status = await git.getStatus(dir); - expect(status.isGitRepo).toBe(false); - expect(status.branch).toBeNull(); - }); - - test("detects untracked files", async () => { - await fs.writeFile(path.join(repoDir, "newfile.txt"), "hello", "utf-8"); - const status = await git.getStatus(repoDir); - expect(status.isDirty).toBe(true); - expect(status.untrackedCount).toBe(1); - }); - - test("detects staged files", async () => { - await fs.writeFile(path.join(repoDir, "staged.txt"), "staged", "utf-8"); - await rawGit(repoDir, "add", "staged.txt"); - - const status = await git.getStatus(repoDir); - expect(status.stagedCount).toBe(1); - expect(status.isDirty).toBe(true); - }); - - test("detects unstaged modifications", async () => { - await commitFile(repoDir, "file.txt", "original", "initial"); - await fs.writeFile(path.join(repoDir, "file.txt"), "modified", "utf-8"); - - const status = await git.getStatus(repoDir); - expect(status.unstagedCount).toBe(1); - expect(status.isDirty).toBe(true); - }); - - test("returns branch name", async () => { - await commitFile(repoDir, "file.txt", "content", "first commit"); - const status = await git.getStatus(repoDir); - expect(status.branch).toBe("main"); - }); - - test("returns headCommit hash", async () => { - await commitFile(repoDir, "file.txt", "content", "first commit"); - const status = await git.getStatus(repoDir); - expect(status.headCommit).toBeDefined(); - expect(status.headCommit!.length).toBe(8); - }); + test("returns clean status for empty repo", async () => { + const status = await git.getStatus(repoDir); + expect(status.isGitRepo).toBe(true); + expect(status.isDirty).toBe(false); + expect(status.stagedCount).toBe(0); + expect(status.unstagedCount).toBe(0); + expect(status.untrackedCount).toBe(0); + }); + + test("returns not-a-repo status for plain directory", async () => { + const dir = path.join(TEST_ROOT, "not-a-repo-" + Date.now()); + await fs.mkdir(dir, { recursive: true }); + + const status = await git.getStatus(dir); + expect(status.isGitRepo).toBe(false); + expect(status.branch).toBeNull(); + }); + + test("detects untracked files", async () => { + await fs.writeFile(path.join(repoDir, "newfile.txt"), "hello", "utf-8"); + const status = await git.getStatus(repoDir); + expect(status.isDirty).toBe(true); + expect(status.untrackedCount).toBe(1); + }); + + test("detects staged files", async () => { + await fs.writeFile(path.join(repoDir, "staged.txt"), "staged", "utf-8"); + await rawGit(repoDir, "add", "staged.txt"); + + const status = await git.getStatus(repoDir); + expect(status.stagedCount).toBe(1); + expect(status.isDirty).toBe(true); + }); + + test("detects unstaged modifications", async () => { + await commitFile(repoDir, "file.txt", "original", "initial"); + await fs.writeFile(path.join(repoDir, "file.txt"), "modified", "utf-8"); + + const status = await git.getStatus(repoDir); + expect(status.unstagedCount).toBe(1); + expect(status.isDirty).toBe(true); + }); + + test("returns branch name", async () => { + await commitFile(repoDir, "file.txt", "content", "first commit"); + const status = await git.getStatus(repoDir); + expect(status.branch).toBe("main"); + }); + + test("returns headCommit hash", async () => { + await commitFile(repoDir, "file.txt", "content", "first commit"); + const status = await git.getStatus(repoDir); + expect(status.headCommit).toBeDefined(); + expect(status.headCommit!.length).toBe(8); + }); }); // ========================================== @@ -162,40 +162,40 @@ describe("GitService — Status", () => { // ========================================== describe("GitService — Changed Files", () => { - test("returns empty for clean repo", async () => { - await commitFile(repoDir, "file.txt", "content", "initial"); - const changes = await git.getChangedFiles(repoDir); - expect(changes).toEqual([]); - }); - - test("detects untracked files", async () => { - await fs.writeFile(path.join(repoDir, "new.txt"), "new", "utf-8"); - const changes = await git.getChangedFiles(repoDir); - expect(changes).toHaveLength(1); - expect(changes[0].status).toBe("?"); - expect(changes[0].staged).toBe(false); - expect(changes[0].path).toBe("new.txt"); - }); - - test("detects staged modifications", async () => { - await commitFile(repoDir, "file.txt", "original", "init"); - await fs.writeFile(path.join(repoDir, "file.txt"), "changed", "utf-8"); - await rawGit(repoDir, "add", "file.txt"); - - const changes = await git.getChangedFiles(repoDir); - const staged = changes.filter((c) => c.staged); - expect(staged.length).toBeGreaterThanOrEqual(1); - expect(staged[0].status).toBe("M"); - }); - - test("detects deleted files", async () => { - await commitFile(repoDir, "file.txt", "content", "init"); - await fs.unlink(path.join(repoDir, "file.txt")); - - const changes = await git.getChangedFiles(repoDir); - const deleted = changes.filter((c) => c.status === "D"); - expect(deleted.length).toBe(1); - }); + test("returns empty for clean repo", async () => { + await commitFile(repoDir, "file.txt", "content", "initial"); + const changes = await git.getChangedFiles(repoDir); + expect(changes).toEqual([]); + }); + + test("detects untracked files", async () => { + await fs.writeFile(path.join(repoDir, "new.txt"), "new", "utf-8"); + const changes = await git.getChangedFiles(repoDir); + expect(changes).toHaveLength(1); + expect(changes[0].status).toBe("?"); + expect(changes[0].staged).toBe(false); + expect(changes[0].path).toBe("new.txt"); + }); + + test("detects staged modifications", async () => { + await commitFile(repoDir, "file.txt", "original", "init"); + await fs.writeFile(path.join(repoDir, "file.txt"), "changed", "utf-8"); + await rawGit(repoDir, "add", "file.txt"); + + const changes = await git.getChangedFiles(repoDir); + const staged = changes.filter((c) => c.staged); + expect(staged.length).toBeGreaterThanOrEqual(1); + expect(staged[0].status).toBe("M"); + }); + + test("detects deleted files", async () => { + await commitFile(repoDir, "file.txt", "content", "init"); + await fs.unlink(path.join(repoDir, "file.txt")); + + const changes = await git.getChangedFiles(repoDir); + const deleted = changes.filter((c) => c.status === "D"); + expect(deleted.length).toBe(1); + }); }); // ========================================== @@ -203,67 +203,67 @@ describe("GitService — Changed Files", () => { // ========================================== describe("GitService — Stage & Commit", () => { - test("stageFiles stages specific files", async () => { - await fs.writeFile(path.join(repoDir, "a.txt"), "a", "utf-8"); - await fs.writeFile(path.join(repoDir, "b.txt"), "b", "utf-8"); - - await git.stageFiles(repoDir, ["a.txt"]); - - const status = await git.getStatus(repoDir); - expect(status.stagedCount).toBe(1); - expect(status.untrackedCount).toBe(1); - }); - - test("stageFiles is no-op for empty array", async () => { - // Should not throw - await expect(git.stageFiles(repoDir, [])).resolves.not.toThrow(); - }); - - test("stageAll stages everything", async () => { - await fs.writeFile(path.join(repoDir, "a.txt"), "a", "utf-8"); - await fs.writeFile(path.join(repoDir, "b.txt"), "b", "utf-8"); - - await git.stageAll(repoDir); - - const status = await git.getStatus(repoDir); - expect(status.stagedCount).toBe(2); - expect(status.untrackedCount).toBe(0); - }); - - test("commit returns a string (may be hash or empty)", async () => { - await fs.writeFile(path.join(repoDir, "file.txt"), "data", "utf-8"); - await git.stageAll(repoDir); - - const hash = await git.commit(repoDir, "test commit"); - expect(typeof hash).toBe("string"); - - // Verify the commit actually happened - const log = await git.log(repoDir, 1); - expect(log).toHaveLength(1); - expect(log[0].subject).toBe("test commit"); - }); - - test("unstageFiles removes files from staging", async () => { - await fs.writeFile(path.join(repoDir, "file.txt"), "data", "utf-8"); - await git.stageAll(repoDir); - expect((await git.getStatus(repoDir)).stagedCount).toBe(1); - - await git.unstageFiles(repoDir, ["file.txt"]); - // After unstaging a new file, it goes back to untracked - const status = await git.getStatus(repoDir); - expect(status.stagedCount).toBe(0); - }); - - test("commitFiles stages and commits in one call", async () => { - await commitFile(repoDir, "base.txt", "base", "initial"); // Need a first commit - await fs.writeFile(path.join(repoDir, "auto.txt"), "auto", "utf-8"); - - const hash = await git.commitFiles(repoDir, ["auto.txt"], "auto commit"); - expect(hash).toBeDefined(); - - const status = await git.getStatus(repoDir); - expect(status.isDirty).toBe(false); - }); + test("stageFiles stages specific files", async () => { + await fs.writeFile(path.join(repoDir, "a.txt"), "a", "utf-8"); + await fs.writeFile(path.join(repoDir, "b.txt"), "b", "utf-8"); + + await git.stageFiles(repoDir, ["a.txt"]); + + const status = await git.getStatus(repoDir); + expect(status.stagedCount).toBe(1); + expect(status.untrackedCount).toBe(1); + }); + + test("stageFiles is no-op for empty array", async () => { + // Should not throw + await expect(git.stageFiles(repoDir, [])).resolves.not.toThrow(); + }); + + test("stageAll stages everything", async () => { + await fs.writeFile(path.join(repoDir, "a.txt"), "a", "utf-8"); + await fs.writeFile(path.join(repoDir, "b.txt"), "b", "utf-8"); + + await git.stageAll(repoDir); + + const status = await git.getStatus(repoDir); + expect(status.stagedCount).toBe(2); + expect(status.untrackedCount).toBe(0); + }); + + test("commit returns a string (may be hash or empty)", async () => { + await fs.writeFile(path.join(repoDir, "file.txt"), "data", "utf-8"); + await git.stageAll(repoDir); + + const hash = await git.commit(repoDir, "test commit"); + expect(typeof hash).toBe("string"); + + // Verify the commit actually happened + const log = await git.log(repoDir, 1); + expect(log).toHaveLength(1); + expect(log[0].subject).toBe("test commit"); + }); + + test("unstageFiles removes files from staging", async () => { + await fs.writeFile(path.join(repoDir, "file.txt"), "data", "utf-8"); + await git.stageAll(repoDir); + expect((await git.getStatus(repoDir)).stagedCount).toBe(1); + + await git.unstageFiles(repoDir, ["file.txt"]); + // After unstaging a new file, it goes back to untracked + const status = await git.getStatus(repoDir); + expect(status.stagedCount).toBe(0); + }); + + test("commitFiles stages and commits in one call", async () => { + await commitFile(repoDir, "base.txt", "base", "initial"); // Need a first commit + await fs.writeFile(path.join(repoDir, "auto.txt"), "auto", "utf-8"); + + const hash = await git.commitFiles(repoDir, ["auto.txt"], "auto commit"); + expect(hash).toBeDefined(); + + const status = await git.getStatus(repoDir); + expect(status.isDirty).toBe(false); + }); }); // ========================================== @@ -271,50 +271,50 @@ describe("GitService — Stage & Commit", () => { // ========================================== describe("GitService — Log", () => { - test("returns empty log for fresh repo", async () => { - const entries = await git.log(repoDir); - expect(entries).toEqual([]); - }); - - test("returns commit entries", async () => { - await commitFile(repoDir, "a.txt", "a", "first commit"); - await commitFile(repoDir, "b.txt", "b", "second commit"); - - const entries = await git.log(repoDir); - expect(entries).toHaveLength(2); - expect(entries[0].subject).toBe("second commit"); - expect(entries[1].subject).toBe("first commit"); - }); - - test("entries have correct fields", async () => { - await commitFile(repoDir, "file.txt", "data", "test message"); - - const [entry] = await git.log(repoDir, 1); - expect(entry.hash).toBeDefined(); - expect(entry.fullHash).toBeDefined(); - expect(entry.author).toBe("Test User"); - expect(entry.date).toBeDefined(); - expect(entry.subject).toBe("test message"); - }); - - test("respects count limit", async () => { - for (let i = 0; i < 5; i++) { - await commitFile(repoDir, `f${i}.txt`, `${i}`, `commit ${i}`); - } - - const limited = await git.log(repoDir, 3); - expect(limited).toHaveLength(3); - }); - - test("fileLog returns commits for specific file", async () => { - await commitFile(repoDir, "a.txt", "v1", "commit a"); - await commitFile(repoDir, "b.txt", "v1", "commit b"); - await commitFile(repoDir, "a.txt", "v2", "update a"); - - const aLog = await git.fileLog(repoDir, "a.txt"); - expect(aLog).toHaveLength(2); - expect(aLog.map((e) => e.subject)).toEqual(["update a", "commit a"]); - }); + test("returns empty log for fresh repo", async () => { + const entries = await git.log(repoDir); + expect(entries).toEqual([]); + }); + + test("returns commit entries", async () => { + await commitFile(repoDir, "a.txt", "a", "first commit"); + await commitFile(repoDir, "b.txt", "b", "second commit"); + + const entries = await git.log(repoDir); + expect(entries).toHaveLength(2); + expect(entries[0].subject).toBe("second commit"); + expect(entries[1].subject).toBe("first commit"); + }); + + test("entries have correct fields", async () => { + await commitFile(repoDir, "file.txt", "data", "test message"); + + const [entry] = await git.log(repoDir, 1); + expect(entry.hash).toBeDefined(); + expect(entry.fullHash).toBeDefined(); + expect(entry.author).toBe("Test User"); + expect(entry.date).toBeDefined(); + expect(entry.subject).toBe("test message"); + }); + + test("respects count limit", async () => { + for (let i = 0; i < 5; i++) { + await commitFile(repoDir, `f${i}.txt`, `${i}`, `commit ${i}`); + } + + const limited = await git.log(repoDir, 3); + expect(limited).toHaveLength(3); + }); + + test("fileLog returns commits for specific file", async () => { + await commitFile(repoDir, "a.txt", "v1", "commit a"); + await commitFile(repoDir, "b.txt", "v1", "commit b"); + await commitFile(repoDir, "a.txt", "v2", "update a"); + + const aLog = await git.fileLog(repoDir, "a.txt"); + expect(aLog).toHaveLength(2); + expect(aLog.map((e) => e.subject)).toEqual(["update a", "commit a"]); + }); }); // ========================================== @@ -322,47 +322,47 @@ describe("GitService — Log", () => { // ========================================== describe("GitService — Branches", () => { - beforeEach(async () => { - await commitFile(repoDir, "init.txt", "init", "initial commit"); - }); - - test("lists branches with current indicator", async () => { - const branches = await git.listBranches(repoDir); - expect(branches).toHaveLength(1); - expect(branches[0].name).toBe("main"); - expect(branches[0].current).toBe(true); - }); - - test("creates and lists new branches", async () => { - await git.createBranch(repoDir, "feature"); - - const branches = await git.listBranches(repoDir); - expect(branches).toHaveLength(2); - - const feature = branches.find((b) => b.name === "feature"); - expect(feature).toBeDefined(); - expect(feature!.current).toBe(true); // createBranch does checkout -b - }); - - test("checkout switches branches", async () => { - await git.createBranch(repoDir, "feature"); - await git.checkoutBranch(repoDir, "main"); - - const branches = await git.listBranches(repoDir); - const main = branches.find((b) => b.name === "main"); - expect(main!.current).toBe(true); - }); - - test("resolveRef returns commit hash", async () => { - const hash = await git.resolveRef(repoDir, "HEAD"); - expect(hash).toBeDefined(); - expect(hash!.length).toBe(40); - }); - - test("resolveRef returns null for invalid ref", async () => { - const hash = await git.resolveRef(repoDir, "nonexistent"); - expect(hash).toBeNull(); - }); + beforeEach(async () => { + await commitFile(repoDir, "init.txt", "init", "initial commit"); + }); + + test("lists branches with current indicator", async () => { + const branches = await git.listBranches(repoDir); + expect(branches).toHaveLength(1); + expect(branches[0].name).toBe("main"); + expect(branches[0].current).toBe(true); + }); + + test("creates and lists new branches", async () => { + await git.createBranch(repoDir, "feature"); + + const branches = await git.listBranches(repoDir); + expect(branches).toHaveLength(2); + + const feature = branches.find((b) => b.name === "feature"); + expect(feature).toBeDefined(); + expect(feature!.current).toBe(true); // createBranch does checkout -b + }); + + test("checkout switches branches", async () => { + await git.createBranch(repoDir, "feature"); + await git.checkoutBranch(repoDir, "main"); + + const branches = await git.listBranches(repoDir); + const main = branches.find((b) => b.name === "main"); + expect(main!.current).toBe(true); + }); + + test("resolveRef returns commit hash", async () => { + const hash = await git.resolveRef(repoDir, "HEAD"); + expect(hash).toBeDefined(); + expect(hash!.length).toBe(40); + }); + + test("resolveRef returns null for invalid ref", async () => { + const hash = await git.resolveRef(repoDir, "nonexistent"); + expect(hash).toBeNull(); + }); }); // ========================================== @@ -370,31 +370,31 @@ describe("GitService — Branches", () => { // ========================================== describe("GitService — Discard & Stash", () => { - beforeEach(async () => { - await commitFile(repoDir, "file.txt", "original", "initial"); - }); - - test("discardChanges restores file content", async () => { - await fs.writeFile(path.join(repoDir, "file.txt"), "modified", "utf-8"); - await git.discardChanges(repoDir, ["file.txt"]); - - const content = await fs.readFile(path.join(repoDir, "file.txt"), "utf-8"); - expect(content).toBe("original"); - }); - - test("stash saves and restores changes", async () => { - await fs.writeFile(path.join(repoDir, "file.txt"), "modified", "utf-8"); - await git.stash(repoDir, "wip changes"); - - // Working tree should be clean after stash - const status = await git.getStatus(repoDir); - expect(status.isDirty).toBe(false); - - // Pop restores - await git.stashPop(repoDir); - const content = await fs.readFile(path.join(repoDir, "file.txt"), "utf-8"); - expect(content).toBe("modified"); - }); + beforeEach(async () => { + await commitFile(repoDir, "file.txt", "original", "initial"); + }); + + test("discardChanges restores file content", async () => { + await fs.writeFile(path.join(repoDir, "file.txt"), "modified", "utf-8"); + await git.discardChanges(repoDir, ["file.txt"]); + + const content = await fs.readFile(path.join(repoDir, "file.txt"), "utf-8"); + expect(content).toBe("original"); + }); + + test("stash saves and restores changes", async () => { + await fs.writeFile(path.join(repoDir, "file.txt"), "modified", "utf-8"); + await git.stash(repoDir, "wip changes"); + + // Working tree should be clean after stash + const status = await git.getStatus(repoDir); + expect(status.isDirty).toBe(false); + + // Pop restores + await git.stashPop(repoDir); + const content = await fs.readFile(path.join(repoDir, "file.txt"), "utf-8"); + expect(content).toBe("modified"); + }); }); // ========================================== @@ -402,30 +402,30 @@ describe("GitService — Discard & Stash", () => { // ========================================== describe("GitService — Diff", () => { - beforeEach(async () => { - await commitFile(repoDir, "file.txt", "line1\nline2\n", "initial"); - }); - - test("diff shows unstaged changes", async () => { - await fs.writeFile(path.join(repoDir, "file.txt"), "line1\nline2\nline3\n", "utf-8"); - - const diff = await git.diff(repoDir, "file.txt"); - expect(diff).toContain("+line3"); - }); - - test("diff shows staged changes with --staged", async () => { - await fs.writeFile(path.join(repoDir, "file.txt"), "changed\n", "utf-8"); - await rawGit(repoDir, "add", "file.txt"); - - const diff = await git.diff(repoDir, "file.txt", true); - expect(diff).toContain("-line1"); - expect(diff).toContain("+changed"); - }); - - test("diff returns empty for no changes", async () => { - const diff = await git.diff(repoDir); - expect(diff).toBe(""); - }); + beforeEach(async () => { + await commitFile(repoDir, "file.txt", "line1\nline2\n", "initial"); + }); + + test("diff shows unstaged changes", async () => { + await fs.writeFile(path.join(repoDir, "file.txt"), "line1\nline2\nline3\n", "utf-8"); + + const diff = await git.diff(repoDir, "file.txt"); + expect(diff).toContain("+line3"); + }); + + test("diff shows staged changes with --staged", async () => { + await fs.writeFile(path.join(repoDir, "file.txt"), "changed\n", "utf-8"); + await rawGit(repoDir, "add", "file.txt"); + + const diff = await git.diff(repoDir, "file.txt", true); + expect(diff).toContain("-line1"); + expect(diff).toContain("+changed"); + }); + + test("diff returns empty for no changes", async () => { + const diff = await git.diff(repoDir); + expect(diff).toBe(""); + }); }); // ========================================== @@ -433,36 +433,36 @@ describe("GitService — Diff", () => { // ========================================== describe("GitService — Gitignore", () => { - test("generateGitignore returns rules containing relwave.local.json", () => { - const content = git.generateGitignore(); - expect(content).toContain("relwave.local.json"); - expect(content).toContain(".credentials"); - expect(content).toContain(".DS_Store"); - }); - - test("ensureGitignore creates new file", async () => { - const modified = await git.ensureGitignore(repoDir); - expect(modified).toBe(true); - - const content = await fs.readFile(path.join(repoDir, ".gitignore"), "utf-8"); - expect(content).toContain("relwave.local.json"); - }); - - test("ensureGitignore is idempotent", async () => { - await git.ensureGitignore(repoDir); - const secondCall = await git.ensureGitignore(repoDir); - expect(secondCall).toBe(false); - }); - - test("ensureGitignore appends to existing file", async () => { - await fs.writeFile(path.join(repoDir, ".gitignore"), "node_modules/\n", "utf-8"); - const modified = await git.ensureGitignore(repoDir); - expect(modified).toBe(true); - - const content = await fs.readFile(path.join(repoDir, ".gitignore"), "utf-8"); - expect(content).toContain("node_modules/"); - expect(content).toContain("relwave.local.json"); - }); + test("generateGitignore returns rules containing relwave.local.json", () => { + const content = git.generateGitignore(); + expect(content).toContain("relwave.local.json"); + expect(content).toContain(".credentials"); + expect(content).toContain(".DS_Store"); + }); + + test("ensureGitignore creates new file", async () => { + const modified = await git.ensureGitignore(repoDir); + expect(modified).toBe(true); + + const content = await fs.readFile(path.join(repoDir, ".gitignore"), "utf-8"); + expect(content).toContain("relwave.local.json"); + }); + + test("ensureGitignore is idempotent", async () => { + await git.ensureGitignore(repoDir); + const secondCall = await git.ensureGitignore(repoDir); + expect(secondCall).toBe(false); + }); + + test("ensureGitignore appends to existing file", async () => { + await fs.writeFile(path.join(repoDir, ".gitignore"), "node_modules/\n", "utf-8"); + const modified = await git.ensureGitignore(repoDir); + expect(modified).toBe(true); + + const content = await fs.readFile(path.join(repoDir, ".gitignore"), "utf-8"); + expect(content).toContain("node_modules/"); + expect(content).toContain("relwave.local.json"); + }); }); // ========================================== @@ -470,60 +470,60 @@ describe("GitService — Gitignore", () => { // ========================================== describe("GitService — Remote Management", () => { - beforeEach(async () => { - await commitFile(repoDir, "init.txt", "init", "initial"); - }); - - test("remoteList returns empty for no remotes", async () => { - const remotes = await git.remoteList(repoDir); - expect(remotes).toEqual([]); - }); - - test("remoteAdd and remoteList", async () => { - await git.remoteAdd(repoDir, "origin", "https://github.com/test/repo.git"); - - const remotes = await git.remoteList(repoDir); - expect(remotes).toHaveLength(1); - expect(remotes[0].name).toBe("origin"); - expect(remotes[0].fetchUrl).toBe("https://github.com/test/repo.git"); - expect(remotes[0].pushUrl).toBe("https://github.com/test/repo.git"); - }); - - test("remoteRemove removes a remote", async () => { - await git.remoteAdd(repoDir, "origin", "https://github.com/test/repo.git"); - await git.remoteRemove(repoDir, "origin"); - - const remotes = await git.remoteList(repoDir); - expect(remotes).toEqual([]); - }); - - test("remoteGetUrl returns URL", async () => { - await git.remoteAdd(repoDir, "origin", "https://github.com/test/repo.git"); - const url = await git.remoteGetUrl(repoDir, "origin"); - expect(url).toBe("https://github.com/test/repo.git"); - }); - - test("remoteGetUrl returns null for non-existent remote", async () => { - const url = await git.remoteGetUrl(repoDir, "nonexistent"); - expect(url).toBeNull(); - }); - - test("remoteSetUrl changes URL", async () => { - await git.remoteAdd(repoDir, "origin", "https://old.url/repo.git"); - await git.remoteSetUrl(repoDir, "origin", "https://new.url/repo.git"); - - const url = await git.remoteGetUrl(repoDir, "origin"); - expect(url).toBe("https://new.url/repo.git"); - }); - - test("multiple remotes", async () => { - await git.remoteAdd(repoDir, "origin", "https://github.com/main.git"); - await git.remoteAdd(repoDir, "upstream", "https://github.com/upstream.git"); - - const remotes = await git.remoteList(repoDir); - expect(remotes).toHaveLength(2); - expect(remotes.map((r) => r.name).sort()).toEqual(["origin", "upstream"]); - }); + beforeEach(async () => { + await commitFile(repoDir, "init.txt", "init", "initial"); + }); + + test("remoteList returns empty for no remotes", async () => { + const remotes = await git.remoteList(repoDir); + expect(remotes).toEqual([]); + }); + + test("remoteAdd and remoteList", async () => { + await git.remoteAdd(repoDir, "origin", "https://github.com/test/repo.git"); + + const remotes = await git.remoteList(repoDir); + expect(remotes).toHaveLength(1); + expect(remotes[0].name).toBe("origin"); + expect(remotes[0].fetchUrl).toBe("https://github.com/test/repo.git"); + expect(remotes[0].pushUrl).toBe("https://github.com/test/repo.git"); + }); + + test("remoteRemove removes a remote", async () => { + await git.remoteAdd(repoDir, "origin", "https://github.com/test/repo.git"); + await git.remoteRemove(repoDir, "origin"); + + const remotes = await git.remoteList(repoDir); + expect(remotes).toEqual([]); + }); + + test("remoteGetUrl returns URL", async () => { + await git.remoteAdd(repoDir, "origin", "https://github.com/test/repo.git"); + const url = await git.remoteGetUrl(repoDir, "origin"); + expect(url).toBe("https://github.com/test/repo.git"); + }); + + test("remoteGetUrl returns null for non-existent remote", async () => { + const url = await git.remoteGetUrl(repoDir, "nonexistent"); + expect(url).toBeNull(); + }); + + test("remoteSetUrl changes URL", async () => { + await git.remoteAdd(repoDir, "origin", "https://old.url/repo.git"); + await git.remoteSetUrl(repoDir, "origin", "https://new.url/repo.git"); + + const url = await git.remoteGetUrl(repoDir, "origin"); + expect(url).toBe("https://new.url/repo.git"); + }); + + test("multiple remotes", async () => { + await git.remoteAdd(repoDir, "origin", "https://github.com/main.git"); + await git.remoteAdd(repoDir, "upstream", "https://github.com/upstream.git"); + + const remotes = await git.remoteList(repoDir); + expect(remotes).toHaveLength(2); + expect(remotes.map((r) => r.name).sort()).toEqual(["origin", "upstream"]); + }); }); // ========================================== @@ -531,39 +531,39 @@ describe("GitService — Remote Management", () => { // ========================================== describe("GitService — Tags", () => { - beforeEach(async () => { - await commitFile(repoDir, "init.txt", "init", "initial commit"); - }); - - test("createTag creates a lightweight tag", async () => { - await git.createTag(repoDir, "v1.0.0"); - const tags = await git.listTags(repoDir); - expect(tags).toContain("v1.0.0"); - }); - - test("createTag creates an annotated tag", async () => { - await git.createTag(repoDir, "v2.0.0", "Release 2.0"); - const tags = await git.listTags(repoDir); - expect(tags).toContain("v2.0.0"); - }); - - test("deleteTag removes a tag", async () => { - await git.createTag(repoDir, "v1.0.0"); - await git.deleteTag(repoDir, "v1.0.0"); - const tags = await git.listTags(repoDir); - expect(tags).not.toContain("v1.0.0"); - }); - - test("listTags returns all tags", async () => { - await git.createTag(repoDir, "v1.0.0"); - await commitFile(repoDir, "b.txt", "b", "second"); - await git.createTag(repoDir, "v2.0.0"); - - const tags = await git.listTags(repoDir); - expect(tags).toHaveLength(2); - expect(tags).toContain("v1.0.0"); - expect(tags).toContain("v2.0.0"); - }); + beforeEach(async () => { + await commitFile(repoDir, "init.txt", "init", "initial commit"); + }); + + test("createTag creates a lightweight tag", async () => { + await git.createTag(repoDir, "v1.0.0"); + const tags = await git.listTags(repoDir); + expect(tags).toContain("v1.0.0"); + }); + + test("createTag creates an annotated tag", async () => { + await git.createTag(repoDir, "v2.0.0", "Release 2.0"); + const tags = await git.listTags(repoDir); + expect(tags).toContain("v2.0.0"); + }); + + test("deleteTag removes a tag", async () => { + await git.createTag(repoDir, "v1.0.0"); + await git.deleteTag(repoDir, "v1.0.0"); + const tags = await git.listTags(repoDir); + expect(tags).not.toContain("v1.0.0"); + }); + + test("listTags returns all tags", async () => { + await git.createTag(repoDir, "v1.0.0"); + await commitFile(repoDir, "b.txt", "b", "second"); + await git.createTag(repoDir, "v2.0.0"); + + const tags = await git.listTags(repoDir); + expect(tags).toHaveLength(2); + expect(tags).toContain("v1.0.0"); + expect(tags).toContain("v2.0.0"); + }); }); // ========================================== @@ -571,16 +571,16 @@ describe("GitService — Tags", () => { // ========================================== describe("GitService — Revert", () => { - test("revert creates a revert commit", async () => { - await commitFile(repoDir, "file.txt", "version1", "commit 1"); - await commitFile(repoDir, "file.txt", "version2", "commit 2"); + test("revert creates a revert commit", async () => { + await commitFile(repoDir, "file.txt", "version1", "commit 1"); + await commitFile(repoDir, "file.txt", "version2", "commit 2"); - const log = await git.log(repoDir, 1); - await git.revert(repoDir, log[0].hash); + const log = await git.log(repoDir, 1); + await git.revert(repoDir, log[0].hash); - const afterLog = await git.log(repoDir); - expect(afterLog[0].subject).toContain("Revert"); - }); + const afterLog = await git.log(repoDir); + expect(afterLog[0].subject).toContain("Revert"); + }); }); // ========================================== @@ -588,21 +588,21 @@ describe("GitService — Revert", () => { // ========================================== describe("GitService — File at Ref", () => { - test("getFileAtRef returns file content at HEAD", async () => { - await commitFile(repoDir, "file.txt", "hello world", "add file"); - const content = await git.getFileAtRef(repoDir, "file.txt", "HEAD"); - expect(content).toBe("hello world"); - }); - - test("getFileAtRef returns null for missing file", async () => { - await commitFile(repoDir, "file.txt", "data", "init"); - const content = await git.getFileAtRef(repoDir, "nonexistent.txt", "HEAD"); - expect(content).toBeNull(); - }); - - test("show is alias for getFileAtRef", async () => { - await commitFile(repoDir, "file.txt", "show me", "add"); - const content = await git.show(repoDir, "HEAD", "file.txt"); - expect(content).toBe("show me"); - }); + test("getFileAtRef returns file content at HEAD", async () => { + await commitFile(repoDir, "file.txt", "hello world", "add file"); + const content = await git.getFileAtRef(repoDir, "file.txt", "HEAD"); + expect(content).toBe("hello world"); + }); + + test("getFileAtRef returns null for missing file", async () => { + await commitFile(repoDir, "file.txt", "data", "init"); + const content = await git.getFileAtRef(repoDir, "nonexistent.txt", "HEAD"); + expect(content).toBeNull(); + }); + + test("show is alias for getFileAtRef", async () => { + await commitFile(repoDir, "file.txt", "show me", "add"); + const content = await git.show(repoDir, "HEAD", "file.txt"); + expect(content).toBe("show me"); + }); }); diff --git a/bridge/__tests__/importProject.test.ts b/bridge/__tests__/importProject.test.ts index 05fa45b3..c71a0894 100644 --- a/bridge/__tests__/importProject.test.ts +++ b/bridge/__tests__/importProject.test.ts @@ -16,48 +16,48 @@ const SOURCE_DIR = path.join(TEST_ROOT, "cloned-repo"); * Mock config module to redirect to our temp folders */ jest.mock("../src/utils/config", () => { - const original = jest.requireActual("../src/utils/config") as any; - const _path = require("path"); - const _os = require("os"); - const testRoot = _path.join(_os.tmpdir(), "import-test-" + Date.now(), "projects"); - return { - ...original, - PROJECTS_FOLDER: testRoot, - PROJECTS_INDEX_FILE: _path.join(testRoot, "index.json"), - getProjectDir: (id: string) => _path.join(testRoot, id), - }; + const original = jest.requireActual("../src/utils/config") as any; + const _path = require("path"); + const _os = require("os"); + const testRoot = _path.join(_os.tmpdir(), "import-test-" + Date.now(), "projects"); + return { + ...original, + PROJECTS_FOLDER: testRoot, + PROJECTS_INDEX_FILE: _path.join(testRoot, "index.json"), + getProjectDir: (id: string) => _path.join(testRoot, id), + }; }); /** * Mock dbStoreInstance */ jest.mock("../src/services/dbStore", () => { - const addDBMock = jest.fn<(payload: any) => Promise>().mockImplementation((payload) => - Promise.resolve({ - id: "auto-created-db-id", - name: payload.name, - type: payload.type || "postgresql", - host: payload.host, - port: payload.port, - user: payload.user, - database: payload.database, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }) - ); - return { - dbStoreInstance: { - getDB: jest.fn<() => Promise>().mockResolvedValue({ - id: "test-db-id", - name: "TestDB", - type: "postgresql", - host: "localhost", - port: 5432, - }), - addDB: addDBMock, - }, - DBMeta: {}, - }; + const addDBMock = jest.fn<(payload: any) => Promise>().mockImplementation((payload) => + Promise.resolve({ + id: "auto-created-db-id", + name: payload.name, + type: payload.type || "postgresql", + host: payload.host, + port: payload.port, + user: payload.user, + database: payload.database, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }), + ); + return { + dbStoreInstance: { + getDB: jest.fn<() => Promise>().mockResolvedValue({ + id: "test-db-id", + name: "TestDB", + type: "postgresql", + host: "localhost", + port: 5432, + }), + addDB: addDBMock, + }, + DBMeta: {}, + }; }); import { dbStoreInstance } from "../src/services/dbStore"; @@ -68,849 +68,843 @@ import { PROJECTS_FOLDER, PROJECTS_INDEX_FILE, getProjectDir } from "../src/util // ─── Helpers ────────────────────────────────────── async function createSourceProject(opts: { - name?: string; - description?: string; - engine?: string; - envContent?: string; - schemaData?: any; - erData?: any; - queriesData?: any; - skipRelwaveJson?: boolean; + name?: string; + description?: string; + engine?: string; + envContent?: string; + schemaData?: any; + erData?: any; + queriesData?: any; + skipRelwaveJson?: boolean; }) { - await fs.mkdir(SOURCE_DIR, { recursive: true }); - await fs.mkdir(path.join(SOURCE_DIR, "schema"), { recursive: true }); - await fs.mkdir(path.join(SOURCE_DIR, "diagrams"), { recursive: true }); - await fs.mkdir(path.join(SOURCE_DIR, "queries"), { recursive: true }); - - // Write relwave.json - if (!opts.skipRelwaveJson) { - const meta = { - version: 1, - id: "original-project-id", - databaseId: "original-db-id", - name: opts.name || "Cloned Project", - description: opts.description, - engine: opts.engine, - defaultSchema: "public", - createdAt: "2024-01-01T00:00:00.000Z", - updatedAt: "2024-01-01T00:00:00.000Z", - }; - await fs.writeFile( - path.join(SOURCE_DIR, "relwave.json"), - JSON.stringify(meta, null, 2) - ); - } + await fs.mkdir(SOURCE_DIR, { recursive: true }); + await fs.mkdir(path.join(SOURCE_DIR, "schema"), { recursive: true }); + await fs.mkdir(path.join(SOURCE_DIR, "diagrams"), { recursive: true }); + await fs.mkdir(path.join(SOURCE_DIR, "queries"), { recursive: true }); + + // Write relwave.json + if (!opts.skipRelwaveJson) { + const meta = { + version: 1, + id: "original-project-id", + databaseId: "original-db-id", + name: opts.name || "Cloned Project", + description: opts.description, + engine: opts.engine, + defaultSchema: "public", + createdAt: "2024-01-01T00:00:00.000Z", + updatedAt: "2024-01-01T00:00:00.000Z", + }; + await fs.writeFile(path.join(SOURCE_DIR, "relwave.json"), JSON.stringify(meta, null, 2)); + } + + // Write .env if content provided + if (opts.envContent !== undefined) { + await fs.writeFile(path.join(SOURCE_DIR, ".env"), opts.envContent); + } + + // Write sub-resource files + if (opts.schemaData) { + await fs.writeFile( + path.join(SOURCE_DIR, "schema", "schema.json"), + JSON.stringify(opts.schemaData, null, 2), + ); + } + if (opts.erData) { + await fs.writeFile( + path.join(SOURCE_DIR, "diagrams", "er.json"), + JSON.stringify(opts.erData, null, 2), + ); + } + if (opts.queriesData) { + await fs.writeFile( + path.join(SOURCE_DIR, "queries", "queries.json"), + JSON.stringify(opts.queriesData, null, 2), + ); + } +} - // Write .env if content provided - if (opts.envContent !== undefined) { - await fs.writeFile(path.join(SOURCE_DIR, ".env"), opts.envContent); - } +// ─── Tests ────────────────────────────────────── - // Write sub-resource files - if (opts.schemaData) { - await fs.writeFile( - path.join(SOURCE_DIR, "schema", "schema.json"), - JSON.stringify(opts.schemaData, null, 2) - ); - } - if (opts.erData) { - await fs.writeFile( - path.join(SOURCE_DIR, "diagrams", "er.json"), - JSON.stringify(opts.erData, null, 2) - ); +describe("ProjectStore — Import Project", () => { + let store: ProjectStore; + + beforeEach(async () => { + // Clean up + for (const dir of [PROJECTS_FOLDER, SOURCE_DIR]) { + if (fsSync.existsSync(dir)) { + await fs.rm(dir, { recursive: true, force: true }); + } } - if (opts.queriesData) { - await fs.writeFile( - path.join(SOURCE_DIR, "queries", "queries.json"), - JSON.stringify(opts.queriesData, null, 2) - ); + await fs.mkdir(PROJECTS_FOLDER, { recursive: true }); + + store = new ProjectStore(PROJECTS_FOLDER, PROJECTS_INDEX_FILE); + mockAddDB.mockClear(); + }); + + afterEach(async () => { + for (const dir of [PROJECTS_FOLDER, SOURCE_DIR, TEST_ROOT]) { + if (fsSync.existsSync(dir)) { + await fs.rm(dir, { recursive: true, force: true }); + } } -} + }); + + // ========================================== + // .env Parsing (static methods) + // ========================================== + + describe("parseEnvFile", () => { + test("should parse simple KEY=VALUE pairs", () => { + const result = ProjectStore.parseEnvFile("DB_HOST=localhost\nDB_PORT=5432\nDB_USER=admin"); + expect(result).toEqual({ + DB_HOST: "localhost", + DB_PORT: "5432", + DB_USER: "admin", + }); + }); -// ─── Tests ────────────────────────────────────── + test("should handle double-quoted values", () => { + const result = ProjectStore.parseEnvFile('DB_PASSWORD="my secret"'); + expect(result).toEqual({ DB_PASSWORD: "my secret" }); + }); -describe("ProjectStore — Import Project", () => { - let store: ProjectStore; - - beforeEach(async () => { - // Clean up - for (const dir of [PROJECTS_FOLDER, SOURCE_DIR]) { - if (fsSync.existsSync(dir)) { - await fs.rm(dir, { recursive: true, force: true }); - } - } - await fs.mkdir(PROJECTS_FOLDER, { recursive: true }); - - store = new ProjectStore(PROJECTS_FOLDER, PROJECTS_INDEX_FILE); - mockAddDB.mockClear(); - }); - - afterEach(async () => { - for (const dir of [PROJECTS_FOLDER, SOURCE_DIR, TEST_ROOT]) { - if (fsSync.existsSync(dir)) { - await fs.rm(dir, { recursive: true, force: true }); - } - } - }); - - // ========================================== - // .env Parsing (static methods) - // ========================================== - - describe("parseEnvFile", () => { - test("should parse simple KEY=VALUE pairs", () => { - const result = ProjectStore.parseEnvFile( - "DB_HOST=localhost\nDB_PORT=5432\nDB_USER=admin" - ); - expect(result).toEqual({ - DB_HOST: "localhost", - DB_PORT: "5432", - DB_USER: "admin", - }); - }); - - test("should handle double-quoted values", () => { - const result = ProjectStore.parseEnvFile('DB_PASSWORD="my secret"'); - expect(result).toEqual({ DB_PASSWORD: "my secret" }); - }); - - test("should handle single-quoted values", () => { - const result = ProjectStore.parseEnvFile("DB_PASSWORD='pass word'"); - expect(result).toEqual({ DB_PASSWORD: "pass word" }); - }); - - test("should skip blank lines and comments", () => { - const result = ProjectStore.parseEnvFile( - "# This is a comment\n\nDB_HOST=localhost\n \n# Another comment\nDB_PORT=3306" - ); - expect(result).toEqual({ - DB_HOST: "localhost", - DB_PORT: "3306", - }); - }); - - test("should handle values with equals signs", () => { - const result = ProjectStore.parseEnvFile("DB_PASSWORD=p@ss=word"); - expect(result).toEqual({ DB_PASSWORD: "p@ss=word" }); - }); - - test("should handle empty values", () => { - const result = ProjectStore.parseEnvFile("DB_PASSWORD="); - expect(result).toEqual({ DB_PASSWORD: "" }); - }); - - test("should handle Windows-style line endings", () => { - const result = ProjectStore.parseEnvFile( - "DB_HOST=localhost\r\nDB_PORT=5432\r\n" - ); - expect(result).toEqual({ - DB_HOST: "localhost", - DB_PORT: "5432", - }); - }); - - test("should trim whitespace from keys and values", () => { - const result = ProjectStore.parseEnvFile( - " DB_HOST = localhost \n DB_PORT = 5432 " - ); - expect(result).toEqual({ - DB_HOST: "localhost", - DB_PORT: "5432", - }); - }); - - test("should return empty object for empty content", () => { - expect(ProjectStore.parseEnvFile("")).toEqual({}); - }); - - test("should return empty object for comment-only content", () => { - expect(ProjectStore.parseEnvFile("# just a comment\n# another one")).toEqual({}); - }); - }); - - describe("extractDbParamsFromEnv", () => { - test("should extract standard DB_ prefixed variables", () => { - const result = ProjectStore.extractDbParamsFromEnv({ - DB_HOST: "db.example.com", - DB_PORT: "3306", - DB_USER: "root", - DB_PASSWORD: "secret", - DB_NAME: "myapp", - DB_TYPE: "mysql", - }); - expect(result).toEqual({ - host: "db.example.com", - port: 3306, - user: "root", - password: "secret", - database: "myapp", - type: "mysql", - ssl: undefined, - name: undefined, - }); - }); - - test("should handle PostgreSQL-style PG* variables", () => { - const result = ProjectStore.extractDbParamsFromEnv({ - PGHOST: "pg.example.com", - PGPORT: "5433", - PGUSER: "pgadmin", - PGPASSWORD: "pgpass", - PGDATABASE: "pgdb", - }); - expect(result).toEqual({ - host: "pg.example.com", - port: 5433, - user: "pgadmin", - password: "pgpass", - database: "pgdb", - type: undefined, - ssl: undefined, - name: undefined, - }); - }); - - test("should handle DATABASE_ prefixed variables", () => { - const result = ProjectStore.extractDbParamsFromEnv({ - DATABASE_HOST: "db.prod.com", - DATABASE_PORT: "5432", - DATABASE_USER: "appuser", - DATABASE_PASSWORD: "prodpass", - DATABASE_NAME: "proddb", - DATABASE_TYPE: "PostgreSQL", - }); - expect(result).toEqual({ - host: "db.prod.com", - port: 5432, - user: "appuser", - password: "prodpass", - database: "proddb", - type: "postgresql", - ssl: undefined, - name: undefined, - }); - }); - - test("should handle MYSQL_ prefixed variables", () => { - const result = ProjectStore.extractDbParamsFromEnv({ - MYSQL_HOST: "mysql.local", - MYSQL_PORT: "3307", - MYSQL_USER: "myuser", - MYSQL_PASSWORD: "mypass", - MYSQL_DATABASE: "mydb", - }); - expect(result).toEqual({ - host: "mysql.local", - port: 3307, - user: "myuser", - password: "mypass", - database: "mydb", - type: undefined, - ssl: undefined, - name: undefined, - }); - }); - - test("should handle SSL flag", () => { - const result = ProjectStore.extractDbParamsFromEnv({ - DB_HOST: "secure.db.com", - DB_SSL: "true", - }); - expect(result?.ssl).toBe(true); - }); - - test("should handle SSL=false", () => { - const result = ProjectStore.extractDbParamsFromEnv({ - DB_HOST: "local.db.com", - DB_SSL: "false", - }); - expect(result?.ssl).toBe(false); - }); - - test("should return null when no host or database is provided", () => { - const result = ProjectStore.extractDbParamsFromEnv({ - DB_USER: "user", - DB_PASSWORD: "pass", - }); - expect(result).toBeNull(); - }); - - test("should handle non-numeric port gracefully", () => { - const result = ProjectStore.extractDbParamsFromEnv({ - DB_HOST: "localhost", - DB_PORT: "not-a-number", - }); - expect(result?.port).toBeUndefined(); - }); - - test("should prefer DB_ prefix over fallbacks", () => { - const result = ProjectStore.extractDbParamsFromEnv({ - DB_HOST: "primary.host", - PGHOST: "fallback.host", - DB_USER: "primary_user", - DATABASE_USER: "fallback_user", - }); - expect(result?.host).toBe("primary.host"); - expect(result?.user).toBe("primary_user"); - }); - - test("should extract connection name", () => { - const result = ProjectStore.extractDbParamsFromEnv({ - DB_HOST: "localhost", - DB_CONNECTION_NAME: "My Custom DB", - }); - expect(result?.name).toBe("My Custom DB"); - }); - }); - - // ========================================== - // scanImportSource (read-only preview) - // ========================================== - - describe("scanImportSource", () => { - test("should scan a valid project directory", async () => { - await createSourceProject({ - name: "Scan Test", - description: "A project to scan", - engine: "postgresql", - }); - - const result = await store.scanImportSource(SOURCE_DIR); - - expect(result.metadata.name).toBe("Scan Test"); - expect(result.metadata.description).toBe("A project to scan"); - expect(result.metadata.engine).toBe("postgresql"); - expect(result.metadata.defaultSchema).toBe("public"); - expect(result.envFound).toBe(false); - expect(result.parsedEnv).toBeNull(); - }); - - test("should detect and parse .env file", async () => { - await createSourceProject({ - name: "Env Scan", - envContent: [ - "DB_HOST=db.example.com", - "DB_PORT=5432", - "DB_USER=admin", - "DB_PASSWORD=secret", - "DB_NAME=mydb", - "DB_TYPE=postgresql", - ].join("\n"), - }); - - const result = await store.scanImportSource(SOURCE_DIR); - - expect(result.envFound).toBe(true); - expect(result.parsedEnv).toBeDefined(); - expect(result.parsedEnv?.host).toBe("db.example.com"); - expect(result.parsedEnv?.port).toBe(5432); - expect(result.parsedEnv?.user).toBe("admin"); - expect(result.parsedEnv?.password).toBe("secret"); - expect(result.parsedEnv?.database).toBe("mydb"); - expect(result.parsedEnv?.type).toBe("postgresql"); - }); - - test("should return envFound=true but parsedEnv=null for incomplete .env", async () => { - await createSourceProject({ - name: "Partial Env", - envContent: "DB_USER=admin\nDB_PASSWORD=pass\n# no host or db", - }); - - const result = await store.scanImportSource(SOURCE_DIR); - - expect(result.envFound).toBe(true); - expect(result.parsedEnv).toBeNull(); - }); - - test("should throw when relwave.json is missing", async () => { - await fs.mkdir(SOURCE_DIR, { recursive: true }); - - await expect(store.scanImportSource(SOURCE_DIR)).rejects.toThrow( - "Not a valid RelWave project" - ); - }); - - test("should throw when relwave.json has no name", async () => { - await fs.mkdir(SOURCE_DIR, { recursive: true }); - await fs.writeFile( - path.join(SOURCE_DIR, "relwave.json"), - JSON.stringify({ version: 1, id: "x" }) - ); - - await expect(store.scanImportSource(SOURCE_DIR)).rejects.toThrow( - "Invalid relwave.json" - ); - }); - - test("should NOT create any files or modify the store", async () => { - await createSourceProject({ name: "No Side Effects" }); - - await store.scanImportSource(SOURCE_DIR); - - // Should have no projects in the index - const listed = await store.listProjects(); - expect(listed).toHaveLength(0); - }); - }); - - // ========================================== - // importProject - // ========================================== - - describe("importProject", () => { - test("should throw when relwave.json is missing", async () => { - await fs.mkdir(SOURCE_DIR, { recursive: true }); - - await expect( - store.importProject({ sourcePath: SOURCE_DIR, databaseId: "db-1" }) - ).rejects.toThrow("Not a valid RelWave project"); - }); - - test("should throw when relwave.json has no name", async () => { - await fs.mkdir(SOURCE_DIR, { recursive: true }); - await fs.writeFile( - path.join(SOURCE_DIR, "relwave.json"), - JSON.stringify({ version: 1, id: "x" }) - ); - - await expect( - store.importProject({ sourcePath: SOURCE_DIR, databaseId: "db-1" }) - ).rejects.toThrow("Invalid relwave.json"); - }); - - test("should throw when databaseId is missing", async () => { - await createSourceProject({ name: "No DB ID" }); - - await expect( - store.importProject({ sourcePath: SOURCE_DIR, databaseId: "" }) - ).rejects.toThrow("databaseId is required"); - }); - - test("should import project with supplied databaseId", async () => { - await createSourceProject({ - name: "Imported Project", - description: "A test import", - }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "my-db-id", - }); - - expect(project).toBeDefined(); - expect(project.name).toBe("Imported Project"); - expect(project.description).toBe("A test import"); - // Effective databaseId comes from local config - expect(project.databaseId).toBe("my-db-id"); - expect(project.sourcePath).toBe(SOURCE_DIR); - // Must keep the original projectId from relwave.json - expect(project.id).toBe("original-project-id"); - }); - - test("should NOT modify tracked files (read-only import)", async () => { - const schemaData = { - version: 1, - projectId: "original-id", - databaseId: "original-db-id", - schemas: [{ name: "public", tables: [{ name: "users" }] }], - cachedAt: "2024-01-01T00:00:00.000Z", - }; - const erData = { - version: 1, - projectId: "original-id", - nodes: [{ tableId: "users", x: 100, y: 200 }], - updatedAt: "2024-01-01T00:00:00.000Z", - }; - const queriesData = { - version: 1, - projectId: "original-id", - queries: [{ id: "q1", name: "All users", sql: "SELECT * FROM users" }], - }; - - await createSourceProject({ - name: "Full Project", - schemaData, - erData, - queriesData, - }); - - // Snapshot the original file contents BEFORE import - const origRelwave = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); - const origSchema = await fs.readFile(path.join(SOURCE_DIR, "schema", "schema.json"), "utf-8"); - const origER = await fs.readFile(path.join(SOURCE_DIR, "diagrams", "er.json"), "utf-8"); - const origQueries = await fs.readFile(path.join(SOURCE_DIR, "queries", "queries.json"), "utf-8"); - - await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "copy-db-id", - }); - - // ALL tracked files must be IDENTICAL after import - const afterRelwave = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); - const afterSchema = await fs.readFile(path.join(SOURCE_DIR, "schema", "schema.json"), "utf-8"); - const afterER = await fs.readFile(path.join(SOURCE_DIR, "diagrams", "er.json"), "utf-8"); - const afterQueries = await fs.readFile(path.join(SOURCE_DIR, "queries", "queries.json"), "utf-8"); - - expect(afterRelwave).toBe(origRelwave); - expect(afterSchema).toBe(origSchema); - expect(afterER).toBe(origER); - expect(afterQueries).toBe(origQueries); - }); - - test("should store databaseId in local config (git-ignored)", async () => { - await createSourceProject({ name: "Local Config Test" }); - - await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "local-db-id", - }); - - // databaseId should be in relwave.local.json (git-ignored) - const localConfig = JSON.parse( - await fs.readFile(path.join(SOURCE_DIR, "relwave.local.json"), "utf-8") - ); - expect(localConfig.databaseId).toBe("local-db-id"); - - // relwave.json should still have the ORIGINAL databaseId (untouched) - const meta = JSON.parse( - await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8") - ); - expect(meta.databaseId).toBe("original-db-id"); - }); - - test("should handle missing sub-resource files gracefully", async () => { - await createSourceProject({ - name: "Minimal Project", - // No schema/ER/queries files - }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "min-db-id", - }); - - // Should still succeed — import doesn't require sub-resources - expect(project).toBeDefined(); - expect(project.name).toBe("Minimal Project"); - }); - - test("should add imported project to the global index with sourcePath", async () => { - await createSourceProject({ name: "Indexed Project" }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "idx-db-id", - }); - - const listed = await store.listProjects(); - expect(listed).toHaveLength(1); - expect(listed[0].id).toBe(project.id); - expect(listed[0].name).toBe("Indexed Project"); - expect(listed[0].sourcePath).toBe(SOURCE_DIR); - }); - - test("should ensure subdirectories exist in source dir", async () => { - await createSourceProject({ name: "Dir Check" }); - - await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "dir-db-id", - }); - - // Directories should exist in the SOURCE dir (not internal) - expect(fsSync.existsSync(path.join(SOURCE_DIR, "schema"))).toBe(true); - expect(fsSync.existsSync(path.join(SOURCE_DIR, "diagrams"))).toBe(true); - expect(fsSync.existsSync(path.join(SOURCE_DIR, "queries"))).toBe(true); - expect(fsSync.existsSync(path.join(SOURCE_DIR, ".gitignore"))).toBe(true); - }); - - test("should resolve project dir to sourcePath for imported projects", async () => { - await createSourceProject({ name: "Resolve Test" }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "res-db-id", - }); - - const resolvedDir = await store.resolveProjectDir(project.id); - expect(resolvedDir).toBe(SOURCE_DIR); - }); - - test("should keep the original project ID from relwave.json", async () => { - await createSourceProject({ name: "Keep ID Test" }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "uid-db-id", - }); - - // Must reuse the original projectId — never generate a new one - expect(project.id).toBe("original-project-id"); - }); - - test("should preserve defaultSchema from source metadata", async () => { - await createSourceProject({ name: "Schema Test" }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "schema-db-id", - }); - - expect(project.defaultSchema).toBe("public"); - }); - - test("should reject importing the same project twice", async () => { - await createSourceProject({ name: "Duplicate Test" }); - - // First import succeeds - await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "dup-db-id", - }); - - // Second import of the same project ID should fail - await expect( - store.importProject({ sourcePath: SOURCE_DIR, databaseId: "dup-db-id" }) - ).rejects.toThrow("already imported"); - }); - - test("should merge databaseId from local config in getProject", async () => { - await createSourceProject({ name: "Merge Test" }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "merged-db-id", - }); - - // getProject should return the local databaseId, not the original - const loaded = await store.getProject(project.id); - expect(loaded).toBeDefined(); - expect(loaded!.databaseId).toBe("merged-db-id"); - expect(loaded!.name).toBe("Merge Test"); - }); - }); - - // ========================================== - // linkDatabase - // ========================================== - - describe("linkDatabase", () => { - test("should link a database to a project", async () => { - const project = await store.createProject({ - databaseId: "pending", - name: "Pending Project", - }); - - const updated = await store.linkDatabase(project.id, "real-db-id"); - - expect(updated).toBeDefined(); - expect(updated!.databaseId).toBe("real-db-id"); - }); - - test("should update engine type from linked database", async () => { - const project = await store.createProject({ - databaseId: "pending", - name: "Engine Test", - }); - - const updated = await store.linkDatabase(project.id, "test-db-id"); - - // Engine should be resolved from mocked dbStore - expect(updated!.engine).toBe("postgresql"); - }); - - test("should update the global index", async () => { - const project = await store.createProject({ - databaseId: "pending", - name: "Index Sync Test", - }); + test("should handle single-quoted values", () => { + const result = ProjectStore.parseEnvFile("DB_PASSWORD='pass word'"); + expect(result).toEqual({ DB_PASSWORD: "pass word" }); + }); + + test("should skip blank lines and comments", () => { + const result = ProjectStore.parseEnvFile( + "# This is a comment\n\nDB_HOST=localhost\n \n# Another comment\nDB_PORT=3306", + ); + expect(result).toEqual({ + DB_HOST: "localhost", + DB_PORT: "3306", + }); + }); + + test("should handle values with equals signs", () => { + const result = ProjectStore.parseEnvFile("DB_PASSWORD=p@ss=word"); + expect(result).toEqual({ DB_PASSWORD: "p@ss=word" }); + }); + + test("should handle empty values", () => { + const result = ProjectStore.parseEnvFile("DB_PASSWORD="); + expect(result).toEqual({ DB_PASSWORD: "" }); + }); + + test("should handle Windows-style line endings", () => { + const result = ProjectStore.parseEnvFile("DB_HOST=localhost\r\nDB_PORT=5432\r\n"); + expect(result).toEqual({ + DB_HOST: "localhost", + DB_PORT: "5432", + }); + }); + + test("should trim whitespace from keys and values", () => { + const result = ProjectStore.parseEnvFile(" DB_HOST = localhost \n DB_PORT = 5432 "); + expect(result).toEqual({ + DB_HOST: "localhost", + DB_PORT: "5432", + }); + }); + + test("should return empty object for empty content", () => { + expect(ProjectStore.parseEnvFile("")).toEqual({}); + }); + + test("should return empty object for comment-only content", () => { + expect(ProjectStore.parseEnvFile("# just a comment\n# another one")).toEqual({}); + }); + }); + + describe("extractDbParamsFromEnv", () => { + test("should extract standard DB_ prefixed variables", () => { + const result = ProjectStore.extractDbParamsFromEnv({ + DB_HOST: "db.example.com", + DB_PORT: "3306", + DB_USER: "root", + DB_PASSWORD: "secret", + DB_NAME: "myapp", + DB_TYPE: "mysql", + }); + expect(result).toEqual({ + host: "db.example.com", + port: 3306, + user: "root", + password: "secret", + database: "myapp", + type: "mysql", + ssl: undefined, + name: undefined, + }); + }); + + test("should handle PostgreSQL-style PG* variables", () => { + const result = ProjectStore.extractDbParamsFromEnv({ + PGHOST: "pg.example.com", + PGPORT: "5433", + PGUSER: "pgadmin", + PGPASSWORD: "pgpass", + PGDATABASE: "pgdb", + }); + expect(result).toEqual({ + host: "pg.example.com", + port: 5433, + user: "pgadmin", + password: "pgpass", + database: "pgdb", + type: undefined, + ssl: undefined, + name: undefined, + }); + }); + + test("should handle DATABASE_ prefixed variables", () => { + const result = ProjectStore.extractDbParamsFromEnv({ + DATABASE_HOST: "db.prod.com", + DATABASE_PORT: "5432", + DATABASE_USER: "appuser", + DATABASE_PASSWORD: "prodpass", + DATABASE_NAME: "proddb", + DATABASE_TYPE: "PostgreSQL", + }); + expect(result).toEqual({ + host: "db.prod.com", + port: 5432, + user: "appuser", + password: "prodpass", + database: "proddb", + type: "postgresql", + ssl: undefined, + name: undefined, + }); + }); + + test("should handle MYSQL_ prefixed variables", () => { + const result = ProjectStore.extractDbParamsFromEnv({ + MYSQL_HOST: "mysql.local", + MYSQL_PORT: "3307", + MYSQL_USER: "myuser", + MYSQL_PASSWORD: "mypass", + MYSQL_DATABASE: "mydb", + }); + expect(result).toEqual({ + host: "mysql.local", + port: 3307, + user: "myuser", + password: "mypass", + database: "mydb", + type: undefined, + ssl: undefined, + name: undefined, + }); + }); + + test("should handle SSL flag", () => { + const result = ProjectStore.extractDbParamsFromEnv({ + DB_HOST: "secure.db.com", + DB_SSL: "true", + }); + expect(result?.ssl).toBe(true); + }); + + test("should handle SSL=false", () => { + const result = ProjectStore.extractDbParamsFromEnv({ + DB_HOST: "local.db.com", + DB_SSL: "false", + }); + expect(result?.ssl).toBe(false); + }); + + test("should return null when no host or database is provided", () => { + const result = ProjectStore.extractDbParamsFromEnv({ + DB_USER: "user", + DB_PASSWORD: "pass", + }); + expect(result).toBeNull(); + }); + + test("should handle non-numeric port gracefully", () => { + const result = ProjectStore.extractDbParamsFromEnv({ + DB_HOST: "localhost", + DB_PORT: "not-a-number", + }); + expect(result?.port).toBeUndefined(); + }); + + test("should prefer DB_ prefix over fallbacks", () => { + const result = ProjectStore.extractDbParamsFromEnv({ + DB_HOST: "primary.host", + PGHOST: "fallback.host", + DB_USER: "primary_user", + DATABASE_USER: "fallback_user", + }); + expect(result?.host).toBe("primary.host"); + expect(result?.user).toBe("primary_user"); + }); + + test("should extract connection name", () => { + const result = ProjectStore.extractDbParamsFromEnv({ + DB_HOST: "localhost", + DB_CONNECTION_NAME: "My Custom DB", + }); + expect(result?.name).toBe("My Custom DB"); + }); + }); + + // ========================================== + // scanImportSource (read-only preview) + // ========================================== + + describe("scanImportSource", () => { + test("should scan a valid project directory", async () => { + await createSourceProject({ + name: "Scan Test", + description: "A project to scan", + engine: "postgresql", + }); + + const result = await store.scanImportSource(SOURCE_DIR); + + expect(result.metadata.name).toBe("Scan Test"); + expect(result.metadata.description).toBe("A project to scan"); + expect(result.metadata.engine).toBe("postgresql"); + expect(result.metadata.defaultSchema).toBe("public"); + expect(result.envFound).toBe(false); + expect(result.parsedEnv).toBeNull(); + }); + + test("should detect and parse .env file", async () => { + await createSourceProject({ + name: "Env Scan", + envContent: [ + "DB_HOST=db.example.com", + "DB_PORT=5432", + "DB_USER=admin", + "DB_PASSWORD=secret", + "DB_NAME=mydb", + "DB_TYPE=postgresql", + ].join("\n"), + }); + + const result = await store.scanImportSource(SOURCE_DIR); + + expect(result.envFound).toBe(true); + expect(result.parsedEnv).toBeDefined(); + expect(result.parsedEnv?.host).toBe("db.example.com"); + expect(result.parsedEnv?.port).toBe(5432); + expect(result.parsedEnv?.user).toBe("admin"); + expect(result.parsedEnv?.password).toBe("secret"); + expect(result.parsedEnv?.database).toBe("mydb"); + expect(result.parsedEnv?.type).toBe("postgresql"); + }); + + test("should return envFound=true but parsedEnv=null for incomplete .env", async () => { + await createSourceProject({ + name: "Partial Env", + envContent: "DB_USER=admin\nDB_PASSWORD=pass\n# no host or db", + }); + + const result = await store.scanImportSource(SOURCE_DIR); + + expect(result.envFound).toBe(true); + expect(result.parsedEnv).toBeNull(); + }); + + test("should throw when relwave.json is missing", async () => { + await fs.mkdir(SOURCE_DIR, { recursive: true }); + + await expect(store.scanImportSource(SOURCE_DIR)).rejects.toThrow( + "Not a valid RelWave project", + ); + }); + + test("should throw when relwave.json has no name", async () => { + await fs.mkdir(SOURCE_DIR, { recursive: true }); + await fs.writeFile( + path.join(SOURCE_DIR, "relwave.json"), + JSON.stringify({ version: 1, id: "x" }), + ); + + await expect(store.scanImportSource(SOURCE_DIR)).rejects.toThrow("Invalid relwave.json"); + }); + + test("should NOT create any files or modify the store", async () => { + await createSourceProject({ name: "No Side Effects" }); + + await store.scanImportSource(SOURCE_DIR); + + // Should have no projects in the index + const listed = await store.listProjects(); + expect(listed).toHaveLength(0); + }); + }); + + // ========================================== + // importProject + // ========================================== + + describe("importProject", () => { + test("should throw when relwave.json is missing", async () => { + await fs.mkdir(SOURCE_DIR, { recursive: true }); + + await expect( + store.importProject({ sourcePath: SOURCE_DIR, databaseId: "db-1" }), + ).rejects.toThrow("Not a valid RelWave project"); + }); + + test("should throw when relwave.json has no name", async () => { + await fs.mkdir(SOURCE_DIR, { recursive: true }); + await fs.writeFile( + path.join(SOURCE_DIR, "relwave.json"), + JSON.stringify({ version: 1, id: "x" }), + ); + + await expect( + store.importProject({ sourcePath: SOURCE_DIR, databaseId: "db-1" }), + ).rejects.toThrow("Invalid relwave.json"); + }); + + test("should throw when databaseId is missing", async () => { + await createSourceProject({ name: "No DB ID" }); + + await expect(store.importProject({ sourcePath: SOURCE_DIR, databaseId: "" })).rejects.toThrow( + "databaseId is required", + ); + }); + + test("should import project with supplied databaseId", async () => { + await createSourceProject({ + name: "Imported Project", + description: "A test import", + }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "my-db-id", + }); + + expect(project).toBeDefined(); + expect(project.name).toBe("Imported Project"); + expect(project.description).toBe("A test import"); + // Effective databaseId comes from local config + expect(project.databaseId).toBe("my-db-id"); + expect(project.sourcePath).toBe(SOURCE_DIR); + // Must keep the original projectId from relwave.json + expect(project.id).toBe("original-project-id"); + }); + + test("should NOT modify tracked files (read-only import)", async () => { + const schemaData = { + version: 1, + projectId: "original-id", + databaseId: "original-db-id", + schemas: [{ name: "public", tables: [{ name: "users" }] }], + cachedAt: "2024-01-01T00:00:00.000Z", + }; + const erData = { + version: 1, + projectId: "original-id", + nodes: [{ tableId: "users", x: 100, y: 200 }], + updatedAt: "2024-01-01T00:00:00.000Z", + }; + const queriesData = { + version: 1, + projectId: "original-id", + queries: [{ id: "q1", name: "All users", sql: "SELECT * FROM users" }], + }; + + await createSourceProject({ + name: "Full Project", + schemaData, + erData, + queriesData, + }); + + // Snapshot the original file contents BEFORE import + const origRelwave = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); + const origSchema = await fs.readFile(path.join(SOURCE_DIR, "schema", "schema.json"), "utf-8"); + const origER = await fs.readFile(path.join(SOURCE_DIR, "diagrams", "er.json"), "utf-8"); + const origQueries = await fs.readFile( + path.join(SOURCE_DIR, "queries", "queries.json"), + "utf-8", + ); + + await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "copy-db-id", + }); + + // ALL tracked files must be IDENTICAL after import + const afterRelwave = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); + const afterSchema = await fs.readFile( + path.join(SOURCE_DIR, "schema", "schema.json"), + "utf-8", + ); + const afterER = await fs.readFile(path.join(SOURCE_DIR, "diagrams", "er.json"), "utf-8"); + const afterQueries = await fs.readFile( + path.join(SOURCE_DIR, "queries", "queries.json"), + "utf-8", + ); + + expect(afterRelwave).toBe(origRelwave); + expect(afterSchema).toBe(origSchema); + expect(afterER).toBe(origER); + expect(afterQueries).toBe(origQueries); + }); + + test("should store databaseId in local config (git-ignored)", async () => { + await createSourceProject({ name: "Local Config Test" }); + + await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "local-db-id", + }); + + // databaseId should be in relwave.local.json (git-ignored) + const localConfig = JSON.parse( + await fs.readFile(path.join(SOURCE_DIR, "relwave.local.json"), "utf-8"), + ); + expect(localConfig.databaseId).toBe("local-db-id"); + + // relwave.json should still have the ORIGINAL databaseId (untouched) + const meta = JSON.parse(await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8")); + expect(meta.databaseId).toBe("original-db-id"); + }); + + test("should handle missing sub-resource files gracefully", async () => { + await createSourceProject({ + name: "Minimal Project", + // No schema/ER/queries files + }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "min-db-id", + }); + + // Should still succeed — import doesn't require sub-resources + expect(project).toBeDefined(); + expect(project.name).toBe("Minimal Project"); + }); + + test("should add imported project to the global index with sourcePath", async () => { + await createSourceProject({ name: "Indexed Project" }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "idx-db-id", + }); + + const listed = await store.listProjects(); + expect(listed).toHaveLength(1); + expect(listed[0].id).toBe(project.id); + expect(listed[0].name).toBe("Indexed Project"); + expect(listed[0].sourcePath).toBe(SOURCE_DIR); + }); + + test("should ensure subdirectories exist in source dir", async () => { + await createSourceProject({ name: "Dir Check" }); + + await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "dir-db-id", + }); + + // Directories should exist in the SOURCE dir (not internal) + expect(fsSync.existsSync(path.join(SOURCE_DIR, "schema"))).toBe(true); + expect(fsSync.existsSync(path.join(SOURCE_DIR, "diagrams"))).toBe(true); + expect(fsSync.existsSync(path.join(SOURCE_DIR, "queries"))).toBe(true); + expect(fsSync.existsSync(path.join(SOURCE_DIR, ".gitignore"))).toBe(true); + }); + + test("should resolve project dir to sourcePath for imported projects", async () => { + await createSourceProject({ name: "Resolve Test" }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "res-db-id", + }); + + const resolvedDir = await store.resolveProjectDir(project.id); + expect(resolvedDir).toBe(SOURCE_DIR); + }); + + test("should keep the original project ID from relwave.json", async () => { + await createSourceProject({ name: "Keep ID Test" }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "uid-db-id", + }); + + // Must reuse the original projectId — never generate a new one + expect(project.id).toBe("original-project-id"); + }); + + test("should preserve defaultSchema from source metadata", async () => { + await createSourceProject({ name: "Schema Test" }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "schema-db-id", + }); + + expect(project.defaultSchema).toBe("public"); + }); + + test("should reject importing the same project twice", async () => { + await createSourceProject({ name: "Duplicate Test" }); + + // First import succeeds + await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "dup-db-id", + }); + + // Second import of the same project ID should fail + await expect( + store.importProject({ sourcePath: SOURCE_DIR, databaseId: "dup-db-id" }), + ).rejects.toThrow("already imported"); + }); + + test("should merge databaseId from local config in getProject", async () => { + await createSourceProject({ name: "Merge Test" }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "merged-db-id", + }); + + // getProject should return the local databaseId, not the original + const loaded = await store.getProject(project.id); + expect(loaded).toBeDefined(); + expect(loaded!.databaseId).toBe("merged-db-id"); + expect(loaded!.name).toBe("Merge Test"); + }); + }); + + // ========================================== + // linkDatabase + // ========================================== + + describe("linkDatabase", () => { + test("should link a database to a project", async () => { + const project = await store.createProject({ + databaseId: "pending", + name: "Pending Project", + }); + + const updated = await store.linkDatabase(project.id, "real-db-id"); + + expect(updated).toBeDefined(); + expect(updated!.databaseId).toBe("real-db-id"); + }); + + test("should update engine type from linked database", async () => { + const project = await store.createProject({ + databaseId: "pending", + name: "Engine Test", + }); + + const updated = await store.linkDatabase(project.id, "test-db-id"); + + // Engine should be resolved from mocked dbStore + expect(updated!.engine).toBe("postgresql"); + }); + + test("should update the global index", async () => { + const project = await store.createProject({ + databaseId: "pending", + name: "Index Sync Test", + }); + + await store.linkDatabase(project.id, "linked-db-id"); + + const listed = await store.listProjects(); + expect(listed[0].databaseId).toBe("linked-db-id"); + }); + + test("should update schema file's databaseId", async () => { + const project = await store.createProject({ + databaseId: "pending", + name: "Schema Sync", + }); + + // Save a schema first + await store.saveSchema(project.id, [{ name: "public", tables: [] }]); + + await store.linkDatabase(project.id, "new-db-id"); + + const schema = await store.getSchema(project.id); + expect(schema!.databaseId).toBe("new-db-id"); + }); + + test("should return null for non-existent project", async () => { + const result = await store.linkDatabase("no-such-project", "db-id"); + expect(result).toBeNull(); + }); + + test("should update the updatedAt timestamp", async () => { + const project = await store.createProject({ + databaseId: "pending", + name: "Timestamp Test", + }); + + // Wait a tick to ensure timestamp difference + await new Promise((r) => setTimeout(r, 10)); + + const updated = await store.linkDatabase(project.id, "db-id"); + + expect(updated!.updatedAt).not.toBe(project.updatedAt); + }); + + test("should write to local config (not relwave.json) for imported projects", async () => { + await createSourceProject({ name: "Link Imported" }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "initial-db-id", + }); + + // Snapshot relwave.json BEFORE linkDatabase + const beforeMeta = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); + + // Re-link to a different database + const updated = await store.linkDatabase(project.id, "relinked-db-id"); + expect(updated!.databaseId).toBe("relinked-db-id"); + + // relwave.json must NOT have changed + const afterMeta = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); + expect(afterMeta).toBe(beforeMeta); + + // databaseId should be in local config + const localConfig = JSON.parse( + await fs.readFile(path.join(SOURCE_DIR, "relwave.local.json"), "utf-8"), + ); + expect(localConfig.databaseId).toBe("relinked-db-id"); + + // Index should have the updated databaseId + const listed = await store.listProjects(); + expect(listed[0].databaseId).toBe("relinked-db-id"); + }); + }); + + // ─── updateProject for imported projects ────────────────────────── + + describe("updateProject (imported)", () => { + test("should NOT modify relwave.json for imported projects", async () => { + await createSourceProject({ name: "Imported Update", description: "Old desc" }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "db-1", + }); + + // Snapshot relwave.json BEFORE update + const beforeMeta = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); + + await store.updateProject(project.id, { + name: "Renamed Locally", + description: "New desc", + }); + + // relwave.json must NOT have changed + const afterMeta = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); + expect(afterMeta).toBe(beforeMeta); + }); + + test("should store overrides in local config", async () => { + await createSourceProject({ name: "Override Test" }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "db-1", + }); + + await store.updateProject(project.id, { + name: "Local Name", + description: "Local desc", + defaultSchema: "custom", + }); + + const localConfig = JSON.parse( + await fs.readFile(path.join(SOURCE_DIR, "relwave.local.json"), "utf-8"), + ); + expect(localConfig.overrides).toBeDefined(); + expect(localConfig.overrides.name).toBe("Local Name"); + expect(localConfig.overrides.description).toBe("Local desc"); + expect(localConfig.overrides.defaultSchema).toBe("custom"); + }); + + test("should merge overrides into getProject result", async () => { + await createSourceProject({ name: "Merge Test", description: "Original" }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "db-1", + }); + + await store.updateProject(project.id, { name: "Overridden" }); + + const fetched = await store.getProject(project.id); + expect(fetched!.name).toBe("Overridden"); + // Description stays from relwave.json (not overridden) + expect(fetched!.description).toBe("Original"); + }); + + test("should sync index after imported project update", async () => { + await createSourceProject({ name: "Index Sync" }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "db-1", + }); + + await store.updateProject(project.id, { name: "Updated Name" }); + + const listed = await store.listProjects(); + const entry = listed.find((p) => p.id === project.id); + expect(entry!.name).toBe("Updated Name"); + }); + + test("should preserve existing local config fields when adding overrides", async () => { + await createSourceProject({ name: "Preserve Fields" }); + + const project = await store.importProject({ + sourcePath: SOURCE_DIR, + databaseId: "db-1", + }); + + // Local config already has databaseId from import + await store.updateProject(project.id, { name: "New Name" }); + + const localConfig = JSON.parse( + await fs.readFile(path.join(SOURCE_DIR, "relwave.local.json"), "utf-8"), + ); + // databaseId should still be there + expect(localConfig.databaseId).toBe("db-1"); + // And overrides should be added + expect(localConfig.overrides.name).toBe("New Name"); + }); + + test("should still modify relwave.json for regular (non-imported) projects", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "Regular Project", + }); - await store.linkDatabase(project.id, "linked-db-id"); + const updated = await store.updateProject(project.id, { + name: "Renamed Regular", + }); - const listed = await store.listProjects(); - expect(listed[0].databaseId).toBe("linked-db-id"); - }); + expect(updated!.name).toBe("Renamed Regular"); - test("should update schema file's databaseId", async () => { - const project = await store.createProject({ - databaseId: "pending", - name: "Schema Sync", - }); - - // Save a schema first - await store.saveSchema(project.id, [ - { name: "public", tables: [] }, - ]); - - await store.linkDatabase(project.id, "new-db-id"); - - const schema = await store.getSchema(project.id); - expect(schema!.databaseId).toBe("new-db-id"); - }); - - test("should return null for non-existent project", async () => { - const result = await store.linkDatabase("no-such-project", "db-id"); - expect(result).toBeNull(); - }); - - test("should update the updatedAt timestamp", async () => { - const project = await store.createProject({ - databaseId: "pending", - name: "Timestamp Test", - }); - - // Wait a tick to ensure timestamp difference - await new Promise((r) => setTimeout(r, 10)); - - const updated = await store.linkDatabase(project.id, "db-id"); - - expect(updated!.updatedAt).not.toBe(project.updatedAt); - }); - - test("should write to local config (not relwave.json) for imported projects", async () => { - await createSourceProject({ name: "Link Imported" }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "initial-db-id", - }); - - // Snapshot relwave.json BEFORE linkDatabase - const beforeMeta = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); - - // Re-link to a different database - const updated = await store.linkDatabase(project.id, "relinked-db-id"); - expect(updated!.databaseId).toBe("relinked-db-id"); - - // relwave.json must NOT have changed - const afterMeta = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); - expect(afterMeta).toBe(beforeMeta); - - // databaseId should be in local config - const localConfig = JSON.parse( - await fs.readFile(path.join(SOURCE_DIR, "relwave.local.json"), "utf-8") - ); - expect(localConfig.databaseId).toBe("relinked-db-id"); - - // Index should have the updated databaseId - const listed = await store.listProjects(); - expect(listed[0].databaseId).toBe("relinked-db-id"); - }); - }); - - // ─── updateProject for imported projects ────────────────────────── - - describe("updateProject (imported)", () => { - test("should NOT modify relwave.json for imported projects", async () => { - await createSourceProject({ name: "Imported Update", description: "Old desc" }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "db-1", - }); - - // Snapshot relwave.json BEFORE update - const beforeMeta = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); - - await store.updateProject(project.id, { - name: "Renamed Locally", - description: "New desc", - }); - - // relwave.json must NOT have changed - const afterMeta = await fs.readFile(path.join(SOURCE_DIR, "relwave.json"), "utf-8"); - expect(afterMeta).toBe(beforeMeta); - }); - - test("should store overrides in local config", async () => { - await createSourceProject({ name: "Override Test" }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "db-1", - }); - - await store.updateProject(project.id, { - name: "Local Name", - description: "Local desc", - defaultSchema: "custom", - }); - - const localConfig = JSON.parse( - await fs.readFile(path.join(SOURCE_DIR, "relwave.local.json"), "utf-8") - ); - expect(localConfig.overrides).toBeDefined(); - expect(localConfig.overrides.name).toBe("Local Name"); - expect(localConfig.overrides.description).toBe("Local desc"); - expect(localConfig.overrides.defaultSchema).toBe("custom"); - }); - - test("should merge overrides into getProject result", async () => { - await createSourceProject({ name: "Merge Test", description: "Original" }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "db-1", - }); - - await store.updateProject(project.id, { name: "Overridden" }); - - const fetched = await store.getProject(project.id); - expect(fetched!.name).toBe("Overridden"); - // Description stays from relwave.json (not overridden) - expect(fetched!.description).toBe("Original"); - }); - - test("should sync index after imported project update", async () => { - await createSourceProject({ name: "Index Sync" }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "db-1", - }); - - await store.updateProject(project.id, { name: "Updated Name" }); - - const listed = await store.listProjects(); - const entry = listed.find((p) => p.id === project.id); - expect(entry!.name).toBe("Updated Name"); - }); - - test("should preserve existing local config fields when adding overrides", async () => { - await createSourceProject({ name: "Preserve Fields" }); - - const project = await store.importProject({ - sourcePath: SOURCE_DIR, - databaseId: "db-1", - }); - - // Local config already has databaseId from import - await store.updateProject(project.id, { name: "New Name" }); - - const localConfig = JSON.parse( - await fs.readFile(path.join(SOURCE_DIR, "relwave.local.json"), "utf-8") - ); - // databaseId should still be there - expect(localConfig.databaseId).toBe("db-1"); - // And overrides should be added - expect(localConfig.overrides.name).toBe("New Name"); - }); - - test("should still modify relwave.json for regular (non-imported) projects", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "Regular Project", - }); - - const updated = await store.updateProject(project.id, { - name: "Renamed Regular", - }); - - expect(updated!.name).toBe("Renamed Regular"); - - // For regular projects, relwave.json should be updated directly - const fetched = await store.getProject(project.id); - expect(fetched!.name).toBe("Renamed Regular"); - }); + // For regular projects, relwave.json should be updated directly + const fetched = await store.getProject(project.id); + expect(fetched!.name).toBe("Renamed Regular"); }); + }); }); diff --git a/bridge/__tests__/monitoringHandlers.test.ts b/bridge/__tests__/monitoringHandlers.test.ts index d845bcf5..7ab2906d 100644 --- a/bridge/__tests__/monitoringHandlers.test.ts +++ b/bridge/__tests__/monitoringHandlers.test.ts @@ -4,103 +4,106 @@ import { DBType } from "../src/types"; import type { Rpc } from "../src/types"; function createMockRpc(): Rpc & { _responses: any[]; _errors: any[] } { - const responses: any[] = []; - const errors: any[] = []; - - return { - sendResponse: jest.fn((id: number | string, payload: any) => { - responses.push({ id, payload }); - }), - sendError: jest.fn((id: number | string, err: any) => { - errors.push({ id, err }); - }), - _responses: responses, - _errors: errors, - }; + const responses: any[] = []; + const errors: any[] = []; + + return { + sendResponse: jest.fn((id: number | string, payload: any) => { + responses.push({ id, payload }); + }), + sendError: jest.fn((id: number | string, err: any) => { + errors.push({ id, err }); + }), + _responses: responses, + _errors: errors, + }; } function createMockLogger(): any { - return { - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - debug: jest.fn(), - child: jest.fn().mockReturnThis(), - }; + return { + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + debug: jest.fn(), + child: jest.fn().mockReturnThis(), + }; } function createMockDbService() { - return { - getDatabaseConnection: jest.fn(), - }; + return { + getDatabaseConnection: jest.fn(), + }; } function createMockMonitoringService() { - return { - getSnapshot: jest.fn(), - }; + return { + getSnapshot: jest.fn(), + }; } describe("MonitoringHandlers", () => { - let rpc: ReturnType; - let logger: any; - let dbService: ReturnType; - let monitoringService: ReturnType; - let handlers: MonitoringHandlers; - - beforeEach(() => { - rpc = createMockRpc(); - logger = createMockLogger(); - dbService = createMockDbService(); - monitoringService = createMockMonitoringService(); - handlers = new MonitoringHandlers(rpc, logger, dbService as any, monitoringService as any); + let rpc: ReturnType; + let logger: any; + let dbService: ReturnType; + let monitoringService: ReturnType; + let handlers: MonitoringHandlers; + + beforeEach(() => { + rpc = createMockRpc(); + logger = createMockLogger(); + dbService = createMockDbService(); + monitoringService = createMockMonitoringService(); + handlers = new MonitoringHandlers(rpc, logger, dbService as any, monitoringService as any); + }); + + test("returns BAD_REQUEST when db id is missing", async () => { + await handlers.handleGetSnapshot({}, 1); + + expect(rpc.sendError).toHaveBeenCalledWith(1, { + code: "BAD_REQUEST", + message: "Missing id", }); + expect(dbService.getDatabaseConnection).not.toHaveBeenCalled(); + }); + + test("returns monitoring snapshot for a valid database", async () => { + const conn = { connection: true }; + const snapshot = { + databaseType: DBType.POSTGRES, + sampledAt: "2026-05-16T00:00:00.000Z", + health: { ok: true, latencyMs: 12 }, + connections: { active: 2, max: 100, usagePct: 2 }, + throughput: { qps: 3.5, totalQueries: 1000 }, + cacheHitRatio: 99.2, + activeQueries: [], + }; - test("returns BAD_REQUEST when db id is missing", async () => { - await handlers.handleGetSnapshot({}, 1); + (dbService.getDatabaseConnection as any).mockResolvedValue({ conn, dbType: DBType.POSTGRES }); + (monitoringService.getSnapshot as any).mockResolvedValue(snapshot); - expect(rpc.sendError).toHaveBeenCalledWith(1, { - code: "BAD_REQUEST", - message: "Missing id", - }); - expect(dbService.getDatabaseConnection).not.toHaveBeenCalled(); - }); + await handlers.handleGetSnapshot({ id: "db-1" }, 2); - test("returns monitoring snapshot for a valid database", async () => { - const conn = { connection: true }; - const snapshot = { - databaseType: DBType.POSTGRES, - sampledAt: "2026-05-16T00:00:00.000Z", - health: { ok: true, latencyMs: 12 }, - connections: { active: 2, max: 100, usagePct: 2 }, - throughput: { qps: 3.5, totalQueries: 1000 }, - cacheHitRatio: 99.2, - activeQueries: [], - }; - - (dbService.getDatabaseConnection as any).mockResolvedValue({ conn, dbType: DBType.POSTGRES }); - (monitoringService.getSnapshot as any).mockResolvedValue(snapshot); - - await handlers.handleGetSnapshot({ id: "db-1" }, 2); - - expect(dbService.getDatabaseConnection).toHaveBeenCalledWith("db-1"); - expect(monitoringService.getSnapshot).toHaveBeenCalledWith("db-1", conn, DBType.POSTGRES); - expect(rpc.sendResponse).toHaveBeenCalledWith(2, { - ok: true, - data: snapshot, - }); + expect(dbService.getDatabaseConnection).toHaveBeenCalledWith("db-1"); + expect(monitoringService.getSnapshot).toHaveBeenCalledWith("db-1", conn, DBType.POSTGRES); + expect(rpc.sendResponse).toHaveBeenCalledWith(2, { + ok: true, + data: snapshot, }); + }); - test("returns MONITORING_ERROR when snapshot generation fails", async () => { - (dbService.getDatabaseConnection as any).mockResolvedValue({ conn: {}, dbType: DBType.POSTGRES }); - (monitoringService.getSnapshot as any).mockRejectedValue(new Error("snapshot failed")); + test("returns MONITORING_ERROR when snapshot generation fails", async () => { + (dbService.getDatabaseConnection as any).mockResolvedValue({ + conn: {}, + dbType: DBType.POSTGRES, + }); + (monitoringService.getSnapshot as any).mockRejectedValue(new Error("snapshot failed")); - await handlers.handleGetSnapshot({ id: "db-1" }, 3); + await handlers.handleGetSnapshot({ id: "db-1" }, 3); - expect(logger.error).toHaveBeenCalled(); - expect(rpc.sendError).toHaveBeenCalledWith(3, { - code: "MONITORING_ERROR", - message: "snapshot failed", - }); + expect(logger.error).toHaveBeenCalled(); + expect(rpc.sendError).toHaveBeenCalledWith(3, { + code: "MONITORING_ERROR", + message: "snapshot failed", }); + }); }); diff --git a/bridge/__tests__/monitoringWebSocketServer.test.ts b/bridge/__tests__/monitoringWebSocketServer.test.ts index 16293228..667c0cf6 100644 --- a/bridge/__tests__/monitoringWebSocketServer.test.ts +++ b/bridge/__tests__/monitoringWebSocketServer.test.ts @@ -5,158 +5,170 @@ import { DBType } from "../src/types"; const mockWebSocketServerInstances: any[] = []; jest.mock("ws", () => ({ - WebSocketServer: jest.fn().mockImplementation((options) => { - const listeners: Record void> = {}; - - const instance = { - options, - on: jest.fn((event: string, handler: (...args: any[]) => void) => { - listeners[event] = handler; - }), - close: jest.fn(), - address: jest.fn(() => ({ port: 4567 })), - emit: async (event: string, ...args: any[]) => { - const handler = listeners[event]; - if (!handler) return undefined; - return handler(...args); - }, - _listeners: listeners, - }; - - mockWebSocketServerInstances.push(instance); - return instance; - }), + WebSocketServer: jest.fn().mockImplementation((options) => { + const listeners: Record void> = {}; + + const instance = { + options, + on: jest.fn((event: string, handler: (...args: any[]) => void) => { + listeners[event] = handler; + }), + close: jest.fn(), + address: jest.fn(() => ({ port: 4567 })), + emit: async (event: string, ...args: any[]) => { + const handler = listeners[event]; + if (!handler) return undefined; + return handler(...args); + }, + _listeners: listeners, + }; + + mockWebSocketServerInstances.push(instance); + return instance; + }), })); function createMockLogger(): any { - return { - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - debug: jest.fn(), - child: jest.fn().mockReturnThis(), - }; + return { + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + debug: jest.fn(), + child: jest.fn().mockReturnThis(), + }; } function createMockDbService() { - return { - getDatabaseConnection: jest.fn(), - }; + return { + getDatabaseConnection: jest.fn(), + }; } function createMockMonitoringService() { - return { - getSnapshot: jest.fn(), - }; + return { + getSnapshot: jest.fn(), + }; } function createMockSocket() { - const listeners: Record void> = {}; - return { - readyState: 1, - send: jest.fn(), - close: jest.fn(), - on: jest.fn((event: string, handler: (...args: any[]) => void) => { - listeners[event] = handler; - }), - emit: async (event: string, ...args: any[]) => { - const handler = listeners[event]; - if (!handler) return undefined; - return handler(...args); - }, - _listeners: listeners, - }; + const listeners: Record void> = {}; + return { + readyState: 1, + send: jest.fn(), + close: jest.fn(), + on: jest.fn((event: string, handler: (...args: any[]) => void) => { + listeners[event] = handler; + }), + emit: async (event: string, ...args: any[]) => { + const handler = listeners[event]; + if (!handler) return undefined; + return handler(...args); + }, + _listeners: listeners, + }; } describe("MonitoringWebSocketServer", () => { - let logger: any; - let dbService: ReturnType; - let monitoringService: ReturnType; - let server: MonitoringWebSocketServer; - let setIntervalSpy: jest.SpiedFunction; - let clearIntervalSpy: jest.SpiedFunction; - - beforeEach(() => { - mockWebSocketServerInstances.length = 0; - logger = createMockLogger(); - dbService = createMockDbService(); - monitoringService = createMockMonitoringService(); - server = new MonitoringWebSocketServer(dbService as any, monitoringService as any, logger); - setIntervalSpy = jest.spyOn(global, "setInterval").mockReturnValue(123 as any); - clearIntervalSpy = jest.spyOn(global, "clearInterval").mockImplementation(() => undefined); - }); - - afterEach(() => { - jest.restoreAllMocks(); - server.close(); + let logger: any; + let dbService: ReturnType; + let monitoringService: ReturnType; + let server: MonitoringWebSocketServer; + let setIntervalSpy: jest.SpiedFunction; + let clearIntervalSpy: jest.SpiedFunction; + + beforeEach(() => { + mockWebSocketServerInstances.length = 0; + logger = createMockLogger(); + dbService = createMockDbService(); + monitoringService = createMockMonitoringService(); + server = new MonitoringWebSocketServer(dbService as any, monitoringService as any, logger); + setIntervalSpy = jest.spyOn(global, "setInterval").mockReturnValue(123 as any); + clearIntervalSpy = jest.spyOn(global, "clearInterval").mockImplementation(() => undefined); + }); + + afterEach(() => { + jest.restoreAllMocks(); + server.close(); + }); + + test("starts once and exposes websocket info after listening", () => { + expect(() => server.getInfo()).toThrow("Monitoring WebSocket server is not ready"); + + server.start(); + server.start(); + + expect(mockWebSocketServerInstances).toHaveLength(1); + expect(mockWebSocketServerInstances[0].options).toEqual({ + host: "127.0.0.1", + port: 0, + path: "/monitoring", }); - test("starts once and exposes websocket info after listening", () => { - expect(() => server.getInfo()).toThrow("Monitoring WebSocket server is not ready"); - - server.start(); - server.start(); - - expect(mockWebSocketServerInstances).toHaveLength(1); - expect(mockWebSocketServerInstances[0].options).toEqual({ - host: "127.0.0.1", - port: 0, - path: "/monitoring", - }); + mockWebSocketServerInstances[0].emit("listening"); - mockWebSocketServerInstances[0].emit("listening"); - - expect(logger.info).toHaveBeenCalledWith({ port: 4567 }, "Monitoring WebSocket server started"); - expect(server.getInfo()).toEqual({ - url: "ws://127.0.0.1:4567/monitoring", - intervalMs: 5000, - }); + expect(logger.info).toHaveBeenCalledWith({ port: 4567 }, "Monitoring WebSocket server started"); + expect(server.getInfo()).toEqual({ + url: "ws://127.0.0.1:4567/monitoring", + intervalMs: 5000, }); + }); - test("closes unsupported websocket connections immediately", async () => { - server.start(); - const wsServer = mockWebSocketServerInstances[0]; - const socket = createMockSocket(); - - (dbService.getDatabaseConnection as any).mockResolvedValue({ conn: { id: "conn" }, dbType: DBType.SQLITE }); + test("closes unsupported websocket connections immediately", async () => { + server.start(); + const wsServer = mockWebSocketServerInstances[0]; + const socket = createMockSocket(); - await wsServer.emit("connection", socket, { url: "/monitoring?dbId=db-1" } as any); + (dbService.getDatabaseConnection as any).mockResolvedValue({ + conn: { id: "conn" }, + dbType: DBType.SQLITE, + }); - expect(dbService.getDatabaseConnection).toHaveBeenCalledWith("db-1"); - expect(socket.send).toHaveBeenCalledWith( - JSON.stringify({ - type: "unsupported", - message: "Monitoring is not supported for sqlite", - }) - ); - expect(socket.close).toHaveBeenCalledWith(1008, "Unsupported database type"); + await wsServer.emit("connection", socket, { url: "/monitoring?dbId=db-1" } as any); + + expect(dbService.getDatabaseConnection).toHaveBeenCalledWith("db-1"); + expect(socket.send).toHaveBeenCalledWith( + JSON.stringify({ + type: "unsupported", + message: "Monitoring is not supported for sqlite", + }), + ); + expect(socket.close).toHaveBeenCalledWith(1008, "Unsupported database type"); + }); + + test("sends snapshots over websocket and enforces minimum interval", async () => { + server.start(); + const wsServer = mockWebSocketServerInstances[0]; + const socket = createMockSocket(); + + (dbService.getDatabaseConnection as any).mockResolvedValue({ + conn: { id: "conn" }, + dbType: DBType.POSTGRES, + }); + (monitoringService.getSnapshot as any).mockResolvedValue({ + databaseType: DBType.POSTGRES, + sampledAt: "2026-05-16T00:00:00.000Z", + health: { ok: true, latencyMs: 11 }, + connections: { active: 1, max: 50, usagePct: 2 }, + throughput: { qps: 5, totalQueries: 100 }, + cacheHitRatio: 98.5, + activeQueries: [], }); - test("sends snapshots over websocket and enforces minimum interval", async () => { - server.start(); - const wsServer = mockWebSocketServerInstances[0]; - const socket = createMockSocket(); - - (dbService.getDatabaseConnection as any).mockResolvedValue({ conn: { id: "conn" }, dbType: DBType.POSTGRES }); - (monitoringService.getSnapshot as any).mockResolvedValue({ - databaseType: DBType.POSTGRES, - sampledAt: "2026-05-16T00:00:00.000Z", - health: { ok: true, latencyMs: 11 }, - connections: { active: 1, max: 50, usagePct: 2 }, - throughput: { qps: 5, totalQueries: 100 }, - cacheHitRatio: 98.5, - activeQueries: [], - }); - - await wsServer.emit("connection", socket, { url: "/monitoring?dbId=db-1&intervalMs=1000" } as any); - - expect(dbService.getDatabaseConnection).toHaveBeenCalledWith("db-1"); - expect(monitoringService.getSnapshot).toHaveBeenCalledWith("db-1", { id: "conn" }, DBType.POSTGRES); - expect(JSON.parse(socket.send.mock.calls[0][0] as string)).toMatchObject({ - type: "snapshot", - data: expect.objectContaining({ databaseType: DBType.POSTGRES }), - }); - expect(setIntervalSpy).toHaveBeenCalledWith(expect.any(Function), 2000); - expect(clearIntervalSpy).not.toHaveBeenCalled(); + await wsServer.emit("connection", socket, { + url: "/monitoring?dbId=db-1&intervalMs=1000", + } as any); + + expect(dbService.getDatabaseConnection).toHaveBeenCalledWith("db-1"); + expect(monitoringService.getSnapshot).toHaveBeenCalledWith( + "db-1", + { id: "conn" }, + DBType.POSTGRES, + ); + expect(JSON.parse(socket.send.mock.calls[0][0] as string)).toMatchObject({ + type: "snapshot", + data: expect.objectContaining({ databaseType: DBType.POSTGRES }), }); + expect(setIntervalSpy).toHaveBeenCalledWith(expect.any(Function), 2000); + expect(clearIntervalSpy).not.toHaveBeenCalled(); + }); }); diff --git a/bridge/__tests__/projectStore.test.ts b/bridge/__tests__/projectStore.test.ts index 8acecda4..29d3767f 100644 --- a/bridge/__tests__/projectStore.test.ts +++ b/bridge/__tests__/projectStore.test.ts @@ -16,643 +16,671 @@ const INDEX_FILE = path.join(PROJECTS_DIR, "index.json"); * We mock the config module to redirect to our temp folder. */ jest.mock("../src/utils/config", () => { - const original = jest.requireActual("../src/utils/config") as any; - const _path = require("path"); - const _os = require("os"); - const testProjects = _path.join(_os.tmpdir(), "projectstore-test-" + Date.now(), "projects"); - return { - ...original, - PROJECTS_FOLDER: testProjects, - PROJECTS_INDEX_FILE: _path.join(testProjects, "index.json"), - getProjectDir: (id: string) => _path.join(testProjects, id), - }; + const original = jest.requireActual("../src/utils/config") as any; + const _path = require("path"); + const _os = require("os"); + const testProjects = _path.join(_os.tmpdir(), "projectstore-test-" + Date.now(), "projects"); + return { + ...original, + PROJECTS_FOLDER: testProjects, + PROJECTS_INDEX_FILE: _path.join(testProjects, "index.json"), + getProjectDir: (id: string) => _path.join(testProjects, id), + }; }); /** * Mock dbStoreInstance.getDB to avoid needing a real database store */ jest.mock("../src/services/dbStore", () => ({ - dbStoreInstance: { - getDB: jest.fn<() => Promise>().mockResolvedValue({ - id: "test-db-id", - name: "TestDB", - type: "POSTGRES", - host: "localhost", - port: 5432, - }), - }, - DBMeta: {}, + dbStoreInstance: { + getDB: jest.fn<() => Promise>().mockResolvedValue({ + id: "test-db-id", + name: "TestDB", + type: "POSTGRES", + host: "localhost", + port: 5432, + }), + }, + DBMeta: {}, })); // After mocking, get the actual folder being used import { PROJECTS_FOLDER, PROJECTS_INDEX_FILE, getProjectDir } from "../src/utils/config"; describe("ProjectStore", () => { - let store: ProjectStore; + let store: ProjectStore; + + beforeEach(async () => { + // Clean & create test directory + if (fsSync.existsSync(PROJECTS_FOLDER)) { + await fs.rm(PROJECTS_FOLDER, { recursive: true, force: true }); + } + await fs.mkdir(PROJECTS_FOLDER, { recursive: true }); + + store = new ProjectStore(PROJECTS_FOLDER, PROJECTS_INDEX_FILE); + }); + + afterEach(async () => { + if (fsSync.existsSync(PROJECTS_FOLDER)) { + await fs.rm(PROJECTS_FOLDER, { recursive: true, force: true }); + } + }); + + // ========================================== + // Project CRUD + // ========================================== + + describe("CRUD Operations", () => { + test("should create a new project", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "My Project", + description: "A test project", + }); + + expect(project).toBeDefined(); + expect(project.id).toBeDefined(); + expect(project.name).toBe("My Project"); + expect(project.description).toBe("A test project"); + expect(project.databaseId).toBe("db-1"); + expect(project.engine).toBe("POSTGRES"); // from mocked dbStore + expect(project.version).toBe(1); + expect(project.createdAt).toBeDefined(); + expect(project.updatedAt).toBeDefined(); + }); + + test("should create project directories", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "DirTest", + }); + + const dir = getProjectDir(project.id); + expect(fsSync.existsSync(dir)).toBe(true); + expect(fsSync.existsSync(path.join(dir, "schema"))).toBe(true); + expect(fsSync.existsSync(path.join(dir, "diagrams"))).toBe(true); + expect(fsSync.existsSync(path.join(dir, "queries"))).toBe(true); + }); + + test("should create initial sub-files", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "SubFileTest", + }); + + const dir = getProjectDir(project.id); + expect(fsSync.existsSync(path.join(dir, "relwave.json"))).toBe(true); + expect(fsSync.existsSync(path.join(dir, "relwave.local.json"))).toBe(true); + expect(fsSync.existsSync(path.join(dir, "schema", "schema.json"))).toBe(true); + expect(fsSync.existsSync(path.join(dir, "diagrams", "er.json"))).toBe(true); + expect(fsSync.existsSync(path.join(dir, "queries", "queries.json"))).toBe(true); + expect(fsSync.existsSync(path.join(dir, ".gitignore"))).toBe(true); + }); + + test("should get project by ID", async () => { + const created = await store.createProject({ + databaseId: "db-1", + name: "GetTest", + }); + + const found = await store.getProject(created.id); + expect(found).toBeDefined(); + expect(found!.id).toBe(created.id); + expect(found!.name).toBe("GetTest"); + }); + + test("should return null for non-existent project", async () => { + const found = await store.getProject("non-existent-id"); + expect(found).toBeNull(); + }); + + test("should get project by databaseId", async () => { + await store.createProject({ + databaseId: "db-unique", + name: "Linked Project", + }); + + const found = await store.getProjectByDatabaseId("db-unique"); + expect(found).toBeDefined(); + expect(found!.name).toBe("Linked Project"); + }); + + test("should return null for unlinked databaseId", async () => { + const found = await store.getProjectByDatabaseId("no-such-db"); + expect(found).toBeNull(); + }); + + test("should list all projects", async () => { + await store.createProject({ databaseId: "db-1", name: "P1" }); + await store.createProject({ databaseId: "db-2", name: "P2" }); + await store.createProject({ databaseId: "db-3", name: "P3" }); + + const projects = await store.listProjects(); + expect(projects).toHaveLength(3); + expect(projects.map((p) => p.name).sort()).toEqual(["P1", "P2", "P3"]); + }); + + test("should update project metadata", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "Original", + description: "Old desc", + }); + + const updated = await store.updateProject(project.id, { + name: "Renamed", + description: "New desc", + }); + + expect(updated).toBeDefined(); + expect(updated!.name).toBe("Renamed"); + expect(updated!.description).toBe("New desc"); + expect(updated!.updatedAt).not.toBe(project.updatedAt); + }); + + test("should only update whitelisted fields", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "WhitelistTest", + }); + + const updated = await store.updateProject(project.id, { + name: "NewName", + // These should be ignored / not writable: + ...({ id: "injected-id", databaseId: "injected-db" } as any), + }); + + expect(updated!.name).toBe("NewName"); + expect(updated!.id).toBe(project.id); // unchanged + expect(updated!.databaseId).toBe(project.databaseId); // unchanged + }); + + test("should return null when updating non-existent project", async () => { + const result = await store.updateProject("no-such-id", { name: "x" }); + expect(result).toBeNull(); + }); + + test("should sync index after update", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "SyncTest", + }); + + await store.updateProject(project.id, { name: "Updated" }); + + const projects = await store.listProjects(); + expect(projects.find((p) => p.id === project.id)?.name).toBe("Updated"); + }); + + test("should delete a project", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "DeleteTest", + }); + + const dir = getProjectDir(project.id); + expect(fsSync.existsSync(dir)).toBe(true); + + await store.deleteProject(project.id); + + expect(fsSync.existsSync(dir)).toBe(false); + const projects = await store.listProjects(); + expect(projects.find((p) => p.id === project.id)).toBeUndefined(); + }); + + test("should handle deleting non-existent project gracefully", async () => { + // Should not throw + await expect(store.deleteProject("no-such-id")).resolves.not.toThrow(); + }); + }); + + // ========================================== + // Schema Operations + // ========================================== + + describe("Schema Operations", () => { + let projectId: string; beforeEach(async () => { - // Clean & create test directory - if (fsSync.existsSync(PROJECTS_FOLDER)) { - await fs.rm(PROJECTS_FOLDER, { recursive: true, force: true }); - } - await fs.mkdir(PROJECTS_FOLDER, { recursive: true }); - - store = new ProjectStore(PROJECTS_FOLDER, PROJECTS_INDEX_FILE); - }); - - afterEach(async () => { - if (fsSync.existsSync(PROJECTS_FOLDER)) { - await fs.rm(PROJECTS_FOLDER, { recursive: true, force: true }); - } - }); - - // ========================================== - // Project CRUD - // ========================================== - - describe("CRUD Operations", () => { - test("should create a new project", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "My Project", - description: "A test project", - }); - - expect(project).toBeDefined(); - expect(project.id).toBeDefined(); - expect(project.name).toBe("My Project"); - expect(project.description).toBe("A test project"); - expect(project.databaseId).toBe("db-1"); - expect(project.engine).toBe("POSTGRES"); // from mocked dbStore - expect(project.version).toBe(1); - expect(project.createdAt).toBeDefined(); - expect(project.updatedAt).toBeDefined(); - }); - - test("should create project directories", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "DirTest", - }); - - const dir = getProjectDir(project.id); - expect(fsSync.existsSync(dir)).toBe(true); - expect(fsSync.existsSync(path.join(dir, "schema"))).toBe(true); - expect(fsSync.existsSync(path.join(dir, "diagrams"))).toBe(true); - expect(fsSync.existsSync(path.join(dir, "queries"))).toBe(true); - }); - - test("should create initial sub-files", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "SubFileTest", - }); - - const dir = getProjectDir(project.id); - expect(fsSync.existsSync(path.join(dir, "relwave.json"))).toBe(true); - expect(fsSync.existsSync(path.join(dir, "relwave.local.json"))).toBe(true); - expect(fsSync.existsSync(path.join(dir, "schema", "schema.json"))).toBe(true); - expect(fsSync.existsSync(path.join(dir, "diagrams", "er.json"))).toBe(true); - expect(fsSync.existsSync(path.join(dir, "queries", "queries.json"))).toBe(true); - expect(fsSync.existsSync(path.join(dir, ".gitignore"))).toBe(true); - }); - - test("should get project by ID", async () => { - const created = await store.createProject({ - databaseId: "db-1", - name: "GetTest", - }); - - const found = await store.getProject(created.id); - expect(found).toBeDefined(); - expect(found!.id).toBe(created.id); - expect(found!.name).toBe("GetTest"); - }); - - test("should return null for non-existent project", async () => { - const found = await store.getProject("non-existent-id"); - expect(found).toBeNull(); - }); - - test("should get project by databaseId", async () => { - await store.createProject({ - databaseId: "db-unique", - name: "Linked Project", - }); - - const found = await store.getProjectByDatabaseId("db-unique"); - expect(found).toBeDefined(); - expect(found!.name).toBe("Linked Project"); - }); - - test("should return null for unlinked databaseId", async () => { - const found = await store.getProjectByDatabaseId("no-such-db"); - expect(found).toBeNull(); - }); - - test("should list all projects", async () => { - await store.createProject({ databaseId: "db-1", name: "P1" }); - await store.createProject({ databaseId: "db-2", name: "P2" }); - await store.createProject({ databaseId: "db-3", name: "P3" }); - - const projects = await store.listProjects(); - expect(projects).toHaveLength(3); - expect(projects.map((p) => p.name).sort()).toEqual(["P1", "P2", "P3"]); - }); - - test("should update project metadata", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "Original", - description: "Old desc", - }); - - const updated = await store.updateProject(project.id, { - name: "Renamed", - description: "New desc", - }); - - expect(updated).toBeDefined(); - expect(updated!.name).toBe("Renamed"); - expect(updated!.description).toBe("New desc"); - expect(updated!.updatedAt).not.toBe(project.updatedAt); - }); - - test("should only update whitelisted fields", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "WhitelistTest", - }); - - const updated = await store.updateProject(project.id, { - name: "NewName", - // These should be ignored / not writable: - ...({ id: "injected-id", databaseId: "injected-db" } as any), - }); - - expect(updated!.name).toBe("NewName"); - expect(updated!.id).toBe(project.id); // unchanged - expect(updated!.databaseId).toBe(project.databaseId); // unchanged - }); - - test("should return null when updating non-existent project", async () => { - const result = await store.updateProject("no-such-id", { name: "x" }); - expect(result).toBeNull(); - }); - - test("should sync index after update", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "SyncTest", - }); - - await store.updateProject(project.id, { name: "Updated" }); - - const projects = await store.listProjects(); - expect(projects.find((p) => p.id === project.id)?.name).toBe("Updated"); - }); - - test("should delete a project", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "DeleteTest", - }); - - const dir = getProjectDir(project.id); - expect(fsSync.existsSync(dir)).toBe(true); - - await store.deleteProject(project.id); - - expect(fsSync.existsSync(dir)).toBe(false); - const projects = await store.listProjects(); - expect(projects.find((p) => p.id === project.id)).toBeUndefined(); - }); - - test("should handle deleting non-existent project gracefully", async () => { - // Should not throw - await expect(store.deleteProject("no-such-id")).resolves.not.toThrow(); - }); - }); - - // ========================================== - // Schema Operations - // ========================================== - - describe("Schema Operations", () => { - let projectId: string; - - beforeEach(async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "SchemaTest", - }); - projectId = project.id; - }); - - const mockSchemas: SchemaSnapshot[] = [ - { - name: "public", - tables: [ - { - name: "users", - type: "BASE TABLE", - columns: [ - { name: "id", type: "integer", nullable: false, isPrimaryKey: true, isForeignKey: false, defaultValue: null, isUnique: true, isSerial: true, ordinalPosition: 1 }, - { name: "email", type: "varchar(255)", nullable: false, isPrimaryKey: false, isForeignKey: false, defaultValue: null, isUnique: true, isSerial: false, ordinalPosition: 2 }, - ], - indexes: [], - foreignKeys: [], - checks: [], - }, - ], - }, - ]; + const project = await store.createProject({ + databaseId: "db-1", + name: "SchemaTest", + }); + projectId = project.id; + }); - test("should get initial empty schema", async () => { - const schema = await store.getSchema(projectId); - expect(schema).toBeDefined(); - expect(schema!.schemas).toEqual([]); - }); + const mockSchemas: SchemaSnapshot[] = [ + { + name: "public", + tables: [ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: true, + isSerial: true, + ordinalPosition: 1, + }, + { + name: "email", + type: "varchar(255)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: true, + isSerial: false, + ordinalPosition: 2, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + }, + ]; + + test("should get initial empty schema", async () => { + const schema = await store.getSchema(projectId); + expect(schema).toBeDefined(); + expect(schema!.schemas).toEqual([]); + }); - test("should save and retrieve schema", async () => { - await store.saveSchema(projectId, mockSchemas); - const saved = await store.getSchema(projectId); + test("should save and retrieve schema", async () => { + await store.saveSchema(projectId, mockSchemas); + const saved = await store.getSchema(projectId); - expect(saved).toBeDefined(); - expect(saved!.schemas).toHaveLength(1); - expect(saved!.schemas[0].name).toBe("public"); - expect(saved!.schemas[0].tables[0].name).toBe("users"); - }); + expect(saved).toBeDefined(); + expect(saved!.schemas).toHaveLength(1); + expect(saved!.schemas[0].name).toBe("public"); + expect(saved!.schemas[0].tables[0].name).toBe("users"); + }); - test("should skip write when schema is identical (cachedAt dedup)", async () => { - const first = await store.saveSchema(projectId, mockSchemas); - const second = await store.saveSchema(projectId, mockSchemas); + test("should skip write when schema is identical (cachedAt dedup)", async () => { + const first = await store.saveSchema(projectId, mockSchemas); + const second = await store.saveSchema(projectId, mockSchemas); - // Same cachedAt means the write was skipped - expect(second.cachedAt).toBe(first.cachedAt); - }); + // Same cachedAt means the write was skipped + expect(second.cachedAt).toBe(first.cachedAt); + }); - test("should write when schema changes", async () => { - const first = await store.saveSchema(projectId, mockSchemas); + test("should write when schema changes", async () => { + const first = await store.saveSchema(projectId, mockSchemas); - const changedSchemas: SchemaSnapshot[] = [ + const changedSchemas: SchemaSnapshot[] = [ + { + ...mockSchemas[0], + tables: [ + ...mockSchemas[0].tables, + { + name: "posts", + type: "BASE TABLE", + columns: [ { - ...mockSchemas[0], - tables: [ - ...mockSchemas[0].tables, - { - name: "posts", - type: "BASE TABLE", - columns: [ - { name: "id", type: "integer", nullable: false, isPrimaryKey: true, isForeignKey: false, defaultValue: null, isUnique: true, isSerial: true, ordinalPosition: 1 }, - ], - indexes: [], - foreignKeys: [], - checks: [], - }, - ], + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: true, + isSerial: true, + ordinalPosition: 1, }, - ]; - - // Allow time difference - await new Promise((r) => setTimeout(r, 10)); - const second = await store.saveSchema(projectId, changedSchemas); - - expect(second.cachedAt).not.toBe(first.cachedAt); - expect(second.schemas[0].tables).toHaveLength(2); - }); - - test("should throw when saving schema for non-existent project", async () => { - await expect( - store.saveSchema("no-such-project", mockSchemas) - ).rejects.toThrow("Project no-such-project not found"); - }); - }); - - // ========================================== - // ER Diagram Operations - // ========================================== - - describe("ER Diagram Operations", () => { - let projectId: string; - - beforeEach(async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "ERTest", - }); - projectId = project.id; - }); - - test("should get initial empty diagram", async () => { - const diagram = await store.getERDiagram(projectId); - expect(diagram).toBeDefined(); - expect(diagram!.nodes).toEqual([]); - }); - - test("should save and retrieve diagram", async () => { - const nodes = [ - { tableId: "users", x: 100, y: 200 }, - { tableId: "posts", x: 300, y: 400, collapsed: true }, - ]; - - const saved = await store.saveERDiagram(projectId, { - nodes, - zoom: 1.5, - panX: 50, - panY: 75, - }); - - expect(saved.nodes).toHaveLength(2); - expect(saved.zoom).toBe(1.5); - expect(saved.panX).toBe(50); - - const retrieved = await store.getERDiagram(projectId); - expect(retrieved!.nodes).toHaveLength(2); - expect(retrieved!.nodes[0].tableId).toBe("users"); - }); - }); - - // ========================================== - // Query Operations - // ========================================== - - describe("Query Operations", () => { - let projectId: string; - - beforeEach(async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "QueryTest", - }); - projectId = project.id; - }); - - test("should get initial empty queries", async () => { - const queries = await store.getQueries(projectId); - expect(queries).toBeDefined(); - expect(queries!.queries).toEqual([]); - }); - - test("should add a query", async () => { - const query = await store.addQuery(projectId, { - name: "Get Users", - sql: "SELECT * FROM users", - description: "Fetch all users", - }); - - expect(query).toBeDefined(); - expect(query.id).toBeDefined(); - expect(query.name).toBe("Get Users"); - expect(query.sql).toBe("SELECT * FROM users"); - expect(query.description).toBe("Fetch all users"); - }); - - test("should list queries after adding", async () => { - await store.addQuery(projectId, { name: "Q1", sql: "SELECT 1" }); - await store.addQuery(projectId, { name: "Q2", sql: "SELECT 2" }); - - const queries = await store.getQueries(projectId); - expect(queries!.queries).toHaveLength(2); - }); - - test("should update a query", async () => { - const query = await store.addQuery(projectId, { - name: "Old Name", - sql: "SELECT 1", - }); - - const updated = await store.updateQuery(projectId, query.id, { - name: "New Name", - sql: "SELECT 2", - }); - - expect(updated).toBeDefined(); - expect(updated!.name).toBe("New Name"); - expect(updated!.sql).toBe("SELECT 2"); - expect(updated!.updatedAt).not.toBe(query.updatedAt); - }); - - test("should return null when updating non-existent query", async () => { - const result = await store.updateQuery(projectId, "no-such-query", { - name: "x", - }); - expect(result).toBeNull(); - }); - - test("should delete a query", async () => { - const query = await store.addQuery(projectId, { - name: "To Delete", - sql: "SELECT 1", - }); - - await store.deleteQuery(projectId, query.id); - - const queries = await store.getQueries(projectId); - expect(queries!.queries.find((q) => q.id === query.id)).toBeUndefined(); - }); - }); - - // ========================================== - // Export - // ========================================== - - describe("Export", () => { - test("should export full project bundle", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "ExportTest", - }); - - // Add some data - await store.saveSchema(project.id, [ - { name: "public", tables: [] }, - ]); - await store.saveERDiagram(project.id, { nodes: [{ tableId: "t1", x: 0, y: 0 }] }); - await store.addQuery(project.id, { name: "Q1", sql: "SELECT 1" }); - - const bundle = await store.exportProject(project.id); - expect(bundle).toBeDefined(); - expect(bundle!.metadata.name).toBe("ExportTest"); - expect(bundle!.schema).toBeDefined(); - expect(bundle!.erDiagram!.nodes).toHaveLength(1); - expect(bundle!.queries!.queries).toHaveLength(1); - }); - - test("should return null for non-existent project export", async () => { - const bundle = await store.exportProject("no-such-id"); - expect(bundle).toBeNull(); - }); - }); - - // ========================================== - // Local Config (git-ignored) - // ========================================== - - describe("Local Config", () => { - let projectId: string; - - beforeEach(async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "ConfigTest", - }); - projectId = project.id; - }); - - test("should get initial empty local config", async () => { - const config = await store.getLocalConfig(projectId); - expect(config).toBeDefined(); - expect(config).toEqual({}); - }); - - test("should save and retrieve local config", async () => { - const saved = await store.saveLocalConfig(projectId, { - connectionUrl: "postgres://localhost:5432/mydb", - environment: "development", - notes: "My dev setup", - }); - - expect(saved.connectionUrl).toBe("postgres://localhost:5432/mydb"); - - const retrieved = await store.getLocalConfig(projectId); - expect(retrieved!.environment).toBe("development"); - }); - }); - - // ========================================== - // .gitignore Management - // ========================================== - - describe("Gitignore Management", () => { - let projectId: string; - - beforeEach(async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "GitignoreTest", - }); - projectId = project.id; - }); - - test("should create .gitignore on project creation", async () => { - const dir = getProjectDir(projectId); - const giPath = path.join(dir, ".gitignore"); - expect(fsSync.existsSync(giPath)).toBe(true); - }); - - test("should include relwave.local.json in .gitignore", async () => { - const dir = getProjectDir(projectId); - const content = await fs.readFile(path.join(dir, ".gitignore"), "utf-8"); - expect(content).toContain("relwave.local.json"); - }); - - test("should be idempotent", async () => { - // Already created once during project creation - const result = await store.ensureGitignore(projectId); - // Should return false = already has our rules - expect(result).toBe(false); - }); - - test("should append to existing .gitignore without our rules", async () => { - const dir = getProjectDir(projectId); - const giPath = path.join(dir, ".gitignore"); - - // Overwrite with custom content (without our rules) - await fs.writeFile(giPath, "node_modules/\n*.log\n", "utf-8"); - - const result = await store.ensureGitignore(projectId); - expect(result).toBe(true); - - const content = await fs.readFile(giPath, "utf-8"); - expect(content).toContain("node_modules/"); - expect(content).toContain("relwave.local.json"); - }); - }); - - // ========================================== - // README Generation - // ========================================== - - describe("README Generation", () => { - test("should create README.md on project creation", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "My Project", - description: "A cool database project", - }); - const dir = getProjectDir(project.id); - const readmePath = path.join(dir, "README.md"); - expect(fsSync.existsSync(readmePath)).toBe(true); - }); - - test("should include project name and description", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "ReadmeProject", - description: "This is the project description", - }); - const dir = getProjectDir(project.id); - const content = await fs.readFile(path.join(dir, "README.md"), "utf-8"); - expect(content).toContain("# ReadmeProject"); - expect(content).toContain("This is the project description"); - }); - - test("should include .env reference and variable table", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "EnvRef", - }); - const dir = getProjectDir(project.id); - const content = await fs.readFile(path.join(dir, "README.md"), "utf-8"); - expect(content).toContain(".env"); - expect(content).toContain("DB_HOST"); - expect(content).toContain("PGHOST"); - expect(content).toContain("MYSQL_HOST"); - }); - - test("should include project structure section", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "StructureRef", - }); - const dir = getProjectDir(project.id); - const content = await fs.readFile(path.join(dir, "README.md"), "utf-8"); - expect(content).toContain("relwave.json"); - expect(content).toContain("relwave.local.json"); - expect(content).toContain("schema.json"); - expect(content).toContain("er.json"); - expect(content).toContain("queries.json"); - }); - - test("should include collaboration notes", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "CollabRef", - }); - const dir = getProjectDir(project.id); - const content = await fs.readFile(path.join(dir, "README.md"), "utf-8"); - expect(content).toContain("Collaboration"); - expect(content).toContain("git-ignored"); - }); - - test("should be idempotent (not overwrite existing README)", async () => { - const project = await store.createProject({ - databaseId: "db-1", - name: "IdempotentReadme", - }); - const dir = getProjectDir(project.id); - const readmePath = path.join(dir, "README.md"); - - // Overwrite with custom content - await fs.writeFile(readmePath, "# Custom README\n", "utf-8"); - - // ensureReadme should NOT replace it - const result = await store.ensureReadme(project.id, { name: "IdempotentReadme" }); - expect(result).toBe(false); - - const content = await fs.readFile(readmePath, "utf-8"); - expect(content).toBe("# Custom README\n"); - }); + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + }, + ]; + + // Allow time difference + await new Promise((r) => setTimeout(r, 10)); + const second = await store.saveSchema(projectId, changedSchemas); + + expect(second.cachedAt).not.toBe(first.cachedAt); + expect(second.schemas[0].tables).toHaveLength(2); + }); + + test("should throw when saving schema for non-existent project", async () => { + await expect(store.saveSchema("no-such-project", mockSchemas)).rejects.toThrow( + "Project no-such-project not found", + ); + }); + }); + + // ========================================== + // ER Diagram Operations + // ========================================== + + describe("ER Diagram Operations", () => { + let projectId: string; + + beforeEach(async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "ERTest", + }); + projectId = project.id; + }); + + test("should get initial empty diagram", async () => { + const diagram = await store.getERDiagram(projectId); + expect(diagram).toBeDefined(); + expect(diagram!.nodes).toEqual([]); + }); + + test("should save and retrieve diagram", async () => { + const nodes = [ + { tableId: "users", x: 100, y: 200 }, + { tableId: "posts", x: 300, y: 400, collapsed: true }, + ]; + + const saved = await store.saveERDiagram(projectId, { + nodes, + zoom: 1.5, + panX: 50, + panY: 75, + }); + + expect(saved.nodes).toHaveLength(2); + expect(saved.zoom).toBe(1.5); + expect(saved.panX).toBe(50); + + const retrieved = await store.getERDiagram(projectId); + expect(retrieved!.nodes).toHaveLength(2); + expect(retrieved!.nodes[0].tableId).toBe("users"); + }); + }); + + // ========================================== + // Query Operations + // ========================================== + + describe("Query Operations", () => { + let projectId: string; + + beforeEach(async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "QueryTest", + }); + projectId = project.id; + }); + + test("should get initial empty queries", async () => { + const queries = await store.getQueries(projectId); + expect(queries).toBeDefined(); + expect(queries!.queries).toEqual([]); + }); + + test("should add a query", async () => { + const query = await store.addQuery(projectId, { + name: "Get Users", + sql: "SELECT * FROM users", + description: "Fetch all users", + }); + + expect(query).toBeDefined(); + expect(query.id).toBeDefined(); + expect(query.name).toBe("Get Users"); + expect(query.sql).toBe("SELECT * FROM users"); + expect(query.description).toBe("Fetch all users"); + }); + + test("should list queries after adding", async () => { + await store.addQuery(projectId, { name: "Q1", sql: "SELECT 1" }); + await store.addQuery(projectId, { name: "Q2", sql: "SELECT 2" }); + + const queries = await store.getQueries(projectId); + expect(queries!.queries).toHaveLength(2); + }); + + test("should update a query", async () => { + const query = await store.addQuery(projectId, { + name: "Old Name", + sql: "SELECT 1", + }); + + const updated = await store.updateQuery(projectId, query.id, { + name: "New Name", + sql: "SELECT 2", + }); + + expect(updated).toBeDefined(); + expect(updated!.name).toBe("New Name"); + expect(updated!.sql).toBe("SELECT 2"); + expect(updated!.updatedAt).not.toBe(query.updatedAt); + }); + + test("should return null when updating non-existent query", async () => { + const result = await store.updateQuery(projectId, "no-such-query", { + name: "x", + }); + expect(result).toBeNull(); + }); + + test("should delete a query", async () => { + const query = await store.addQuery(projectId, { + name: "To Delete", + sql: "SELECT 1", + }); + + await store.deleteQuery(projectId, query.id); + + const queries = await store.getQueries(projectId); + expect(queries!.queries.find((q) => q.id === query.id)).toBeUndefined(); + }); + }); + + // ========================================== + // Export + // ========================================== + + describe("Export", () => { + test("should export full project bundle", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "ExportTest", + }); + + // Add some data + await store.saveSchema(project.id, [{ name: "public", tables: [] }]); + await store.saveERDiagram(project.id, { nodes: [{ tableId: "t1", x: 0, y: 0 }] }); + await store.addQuery(project.id, { name: "Q1", sql: "SELECT 1" }); + + const bundle = await store.exportProject(project.id); + expect(bundle).toBeDefined(); + expect(bundle!.metadata.name).toBe("ExportTest"); + expect(bundle!.schema).toBeDefined(); + expect(bundle!.erDiagram!.nodes).toHaveLength(1); + expect(bundle!.queries!.queries).toHaveLength(1); + }); + + test("should return null for non-existent project export", async () => { + const bundle = await store.exportProject("no-such-id"); + expect(bundle).toBeNull(); + }); + }); + + // ========================================== + // Local Config (git-ignored) + // ========================================== + + describe("Local Config", () => { + let projectId: string; + + beforeEach(async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "ConfigTest", + }); + projectId = project.id; + }); + + test("should get initial empty local config", async () => { + const config = await store.getLocalConfig(projectId); + expect(config).toBeDefined(); + expect(config).toEqual({}); + }); + + test("should save and retrieve local config", async () => { + const saved = await store.saveLocalConfig(projectId, { + connectionUrl: "postgres://localhost:5432/mydb", + environment: "development", + notes: "My dev setup", + }); + + expect(saved.connectionUrl).toBe("postgres://localhost:5432/mydb"); + + const retrieved = await store.getLocalConfig(projectId); + expect(retrieved!.environment).toBe("development"); + }); + }); + + // ========================================== + // .gitignore Management + // ========================================== + + describe("Gitignore Management", () => { + let projectId: string; + + beforeEach(async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "GitignoreTest", + }); + projectId = project.id; + }); + + test("should create .gitignore on project creation", async () => { + const dir = getProjectDir(projectId); + const giPath = path.join(dir, ".gitignore"); + expect(fsSync.existsSync(giPath)).toBe(true); + }); + + test("should include relwave.local.json in .gitignore", async () => { + const dir = getProjectDir(projectId); + const content = await fs.readFile(path.join(dir, ".gitignore"), "utf-8"); + expect(content).toContain("relwave.local.json"); + }); + + test("should be idempotent", async () => { + // Already created once during project creation + const result = await store.ensureGitignore(projectId); + // Should return false = already has our rules + expect(result).toBe(false); + }); + + test("should append to existing .gitignore without our rules", async () => { + const dir = getProjectDir(projectId); + const giPath = path.join(dir, ".gitignore"); + + // Overwrite with custom content (without our rules) + await fs.writeFile(giPath, "node_modules/\n*.log\n", "utf-8"); + + const result = await store.ensureGitignore(projectId); + expect(result).toBe(true); + + const content = await fs.readFile(giPath, "utf-8"); + expect(content).toContain("node_modules/"); + expect(content).toContain("relwave.local.json"); + }); + }); + + // ========================================== + // README Generation + // ========================================== + + describe("README Generation", () => { + test("should create README.md on project creation", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "My Project", + description: "A cool database project", + }); + const dir = getProjectDir(project.id); + const readmePath = path.join(dir, "README.md"); + expect(fsSync.existsSync(readmePath)).toBe(true); + }); + + test("should include project name and description", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "ReadmeProject", + description: "This is the project description", + }); + const dir = getProjectDir(project.id); + const content = await fs.readFile(path.join(dir, "README.md"), "utf-8"); + expect(content).toContain("# ReadmeProject"); + expect(content).toContain("This is the project description"); + }); + + test("should include .env reference and variable table", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "EnvRef", + }); + const dir = getProjectDir(project.id); + const content = await fs.readFile(path.join(dir, "README.md"), "utf-8"); + expect(content).toContain(".env"); + expect(content).toContain("DB_HOST"); + expect(content).toContain("PGHOST"); + expect(content).toContain("MYSQL_HOST"); + }); + + test("should include project structure section", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "StructureRef", + }); + const dir = getProjectDir(project.id); + const content = await fs.readFile(path.join(dir, "README.md"), "utf-8"); + expect(content).toContain("relwave.json"); + expect(content).toContain("relwave.local.json"); + expect(content).toContain("schema.json"); + expect(content).toContain("er.json"); + expect(content).toContain("queries.json"); + }); + + test("should include collaboration notes", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "CollabRef", + }); + const dir = getProjectDir(project.id); + const content = await fs.readFile(path.join(dir, "README.md"), "utf-8"); + expect(content).toContain("Collaboration"); + expect(content).toContain("git-ignored"); + }); + + test("should be idempotent (not overwrite existing README)", async () => { + const project = await store.createProject({ + databaseId: "db-1", + name: "IdempotentReadme", + }); + const dir = getProjectDir(project.id); + const readmePath = path.join(dir, "README.md"); + + // Overwrite with custom content + await fs.writeFile(readmePath, "# Custom README\n", "utf-8"); + + // ensureReadme should NOT replace it + const result = await store.ensureReadme(project.id, { name: "IdempotentReadme" }); + expect(result).toBe(false); + + const content = await fs.readFile(readmePath, "utf-8"); + expect(content).toBe("# Custom README\n"); }); + }); }); diff --git a/bridge/__tests__/schemaContext.test.ts b/bridge/__tests__/schemaContext.test.ts index 93727eb4..026c460a 100644 --- a/bridge/__tests__/schemaContext.test.ts +++ b/bridge/__tests__/schemaContext.test.ts @@ -19,76 +19,170 @@ describe("buildSchemaContext", () => { name: "users", type: "BASE TABLE", columns: [ - { name: "id", type: "uuid", isPrimaryKey: true, nullable: false, isForeignKey: false, isUnique: false, isSerial: false, ordinalPosition: 1, defaultValue: "uuid_generate_v4()" }, - { name: "email", type: "varchar", isPrimaryKey: false, nullable: false, isForeignKey: false, isUnique: true, isSerial: false, ordinalPosition: 2, defaultValue: null }, - { name: "password_hash", type: "varchar", isPrimaryKey: false, nullable: false, isForeignKey: false, isUnique: false, isSerial: false, ordinalPosition: 3, defaultValue: null }, - { name: "status", type: "user_status", isPrimaryKey: false, nullable: false, isForeignKey: false, isUnique: false, isSerial: false, ordinalPosition: 4, defaultValue: "'active'" } + { + name: "id", + type: "uuid", + isPrimaryKey: true, + nullable: false, + isForeignKey: false, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + defaultValue: "uuid_generate_v4()", + }, + { + name: "email", + type: "varchar", + isPrimaryKey: false, + nullable: false, + isForeignKey: false, + isUnique: true, + isSerial: false, + ordinalPosition: 2, + defaultValue: null, + }, + { + name: "password_hash", + type: "varchar", + isPrimaryKey: false, + nullable: false, + isForeignKey: false, + isUnique: false, + isSerial: false, + ordinalPosition: 3, + defaultValue: null, + }, + { + name: "status", + type: "user_status", + isPrimaryKey: false, + nullable: false, + isForeignKey: false, + isUnique: false, + isSerial: false, + ordinalPosition: 4, + defaultValue: "'active'", + }, ], indexes: [{ name: "users_email_idx", columns: ["email"], unique: true }], foreignKeys: [], - checks: [] + checks: [], }, { name: "orders", type: "BASE TABLE", columns: [ - { name: "id", type: "integer", isPrimaryKey: true, nullable: false, isForeignKey: false, isUnique: false, isSerial: true, ordinalPosition: 1, defaultValue: null }, - { name: "user_id", type: "uuid", isPrimaryKey: false, nullable: false, isForeignKey: true, isUnique: false, isSerial: false, ordinalPosition: 2, defaultValue: null, foreignKey: { schema: "public", table: "users", column: "id" } }, - { name: "total", type: "numeric", isPrimaryKey: false, nullable: false, isForeignKey: false, isUnique: false, isSerial: false, ordinalPosition: 3, defaultValue: null } + { + name: "id", + type: "integer", + isPrimaryKey: true, + nullable: false, + isForeignKey: false, + isUnique: false, + isSerial: true, + ordinalPosition: 1, + defaultValue: null, + }, + { + name: "user_id", + type: "uuid", + isPrimaryKey: false, + nullable: false, + isForeignKey: true, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + defaultValue: null, + foreignKey: { schema: "public", table: "users", column: "id" }, + }, + { + name: "total", + type: "numeric", + isPrimaryKey: false, + nullable: false, + isForeignKey: false, + isUnique: false, + isSerial: false, + ordinalPosition: 3, + defaultValue: null, + }, ], indexes: [], foreignKeys: [ - { name: "orders_user_id_fkey", columns: ["user_id"], referencedSchema: "public", referencedTable: "users", referencedColumns: ["id"], onDelete: "CASCADE", onUpdate: "NO ACTION" } + { + name: "orders_user_id_fkey", + columns: ["user_id"], + referencedSchema: "public", + referencedTable: "users", + referencedColumns: ["id"], + onDelete: "CASCADE", + onUpdate: "NO ACTION", + }, ], - checks: [] + checks: [], }, { name: "schema_migrations", type: "BASE TABLE", - columns: [{ name: "version", type: "varchar", isPrimaryKey: true, nullable: false, isForeignKey: false, isUnique: false, isSerial: false, ordinalPosition: 1, defaultValue: null }], + columns: [ + { + name: "version", + type: "varchar", + isPrimaryKey: true, + nullable: false, + isForeignKey: false, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + defaultValue: null, + }, + ], indexes: [], foreignKeys: [], - checks: [] - } - ] - } - ] + checks: [], + }, + ], + }, + ], }; it("should build a compact context", () => { const result = buildSchemaContext(mockSchema); - + // Check header expect(result).toContain("Database: postgresql | Schema captured: 2023-01-01T00:00:00.000Z"); - + // Check enums expect(result).toContain("ENUM TYPES:"); expect(result).toContain("public.user_status = [active, inactive]"); - + // Check tables and columns expect(result).toContain("TABLE public.users"); expect(result).toContain("id uuid [PK, NOT NULL, DEFAULT uuid_generate_v4()]"); expect(result).toContain("email varchar [NOT NULL, UNIQUE]"); - + // Check masking sensitive columns expect(result).toContain("password_hash: [REDACTED]"); - + // Check foreign key column flag expect(result).toContain("user_id uuid [FK→public.users.id, NOT NULL]"); - + // Check indexes expect(result).toContain("UNIQUE INDEX (email)"); - + // Check relationships expect(result).toContain("RELATIONSHIPS:"); expect(result).toContain("RELATIONSHIP public.orders.user_id → public.users.id"); - + // Check that excluded tables are absent expect(result).not.toContain("TABLE public.schema_migrations"); }); it("should respect excludeTables and targetSchema options", () => { - const result = buildSchemaContext(mockSchema, { excludeTables: ["orders"], targetSchema: "public" }); + const result = buildSchemaContext(mockSchema, { + excludeTables: ["orders"], + targetSchema: "public", + }); expect(result).not.toContain("TABLE public.orders"); expect(result).not.toContain("RELATIONSHIP public.orders.user_id"); expect(result).toContain("TABLE public.users"); diff --git a/bridge/__tests__/sqlValidator.test.ts b/bridge/__tests__/sqlValidator.test.ts index 7b66feef..febdeef0 100644 --- a/bridge/__tests__/sqlValidator.test.ts +++ b/bridge/__tests__/sqlValidator.test.ts @@ -14,22 +14,42 @@ describe("validateGeneratedSQL", () => { { name: "public", tables: [ - { name: "users", type: "BASE TABLE", columns: [], indexes: [], foreignKeys: [], checks: [] }, - { name: "orders", type: "BASE TABLE", columns: [], indexes: [], foreignKeys: [], checks: [] } - ] - } - ] + { + name: "users", + type: "BASE TABLE", + columns: [], + indexes: [], + foreignKeys: [], + checks: [], + }, + { + name: "orders", + type: "BASE TABLE", + columns: [], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + }, + ], }; it("should allow a valid SELECT query with known tables", () => { - const result = validateGeneratedSQL('SELECT * FROM "users" JOIN public.orders on users.id = orders.user_id', mockSchema); + const result = validateGeneratedSQL( + 'SELECT * FROM "users" JOIN public.orders on users.id = orders.user_id', + mockSchema, + ); expect(result.valid).toBe(true); expect(result.intent).toBe("read"); }); it("should block non-SELECT queries", () => { - const result = validateGeneratedSQL('WITH cte AS (SELECT * FROM users) SELECT * FROM cte', mockSchema); - // Actually our simple check blocks WITH if it doesn't start with SELECT. + const result = validateGeneratedSQL( + "WITH cte AS (SELECT * FROM users) SELECT * FROM cte", + mockSchema, + ); + // Actually our simple check blocks WITH if it doesn't start with SELECT. // That's acceptable for a strict auto-execution guard as per TASKS.md expect(result.valid).toBe(false); expect(result.reason).toContain("start with SELECT"); diff --git a/bridge/__tests__/sshTunnelService.integration.test.ts b/bridge/__tests__/sshTunnelService.integration.test.ts index 31f3ec09..13991f7b 100644 --- a/bridge/__tests__/sshTunnelService.integration.test.ts +++ b/bridge/__tests__/sshTunnelService.integration.test.ts @@ -43,101 +43,113 @@ describeOrSkip("SSHTunnelService Integration Tests", () => { } }); - it("should connect to postgres via SSH tunnel using password auth", async () => { - // 1. Create SSH Tunnel - tunnel = await sshTunnelServiceInstance.createSSHTunnel( - { - host: "localhost", - port: 2222, // ssh-server exposed port - username: "testsshuser", - authMethod: "password", - password: "testpassword", - }, - "postgres-behind-ssh", // remote host inside docker network - 5432 // remote port - ); - - expect(tunnel.localPort).toBeGreaterThan(0); - - // 2. Connect to Postgres via the local tunnel port - const pgClient = new PgClient({ - host: "127.0.0.1", - port: tunnel.localPort, - user: "testuser", - password: "testpass", - database: "testdb", - }); - - await pgClient.connect(); - const res = await pgClient.query("SELECT 1 + 1 AS result"); - expect(res.rows[0].result).toBe(2); - await pgClient.end(); - }, TIMEOUT); - - it("should connect to postgres via SSH tunnel using private key auth", async () => { - // 1. Create SSH Tunnel - tunnel = await sshTunnelServiceInstance.createSSHTunnel( - { - host: "localhost", - port: 2222, - username: "testsshuser", - authMethod: "privateKey", - privateKey: TEST_PRIVATE_KEY, - }, - "postgres-behind-ssh", - 5432 - ); - - expect(tunnel.localPort).toBeGreaterThan(0); - - // 2. Connect to Postgres - const pgClient = new PgClient({ - host: "127.0.0.1", - port: tunnel.localPort, - user: "testuser", - password: "testpass", - database: "testdb", - }); - - await pgClient.connect(); - const res = await pgClient.query("SELECT 1 + 1 AS result"); - expect(res.rows[0].result).toBe(2); - await pgClient.end(); - }, TIMEOUT); - - it("tunnel.close() tears down cleanly and subsequent connections fail", async () => { - // 1. Create SSH Tunnel - tunnel = await sshTunnelServiceInstance.createSSHTunnel( - { - host: "localhost", - port: 2222, - username: "testsshuser", - authMethod: "password", - password: "testpassword", - }, - "postgres-behind-ssh", - 5432 - ); - - const localPort = tunnel.localPort; - - // 2. Close tunnel - tunnel.close(); - tunnel = null; - - // 3. Verify connection fails - const socket = new net.Socket(); - const connectionPromise = new Promise((resolve, reject) => { - socket.setTimeout(1000); - socket.connect(localPort, "127.0.0.1", () => { - socket.destroy(); - resolve(true); + it( + "should connect to postgres via SSH tunnel using password auth", + async () => { + // 1. Create SSH Tunnel + tunnel = await sshTunnelServiceInstance.createSSHTunnel( + { + host: "localhost", + port: 2222, // ssh-server exposed port + username: "testsshuser", + authMethod: "password", + password: "testpassword", + }, + "postgres-behind-ssh", // remote host inside docker network + 5432, // remote port + ); + + expect(tunnel.localPort).toBeGreaterThan(0); + + // 2. Connect to Postgres via the local tunnel port + const pgClient = new PgClient({ + host: "127.0.0.1", + port: tunnel.localPort, + user: "testuser", + password: "testpass", + database: "testdb", }); - socket.on("error", () => resolve(false)); - socket.on("timeout", () => resolve(false)); - }); - const isConnected = await connectionPromise; - expect(isConnected).toBe(false); - }, TIMEOUT); + await pgClient.connect(); + const res = await pgClient.query("SELECT 1 + 1 AS result"); + expect(res.rows[0].result).toBe(2); + await pgClient.end(); + }, + TIMEOUT, + ); + + it( + "should connect to postgres via SSH tunnel using private key auth", + async () => { + // 1. Create SSH Tunnel + tunnel = await sshTunnelServiceInstance.createSSHTunnel( + { + host: "localhost", + port: 2222, + username: "testsshuser", + authMethod: "privateKey", + privateKey: TEST_PRIVATE_KEY, + }, + "postgres-behind-ssh", + 5432, + ); + + expect(tunnel.localPort).toBeGreaterThan(0); + + // 2. Connect to Postgres + const pgClient = new PgClient({ + host: "127.0.0.1", + port: tunnel.localPort, + user: "testuser", + password: "testpass", + database: "testdb", + }); + + await pgClient.connect(); + const res = await pgClient.query("SELECT 1 + 1 AS result"); + expect(res.rows[0].result).toBe(2); + await pgClient.end(); + }, + TIMEOUT, + ); + + it( + "tunnel.close() tears down cleanly and subsequent connections fail", + async () => { + // 1. Create SSH Tunnel + tunnel = await sshTunnelServiceInstance.createSSHTunnel( + { + host: "localhost", + port: 2222, + username: "testsshuser", + authMethod: "password", + password: "testpassword", + }, + "postgres-behind-ssh", + 5432, + ); + + const localPort = tunnel.localPort; + + // 2. Close tunnel + tunnel.close(); + tunnel = null; + + // 3. Verify connection fails + const socket = new net.Socket(); + const connectionPromise = new Promise((resolve, reject) => { + socket.setTimeout(1000); + socket.connect(localPort, "127.0.0.1", () => { + socket.destroy(); + resolve(true); + }); + socket.on("error", () => resolve(false)); + socket.on("timeout", () => resolve(false)); + }); + + const isConnected = await connectionPromise; + expect(isConnected).toBe(false); + }, + TIMEOUT, + ); }); diff --git a/bridge/__tests__/sshTunnelService.test.ts b/bridge/__tests__/sshTunnelService.test.ts index 605c76ba..7b128c11 100644 --- a/bridge/__tests__/sshTunnelService.test.ts +++ b/bridge/__tests__/sshTunnelService.test.ts @@ -65,7 +65,11 @@ describe("SSHTunnelService", () => { const tunnelInfo = await tunnelPromise; expect(tunnelInfo.localPort).toBe(12345); - expect(mockServer.listen).toHaveBeenCalledWith(expect.any(Number), "127.0.0.1", expect.any(Function)); + expect(mockServer.listen).toHaveBeenCalledWith( + expect.any(Number), + "127.0.0.1", + expect.any(Function), + ); expect(mockSshClient.connect).toHaveBeenCalled(); }); @@ -92,7 +96,7 @@ describe("SSHTunnelService", () => { it("resolvePrivateKey returns buffer directly for raw PEM string without calling fs", () => { const pemString = "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA..."; - + const result = (service as any).resolvePrivateKey(pemString); expect(fs.readFileSync).not.toHaveBeenCalled(); diff --git a/bridge/package.json b/bridge/package.json index e4b15420..43c802cb 100644 --- a/bridge/package.json +++ b/bridge/package.json @@ -60,4 +60,4 @@ "ts-node-dev": "^2.0.0", "typescript": "^5.0.0" } -} \ No newline at end of file +} diff --git a/bridge/scripts/build-pkg.js b/bridge/scripts/build-pkg.js index bc2f604a..d3b53f28 100644 --- a/bridge/scripts/build-pkg.js +++ b/bridge/scripts/build-pkg.js @@ -10,9 +10,7 @@ const targetScriptByPlatform = { const targetScript = targetScriptByPlatform[process.platform]; if (!targetScript) { - console.error( - `ERROR: Unsupported platform for bridge packaging: ${process.platform}`, - ); + console.error(`ERROR: Unsupported platform for bridge packaging: ${process.platform}`); process.exit(1); } diff --git a/bridge/scripts/copy-native.js b/bridge/scripts/copy-native.js index 60a1ec70..e29e3e16 100644 --- a/bridge/scripts/copy-native.js +++ b/bridge/scripts/copy-native.js @@ -48,9 +48,7 @@ function findFirstNodeBinary(rootDir) { function downloadPkgRuntimeBinary(betterSqlite3Dir) { const packageJsonPath = path.join(betterSqlite3Dir, "package.json"); - const tempDir = fs.mkdtempSync( - path.join(os.tmpdir(), "relwave-better-sqlite3-"), - ); + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "relwave-better-sqlite3-")); const prebuildInstallBin = require.resolve("prebuild-install/bin.js", { paths: [betterSqlite3Dir], }); @@ -96,9 +94,7 @@ function downloadPkgRuntimeBinary(betterSqlite3Dir) { const downloadedBinary = findFirstNodeBinary(tempDir); if (!downloadedBinary) { - console.error( - "ERROR: prebuild-install completed, but no better_sqlite3.node was extracted.", - ); + console.error("ERROR: prebuild-install completed, but no better_sqlite3.node was extracted."); process.exit(1); } @@ -153,12 +149,7 @@ if (!src || !fs.existsSync(src)) { } const repoRoot = path.resolve(__dirname, "..", ".."); -const dest = path.join( - repoRoot, - "src-tauri", - "resources", - "better_sqlite3.node", -); +const dest = path.join(repoRoot, "src-tauri", "resources", "better_sqlite3.node"); fs.mkdirSync(path.dirname(dest), { recursive: true }); fs.copyFileSync(src, dest); diff --git a/bridge/src/ai/README.md b/bridge/src/ai/README.md index 0746cdfc..ee48016b 100644 --- a/bridge/src/ai/README.md +++ b/bridge/src/ai/README.md @@ -3,21 +3,26 @@ This folder contains AI provider implementations and prompt templates used by the bridge. Layout + - `providers/` — concrete provider adapters (OpenAI, Anthropic, Gemini, Mistral, Ollama, Groq). Implement the `AIProvider` interface in `providers/types.ts`. - `prompts/` — prompt builders and parsers for schema analysis, query explanation and chart recommendation. What moved + - The public RPC entry points and handler logic live under `src/handlers/aiHandlers.ts`. - The service factory implementation was moved to `src/services/ai.impl.ts` and a shim `src/services/aiService.ts` exposes `AIService` and `aiService` for consistency with other bridge services. - Shared AI types were moved to `src/types/ai.ts` and are re-exported from the central `src/types/index.ts`. How to add a provider + 1. Create a new file under `providers/` implementing the `AIProvider` interface. 2. Add the provider into `src/services/ai.impl.ts` in the `createProvider` switch. 3. Add any provider-specific configuration notes to this README. Testing + - No tests currently exist for AI. To exercise the integration locally, use the frontend UI features that call `ai.*` RPC methods or create a test that uses the RPC registrar. Notes + - Keep providers small and avoid direct network retries; the bridge surface should translate provider errors into `AIError` using `providers/types.ts`. diff --git a/bridge/src/ai/prompts/chart-recommendation.ts b/bridge/src/ai/prompts/chart-recommendation.ts index bb5316e5..cc8e42e8 100644 --- a/bridge/src/ai/prompts/chart-recommendation.ts +++ b/bridge/src/ai/prompts/chart-recommendation.ts @@ -51,7 +51,11 @@ export function parseChartRecommendation(raw: string): ChartRecommendation { try { parsed = JSON.parse(cleaned); } catch { - throw new AIError("PARSE_ERROR", "chart-recommendation", `Failed to parse chart recommendation JSON: ${raw.slice(0, 200)}`); + throw new AIError( + "PARSE_ERROR", + "chart-recommendation", + `Failed to parse chart recommendation JSON: ${raw.slice(0, 200)}`, + ); } const validTypes = ["bar", "line", "area", "pie"]; diff --git a/bridge/src/ai/prompts/nl-sql-interpreter.ts b/bridge/src/ai/prompts/nl-sql-interpreter.ts index 0f3abb44..26b99926 100644 --- a/bridge/src/ai/prompts/nl-sql-interpreter.ts +++ b/bridge/src/ai/prompts/nl-sql-interpreter.ts @@ -1,6 +1,10 @@ import { SYSTEM_CONTEXT } from "./shared"; -export function buildResultInterpreterPrompt(question: string, sql: string, resultsJSON: string): { +export function buildResultInterpreterPrompt( + question: string, + sql: string, + resultsJSON: string, +): { system: string; user: string; } { diff --git a/bridge/src/ai/prompts/nl-sql.ts b/bridge/src/ai/prompts/nl-sql.ts index 4d39c0ae..8c46a3ae 100644 --- a/bridge/src/ai/prompts/nl-sql.ts +++ b/bridge/src/ai/prompts/nl-sql.ts @@ -1,16 +1,22 @@ import { SYSTEM_CONTEXT } from "./shared"; -export function buildNLSQLPrompt(schemaContext: string, dialect: string): { +export function buildNLSQLPrompt( + schemaContext: string, + dialect: string, +): { system: string; user: (question: string) => string; } { let quoteRule = ""; if (dialect === "postgresql") { - quoteRule = 'Use double quotes (") for identifiers if needed. If qualifying with a schema, quote them separately like "schema"."table".'; + quoteRule = + 'Use double quotes (") for identifiers if needed. If qualifying with a schema, quote them separately like "schema"."table".'; } else if (dialect === "mysql" || dialect === "mariadb") { - quoteRule = "Use backticks (`) for identifiers if needed. If qualifying with a schema, quote them separately like `schema`.`table`."; + quoteRule = + "Use backticks (`) for identifiers if needed. If qualifying with a schema, quote them separately like `schema`.`table`."; } else if (dialect === "sqlite") { - quoteRule = "Do not use quotes for identifiers unless necessary. If qualifying with a schema, quote them separately."; + quoteRule = + "Do not use quotes for identifiers unless necessary. If qualifying with a schema, quote them separately."; } const system = `You are RelWave AI, an expert SQL developer for ${dialect}. @@ -49,6 +55,6 @@ If the question is unclear or unrelated to the schema, return: return { system, - user: (question: string) => `Question: ${question}` + user: (question: string) => `Question: ${question}`, }; } diff --git a/bridge/src/ai/prompts/query-explanation.ts b/bridge/src/ai/prompts/query-explanation.ts index 1897456d..1a714278 100644 --- a/bridge/src/ai/prompts/query-explanation.ts +++ b/bridge/src/ai/prompts/query-explanation.ts @@ -8,13 +8,16 @@ export function buildQueryExplanationPrompt(input: QueryExplanationInput): { const schemaContext = input.schema && input.schema.length > 0 ? input.schema - .map((t) => { - const cols = t.columns - .map((c) => `${c.name} ${c.type}${c.isPrimaryKey ? " PK" : ""}${c.isForeignKey ? " FK" : ""}`) - .join(", "); - return `- ${t.name}(${cols})`; - }) - .join("\n") + .map((t) => { + const cols = t.columns + .map( + (c) => + `${c.name} ${c.type}${c.isPrimaryKey ? " PK" : ""}${c.isForeignKey ? " FK" : ""}`, + ) + .join(", "); + return `- ${t.name}(${cols})`; + }) + .join("\n") : "Schema not provided."; const dbType = input.databaseType ? ` (${input.databaseType})` : ""; diff --git a/bridge/src/ai/prompts/schema-analysis.ts b/bridge/src/ai/prompts/schema-analysis.ts index 8d9a79d0..4d8fc631 100644 --- a/bridge/src/ai/prompts/schema-analysis.ts +++ b/bridge/src/ai/prompts/schema-analysis.ts @@ -25,7 +25,7 @@ export function buildSchemaAnalysisPrompt(input: SchemaAnalysisInput): { const tableName = `${t.schema ? `${t.schema}.` : ""}${t.name}`; const extrasStr = extras.length ? ` | ${extras.join(" | ")}` : ""; - + return `[${tableName}] cols: ${columns}${extrasStr}`; }) .join("\n"); diff --git a/bridge/src/ai/providers/anthropic.provider.ts b/bridge/src/ai/providers/anthropic.provider.ts index d73f3617..7dad2d6c 100644 --- a/bridge/src/ai/providers/anthropic.provider.ts +++ b/bridge/src/ai/providers/anthropic.provider.ts @@ -8,7 +8,10 @@ import { } from "../../types"; import { buildSchemaAnalysisPrompt } from "../prompts/schema-analysis"; import { buildQueryExplanationPrompt } from "../prompts/query-explanation"; -import { buildChartRecommendationPrompt, parseChartRecommendation } from "../prompts/chart-recommendation"; +import { + buildChartRecommendationPrompt, + parseChartRecommendation, +} from "../prompts/chart-recommendation"; const DEFAULT_MODEL = "claude-3-5-haiku-20241022"; diff --git a/bridge/src/ai/providers/gemini.provider.ts b/bridge/src/ai/providers/gemini.provider.ts index 4ab70ad8..e0c89e7b 100644 --- a/bridge/src/ai/providers/gemini.provider.ts +++ b/bridge/src/ai/providers/gemini.provider.ts @@ -8,7 +8,10 @@ import { } from "../../types/"; import { buildSchemaAnalysisPrompt } from "../prompts/schema-analysis"; import { buildQueryExplanationPrompt } from "../prompts/query-explanation"; -import { buildChartRecommendationPrompt, parseChartRecommendation } from "../prompts/chart-recommendation"; +import { + buildChartRecommendationPrompt, + parseChartRecommendation, +} from "../prompts/chart-recommendation"; const DEFAULT_MODEL = "gemini-1.5-flash"; diff --git a/bridge/src/ai/providers/groq.provider.ts b/bridge/src/ai/providers/groq.provider.ts index 3057f27d..06142c32 100644 --- a/bridge/src/ai/providers/groq.provider.ts +++ b/bridge/src/ai/providers/groq.provider.ts @@ -8,7 +8,10 @@ import { } from "../../types/"; import { buildSchemaAnalysisPrompt } from "../prompts/schema-analysis"; import { buildQueryExplanationPrompt } from "../prompts/query-explanation"; -import { buildChartRecommendationPrompt, parseChartRecommendation } from "../prompts/chart-recommendation"; +import { + buildChartRecommendationPrompt, + parseChartRecommendation, +} from "../prompts/chart-recommendation"; const DEFAULT_MODEL = "llama-3.3-70b-versatile"; diff --git a/bridge/src/ai/providers/mistral.provider.ts b/bridge/src/ai/providers/mistral.provider.ts index 24d4dd6b..976e92e2 100644 --- a/bridge/src/ai/providers/mistral.provider.ts +++ b/bridge/src/ai/providers/mistral.provider.ts @@ -8,7 +8,10 @@ import { } from "../../types/"; import { buildSchemaAnalysisPrompt } from "../prompts/schema-analysis"; import { buildQueryExplanationPrompt } from "../prompts/query-explanation"; -import { buildChartRecommendationPrompt, parseChartRecommendation } from "../prompts/chart-recommendation"; +import { + buildChartRecommendationPrompt, + parseChartRecommendation, +} from "../prompts/chart-recommendation"; const DEFAULT_MODEL = "mistral-small-latest"; diff --git a/bridge/src/ai/providers/ollama.provider.ts b/bridge/src/ai/providers/ollama.provider.ts index b82462f3..c2159095 100644 --- a/bridge/src/ai/providers/ollama.provider.ts +++ b/bridge/src/ai/providers/ollama.provider.ts @@ -8,7 +8,10 @@ import { } from "../../types/"; import { buildSchemaAnalysisPrompt } from "../prompts/schema-analysis"; import { buildQueryExplanationPrompt } from "../prompts/query-explanation"; -import { buildChartRecommendationPrompt, parseChartRecommendation } from "../prompts/chart-recommendation"; +import { + buildChartRecommendationPrompt, + parseChartRecommendation, +} from "../prompts/chart-recommendation"; const DEFAULT_MODEL = "llama3.2"; diff --git a/bridge/src/ai/providers/openai.provider.ts b/bridge/src/ai/providers/openai.provider.ts index 7bc61429..13b21dfb 100644 --- a/bridge/src/ai/providers/openai.provider.ts +++ b/bridge/src/ai/providers/openai.provider.ts @@ -8,7 +8,10 @@ import { } from "../../types"; import { buildSchemaAnalysisPrompt } from "../prompts/schema-analysis"; import { buildQueryExplanationPrompt } from "../prompts/query-explanation"; -import { buildChartRecommendationPrompt, parseChartRecommendation } from "../prompts/chart-recommendation"; +import { + buildChartRecommendationPrompt, + parseChartRecommendation, +} from "../prompts/chart-recommendation"; const DEFAULT_MODEL = "gpt-4o-mini"; diff --git a/bridge/src/ai/providers/types.ts b/bridge/src/ai/providers/types.ts index 803423df..1aef5d3f 100644 --- a/bridge/src/ai/providers/types.ts +++ b/bridge/src/ai/providers/types.ts @@ -65,16 +65,31 @@ export function classifyError(err: unknown, provider: string): AIError { const msg = err instanceof Error ? err.message : String(err); const lower = msg.toLowerCase(); - if (lower.includes("api key") || lower.includes("apikey") || lower.includes("authentication") || lower.includes("unauthorized") || lower.includes("401")) { + if ( + lower.includes("api key") || + lower.includes("apikey") || + lower.includes("authentication") || + lower.includes("unauthorized") || + lower.includes("401") + ) { return new AIError("INVALID_API_KEY", provider, msg); } - if (lower.includes("rate limit") || lower.includes("429") || lower.includes("too many requests")) { + if ( + lower.includes("rate limit") || + lower.includes("429") || + lower.includes("too many requests") + ) { return new AIError("RATE_LIMIT", provider, msg); } if (lower.includes("timeout") || lower.includes("timed out")) { return new AIError("TIMEOUT", provider, msg); } - if (lower.includes("econnrefused") || lower.includes("enotfound") || lower.includes("fetch failed") || lower.includes("network")) { + if ( + lower.includes("econnrefused") || + lower.includes("enotfound") || + lower.includes("fetch failed") || + lower.includes("network") + ) { return new AIError("NETWORK_FAILURE", provider, msg); } if (lower.includes("model") && (lower.includes("not found") || lower.includes("invalid"))) { diff --git a/bridge/src/ai/utils/schemaContext.ts b/bridge/src/ai/utils/schemaContext.ts index a4a48307..3c9eee78 100644 --- a/bridge/src/ai/utils/schemaContext.ts +++ b/bridge/src/ai/utils/schemaContext.ts @@ -1,4 +1,9 @@ -import { SchemaFile, SchemaSnapshot, TableSnapshot, ColumnSnapshot } from "../../services/projectStore"; +import { + SchemaFile, + SchemaSnapshot, + TableSnapshot, + ColumnSnapshot, +} from "../../services/projectStore"; export interface SchemaContextOptions { excludeTables?: string[]; @@ -6,7 +11,8 @@ export interface SchemaContextOptions { maskSensitiveColumns?: boolean; } -const SENSITIVE_PATTERN = /password|password_hash|secret|api_key|token|private_key|credit_card|ssn|cvv/i; +const SENSITIVE_PATTERN = + /password|password_hash|secret|api_key|token|private_key|credit_card|ssn|cvv/i; const ALWAYS_EXCLUDED_TABLES = ["schema_migrations", "relwave_migrations", "ai_history"]; export function buildSchemaContext(schema: SchemaFile, options: SchemaContextOptions = {}): string { @@ -58,7 +64,9 @@ export function buildSchemaContext(schema: SchemaFile, options: SchemaContextOpt const flags: string[] = []; if (col.isPrimaryKey) flags.push("PK"); if (col.isForeignKey && col.foreignKey) { - flags.push(`FK→${col.foreignKey.schema}.${col.foreignKey.table}.${col.foreignKey.column}`); + flags.push( + `FK→${col.foreignKey.schema}.${col.foreignKey.table}.${col.foreignKey.column}`, + ); } else if (col.isForeignKey) { // Fallback if foreignKey details are missing but flag is true flags.push("FK"); @@ -87,7 +95,7 @@ export function buildSchemaContext(schema: SchemaFile, options: SchemaContextOpt // e.g. RELATIONSHIP public.users.id → public.orders.user_id // Actually, fk.columns are the local columns. relationships.push( - `RELATIONSHIP ${s.name}.${t.name}.${fk.columns.join(",")} → ${fk.referencedSchema}.${fk.referencedTable}.${fk.referencedColumns.join(",")}` + `RELATIONSHIP ${s.name}.${t.name}.${fk.columns.join(",")} → ${fk.referencedSchema}.${fk.referencedTable}.${fk.referencedColumns.join(",")}`, ); } } diff --git a/bridge/src/ai/utils/sqlValidator.ts b/bridge/src/ai/utils/sqlValidator.ts index 250cb1ca..ebd3bd20 100644 --- a/bridge/src/ai/utils/sqlValidator.ts +++ b/bridge/src/ai/utils/sqlValidator.ts @@ -44,9 +44,13 @@ export function validateGeneratedSQL(sql: string, schema: SchemaFile): Validatio // A semicolon anywhere except at the very end is considered stacked const semiIndex = sql.indexOf(";"); if (semiIndex !== -1 && semiIndex !== sql.trim().length - 1) { - return { valid: false, reason: "Stacked statements (multiple queries) are not allowed", intent: "read" }; + return { + valid: false, + reason: "Stacked statements (multiple queries) are not allowed", + intent: "read", + }; } - + if (sql.includes("--") || sql.includes("/*")) { return { valid: false, reason: "SQL comments are not allowed", intent: "read" }; } @@ -56,7 +60,7 @@ export function validateGeneratedSQL(sql: string, schema: SchemaFile): Validatio // This looks for FROM/JOIN, then optional spaces, then an identifier that might be quoted const tableRegex = /(?:FROM|JOIN)\s+([a-zA-Z0-9_."`]+)/gi; let match; - + const validTables = new Set(); for (const s of schema.schemas) { for (const t of s.tables) { @@ -69,11 +73,11 @@ export function validateGeneratedSQL(sql: string, schema: SchemaFile): Validatio let tableName = match[1]; // Strip quotes tableName = tableName.replace(/["`]/g, "").toLowerCase(); - + // Sometimes aliases are captured if not careful, but the regex only grabs the first word. // If it's a subquery like FROM (SELECT...), it will grab "(" which we ignore if (tableName === "(") continue; - + if (!validTables.has(tableName)) { return { valid: false, reason: `Table not found in schema: ${tableName}`, intent: "read" }; } diff --git a/bridge/src/connectors/README.md b/bridge/src/connectors/README.md index a94891fb..a5cdd86e 100644 --- a/bridge/src/connectors/README.md +++ b/bridge/src/connectors/README.md @@ -3,24 +3,28 @@ This folder contains database-specific connector implementations used by the bridge to execute metadata, query, migration and CRUD operations. Layout + - `postgres.ts` - PostgreSQL connector, cache manager, metadata helpers, streaming query support and PostgreSQL-specific DDL/DML behavior. - `mysql.ts` - MySQL connector for schema/table metadata, stats, migrations and query execution. - `mariadb.ts` - MariaDB connector. Keep MariaDB behavior separate when it diverges from MySQL. - `sqlite.ts` - SQLite connector using `better-sqlite3`, local file handling and SQLite-specific migration/query behavior. How it fits + - `src/services/queryExecutor.ts` routes bridge operations to the correct connector based on `DBType`. - SQL strings should come from `src/queries/*` where practical, not be duplicated inline. - Shared result shapes come from `src/types/common.ts`; database-specific config and metadata types live in `src/types/postgres.ts`, `src/types/mysql.ts` and `src/types/sqlite.ts`. - Connection config objects are built by `src/services/connectionBuilder.ts`; connectors generally create their own driver client from that config for each operation. How to add connector behavior + 1. Add database-specific SQL to `src/queries//` when the operation needs raw SQL. 2. Add or update typed method support in the relevant connector file. 3. Route the operation from `QueryExecutor` or the owning service. 4. Register any new public RPC method through a handler in `src/handlers`. Notes + - Keep connector methods focused on database interaction. Do not read UI payloads directly or handle RPC responses here. - Invalidate or bypass connector caches when an operation mutates schema, table data or migration state. - Prefer shared common types unless a database really needs extra metadata fields. diff --git a/bridge/src/connectors/mariadb.ts b/bridge/src/connectors/mariadb.ts index bfbc2fc4..301357b8 100644 --- a/bridge/src/connectors/mariadb.ts +++ b/bridge/src/connectors/mariadb.ts @@ -1,78 +1,80 @@ -import mysql, { - FieldPacket, - PoolOptions, - RowDataPacket, - PoolConnection, -} from "mysql2/promise"; +import mysql, { FieldPacket, PoolOptions, RowDataPacket, PoolConnection } from "mysql2/promise"; import { loadLocalMigrations, writeBaselineMigration } from "../utils/baselineMigration"; import crypto from "crypto"; import fs from "fs"; import { ensureDir } from "../utils/config"; import { projectStoreInstance } from "../services/projectStore"; +import { CacheEntry, CACHE_TTL, STATS_CACHE_TTL, SCHEMA_CACHE_TTL } from "../types/cache"; import { - CacheEntry, - CACHE_TTL, - STATS_CACHE_TTL, - SCHEMA_CACHE_TTL -} from "../types/cache"; -import { - TableInfo, - DBStats, - SchemaInfo, - ColumnDetail, - PrimaryKeyInfo, - ForeignKeyInfo, - IndexInfo, - UniqueConstraintInfo, - CheckConstraintInfo, - AppliedMigration, + TableInfo, + DBStats, + SchemaInfo, + ColumnDetail, + PrimaryKeyInfo, + ForeignKeyInfo, + IndexInfo, + UniqueConstraintInfo, + CheckConstraintInfo, + AppliedMigration, } from "../types/common"; import { - MySQLConfig, - EnumColumnInfo as MariaDBEnumColumnInfo, - AutoIncrementInfo as MariaDBAutoIncrementInfo, - SchemaMetadataBatch as MariaDBSchemaMetadataBatch, - MySQLAlterTableOperation as MariaDBAlterTableOperation, - MySQLDropMode as MariaDBDropMode, + MySQLConfig, + EnumColumnInfo as MariaDBEnumColumnInfo, + AutoIncrementInfo as MariaDBAutoIncrementInfo, + SchemaMetadataBatch as MariaDBSchemaMetadataBatch, + MySQLAlterTableOperation as MariaDBAlterTableOperation, + MySQLDropMode as MariaDBDropMode, } from "../types/mysql"; import { SchemaFile } from "../services/projectStore"; export type { - ColumnDetail, - TableInfo, - PrimaryKeyInfo, - ForeignKeyInfo, - IndexInfo, - UniqueConstraintInfo, - CheckConstraintInfo, - MariaDBEnumColumnInfo, - MariaDBAutoIncrementInfo, + ColumnDetail, + TableInfo, + PrimaryKeyInfo, + ForeignKeyInfo, + IndexInfo, + UniqueConstraintInfo, + CheckConstraintInfo, + MariaDBEnumColumnInfo, + MariaDBAutoIncrementInfo, }; export type { AppliedMigration } from "../types/common"; // Import MySQL queries (MariaDB uses same SQL syntax) -import { LIST_SCHEMAS, LIST_TABLES_BY_SCHEMA, LIST_TABLES_CURRENT_DB } from "../queries/mysql/schema"; -import { GET_TABLE_DETAILS, LIST_COLUMNS, KILL_QUERY, GET_CONNECTION_ID } from "../queries/mysql/tables"; -import { BATCH_GET_ALL_COLUMNS, BATCH_GET_ENUM_COLUMNS, BATCH_GET_AUTO_INCREMENTS } from "../queries/mysql/columns"; import { - GET_PRIMARY_KEYS, - BATCH_GET_PRIMARY_KEYS, - BATCH_GET_FOREIGN_KEYS, - BATCH_GET_INDEXES, - BATCH_GET_UNIQUE_CONSTRAINTS, - BATCH_GET_CHECK_CONSTRAINTS + LIST_SCHEMAS, + LIST_TABLES_BY_SCHEMA, + LIST_TABLES_CURRENT_DB, +} from "../queries/mysql/schema"; +import { + GET_TABLE_DETAILS, + LIST_COLUMNS, + KILL_QUERY, + GET_CONNECTION_ID, +} from "../queries/mysql/tables"; +import { + BATCH_GET_ALL_COLUMNS, + BATCH_GET_ENUM_COLUMNS, + BATCH_GET_AUTO_INCREMENTS, +} from "../queries/mysql/columns"; +import { + GET_PRIMARY_KEYS, + BATCH_GET_PRIMARY_KEYS, + BATCH_GET_FOREIGN_KEYS, + BATCH_GET_INDEXES, + BATCH_GET_UNIQUE_CONSTRAINTS, + BATCH_GET_CHECK_CONSTRAINTS, } from "../queries/mysql/constraints"; import { GET_DB_STATS } from "../queries/mysql/stats"; import { - CREATE_MIGRATION_TABLE, - CHECK_MIGRATIONS_EXIST, - INSERT_MIGRATION, - LIST_APPLIED_MIGRATIONS, - DELETE_MIGRATION + CREATE_MIGRATION_TABLE, + CHECK_MIGRATIONS_EXIST, + INSERT_MIGRATION, + LIST_APPLIED_MIGRATIONS, + DELETE_MIGRATION, } from "../queries/mysql/migrations"; import logger from "../services/logger"; - // ============================================ // CACHING SYSTEM FOR MARIADB CONNECTOR // ============================================ @@ -81,344 +83,343 @@ import logger from "../services/logger"; * MariaDB Cache Manager - handles all caching for MariaDB connector */ - export type MariaDBConfig = MySQLConfig & { - ssl?: boolean | { + ssl?: + | boolean + | { rejectUnauthorized: boolean; - }; -} + }; +}; class MariaDBCacheManager { - // Cache stores for different data types - private tableListCache = new Map>(); - private columnsCache = new Map>(); - private primaryKeysCache = new Map>(); - private dbStatsCache = new Map>(); - private schemasCache = new Map>(); - private tableDetailsCache = new Map>(); - private schemaMetadataBatchCache = new Map>(); - - /** - * Generate cache key from config - */ - private getConfigKey(cfg: MariaDBConfig): string { - return `${cfg.host}:${cfg.port || 3306}:${cfg.database || ""}`; - } - - /** - * Generate cache key for table-specific data - */ - private getTableKey(cfg: MariaDBConfig, schema: string, table: string): string { - return `${this.getConfigKey(cfg)}:${schema}:${table}`; - } - - /** - * Generate cache key for schema-specific data - */ - private getSchemaKey(cfg: MariaDBConfig, schema: string): string { - return `${this.getConfigKey(cfg)}:${schema}`; - } - - /** - * Check if cache entry is valid - */ - private isValid(entry: CacheEntry | undefined): boolean { - if (!entry) return false; - return Date.now() - entry.timestamp < entry.ttl; - } - - // ============ TABLE LIST CACHE ============ - getTableList(cfg: MariaDBConfig, schema?: string): TableInfo[] | null { - const key = schema ? this.getSchemaKey(cfg, schema) : this.getConfigKey(cfg); - const entry = this.tableListCache.get(key); - if (this.isValid(entry)) { - return entry!.data; - } - return null; - } - - setTableList(cfg: MariaDBConfig, data: TableInfo[], schema?: string): void { - const key = schema ? this.getSchemaKey(cfg, schema) : this.getConfigKey(cfg); - this.tableListCache.set(key, { data, timestamp: Date.now(), ttl: CACHE_TTL }); - } - - // ============ COLUMNS CACHE ============ - getColumns(cfg: MariaDBConfig, schema: string, table: string): RowDataPacket[] | null { - const key = this.getTableKey(cfg, schema, table); - const entry = this.columnsCache.get(key); - if (this.isValid(entry)) { - return entry!.data; - } - return null; + // Cache stores for different data types + private tableListCache = new Map>(); + private columnsCache = new Map>(); + private primaryKeysCache = new Map>(); + private dbStatsCache = new Map>(); + private schemasCache = new Map>(); + private tableDetailsCache = new Map>(); + private schemaMetadataBatchCache = new Map>(); + + /** + * Generate cache key from config + */ + private getConfigKey(cfg: MariaDBConfig): string { + return `${cfg.host}:${cfg.port || 3306}:${cfg.database || ""}`; + } + + /** + * Generate cache key for table-specific data + */ + private getTableKey(cfg: MariaDBConfig, schema: string, table: string): string { + return `${this.getConfigKey(cfg)}:${schema}:${table}`; + } + + /** + * Generate cache key for schema-specific data + */ + private getSchemaKey(cfg: MariaDBConfig, schema: string): string { + return `${this.getConfigKey(cfg)}:${schema}`; + } + + /** + * Check if cache entry is valid + */ + private isValid(entry: CacheEntry | undefined): boolean { + if (!entry) return false; + return Date.now() - entry.timestamp < entry.ttl; + } + + // ============ TABLE LIST CACHE ============ + getTableList(cfg: MariaDBConfig, schema?: string): TableInfo[] | null { + const key = schema ? this.getSchemaKey(cfg, schema) : this.getConfigKey(cfg); + const entry = this.tableListCache.get(key); + if (this.isValid(entry)) { + return entry!.data; } - - setColumns(cfg: MariaDBConfig, schema: string, table: string, data: RowDataPacket[]): void { - const key = this.getTableKey(cfg, schema, table); - this.columnsCache.set(key, { data, timestamp: Date.now(), ttl: CACHE_TTL }); + return null; + } + + setTableList(cfg: MariaDBConfig, data: TableInfo[], schema?: string): void { + const key = schema ? this.getSchemaKey(cfg, schema) : this.getConfigKey(cfg); + this.tableListCache.set(key, { data, timestamp: Date.now(), ttl: CACHE_TTL }); + } + + // ============ COLUMNS CACHE ============ + getColumns(cfg: MariaDBConfig, schema: string, table: string): RowDataPacket[] | null { + const key = this.getTableKey(cfg, schema, table); + const entry = this.columnsCache.get(key); + if (this.isValid(entry)) { + return entry!.data; } - - // ============ PRIMARY KEYS CACHE ============ - getPrimaryKeys(cfg: MariaDBConfig, schema: string, table: string): string[] | null { - const key = this.getTableKey(cfg, schema, table); - const entry = this.primaryKeysCache.get(key); - if (this.isValid(entry)) { - return entry!.data; - } - return null; + return null; + } + + setColumns(cfg: MariaDBConfig, schema: string, table: string, data: RowDataPacket[]): void { + const key = this.getTableKey(cfg, schema, table); + this.columnsCache.set(key, { data, timestamp: Date.now(), ttl: CACHE_TTL }); + } + + // ============ PRIMARY KEYS CACHE ============ + getPrimaryKeys(cfg: MariaDBConfig, schema: string, table: string): string[] | null { + const key = this.getTableKey(cfg, schema, table); + const entry = this.primaryKeysCache.get(key); + if (this.isValid(entry)) { + return entry!.data; } - - setPrimaryKeys(cfg: MariaDBConfig, schema: string, table: string, data: string[]): void { - const key = this.getTableKey(cfg, schema, table); - this.primaryKeysCache.set(key, { data, timestamp: Date.now(), ttl: CACHE_TTL }); + return null; + } + + setPrimaryKeys(cfg: MariaDBConfig, schema: string, table: string, data: string[]): void { + const key = this.getTableKey(cfg, schema, table); + this.primaryKeysCache.set(key, { data, timestamp: Date.now(), ttl: CACHE_TTL }); + } + + // ============ DB STATS CACHE ============ + getDBStats(cfg: MariaDBConfig): DBStats | null { + const key = this.getConfigKey(cfg); + const entry = this.dbStatsCache.get(key); + if (this.isValid(entry)) { + return entry!.data; } - - // ============ DB STATS CACHE ============ - getDBStats(cfg: MariaDBConfig): DBStats | null { - const key = this.getConfigKey(cfg); - const entry = this.dbStatsCache.get(key); - if (this.isValid(entry)) { - return entry!.data; - } - return null; + return null; + } + + setDBStats(cfg: MariaDBConfig, data: DBStats): void { + const key = this.getConfigKey(cfg); + this.dbStatsCache.set(key, { data, timestamp: Date.now(), ttl: STATS_CACHE_TTL }); + } + + // ============ SCHEMAS CACHE ============ + getSchemas(cfg: MariaDBConfig): { name: string }[] | null { + const key = this.getConfigKey(cfg); + const entry = this.schemasCache.get(key); + if (this.isValid(entry)) { + return entry!.data; } - - setDBStats(cfg: MariaDBConfig, data: DBStats): void { - const key = this.getConfigKey(cfg); - this.dbStatsCache.set(key, { data, timestamp: Date.now(), ttl: STATS_CACHE_TTL }); + return null; + } + + setSchemas(cfg: MariaDBConfig, data: { name: string }[]): void { + const key = this.getConfigKey(cfg); + this.schemasCache.set(key, { data, timestamp: Date.now(), ttl: SCHEMA_CACHE_TTL }); + } + + // ============ TABLE DETAILS CACHE ============ + getTableDetails(cfg: MariaDBConfig, schema: string, table: string): ColumnDetail[] | null { + const key = this.getTableKey(cfg, schema, table); + const entry = this.tableDetailsCache.get(key); + if (this.isValid(entry)) { + return entry!.data; } - - // ============ SCHEMAS CACHE ============ - getSchemas(cfg: MariaDBConfig): { name: string }[] | null { - const key = this.getConfigKey(cfg); - const entry = this.schemasCache.get(key); - if (this.isValid(entry)) { - return entry!.data; - } - return null; + return null; + } + + setTableDetails(cfg: MariaDBConfig, schema: string, table: string, data: ColumnDetail[]): void { + const key = this.getTableKey(cfg, schema, table); + this.tableDetailsCache.set(key, { data, timestamp: Date.now(), ttl: CACHE_TTL }); + } + + // ============ SCHEMA METADATA BATCH CACHE ============ + getSchemaMetadataBatch(cfg: MariaDBConfig, schema: string): MariaDBSchemaMetadataBatch | null { + const key = this.getSchemaKey(cfg, schema); + const entry = this.schemaMetadataBatchCache.get(key); + if (this.isValid(entry)) { + return entry!.data; } + return null; + } - setSchemas(cfg: MariaDBConfig, data: { name: string }[]): void { - const key = this.getConfigKey(cfg); - this.schemasCache.set(key, { data, timestamp: Date.now(), ttl: SCHEMA_CACHE_TTL }); + setSchemaMetadataBatch( + cfg: MariaDBConfig, + schema: string, + data: MariaDBSchemaMetadataBatch, + ): void { + const key = this.getSchemaKey(cfg, schema); + this.schemaMetadataBatchCache.set(key, { data, timestamp: Date.now(), ttl: CACHE_TTL }); + } + + // ============ CACHE MANAGEMENT ============ + + /** + * Clear all caches for a specific database connection + */ + clearForConnection(cfg: MariaDBConfig): void { + const configKey = this.getConfigKey(cfg); + + // Clear all entries that start with this config key + for (const [key] of this.tableListCache) { + if (key.startsWith(configKey)) this.tableListCache.delete(key); } - - // ============ TABLE DETAILS CACHE ============ - getTableDetails(cfg: MariaDBConfig, schema: string, table: string): ColumnDetail[] | null { - const key = this.getTableKey(cfg, schema, table); - const entry = this.tableDetailsCache.get(key); - if (this.isValid(entry)) { - return entry!.data; - } - return null; + for (const [key] of this.columnsCache) { + if (key.startsWith(configKey)) this.columnsCache.delete(key); } - - setTableDetails(cfg: MariaDBConfig, schema: string, table: string, data: ColumnDetail[]): void { - const key = this.getTableKey(cfg, schema, table); - this.tableDetailsCache.set(key, { data, timestamp: Date.now(), ttl: CACHE_TTL }); + for (const [key] of this.primaryKeysCache) { + if (key.startsWith(configKey)) this.primaryKeysCache.delete(key); } - - // ============ SCHEMA METADATA BATCH CACHE ============ - getSchemaMetadataBatch(cfg: MariaDBConfig, schema: string): MariaDBSchemaMetadataBatch | null { - const key = this.getSchemaKey(cfg, schema); - const entry = this.schemaMetadataBatchCache.get(key); - if (this.isValid(entry)) { - return entry!.data; - } - return null; + for (const [key] of this.tableDetailsCache) { + if (key.startsWith(configKey)) this.tableDetailsCache.delete(key); } - - setSchemaMetadataBatch(cfg: MariaDBConfig, schema: string, data: MariaDBSchemaMetadataBatch): void { - const key = this.getSchemaKey(cfg, schema); - this.schemaMetadataBatchCache.set(key, { data, timestamp: Date.now(), ttl: CACHE_TTL }); + for (const [key] of this.schemaMetadataBatchCache) { + if (key.startsWith(configKey)) this.schemaMetadataBatchCache.delete(key); } - // ============ CACHE MANAGEMENT ============ - - /** - * Clear all caches for a specific database connection - */ - clearForConnection(cfg: MariaDBConfig): void { - const configKey = this.getConfigKey(cfg); - - // Clear all entries that start with this config key - for (const [key] of this.tableListCache) { - if (key.startsWith(configKey)) this.tableListCache.delete(key); - } - for (const [key] of this.columnsCache) { - if (key.startsWith(configKey)) this.columnsCache.delete(key); - } - for (const [key] of this.primaryKeysCache) { - if (key.startsWith(configKey)) this.primaryKeysCache.delete(key); - } - for (const [key] of this.tableDetailsCache) { - if (key.startsWith(configKey)) this.tableDetailsCache.delete(key); - } - for (const [key] of this.schemaMetadataBatchCache) { - if (key.startsWith(configKey)) this.schemaMetadataBatchCache.delete(key); - } - - this.dbStatsCache.delete(configKey); - this.schemasCache.delete(configKey); - } - - /** - * Clear table-specific cache (useful after DDL operations) - */ - clearTableCache(cfg: MariaDBConfig, schema: string, table: string): void { - const key = this.getTableKey(cfg, schema, table); - this.columnsCache.delete(key); - this.primaryKeysCache.delete(key); - this.tableDetailsCache.delete(key); - } - - /** - * Clear all caches - */ - clearAll(): void { - this.tableListCache.clear(); - this.columnsCache.clear(); - this.primaryKeysCache.clear(); - this.dbStatsCache.clear(); - this.schemasCache.clear(); - this.tableDetailsCache.clear(); - this.schemaMetadataBatchCache.clear(); - } - - /** - * Get cache statistics - */ - getStats(): { - tableLists: number; - columns: number; - primaryKeys: number; - dbStats: number; - schemas: number; - tableDetails: number; - schemaMetadataBatch: number; - } { - return { - tableLists: this.tableListCache.size, - columns: this.columnsCache.size, - primaryKeys: this.primaryKeysCache.size, - dbStats: this.dbStatsCache.size, - schemas: this.schemasCache.size, - tableDetails: this.tableDetailsCache.size, - schemaMetadataBatch: this.schemaMetadataBatchCache.size, - }; - } + this.dbStatsCache.delete(configKey); + this.schemasCache.delete(configKey); + } + + /** + * Clear table-specific cache (useful after DDL operations) + */ + clearTableCache(cfg: MariaDBConfig, schema: string, table: string): void { + const key = this.getTableKey(cfg, schema, table); + this.columnsCache.delete(key); + this.primaryKeysCache.delete(key); + this.tableDetailsCache.delete(key); + } + + /** + * Clear all caches + */ + clearAll(): void { + this.tableListCache.clear(); + this.columnsCache.clear(); + this.primaryKeysCache.clear(); + this.dbStatsCache.clear(); + this.schemasCache.clear(); + this.tableDetailsCache.clear(); + this.schemaMetadataBatchCache.clear(); + } + + /** + * Get cache statistics + */ + getStats(): { + tableLists: number; + columns: number; + primaryKeys: number; + dbStats: number; + schemas: number; + tableDetails: number; + schemaMetadataBatch: number; + } { + return { + tableLists: this.tableListCache.size, + columns: this.columnsCache.size, + primaryKeys: this.primaryKeysCache.size, + dbStats: this.dbStatsCache.size, + schemas: this.schemasCache.size, + tableDetails: this.tableDetailsCache.size, + schemaMetadataBatch: this.schemaMetadataBatchCache.size, + }; + } } // Singleton cache manager instance export const mariadbCache = new MariaDBCacheManager(); // Legacy cache support (for backward compatibility) -const tableListCache = new Map< - string, - { data: TableInfo[]; timestamp: number } ->(); +const tableListCache = new Map(); function getCacheKey(cfg: MariaDBConfig): string { - return `${cfg.host}:${cfg.port}:${cfg.database}`; + return `${cfg.host}:${cfg.port}:${cfg.database}`; } - export function createPoolConfig(cfg: MariaDBConfig): PoolOptions { - - if (cfg.ssl === true) { - const config = { - host: cfg.host, - port: cfg.port ?? 3306, - user: cfg.user, - password: cfg.password, - database: cfg.database, - ssl: { - rejectUnauthorized: false, - minVersion: 'TLSv1.2' - } - }; - return config; - } - return { - host: cfg.host, - port: cfg.port ?? 3306, - user: cfg.user, - password: cfg.password, - database: cfg.database, + if (cfg.ssl === true) { + const config = { + host: cfg.host, + port: cfg.port ?? 3306, + user: cfg.user, + password: cfg.password, + database: cfg.database, + ssl: { + rejectUnauthorized: false, + minVersion: "TLSv1.2", + }, }; - + return config; + } + return { + host: cfg.host, + port: cfg.port ?? 3306, + user: cfg.user, + password: cfg.password, + database: cfg.database, + }; } export async function testConnection( - cfg: MariaDBConfig -): Promise<{ ok: boolean; message?: string; status: 'connected' | 'disconnected' }> { - let connection; - try { - const poolConfig = createPoolConfig(cfg); - connection = await mysql.createConnection(poolConfig); - return { ok: true, status: 'connected', message: "Connection successful" }; - } catch (err) { - logger.error({ error: (err as Error).message }, '[MariaDB] Connection error'); - return { ok: false, message: (err as Error).message, status: 'disconnected' }; - } finally { - if (connection) { - try { - await connection.end(); - } catch (e) { - // Ignore - } - } + cfg: MariaDBConfig, +): Promise<{ ok: boolean; message?: string; status: "connected" | "disconnected" }> { + let connection; + try { + const poolConfig = createPoolConfig(cfg); + connection = await mysql.createConnection(poolConfig); + return { ok: true, status: "connected", message: "Connection successful" }; + } catch (err) { + logger.error({ error: (err as Error).message }, "[MariaDB] Connection error"); + return { ok: false, message: (err as Error).message, status: "disconnected" }; + } finally { + if (connection) { + try { + await connection.end(); + } catch (e) { + // Ignore + } } + } } export async function fetchTableData( - cfg: MariaDBConfig, - schemaName: string, - tableName: string, - limit: number, - page: number + cfg: MariaDBConfig, + schemaName: string, + tableName: string, + limit: number, + page: number, ): Promise<{ rows: RowDataPacket[]; total: number }> { - const pool = mysql.createPool(createPoolConfig(cfg)); - let connection: PoolConnection | null = null; + const pool = mysql.createPool(createPoolConfig(cfg)); + let connection: PoolConnection | null = null; - try { - connection = await pool.getConnection(); + try { + connection = await pool.getConnection(); - const safeSchema = `\`${schemaName.replace(/`/g, "``")}\``; - const safeTable = `\`${tableName.replace(/`/g, "``")}\``; - const offset = (page - 1) * limit; + const safeSchema = `\`${schemaName.replace(/`/g, "``")}\``; + const safeTable = `\`${tableName.replace(/`/g, "``")}\``; + const offset = (page - 1) * limit; - // Get primary keys - const pkColumns = await listPrimaryKeys(cfg, schemaName, tableName); + // Get primary keys + const pkColumns = await listPrimaryKeys(cfg, schemaName, tableName); - let orderBy = ""; - if (pkColumns.length > 0) { - const safePks = pkColumns.map(col => `\`${col.replace(/`/g, "``")}\``); - orderBy = `ORDER BY ${safePks.join(", ")}`; - } else { - const colQuery = ` + let orderBy = ""; + if (pkColumns.length > 0) { + const safePks = pkColumns.map((col) => `\`${col.replace(/`/g, "``")}\``); + orderBy = `ORDER BY ${safePks.join(", ")}`; + } else { + const colQuery = ` SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION; `; - const [colRows] = await connection.execute(colQuery, [ - schemaName, - tableName, - ]); - const safeCols = colRows.map(r => `\`${r.COLUMN_NAME}\``); - orderBy = safeCols.length ? `ORDER BY ${safeCols.join(", ")}` : ""; - } + const [colRows] = await connection.execute(colQuery, [ + schemaName, + tableName, + ]); + const safeCols = colRows.map((r) => `\`${r.COLUMN_NAME}\``); + orderBy = safeCols.length ? `ORDER BY ${safeCols.join(", ")}` : ""; + } - // Count query - const countQuery = ` + // Count query + const countQuery = ` SELECT COUNT(*) AS total FROM ${safeSchema}.${safeTable}; `; - const [countRows] = await connection.execute(countQuery); - const total = Number(countRows[0].total); + const [countRows] = await connection.execute(countQuery); + const total = Number(countRows[0].total); - const dataQuery = ` + const dataQuery = ` SELECT * FROM ${safeSchema}.${safeTable} ${orderBy} @@ -426,395 +427,374 @@ export async function fetchTableData( OFFSET ${Number(offset)}; `; - const [rows] = await connection.execute(dataQuery); + const [rows] = await connection.execute(dataQuery); - return { rows, total }; - } catch (error) { - throw new Error(`Failed to fetch data: ${(error as Error).message}`); - } finally { - if (connection) connection.release(); - await pool.end(); - } + return { rows, total }; + } catch (error) { + throw new Error(`Failed to fetch data: ${(error as Error).message}`); + } finally { + if (connection) connection.release(); + await pool.end(); + } } - export async function listColumns( - cfg: MariaDBConfig, - tableName: string, - schemaName?: string + cfg: MariaDBConfig, + tableName: string, + schemaName?: string, ): Promise { - // Check cache first - if (schemaName) { - const cached = mariadbCache.getColumns(cfg, schemaName, tableName); - if (cached !== null) { - return cached; - } + // Check cache first + if (schemaName) { + const cached = mariadbCache.getColumns(cfg, schemaName, tableName); + if (cached !== null) { + return cached; } + } - const pool = mysql.createPool(createPoolConfig(cfg)); - let connection: PoolConnection | null = null; - - try { - connection = await pool.getConnection(); + const pool = mysql.createPool(createPoolConfig(cfg)); + let connection: PoolConnection | null = null; - const [rows] = await connection.execute(LIST_COLUMNS, [ - schemaName, - tableName, - ]); + try { + connection = await pool.getConnection(); - // Cache the result - if (schemaName) { - mariadbCache.setColumns(cfg, schemaName, tableName, rows); - } + const [rows] = await connection.execute(LIST_COLUMNS, [schemaName, tableName]); - return rows; - } catch (error) { - throw new Error(`Failed to list columns: ${(error as Error).message}`); - } finally { - if (connection) connection.release(); - await pool.end(); + // Cache the result + if (schemaName) { + mariadbCache.setColumns(cfg, schemaName, tableName, rows); } + + return rows; + } catch (error) { + throw new Error(`Failed to list columns: ${(error as Error).message}`); + } finally { + if (connection) connection.release(); + await pool.end(); + } } export async function mariadbKillQuery(cfg: MariaDBConfig, targetPid: number) { - const conn = await mysql.createConnection(createPoolConfig(cfg)); + const conn = await mysql.createConnection(createPoolConfig(cfg)); + try { + await conn.execute(KILL_QUERY, [targetPid]); + return true; + } catch (error) { + return false; + } finally { try { - await conn.execute(KILL_QUERY, [targetPid]); - return true; - } catch (error) { - return false; - } finally { - try { - await conn.end(); - } catch (e) { - // Ignore - } + await conn.end(); + } catch (e) { + // Ignore } + } } export async function listPrimaryKeys( - cfg: MariaDBConfig, - schemaName: string, - tableName: string + cfg: MariaDBConfig, + schemaName: string, + tableName: string, ): Promise { - // Check cache first - const cached = mariadbCache.getPrimaryKeys(cfg, schemaName, tableName); - if (cached !== null) { - return cached; - } + // Check cache first + const cached = mariadbCache.getPrimaryKeys(cfg, schemaName, tableName); + if (cached !== null) { + return cached; + } + + const connection = await mysql.createConnection(createPoolConfig(cfg)); + + try { + const [rows] = await connection.execute(GET_PRIMARY_KEYS, [ + schemaName, + tableName, + ]); + + const result = rows.map((row) => row.COLUMN_NAME as string); + + // Cache the result + mariadbCache.setPrimaryKeys(cfg, schemaName, tableName, result); + + return result; + } catch (error) { + throw new Error(`Failed to list primary keys: ${(error as Error).message}`); + } finally { + await connection.end(); + } +} - const connection = await mysql.createConnection(createPoolConfig(cfg)); +export function streamQueryCancelable( + cfg: MariaDBConfig, + sql: string, + batchSize: number, + onBatch: (rows: RowDataPacket[], columns: FieldPacket[]) => Promise | void, + onDone?: () => void, +) { + let query: any = null; + let finished = false; + let cancelled = false; + let backendPid: number | null = null; + + const pool = mysql.createPool(createPoolConfig(cfg)); + + const promise = (async () => { + let conn: PoolConnection | null = null; try { - const [rows] = await connection.execute(GET_PRIMARY_KEYS, [ - schemaName, - tableName, - ]); + conn = await pool.getConnection(); - const result = rows.map((row) => row.COLUMN_NAME as string); + const [pidRows] = await conn.execute(GET_CONNECTION_ID); + backendPid = (pidRows as any[])[0].pid; - // Cache the result - mariadbCache.setPrimaryKeys(cfg, schemaName, tableName, result); + const raw = (conn as any).connection; + query = raw.query(sql); - return result; - } catch (error) { - throw new Error(`Failed to list primary keys: ${(error as Error).message}`); - } finally { - await connection.end(); - } -} + let columns: FieldPacket[] | null = null; + let buffer: RowDataPacket[] = []; + const flush = async () => { + if (buffer.length === 0) return; + const batch = buffer.splice(0, buffer.length); + await onBatch(batch, columns || []); + }; + await new Promise((resolve, reject) => { + query.on("fields", (flds: FieldPacket[]) => { + columns = flds; + }); -export function streamQueryCancelable( - cfg: MariaDBConfig, - sql: string, - batchSize: number, - onBatch: ( - rows: RowDataPacket[], - columns: FieldPacket[] - ) => Promise | void, - onDone?: () => void -) { - let query: any = null; - let finished = false; - let cancelled = false; - let backendPid: number | null = null; - - const pool = mysql.createPool(createPoolConfig(cfg)); - - const promise = (async () => { - let conn: PoolConnection | null = null; - - try { - conn = await pool.getConnection(); - - const [pidRows] = await conn.execute(GET_CONNECTION_ID); - backendPid = (pidRows as any[])[0].pid; - - const raw = (conn as any).connection; - query = raw.query(sql); - - let columns: FieldPacket[] | null = null; - let buffer: RowDataPacket[] = []; - - const flush = async () => { - if (buffer.length === 0) return; - const batch = buffer.splice(0, buffer.length); - await onBatch(batch, columns || []); - }; - - await new Promise((resolve, reject) => { - query.on("fields", (flds: FieldPacket[]) => { - columns = flds; - }); - - query.on("result", async (row: RowDataPacket) => { - if (cancelled) { - reject(new Error("Query cancelled")); - return; - } - - buffer.push(row); - - if (buffer.length >= batchSize) { - query.pause(); - await flush(); - query.resume(); - } - }); - - query.on("end", async () => { - await flush(); - finished = true; - onDone?.(); - resolve(); - }); - - query.on("error", (err: Error) => { - reject(err); - }); - }); - } finally { - conn?.release(); - await pool.end(); - } - })(); + query.on("result", async (row: RowDataPacket) => { + if (cancelled) { + reject(new Error("Query cancelled")); + return; + } - async function cancel() { - if (finished || cancelled) return; - cancelled = true; + buffer.push(row); - if (backendPid) { - await mariadbKillQuery(cfg, backendPid).catch(() => { }); - } + if (buffer.length >= batchSize) { + query.pause(); + await flush(); + query.resume(); + } + }); + + query.on("end", async () => { + await flush(); + finished = true; + onDone?.(); + resolve(); + }); + + query.on("error", (err: Error) => { + reject(err); + }); + }); + } finally { + conn?.release(); + await pool.end(); + } + })(); + + async function cancel() { + if (finished || cancelled) return; + cancelled = true; - query?.emit("error", new Error("Cancelled")); + if (backendPid) { + await mariadbKillQuery(cfg, backendPid).catch(() => {}); } - return { promise, cancel }; + query?.emit("error", new Error("Cancelled")); + } + + return { promise, cancel }; } export async function getDBStats(cfg: MariaDBConfig): Promise<{ - total_tables: number; - total_db_size_mb: number; - total_rows: number; + total_tables: number; + total_db_size_mb: number; + total_rows: number; }> { - // Check cache first - this is called frequently! - const cached = mariadbCache.getDBStats(cfg); - if (cached !== null) { - return cached; - } + // Check cache first - this is called frequently! + const cached = mariadbCache.getDBStats(cfg); + if (cached !== null) { + return cached; + } - const pool = mysql.createPool(createPoolConfig(cfg)); - let connection: PoolConnection | null = null; + const pool = mysql.createPool(createPoolConfig(cfg)); + let connection: PoolConnection | null = null; - try { - connection = await pool.getConnection(); + try { + connection = await pool.getConnection(); - const [rows] = await connection.execute(GET_DB_STATS); + const [rows] = await connection.execute(GET_DB_STATS); - const result = rows[0] as { - total_tables: number; - total_db_size_mb: number; - total_rows: number; - }; + const result = rows[0] as { + total_tables: number; + total_db_size_mb: number; + total_rows: number; + }; - // Cache the result (shorter TTL since stats change) - mariadbCache.setDBStats(cfg, result); + // Cache the result (shorter TTL since stats change) + mariadbCache.setDBStats(cfg, result); - return result; - } catch (error) { - throw new Error( - `Failed to fetch MariaDB database stats: ${(error as Error).message}` - ); - } finally { - if (connection) { - try { - connection.release(); - } catch (e) { - // Ignore - } - } - try { - await pool.end(); - } catch (e) { - // Ignore - } + return result; + } catch (error) { + throw new Error(`Failed to fetch MariaDB database stats: ${(error as Error).message}`); + } finally { + if (connection) { + try { + connection.release(); + } catch (e) { + // Ignore + } + } + try { + await pool.end(); + } catch (e) { + // Ignore } + } } -export async function listSchemas( - cfg: MariaDBConfig -): Promise<{ name: string }[]> { - // Check cache first - const cached = mariadbCache.getSchemas(cfg); - if (cached !== null) { - return cached; - } +export async function listSchemas(cfg: MariaDBConfig): Promise<{ name: string }[]> { + // Check cache first + const cached = mariadbCache.getSchemas(cfg); + if (cached !== null) { + return cached; + } - const pool = mysql.createPool(createPoolConfig(cfg)); - let connection: PoolConnection | null = null; + const pool = mysql.createPool(createPoolConfig(cfg)); + let connection: PoolConnection | null = null; - try { - connection = await pool.getConnection(); + try { + connection = await pool.getConnection(); - const [rows] = await connection.execute(LIST_SCHEMAS); - const result = rows as { name: string }[]; + const [rows] = await connection.execute(LIST_SCHEMAS); + const result = rows as { name: string }[]; - // Cache the result (longer TTL since schemas rarely change) - mariadbCache.setSchemas(cfg, result); + // Cache the result (longer TTL since schemas rarely change) + mariadbCache.setSchemas(cfg, result); - return result; - } catch (error) { - throw new Error(`Failed to list schemas: ${(error as Error).message}`); - } finally { - if (connection) { - try { - connection.release(); - } catch (e) { - // Ignore - } - } - try { - await pool.end(); - } catch (e) { - // Ignore - } + return result; + } catch (error) { + throw new Error(`Failed to list schemas: ${(error as Error).message}`); + } finally { + if (connection) { + try { + connection.release(); + } catch (e) { + // Ignore + } } + try { + await pool.end(); + } catch (e) { + // Ignore + } + } } -export async function listTables( - cfg: MariaDBConfig, - schemaName?: string -): Promise { - // Check new cache manager first - const cached = mariadbCache.getTableList(cfg, schemaName); - if (cached !== null) { - return cached; - } +export async function listTables(cfg: MariaDBConfig, schemaName?: string): Promise { + // Check new cache manager first + const cached = mariadbCache.getTableList(cfg, schemaName); + if (cached !== null) { + return cached; + } - const pool = mysql.createPool(createPoolConfig(cfg)); - let connection: PoolConnection | null = null; + const pool = mysql.createPool(createPoolConfig(cfg)); + let connection: PoolConnection | null = null; - try { - connection = await pool.getConnection(); - - // CRITICAL OPTIMIZATION: Query only the current database schema - // This avoids scanning the entire information_schema which can be VERY slow - let query: string; - let queryParams: string[] = []; - - if (schemaName) { - // If specific schema requested, only fetch that - query = LIST_TABLES_BY_SCHEMA; - queryParams = [schemaName]; - } else { - // Otherwise, only fetch tables from the CURRENT database (not all databases!) - query = LIST_TABLES_CURRENT_DB; - } + try { + connection = await pool.getConnection(); - const [rows] = await connection.execute( - query, - queryParams - ); + // CRITICAL OPTIMIZATION: Query only the current database schema + // This avoids scanning the entire information_schema which can be VERY slow + let query: string; + let queryParams: string[] = []; - const result = rows as TableInfo[]; + if (schemaName) { + // If specific schema requested, only fetch that + query = LIST_TABLES_BY_SCHEMA; + queryParams = [schemaName]; + } else { + // Otherwise, only fetch tables from the CURRENT database (not all databases!) + query = LIST_TABLES_CURRENT_DB; + } - // Cache the result using new cache manager - mariadbCache.setTableList(cfg, result, schemaName); + const [rows] = await connection.execute(query, queryParams); - return result; - } catch (error) { - console.error("[MariaDB] listTables error:", error); - throw new Error(`Failed to list tables: ${(error as Error).message}`); - } finally { - if (connection) { - try { - connection.release(); - } catch (e) { - // Ignore - } - } - try { - await pool.end(); - } catch (e) { - // Ignore - } + const result = rows as TableInfo[]; + + // Cache the result using new cache manager + mariadbCache.setTableList(cfg, result, schemaName); + + return result; + } catch (error) { + console.error("[MariaDB] listTables error:", error); + throw new Error(`Failed to list tables: ${(error as Error).message}`); + } finally { + if (connection) { + try { + connection.release(); + } catch (e) { + // Ignore + } } + try { + await pool.end(); + } catch (e) { + // Ignore + } + } } // Function to clear cache for a specific database (call after schema changes) export function clearTableListCache(cfg: MariaDBConfig) { - mariadbCache.clearForConnection(cfg); + mariadbCache.clearForConnection(cfg); } export async function getTableDetails( - cfg: MariaDBConfig, - schemaName: string, - tableName: string + cfg: MariaDBConfig, + schemaName: string, + tableName: string, ): Promise { - // Check cache first - const cached = mariadbCache.getTableDetails(cfg, schemaName, tableName); - if (cached !== null) { - return cached; + // Check cache first + const cached = mariadbCache.getTableDetails(cfg, schemaName, tableName); + if (cached !== null) { + return cached; + } + + const pool = mysql.createPool(createPoolConfig(cfg)); + let connection: PoolConnection | null = null; + + try { + connection = await pool.getConnection(); + + const [rows] = await connection.execute(GET_TABLE_DETAILS, [ + schemaName, + tableName, + ]); + + const result = rows as ColumnDetail[]; + + // Cache the result + mariadbCache.setTableDetails(cfg, schemaName, tableName, result); + + return result; + } catch (error) { + throw new Error(`Failed to fetch table details: ${(error as Error).message}`); + } finally { + if (connection) { + try { + connection.release(); + } catch (e) { + // Ignore + } } - - const pool = mysql.createPool(createPoolConfig(cfg)); - let connection: PoolConnection | null = null; - try { - connection = await pool.getConnection(); - - const [rows] = await connection.execute(GET_TABLE_DETAILS, [ - schemaName, - tableName, - ]); - - const result = rows as ColumnDetail[]; - - // Cache the result - mariadbCache.setTableDetails(cfg, schemaName, tableName, result); - - return result; - } catch (error) { - throw new Error( - `Failed to fetch table details: ${(error as Error).message}` - ); - } finally { - if (connection) { - try { - connection.release(); - } catch (e) { - // Ignore - } - } - try { - await pool.end(); - } catch (e) { - // Ignore - } + await pool.end(); + } catch (e) { + // Ignore } + } } // ============================================ @@ -824,285 +804,287 @@ export async function getTableDetails( /** * Fetch all schema metadata in a single batch using parallel queries. * This is much faster than making individual queries per table. - * + * * Note: MariaDB doesn't have true sequences or standalone enum types like PostgreSQL. * - Auto-increment columns are MariaDB's equivalent to sequences * - Enum columns are defined inline in table definitions */ export async function getSchemaMetadataBatch( - cfg: MariaDBConfig, - schemaName: string + cfg: MariaDBConfig, + schemaName: string, ): Promise { - // Check cache first - const cached = mariadbCache.getSchemaMetadataBatch(cfg, schemaName); - if (cached !== null) { - return cached; + // Check cache first + const cached = mariadbCache.getSchemaMetadataBatch(cfg, schemaName); + if (cached !== null) { + return cached; + } + + const pool = mysql.createPool(createPoolConfig(cfg)); + let connection: PoolConnection | null = null; + + try { + connection = await pool.getConnection(); + + // Execute all queries in parallel using imported queries + const [ + columnsResult, + primaryKeysResult, + foreignKeysResult, + indexesResult, + uniqueResult, + checksResult, + enumColumnsResult, + autoIncrementsResult, + ] = await Promise.all([ + // 1. All columns in schema with PK/FK info + connection.execute(BATCH_GET_ALL_COLUMNS, [schemaName, schemaName]), + + // 2. All primary keys in schema + connection.execute(BATCH_GET_PRIMARY_KEYS, [schemaName]), + + // 3. All foreign keys in schema + connection.execute(BATCH_GET_FOREIGN_KEYS, [schemaName]), + + // 4. All indexes in schema + connection.execute(BATCH_GET_INDEXES, [schemaName]), + + // 5. All unique constraints in schema (exclude primary keys) + connection.execute(BATCH_GET_UNIQUE_CONSTRAINTS, [schemaName]), + + // 6. All check constraints in schema (MariaDB 10.2.1+) + connection + .execute(BATCH_GET_CHECK_CONSTRAINTS, [schemaName]) + .catch(() => [[], []]), + + // 7. All enum columns in schema (MariaDB defines enums inline) + connection.execute(BATCH_GET_ENUM_COLUMNS, [schemaName]), + + // 8. All auto_increment columns (MariaDB's equivalent to sequences) + connection.execute(BATCH_GET_AUTO_INCREMENTS, [schemaName]), + ]); + + const columns = columnsResult[0] as RowDataPacket[]; + const primaryKeys = primaryKeysResult[0] as RowDataPacket[]; + const foreignKeys = foreignKeysResult[0] as RowDataPacket[]; + const indexes = indexesResult[0] as RowDataPacket[]; + const uniqueConstraints = uniqueResult[0] as RowDataPacket[]; + const checkConstraints = (checksResult[0] || []) as RowDataPacket[]; + const enumColumns = enumColumnsResult[0] as RowDataPacket[]; + const autoIncrements = autoIncrementsResult[0] as RowDataPacket[]; + + // Group results by table + const tables = new Map< + string, + { + columns: ColumnDetail[]; + primaryKeys: PrimaryKeyInfo[]; + foreignKeys: ForeignKeyInfo[]; + indexes: IndexInfo[]; + uniqueConstraints: UniqueConstraintInfo[]; + checkConstraints: CheckConstraintInfo[]; + } + >(); + + // Process columns + for (const row of columns) { + if (!tables.has(row.table_name)) { + tables.set(row.table_name, { + columns: [], + primaryKeys: [], + foreignKeys: [], + indexes: [], + uniqueConstraints: [], + checkConstraints: [], + }); + } + tables.get(row.table_name)!.columns.push({ + name: row.name, + type: row.type, + not_nullable: Boolean(row.not_nullable), + default_value: row.default_value, + is_primary_key: Boolean(row.is_primary_key), + is_foreign_key: Boolean(row.is_foreign_key), + is_unique: Boolean(row.is_unique), + is_serial: Boolean(row.is_serial), + comment: row.comment, + check_constraint: row.check_constraint, + ordinal_position: row.ordinal_position, + }); } - const pool = mysql.createPool(createPoolConfig(cfg)); - let connection: PoolConnection | null = null; - - try { - connection = await pool.getConnection(); - - // Execute all queries in parallel using imported queries - const [ - columnsResult, - primaryKeysResult, - foreignKeysResult, - indexesResult, - uniqueResult, - checksResult, - enumColumnsResult, - autoIncrementsResult - ] = await Promise.all([ - // 1. All columns in schema with PK/FK info - connection.execute(BATCH_GET_ALL_COLUMNS, [schemaName, schemaName]), - - // 2. All primary keys in schema - connection.execute(BATCH_GET_PRIMARY_KEYS, [schemaName]), - - // 3. All foreign keys in schema - connection.execute(BATCH_GET_FOREIGN_KEYS, [schemaName]), - - // 4. All indexes in schema - connection.execute(BATCH_GET_INDEXES, [schemaName]), - - // 5. All unique constraints in schema (exclude primary keys) - connection.execute(BATCH_GET_UNIQUE_CONSTRAINTS, [schemaName]), - - // 6. All check constraints in schema (MariaDB 10.2.1+) - connection.execute(BATCH_GET_CHECK_CONSTRAINTS, [schemaName]).catch(() => [[], []]), - - // 7. All enum columns in schema (MariaDB defines enums inline) - connection.execute(BATCH_GET_ENUM_COLUMNS, [schemaName]), - - // 8. All auto_increment columns (MariaDB's equivalent to sequences) - connection.execute(BATCH_GET_AUTO_INCREMENTS, [schemaName]) - ]); - - const columns = columnsResult[0] as RowDataPacket[]; - const primaryKeys = primaryKeysResult[0] as RowDataPacket[]; - const foreignKeys = foreignKeysResult[0] as RowDataPacket[]; - const indexes = indexesResult[0] as RowDataPacket[]; - const uniqueConstraints = uniqueResult[0] as RowDataPacket[]; - const checkConstraints = (checksResult[0] || []) as RowDataPacket[]; - const enumColumns = enumColumnsResult[0] as RowDataPacket[]; - const autoIncrements = autoIncrementsResult[0] as RowDataPacket[]; - - // Group results by table - const tables = new Map(); - - // Process columns - for (const row of columns) { - if (!tables.has(row.table_name)) { - tables.set(row.table_name, { - columns: [], - primaryKeys: [], - foreignKeys: [], - indexes: [], - uniqueConstraints: [], - checkConstraints: [] - }); - } - tables.get(row.table_name)!.columns.push({ - name: row.name, - type: row.type, - not_nullable: Boolean(row.not_nullable), - default_value: row.default_value, - is_primary_key: Boolean(row.is_primary_key), - is_foreign_key: Boolean(row.is_foreign_key), - is_unique: Boolean(row.is_unique), - is_serial: Boolean(row.is_serial), - comment: row.comment, - check_constraint: row.check_constraint, - ordinal_position: row.ordinal_position - }); - } - - // Process primary keys - for (const row of primaryKeys) { - if (tables.has(row.table_name)) { - tables.get(row.table_name)!.primaryKeys.push({ - column_name: row.column_name - }); - } - } - - // Process foreign keys - for (const row of foreignKeys) { - if (tables.has(row.source_table)) { - tables.get(row.source_table)!.foreignKeys.push({ - constraint_name: row.constraint_name, - source_schema: row.source_schema, - source_table: row.source_table, - source_column: row.source_column, - target_schema: row.target_schema, - target_table: row.target_table, - target_column: row.target_column, - update_rule: row.update_rule, - delete_rule: row.delete_rule - }); - } - } - - // Process indexes - for (const row of indexes) { - if (tables.has(row.table_name)) { - tables.get(row.table_name)!.indexes.push({ - table_name: row.table_name, - index_name: row.index_name, - column_name: row.column_name, - is_unique: Boolean(row.is_unique), - is_primary: Boolean(row.is_primary), - index_type: row.index_type, - seq_in_index: row.seq_in_index - }); - } - } + // Process primary keys + for (const row of primaryKeys) { + if (tables.has(row.table_name)) { + tables.get(row.table_name)!.primaryKeys.push({ + column_name: row.column_name, + }); + } + } - // Process unique constraints - for (const row of uniqueConstraints) { - if (tables.has(row.table_name)) { - tables.get(row.table_name)!.uniqueConstraints.push({ - constraint_name: row.constraint_name, - table_schema: row.table_schema, - table_name: row.table_name, - column_name: row.column_name, - ordinal_position: row.ordinal_position - }); - } - } + // Process foreign keys + for (const row of foreignKeys) { + if (tables.has(row.source_table)) { + tables.get(row.source_table)!.foreignKeys.push({ + constraint_name: row.constraint_name, + source_schema: row.source_schema, + source_table: row.source_table, + source_column: row.source_column, + target_schema: row.target_schema, + target_table: row.target_table, + target_column: row.target_column, + update_rule: row.update_rule, + delete_rule: row.delete_rule, + }); + } + } - // Process check constraints - for (const row of checkConstraints) { - if (tables.has(row.table_name)) { - tables.get(row.table_name)!.checkConstraints.push({ - constraint_name: row.constraint_name, - table_schema: row.table_schema, - table_name: row.table_name, - check_clause: row.check_clause - }); - } - } + // Process indexes + for (const row of indexes) { + if (tables.has(row.table_name)) { + tables.get(row.table_name)!.indexes.push({ + table_name: row.table_name, + index_name: row.index_name, + column_name: row.column_name, + is_unique: Boolean(row.is_unique), + is_primary: Boolean(row.is_primary), + index_type: row.index_type, + seq_in_index: row.seq_in_index, + }); + } + } - // Process enum columns - extract values from ENUM('val1','val2',...) - const processedEnumColumns: MariaDBEnumColumnInfo[] = enumColumns.map(row => { - const match = row.column_type.match(/^enum\((.+)\)$/i); - let enumValues: string[] = []; - if (match) { - // Parse enum values: 'val1','val2','val3' - enumValues = match[1].split(',').map((v: string) => v.trim().replace(/^'|'$/g, '')); - } - return { - table_name: row.table_name, - column_name: row.column_name, - enum_values: enumValues - }; + // Process unique constraints + for (const row of uniqueConstraints) { + if (tables.has(row.table_name)) { + tables.get(row.table_name)!.uniqueConstraints.push({ + constraint_name: row.constraint_name, + table_schema: row.table_schema, + table_name: row.table_name, + column_name: row.column_name, + ordinal_position: row.ordinal_position, }); + } + } - // Process auto_increment info - const processedAutoIncrements: MariaDBAutoIncrementInfo[] = autoIncrements.map(row => ({ - table_name: row.table_name, - column_name: row.column_name, - auto_increment_value: row.auto_increment_value - })); + // Process check constraints + for (const row of checkConstraints) { + if (tables.has(row.table_name)) { + tables.get(row.table_name)!.checkConstraints.push({ + constraint_name: row.constraint_name, + table_schema: row.table_schema, + table_name: row.table_name, + check_clause: row.check_clause, + }); + } + } - const result: MariaDBSchemaMetadataBatch = { - tables, - enumColumns: processedEnumColumns, - autoIncrements: processedAutoIncrements - }; + // Process enum columns - extract values from ENUM('val1','val2',...) + const processedEnumColumns: MariaDBEnumColumnInfo[] = enumColumns.map((row) => { + const match = row.column_type.match(/^enum\((.+)\)$/i); + let enumValues: string[] = []; + if (match) { + // Parse enum values: 'val1','val2','val3' + enumValues = match[1].split(",").map((v: string) => v.trim().replace(/^'|'$/g, "")); + } + return { + table_name: row.table_name, + column_name: row.column_name, + enum_values: enumValues, + }; + }); - // Cache the result - mariadbCache.setSchemaMetadataBatch(cfg, schemaName, result); + // Process auto_increment info + const processedAutoIncrements: MariaDBAutoIncrementInfo[] = autoIncrements.map((row) => ({ + table_name: row.table_name, + column_name: row.column_name, + auto_increment_value: row.auto_increment_value, + })); + + const result: MariaDBSchemaMetadataBatch = { + tables, + enumColumns: processedEnumColumns, + autoIncrements: processedAutoIncrements, + }; + // Cache the result + mariadbCache.setSchemaMetadataBatch(cfg, schemaName, result); - return result; - } catch (error) { - throw new Error(`Failed to fetch schema metadata batch: ${(error as Error).message}`); - } finally { - if (connection) { - try { - connection.release(); - } catch (e) { - // Ignore - } - } - try { - await pool.end(); - } catch (e) { - // Ignore - } + return result; + } catch (error) { + throw new Error(`Failed to fetch schema metadata batch: ${(error as Error).message}`); + } finally { + if (connection) { + try { + connection.release(); + } catch (e) { + // Ignore + } } + try { + await pool.end(); + } catch (e) { + // Ignore + } + } } const TYPE_MAP: Record = { - INT: "INT", - BIGINT: "BIGINT", - TEXT: "TEXT", - BOOLEAN: "BOOLEAN", - DATETIME: "DATETIME", - TIMESTAMP: "TIMESTAMP", - JSON: "JSON", + INT: "INT", + BIGINT: "BIGINT", + TEXT: "TEXT", + BOOLEAN: "BOOLEAN", + DATETIME: "DATETIME", + TIMESTAMP: "TIMESTAMP", + JSON: "JSON", }; function quoteIdent(name: string) { - return `\`${name.replace(/`/g, "``")}\``; + return `\`${name.replace(/`/g, "``")}\``; } export async function createTable( - conn: MariaDBConfig, - schemaName: string, - tableName: string, - columns: ColumnDetail[], - foreignKeys: ForeignKeyInfo[] = [] + conn: MariaDBConfig, + schemaName: string, + tableName: string, + columns: ColumnDetail[], + foreignKeys: ForeignKeyInfo[] = [], ) { - const connection = await mysql.createPool(createPoolConfig(conn)).getConnection(); + const connection = await mysql.createPool(createPoolConfig(conn)).getConnection(); - const primaryKeys = columns - .filter(c => c.is_primary_key) - .map(c => quoteIdent(c.name)); + const primaryKeys = columns.filter((c) => c.is_primary_key).map((c) => quoteIdent(c.name)); - const columnDefs = columns.map(col => { - if (!TYPE_MAP[col.type]) { - throw new Error(`Invalid type: ${col.type}`); - } + const columnDefs = columns.map((col) => { + if (!TYPE_MAP[col.type]) { + throw new Error(`Invalid type: ${col.type}`); + } - const parts = [ - quoteIdent(col.name), - TYPE_MAP[col.type], - col.not_nullable || col.is_primary_key ? "NOT NULL" : "", - col.default_value ? `DEFAULT ${col.default_value}` : "" - ].filter(Boolean); + const parts = [ + quoteIdent(col.name), + TYPE_MAP[col.type], + col.not_nullable || col.is_primary_key ? "NOT NULL" : "", + col.default_value ? `DEFAULT ${col.default_value}` : "", + ].filter(Boolean); - return parts.join(" "); - }); + return parts.join(" "); + }); - if (primaryKeys.length > 0) { - columnDefs.push(`PRIMARY KEY (${primaryKeys.join(", ")})`); - } + if (primaryKeys.length > 0) { + columnDefs.push(`PRIMARY KEY (${primaryKeys.join(", ")})`); + } - const createTableQuery = ` + const createTableQuery = ` CREATE TABLE IF NOT EXISTS ${quoteIdent(tableName)} ( ${columnDefs.join(",\n")} ) ENGINE=InnoDB; `; - try { - await connection.beginTransaction(); + try { + await connection.beginTransaction(); - await connection.query(createTableQuery); + await connection.query(createTableQuery); - for (const fk of foreignKeys) { - const fkQuery = ` + for (const fk of foreignKeys) { + const fkQuery = ` ALTER TABLE ${quoteIdent(fk.source_table)} ADD CONSTRAINT ${quoteIdent(fk.constraint_name)} FOREIGN KEY (${quoteIdent(fk.source_column)}) @@ -1111,54 +1093,46 @@ export async function createTable( ${fk.delete_rule ? `ON DELETE ${fk.delete_rule}` : ""} ${fk.update_rule ? `ON UPDATE ${fk.update_rule}` : ""}; `; - await connection.query(fkQuery); - } - - await connection.commit(); - return true; - } catch (err) { - await connection.rollback(); - throw err; - } finally { - connection.release(); + await connection.query(fkQuery); } + + await connection.commit(); + return true; + } catch (err) { + await connection.rollback(); + throw err; + } finally { + connection.release(); + } } function groupMariaDBIndexes(indexes: IndexInfo[]) { - const map = new Map(); + const map = new Map(); - for (const idx of indexes) { - if (!map.has(idx.index_name)) { - map.set(idx.index_name, []); - } - map.get(idx.index_name)!.push(idx); + for (const idx of indexes) { + if (!map.has(idx.index_name)) { + map.set(idx.index_name, []); } + map.get(idx.index_name)!.push(idx); + } - return [...map.values()].map(group => - group.sort((a, b) => a.seq_in_index! - b.seq_in_index!) - ); + return [...map.values()].map((group) => group.sort((a, b) => a.seq_in_index! - b.seq_in_index!)); } +export async function createIndexes(conn: MariaDBConfig, indexes: IndexInfo[]): Promise { + const pool = mysql.createPool(createPoolConfig(conn)); + const groupedIndexes = groupMariaDBIndexes(indexes); -export async function createIndexes( - conn: MariaDBConfig, - indexes: IndexInfo[] -): Promise { - const pool = mysql.createPool(createPoolConfig(conn)); - const groupedIndexes = groupMariaDBIndexes(indexes); + try { + for (const group of groupedIndexes) { + const first = group[0]; - try { - for (const group of groupedIndexes) { - const first = group[0]; + // Skip primary key (handled during CREATE TABLE) + if (first.is_primary) continue; - // Skip primary key (handled during CREATE TABLE) - if (first.is_primary) continue; + const columns = group.map((i) => quoteIdent(i.column_name)).join(", "); - const columns = group - .map(i => quoteIdent(i.column_name)) - .join(", "); - - const query = ` + const query = ` CREATE ${first.is_unique ? "UNIQUE" : ""} INDEX ${quoteIdent(first.index_name)} ON ${quoteIdent(first.table_name)} @@ -1166,411 +1140,396 @@ export async function createIndexes( USING ${first.index_type || "BTREE"}; `; - try { - await pool.query(query); - } catch (err: any) { - // Ignore duplicate index creation - if (err.code !== "ER_DUP_KEYNAME") { - throw err; - } - } + try { + await pool.query(query); + } catch (err: any) { + // Ignore duplicate index creation + if (err.code !== "ER_DUP_KEYNAME") { + throw err; } - - return true; - } finally { - await pool.end(); + } } -} - + return true; + } finally { + await pool.end(); + } +} export async function alterTable( - conn: MariaDBConfig, - tableName: string, - operations: MariaDBAlterTableOperation[] + conn: MariaDBConfig, + tableName: string, + operations: MariaDBAlterTableOperation[], ): Promise { - const pool = mysql.createPool(createPoolConfig(conn)); - const connection = await pool.getConnection(); + const pool = mysql.createPool(createPoolConfig(conn)); + const connection = await pool.getConnection(); - try { - await connection.beginTransaction(); + try { + await connection.beginTransaction(); - for (const op of operations) { - let query = ""; + for (const op of operations) { + let query = ""; - switch (op.type) { - case "ADD_COLUMN": - query = ` + switch (op.type) { + case "ADD_COLUMN": + query = ` ALTER TABLE ${quoteIdent(tableName)} ADD COLUMN ${quoteIdent(op.column.name)} ${TYPE_MAP[op.column.type]} ${op.column.not_nullable ? "NOT NULL" : ""} ${op.column.default_value ? `DEFAULT ${op.column.default_value}` : ""}; `; - break; + break; - case "DROP_COLUMN": - query = ` + case "DROP_COLUMN": + query = ` ALTER TABLE ${quoteIdent(tableName)} DROP COLUMN ${quoteIdent(op.column_name)}; `; - break; + break; - case "RENAME_COLUMN": - query = ` + case "RENAME_COLUMN": + query = ` ALTER TABLE ${quoteIdent(tableName)} RENAME COLUMN ${quoteIdent(op.from)} TO ${quoteIdent(op.to)}; `; - break; + break; - case "SET_NOT_NULL": - query = ` + case "SET_NOT_NULL": + query = ` ALTER TABLE ${quoteIdent(tableName)} MODIFY ${quoteIdent(op.column_name)} ${TYPE_MAP[op.new_type]} NOT NULL; `; - break; + break; - case "DROP_NOT_NULL": - query = ` + case "DROP_NOT_NULL": + query = ` ALTER TABLE ${quoteIdent(tableName)} MODIFY ${quoteIdent(op.column_name)} ${TYPE_MAP[op.new_type]}; `; - break; + break; - case "SET_DEFAULT": - query = ` + case "SET_DEFAULT": + query = ` ALTER TABLE ${quoteIdent(tableName)} ALTER ${quoteIdent(op.column_name)} SET DEFAULT ${op.default_value}; `; - break; + break; - case "DROP_DEFAULT": - query = ` + case "DROP_DEFAULT": + query = ` ALTER TABLE ${quoteIdent(tableName)} ALTER ${quoteIdent(op.column_name)} DROP DEFAULT; `; - break; + break; - case "ALTER_TYPE": - query = ` + case "ALTER_TYPE": + query = ` ALTER TABLE ${quoteIdent(tableName)} MODIFY ${quoteIdent(op.column_name)} ${TYPE_MAP[op.new_type]}; `; - break; - } - - await connection.query(query); - } + break; + } - await connection.commit(); - return true; - } catch (err) { - await connection.rollback(); - throw err; - } finally { - connection.release(); - await pool.end(); + await connection.query(query); } + + await connection.commit(); + return true; + } catch (err) { + await connection.rollback(); + throw err; + } finally { + connection.release(); + await pool.end(); + } } export async function dropTable( - conn: MariaDBConfig, - tableName: string, - mode: MariaDBDropMode = "RESTRICT" + conn: MariaDBConfig, + tableName: string, + mode: MariaDBDropMode = "RESTRICT", ): Promise { - const pool = mysql.createPool(createPoolConfig(conn)); - const connection = await pool.getConnection(); + const pool = mysql.createPool(createPoolConfig(conn)); + const connection = await pool.getConnection(); - try { - await connection.beginTransaction(); + try { + await connection.beginTransaction(); - if (mode !== "CASCADE") { - const [rows] = await connection.query( - ` + if (mode !== "CASCADE") { + const [rows] = await connection.query( + ` SELECT CONSTRAINT_NAME, TABLE_NAME FROM information_schema.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = ? AND REFERENCED_TABLE_SCHEMA = DATABASE(); `, - [tableName] - ); - - if (rows.length > 0 && mode === "RESTRICT") { - throw new Error( - `Cannot drop table "${tableName}" — referenced by ${rows.length} foreign key(s)` - ); - } - - if (mode === "DETACH_FKS") { - for (const fk of rows) { - await connection.query(` + [tableName], + ); + + if (rows.length > 0 && mode === "RESTRICT") { + throw new Error( + `Cannot drop table "${tableName}" — referenced by ${rows.length} foreign key(s)`, + ); + } + + if (mode === "DETACH_FKS") { + for (const fk of rows) { + await connection.query(` ALTER TABLE ${quoteIdent(fk.TABLE_NAME)} DROP FOREIGN KEY ${quoteIdent(fk.CONSTRAINT_NAME)}; `); - } - } } + } + } - await connection.query(` + await connection.query(` DROP TABLE IF EXISTS ${quoteIdent(tableName)}; `); - await connection.commit(); - return true; - } catch (err) { - await connection.rollback(); - throw err; - } finally { - connection.release(); - await pool.end(); - } + await connection.commit(); + return true; + } catch (err) { + await connection.rollback(); + throw err; + } finally { + connection.release(); + await pool.end(); + } } export async function ensureMigrationTable(conn: MariaDBConfig) { - const pool = mysql.createPool(createPoolConfig(conn)); - const connection = await pool.getConnection(); - - try { - await connection.query(CREATE_MIGRATION_TABLE); - } finally { - connection.release(); - await pool.end(); - } + const pool = mysql.createPool(createPoolConfig(conn)); + const connection = await pool.getConnection(); + + try { + await connection.query(CREATE_MIGRATION_TABLE); + } finally { + connection.release(); + await pool.end(); + } } - export async function hasAnyMigrations(conn: MariaDBConfig): Promise { - const pool = mysql.createPool(createPoolConfig(conn)); - const connection = await pool.getConnection(); - - try { - const [rows] = await connection.query(CHECK_MIGRATIONS_EXIST); - return rows.length > 0; - } finally { - connection.release(); - await pool.end(); - } + const pool = mysql.createPool(createPoolConfig(conn)); + const connection = await pool.getConnection(); + + try { + const [rows] = await connection.query(CHECK_MIGRATIONS_EXIST); + return rows.length > 0; + } finally { + connection.release(); + await pool.end(); + } } - export async function insertBaseline( - conn: MariaDBConfig, - version: string, - name: string, - checksum: string + conn: MariaDBConfig, + version: string, + name: string, + checksum: string, ) { - const pool = mysql.createPool(createPoolConfig(conn)); - const connection = await pool.getConnection(); - - try { - await connection.query(INSERT_MIGRATION, [version, name, checksum]); - } finally { - connection.release(); - await pool.end(); - } + const pool = mysql.createPool(createPoolConfig(conn)); + const connection = await pool.getConnection(); + + try { + await connection.query(INSERT_MIGRATION, [version, name, checksum]); + } finally { + connection.release(); + await pool.end(); + } } export async function baselineIfNeeded( - conn: MariaDBConfig, - migrationsDir: string, - snapshot?: SchemaFile + conn: MariaDBConfig, + migrationsDir: string, + snapshot?: SchemaFile, ) { - try { - await ensureMigrationTable(conn); - - const hasMigrations = await hasAnyMigrations(conn); - if (hasMigrations) return { baselined: false }; - - const version = Date.now().toString(); - const name = "baseline_existing_schema"; - - const fakeSnapshot = snapshot || { - version: 2, - projectId: "", - databaseId: "", - dialect: "mysql", - schemas: [], - cachedAt: "", - relwaveVersion: "", - schemaHash: "" - }; - - const filePath = writeBaselineMigration( - migrationsDir, - version, - name, - fakeSnapshot - ); + try { + await ensureMigrationTable(conn); + + const hasMigrations = await hasAnyMigrations(conn); + if (hasMigrations) return { baselined: false }; + + const version = Date.now().toString(); + const name = "baseline_existing_schema"; + + const fakeSnapshot = snapshot || { + version: 2, + projectId: "", + databaseId: "", + dialect: "mysql", + schemas: [], + cachedAt: "", + relwaveVersion: "", + schemaHash: "", + }; - const checksum = crypto - .createHash("sha256") - .update(fs.readFileSync(filePath)) - .digest("hex"); + const filePath = writeBaselineMigration(migrationsDir, version, name, fakeSnapshot); - await insertBaseline(conn, version, name, checksum); + const checksum = crypto.createHash("sha256").update(fs.readFileSync(filePath)).digest("hex"); - return { baselined: true, version }; - } catch (err) { - throw err; - } + await insertBaseline(conn, version, name, checksum); + + return { baselined: true, version }; + } catch (err) { + throw err; + } } -export async function listAppliedMigrations( - cfg: MariaDBConfig -): Promise { - const pool = mysql.createPool(createPoolConfig(cfg)); - const connection = await pool.getConnection(); +export async function listAppliedMigrations(cfg: MariaDBConfig): Promise { + const pool = mysql.createPool(createPoolConfig(cfg)); + const connection = await pool.getConnection(); - try { - // Check if schema_migrations table exists in current database - const [tables] = await connection.query( - ` + try { + // Check if schema_migrations table exists in current database + const [tables] = await connection.query( + ` SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'schema_migrations' LIMIT 1; - ` - ); + `, + ); - if (tables.length === 0) { - return []; - } + if (tables.length === 0) { + return []; + } - const [rows] = await connection.query(LIST_APPLIED_MIGRATIONS); + const [rows] = await connection.query(LIST_APPLIED_MIGRATIONS); - return rows as AppliedMigration[]; - } finally { - connection.release(); - await pool.end(); - } + return rows as AppliedMigration[]; + } finally { + connection.release(); + await pool.end(); + } } - export async function connectToDatabase( - cfg: MariaDBConfig, - connectionId: string, - options?: { readOnly?: boolean } + cfg: MariaDBConfig, + connectionId: string, + options?: { readOnly?: boolean }, ) { - let baselineResult = { baselined: false }; - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(connectionId); - ensureDir(migrationsDir); - // 1️⃣ Baseline (ONLY if not read-only) - if (!options?.readOnly) { - // Pass real schema snapshot so baseline contains actual DDL - let snapshot: any = undefined; - try { - const project = await projectStoreInstance.getProjectByDatabaseId(connectionId); - if (project) { - snapshot = await projectStoreInstance.getSchema(project.id) || undefined; - } - } catch { } - baselineResult = await baselineIfNeeded(cfg, migrationsDir, snapshot); - } - - // 2️⃣ Load schema (read-only introspection) - const schema = await listSchemas(cfg); - - // 3️⃣ Load local migrations from AppData - const localMigrations = await loadLocalMigrations(migrationsDir); - - // 4️⃣ Load applied migrations from DB - const appliedMigrations = await listAppliedMigrations(cfg); - - return { - baselined: baselineResult.baselined, - schema, - migrations: { - local: localMigrations, - applied: appliedMigrations - } - }; + let baselineResult = { baselined: false }; + const migrationsDir = await projectStoreInstance.resolveMigrationsDir(connectionId); + ensureDir(migrationsDir); + // 1️⃣ Baseline (ONLY if not read-only) + if (!options?.readOnly) { + // Pass real schema snapshot so baseline contains actual DDL + let snapshot: any = undefined; + try { + const project = await projectStoreInstance.getProjectByDatabaseId(connectionId); + if (project) { + snapshot = (await projectStoreInstance.getSchema(project.id)) || undefined; + } + } catch {} + baselineResult = await baselineIfNeeded(cfg, migrationsDir, snapshot); + } + + // 2️⃣ Load schema (read-only introspection) + const schema = await listSchemas(cfg); + + // 3️⃣ Load local migrations from AppData + const localMigrations = await loadLocalMigrations(migrationsDir); + + // 4️⃣ Load applied migrations from DB + const appliedMigrations = await listAppliedMigrations(cfg); + + return { + baselined: baselineResult.baselined, + schema, + migrations: { + local: localMigrations, + applied: appliedMigrations, + }, + }; } /** * Apply a pending migration */ export async function applyMigration( - cfg: MariaDBConfig, - migrationFilePath: string + cfg: MariaDBConfig, + migrationFilePath: string, ): Promise { - const pool = mysql.createPool(createPoolConfig(cfg)); - const connection = await pool.getConnection(); + const pool = mysql.createPool(createPoolConfig(cfg)); + const connection = await pool.getConnection(); - try { - // Read and parse migration file - const { readMigrationFile } = await import('../utils/migrationFileReader'); - const migration = readMigrationFile(migrationFilePath); + try { + // Read and parse migration file + const { readMigrationFile } = await import("../utils/migrationFileReader"); + const migration = readMigrationFile(migrationFilePath); - // Begin transaction - await connection.beginTransaction(); + // Begin transaction + await connection.beginTransaction(); - // Execute up SQL - await connection.query(migration.upSQL); + // Execute up SQL + await connection.query(migration.upSQL); - // Record in schema_migrations - await connection.query( - `INSERT INTO schema_migrations (version, name, checksum) + // Record in schema_migrations + await connection.query( + `INSERT INTO schema_migrations (version, name, checksum) VALUES (?, ?, ?)`, - [migration.version, migration.name, migration.checksum] - ); + [migration.version, migration.name, migration.checksum], + ); - // Commit transaction - await connection.commit(); + // Commit transaction + await connection.commit(); - // Clear cache - mariadbCache.clearForConnection(cfg); + // Clear cache + mariadbCache.clearForConnection(cfg); - return true; - } catch (error) { - await connection.rollback(); - throw error; - } finally { - connection.release(); - await pool.end(); - } + return true; + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + await pool.end(); + } } /** * Rollback an applied migration */ export async function rollbackMigration( - cfg: MariaDBConfig, - version: string, - migrationFilePath: string + cfg: MariaDBConfig, + version: string, + migrationFilePath: string, ): Promise { - const pool = mysql.createPool(createPoolConfig(cfg)); - const connection = await pool.getConnection(); + const pool = mysql.createPool(createPoolConfig(cfg)); + const connection = await pool.getConnection(); - try { - // Read and parse migration file - const { readMigrationFile } = await import('../utils/migrationFileReader'); - const migration = readMigrationFile(migrationFilePath); + try { + // Read and parse migration file + const { readMigrationFile } = await import("../utils/migrationFileReader"); + const migration = readMigrationFile(migrationFilePath); - // Begin transaction - await connection.beginTransaction(); + // Begin transaction + await connection.beginTransaction(); - // Execute down SQL - await connection.query(migration.downSQL); + // Execute down SQL + await connection.query(migration.downSQL); - // Remove from schema_migrations - await connection.query(DELETE_MIGRATION, [version]); + // Remove from schema_migrations + await connection.query(DELETE_MIGRATION, [version]); - // Commit transaction - await connection.commit(); + // Commit transaction + await connection.commit(); - // Clear cache - mariadbCache.clearForConnection(cfg); + // Clear cache + mariadbCache.clearForConnection(cfg); - return true; - } catch (error) { - await connection.rollback(); - throw error; - } finally { - connection.release(); - await pool.end(); - } + return true; + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + await pool.end(); + } } /** @@ -1582,47 +1541,47 @@ export async function rollbackMigration( * @returns The inserted row data with insertId */ export async function insertRow( - cfg: MariaDBConfig, - schemaName: string, - tableName: string, - rowData: Record + cfg: MariaDBConfig, + schemaName: string, + tableName: string, + rowData: Record, ): Promise { - const pool = mysql.createPool(createPoolConfig(cfg)); - const connection = await pool.getConnection(); + const pool = mysql.createPool(createPoolConfig(cfg)); + const connection = await pool.getConnection(); - try { - const columns = Object.keys(rowData); - const values = Object.values(rowData); + try { + const columns = Object.keys(rowData); + const values = Object.values(rowData); - if (columns.length === 0) { - throw new Error("No data provided for insert"); - } + if (columns.length === 0) { + throw new Error("No data provided for insert"); + } - // Build parameterized query - const columnList = columns.map(col => quoteIdent(col)).join(", "); - const placeholders = columns.map(() => "?").join(", "); + // Build parameterized query + const columnList = columns.map((col) => quoteIdent(col)).join(", "); + const placeholders = columns.map(() => "?").join(", "); - const query = ` + const query = ` INSERT INTO ${quoteIdent(tableName)} (${columnList}) VALUES (${placeholders}); `; - const [result] = await connection.execute(query, values); + const [result] = await connection.execute(query, values); - // Clear cache to refresh table data - mariadbCache.clearForConnection(cfg); + // Clear cache to refresh table data + mariadbCache.clearForConnection(cfg); - return { - success: true, - insertId: (result as any).insertId, - affectedRows: (result as any).affectedRows - }; - } catch (error) { - throw new Error(`Failed to insert row into ${schemaName}.${tableName}: ${error}`); - } finally { - connection.release(); - await pool.end(); - } + return { + success: true, + insertId: (result as any).insertId, + affectedRows: (result as any).affectedRows, + }; + } catch (error) { + throw new Error(`Failed to insert row into ${schemaName}.${tableName}: ${error}`); + } finally { + connection.release(); + await pool.end(); + } } /** @@ -1636,47 +1595,47 @@ export async function insertRow( * @returns The update result */ export async function updateRow( - cfg: MariaDBConfig, - schemaName: string, - tableName: string, - primaryKeyColumn: string, - primaryKeyValue: any, - rowData: Record + cfg: MariaDBConfig, + schemaName: string, + tableName: string, + primaryKeyColumn: string, + primaryKeyValue: any, + rowData: Record, ): Promise { - const pool = mysql.createPool(createPoolConfig(cfg)); - const connection = await pool.getConnection(); + const pool = mysql.createPool(createPoolConfig(cfg)); + const connection = await pool.getConnection(); - try { - const columns = Object.keys(rowData); - const values = Object.values(rowData); + try { + const columns = Object.keys(rowData); + const values = Object.values(rowData); - if (columns.length === 0) { - throw new Error("No data provided for update"); - } + if (columns.length === 0) { + throw new Error("No data provided for update"); + } - const setClause = columns.map(col => `${quoteIdent(col)} = ?`).join(", "); + const setClause = columns.map((col) => `${quoteIdent(col)} = ?`).join(", "); - const query = ` + const query = ` UPDATE ${quoteIdent(tableName)} SET ${setClause} WHERE ${quoteIdent(primaryKeyColumn)} = ?; `; - const [result] = await connection.execute(query, [...values, primaryKeyValue]); + const [result] = await connection.execute(query, [...values, primaryKeyValue]); - // Clear cache to refresh table data - mariadbCache.clearForConnection(cfg); + // Clear cache to refresh table data + mariadbCache.clearForConnection(cfg); - return { - success: true, - affectedRows: (result as any).affectedRows - }; - } catch (error) { - throw new Error(`Failed to update row in ${schemaName}.${tableName}: ${error}`); - } finally { - connection.release(); - await pool.end(); - } + return { + success: true, + affectedRows: (result as any).affectedRows, + }; + } catch (error) { + throw new Error(`Failed to update row in ${schemaName}.${tableName}: ${error}`); + } finally { + connection.release(); + await pool.end(); + } } /** @@ -1689,49 +1648,49 @@ export async function updateRow( * @returns Success status */ export async function deleteRow( - cfg: MariaDBConfig, - schemaName: string, - tableName: string, - primaryKeyColumn: string, - primaryKeyValue: any + cfg: MariaDBConfig, + schemaName: string, + tableName: string, + primaryKeyColumn: string, + primaryKeyValue: any, ): Promise { - const pool = mysql.createPool(createPoolConfig(cfg)); - const connection = await pool.getConnection(); - - try { - let whereClause: string; - let whereValues: any[]; - - if (primaryKeyColumn && typeof primaryKeyColumn === 'string') { - // Single primary key - whereClause = `${quoteIdent(primaryKeyColumn)} = ?`; - whereValues = [primaryKeyValue]; - } else if (typeof primaryKeyValue === 'object' && primaryKeyValue !== null) { - // Composite key - use all columns from the object - const cols = Object.keys(primaryKeyValue); - whereClause = cols.map(col => `${quoteIdent(col)} = ?`).join(" AND "); - whereValues = Object.values(primaryKeyValue); - } else { - throw new Error("Either primary key or where conditions required for delete"); - } + const pool = mysql.createPool(createPoolConfig(cfg)); + const connection = await pool.getConnection(); + + try { + let whereClause: string; + let whereValues: any[]; + + if (primaryKeyColumn && typeof primaryKeyColumn === "string") { + // Single primary key + whereClause = `${quoteIdent(primaryKeyColumn)} = ?`; + whereValues = [primaryKeyValue]; + } else if (typeof primaryKeyValue === "object" && primaryKeyValue !== null) { + // Composite key - use all columns from the object + const cols = Object.keys(primaryKeyValue); + whereClause = cols.map((col) => `${quoteIdent(col)} = ?`).join(" AND "); + whereValues = Object.values(primaryKeyValue); + } else { + throw new Error("Either primary key or where conditions required for delete"); + } - const query = ` + const query = ` DELETE FROM ${quoteIdent(tableName)} WHERE ${whereClause}; `; - const [result] = await connection.execute(query, whereValues); + const [result] = await connection.execute(query, whereValues); - // Clear cache to refresh table data - mariadbCache.clearForConnection(cfg); + // Clear cache to refresh table data + mariadbCache.clearForConnection(cfg); - return (result as any).affectedRows > 0; - } catch (error) { - throw new Error(`Failed to delete row from ${schemaName}.${tableName}: ${error}`); - } finally { - connection.release(); - await pool.end(); - } + return (result as any).affectedRows > 0; + } catch (error) { + throw new Error(`Failed to delete row from ${schemaName}.${tableName}: ${error}`); + } finally { + connection.release(); + await pool.end(); + } } /** @@ -1745,67 +1704,65 @@ export async function deleteRow( * @returns Matching rows */ export async function searchTable( - cfg: MariaDBConfig, - schemaName: string, - tableName: string, - searchTerm: string, - column?: string, - page: number = 1, - pageSize: number = 50 + cfg: MariaDBConfig, + schemaName: string, + tableName: string, + searchTerm: string, + column?: string, + page: number = 1, + pageSize: number = 50, ): Promise<{ rows: any[]; total: number }> { - const pool = mysql.createPool(createPoolConfig(cfg)); - const connection = await pool.getConnection(); - - try { - const searchPattern = `%${searchTerm.replace(/[%_]/g, '\\$&')}%`; - - let whereClause: string; - let values: any[]; - - if (column) { - // Search specific column - whereClause = `${quoteIdent(column)} LIKE ?`; - values = [searchPattern]; - } else { - // Get all columns and search across them - const [colRows] = await connection.query( - `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`, - [schemaName, tableName] - ); - const columns = (colRows as any[]).map(r => r.COLUMN_NAME); - - if (columns.length === 0) { - return { rows: [], total: 0 }; - } - - // Build OR clause for all columns - whereClause = columns - .map(col => `${quoteIdent(col)} LIKE ?`) - .join(" OR "); - values = Array(columns.length).fill(searchPattern); - } + const pool = mysql.createPool(createPoolConfig(cfg)); + const connection = await pool.getConnection(); + + try { + const searchPattern = `%${searchTerm.replace(/[%_]/g, "\\$&")}%`; + + let whereClause: string; + let values: any[]; + + if (column) { + // Search specific column + whereClause = `${quoteIdent(column)} LIKE ?`; + values = [searchPattern]; + } else { + // Get all columns and search across them + const [colRows] = await connection.query( + `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`, + [schemaName, tableName], + ); + const columns = (colRows as any[]).map((r) => r.COLUMN_NAME); + + if (columns.length === 0) { + return { rows: [], total: 0 }; + } + + // Build OR clause for all columns + whereClause = columns.map((col) => `${quoteIdent(col)} LIKE ?`).join(" OR "); + values = Array(columns.length).fill(searchPattern); + } - // Count total matches - const [countRows] = await connection.query( - `SELECT COUNT(*) as total FROM ${quoteIdent(tableName)} WHERE ${whereClause}`, - values - ); - const total = (countRows as any[])[0]?.total || 0; + // Count total matches + const [countRows] = await connection.query( + `SELECT COUNT(*) as total FROM ${quoteIdent(tableName)} WHERE ${whereClause}`, + values, + ); + const total = (countRows as any[])[0]?.total || 0; - // Get matching rows with pagination - const offset = (page - 1) * pageSize; - const [rows] = await connection.query( - `SELECT * FROM ${quoteIdent(tableName)} WHERE ${whereClause} LIMIT ? OFFSET ?`, - [...values, pageSize, offset] - ); + // Get matching rows with pagination + const offset = (page - 1) * pageSize; + const [rows] = await connection.query( + `SELECT * FROM ${quoteIdent(tableName)} WHERE ${whereClause} LIMIT ? OFFSET ?`, + [...values, pageSize, offset], + ); - return { rows: rows as any[], total }; - } catch (error) { - throw new Error(`Failed to search table ${schemaName}.${tableName}: ${error}`); - } finally { - connection.release(); - await pool.end(); - } + return { rows: rows as any[], total }; + } catch (error) { + throw new Error(`Failed to search table ${schemaName}.${tableName}: ${error}`); + } finally { + connection.release(); + await pool.end(); + } } /** @@ -1813,14 +1770,14 @@ export async function searchTable( * Lightweight version for schema selector. */ export async function listSchemaNames(cfg: MariaDBConfig): Promise { - const pool = mysql.createPool(createPoolConfig(cfg)); - const connection = await pool.getConnection(); - - try { - const [rows] = await connection.query(LIST_SCHEMAS); - return (rows as any[]).map((r: any) => r.name); - } finally { - connection.release(); - await pool.end(); - } + const pool = mysql.createPool(createPoolConfig(cfg)); + const connection = await pool.getConnection(); + + try { + const [rows] = await connection.query(LIST_SCHEMAS); + return (rows as any[]).map((r: any) => r.name); + } finally { + connection.release(); + await pool.end(); + } } diff --git a/bridge/src/connectors/mysql.ts b/bridge/src/connectors/mysql.ts index eefc44d4..ae09ea9e 100644 --- a/bridge/src/connectors/mysql.ts +++ b/bridge/src/connectors/mysql.ts @@ -1,20 +1,10 @@ -import mysql, { - FieldPacket, - PoolOptions, - RowDataPacket, - PoolConnection, -} from "mysql2/promise"; +import mysql, { FieldPacket, PoolOptions, RowDataPacket, PoolConnection } from "mysql2/promise"; import { loadLocalMigrations, writeBaselineMigration } from "../utils/baselineMigration"; import crypto from "crypto"; import fs from "fs"; import { ensureDir } from "../utils/config"; import { projectStoreInstance } from "../services/projectStore"; -import { - CacheEntry, - CACHE_TTL, - STATS_CACHE_TTL, - SCHEMA_CACHE_TTL -} from "../types/cache"; +import { CacheEntry, CACHE_TTL, STATS_CACHE_TTL, SCHEMA_CACHE_TTL } from "../types/cache"; import { TableInfo, DBStats, @@ -53,16 +43,29 @@ export type { export type { AppliedMigration } from "../types/common"; // Import centralized queries -import { LIST_SCHEMAS, LIST_TABLES_BY_SCHEMA, LIST_TABLES_CURRENT_DB } from "../queries/mysql/schema"; -import { GET_TABLE_DETAILS, LIST_COLUMNS, KILL_QUERY, GET_CONNECTION_ID } from "../queries/mysql/tables"; -import { BATCH_GET_ALL_COLUMNS, BATCH_GET_ENUM_COLUMNS, BATCH_GET_AUTO_INCREMENTS } from "../queries/mysql/columns"; +import { + LIST_SCHEMAS, + LIST_TABLES_BY_SCHEMA, + LIST_TABLES_CURRENT_DB, +} from "../queries/mysql/schema"; +import { + GET_TABLE_DETAILS, + LIST_COLUMNS, + KILL_QUERY, + GET_CONNECTION_ID, +} from "../queries/mysql/tables"; +import { + BATCH_GET_ALL_COLUMNS, + BATCH_GET_ENUM_COLUMNS, + BATCH_GET_AUTO_INCREMENTS, +} from "../queries/mysql/columns"; import { GET_PRIMARY_KEYS, BATCH_GET_PRIMARY_KEYS, BATCH_GET_FOREIGN_KEYS, BATCH_GET_INDEXES, BATCH_GET_UNIQUE_CONSTRAINTS, - BATCH_GET_CHECK_CONSTRAINTS + BATCH_GET_CHECK_CONSTRAINTS, } from "../queries/mysql/constraints"; import { GET_DB_STATS } from "../queries/mysql/stats"; import { @@ -70,7 +73,7 @@ import { CHECK_MIGRATIONS_EXIST, INSERT_MIGRATION, LIST_APPLIED_MIGRATIONS, - DELETE_MIGRATION + DELETE_MIGRATION, } from "../queries/mysql/migrations"; import { quoteIdentifier } from "../queries/mysql/crud"; @@ -252,7 +255,6 @@ class MySQLCacheManager { this.dbStatsCache.delete(configKey); this.schemasCache.delete(configKey); - } /** @@ -306,10 +308,7 @@ class MySQLCacheManager { export const mysqlCache = new MySQLCacheManager(); // Legacy cache support (for backward compatibility) -const tableListCache = new Map< - string, - { data: TableInfo[]; timestamp: number } ->(); +const tableListCache = new Map(); function getCacheKey(cfg: MySQLConfig): string { return `${cfg.host}:${cfg.port}:${cfg.database}`; @@ -326,14 +325,14 @@ export function createPoolConfig(cfg: MySQLConfig): MySQLConfig & PoolOptions { } export async function testConnection( - cfg: MySQLConfig -): Promise<{ ok: boolean; message?: string; status: 'connected' | 'disconnected' }> { + cfg: MySQLConfig, +): Promise<{ ok: boolean; message?: string; status: "connected" | "disconnected" }> { let connection; try { connection = await mysql.createConnection(cfg); - return { ok: true, status: 'connected', message: "Connection successful" }; + return { ok: true, status: "connected", message: "Connection successful" }; } catch (err) { - return { ok: false, message: (err as Error).message, status: 'disconnected' }; + return { ok: false, message: (err as Error).message, status: "disconnected" }; } finally { if (connection) { try { @@ -350,7 +349,7 @@ export async function fetchTableData( schemaName: string, tableName: string, limit: number, - page: number + page: number, ): Promise<{ rows: RowDataPacket[]; total: number }> { const pool = mysql.createPool(createPoolConfig(cfg)); let connection: PoolConnection | null = null; @@ -367,7 +366,7 @@ export async function fetchTableData( let orderBy = ""; if (pkColumns.length > 0) { - const safePks = pkColumns.map(col => `\`${col.replace(/`/g, "``")}\``); + const safePks = pkColumns.map((col) => `\`${col.replace(/`/g, "``")}\``); orderBy = `ORDER BY ${safePks.join(", ")}`; } else { const colQuery = ` @@ -381,7 +380,7 @@ export async function fetchTableData( schemaName, tableName, ]); - const safeCols = colRows.map(r => `\`${r.COLUMN_NAME}\``); + const safeCols = colRows.map((r) => `\`${r.COLUMN_NAME}\``); orderBy = safeCols.length ? `ORDER BY ${safeCols.join(", ")}` : ""; } @@ -412,11 +411,10 @@ export async function fetchTableData( } } - export async function listColumns( cfg: MySQLConfig, tableName: string, - schemaName?: string + schemaName?: string, ): Promise { // Check cache first if (schemaName) { @@ -432,10 +430,7 @@ export async function listColumns( try { connection = await pool.getConnection(); - const [rows] = await connection.execute(LIST_COLUMNS, [ - schemaName, - tableName, - ]); + const [rows] = await connection.execute(LIST_COLUMNS, [schemaName, tableName]); // Cache the result if (schemaName) { @@ -470,7 +465,7 @@ export async function mysqlKillQuery(cfg: MySQLConfig, targetPid: number) { export async function listPrimaryKeys( cfg: MySQLConfig, schemaName: string, - tableName: string + tableName: string, ): Promise { // Check cache first const cached = mysqlCache.getPrimaryKeys(cfg, schemaName, tableName); @@ -499,17 +494,12 @@ export async function listPrimaryKeys( } } - - export function streamQueryCancelable( cfg: MySQLConfig, sql: string, batchSize: number, - onBatch: ( - rows: RowDataPacket[], - columns: FieldPacket[] - ) => Promise | void, - onDone?: () => void + onBatch: (rows: RowDataPacket[], columns: FieldPacket[]) => Promise | void, + onDone?: () => void, ) { let query: any = null; let finished = false; @@ -581,7 +571,7 @@ export function streamQueryCancelable( cancelled = true; if (backendPid) { - await mysqlKillQuery(cfg, backendPid).catch(() => { }); + await mysqlKillQuery(cfg, backendPid).catch(() => {}); } query?.emit("error", new Error("Cancelled")); @@ -620,9 +610,7 @@ export async function getDBStats(cfg: MySQLConfig): Promise<{ return result; } catch (error) { - throw new Error( - `Failed to fetch MySQL database stats: ${(error as Error).message}` - ); + throw new Error(`Failed to fetch MySQL database stats: ${(error as Error).message}`); } finally { if (connection) { try { @@ -639,9 +627,7 @@ export async function getDBStats(cfg: MySQLConfig): Promise<{ } } -export async function listSchemas( - cfg: MySQLConfig -): Promise<{ name: string }[]> { +export async function listSchemas(cfg: MySQLConfig): Promise<{ name: string }[]> { // Check cache first const cached = mysqlCache.getSchemas(cfg); if (cached !== null) { @@ -679,10 +665,7 @@ export async function listSchemas( } } -export async function listTables( - cfg: MySQLConfig, - schemaName?: string -): Promise { +export async function listTables(cfg: MySQLConfig, schemaName?: string): Promise { // Check new cache manager first const cached = mysqlCache.getTableList(cfg, schemaName); if (cached !== null) { @@ -709,11 +692,7 @@ export async function listTables( query = LIST_TABLES_CURRENT_DB; } - const [rows] = await connection.execute( - query, - queryParams - ); - + const [rows] = await connection.execute(query, queryParams); const result = rows as TableInfo[]; @@ -748,7 +727,7 @@ export function clearTableListCache(cfg: MySQLConfig) { export async function getTableDetails( cfg: MySQLConfig, schemaName: string, - tableName: string + tableName: string, ): Promise { // Check cache first const cached = mysqlCache.getTableDetails(cfg, schemaName, tableName); @@ -774,9 +753,7 @@ export async function getTableDetails( return result; } catch (error) { - throw new Error( - `Failed to fetch table details: ${(error as Error).message}` - ); + throw new Error(`Failed to fetch table details: ${(error as Error).message}`); } finally { if (connection) { try { @@ -800,14 +777,14 @@ export async function getTableDetails( /** * Fetch all schema metadata in a single batch using parallel queries. * This is much faster than making individual queries per table. - * + * * Note: MySQL doesn't have true sequences or standalone enum types like PostgreSQL. * - Auto-increment columns are MySQL's equivalent to sequences * - Enum columns are defined inline in table definitions */ export async function getSchemaMetadataBatch( cfg: MySQLConfig, - schemaName: string + schemaName: string, ): Promise { // Check cache first const cached = mysqlCache.getSchemaMetadataBatch(cfg, schemaName); @@ -829,7 +806,7 @@ export async function getSchemaMetadataBatch( uniqueResult, checksResult, enumColumnsResult, - autoIncrementsResult + autoIncrementsResult, ] = await Promise.all([ // 1. All columns in schema with PK/FK info connection.execute(BATCH_GET_ALL_COLUMNS, [schemaName, schemaName]), @@ -847,13 +824,15 @@ export async function getSchemaMetadataBatch( connection.execute(BATCH_GET_UNIQUE_CONSTRAINTS, [schemaName]), // 6. All check constraints in schema (MySQL 8.0.16+) - connection.execute(BATCH_GET_CHECK_CONSTRAINTS, [schemaName]).catch(() => [[], []]), + connection + .execute(BATCH_GET_CHECK_CONSTRAINTS, [schemaName]) + .catch(() => [[], []]), // 7. All enum columns in schema (MySQL defines enums inline) connection.execute(BATCH_GET_ENUM_COLUMNS, [schemaName]), // 8. All auto_increment columns (MySQL's equivalent to sequences) - connection.execute(BATCH_GET_AUTO_INCREMENTS, [schemaName]) + connection.execute(BATCH_GET_AUTO_INCREMENTS, [schemaName]), ]); // Extract rows from results (mysql2 returns [rows, fields]) @@ -867,14 +846,17 @@ export async function getSchemaMetadataBatch( const autoIncrements = autoIncrementsResult[0] as RowDataPacket[]; // Group results by table - const tables = new Map(); + const tables = new Map< + string, + { + columns: ColumnDetail[]; + primaryKeys: PrimaryKeyInfo[]; + foreignKeys: ForeignKeyInfo[]; + indexes: IndexInfo[]; + uniqueConstraints: UniqueConstraintInfo[]; + checkConstraints: CheckConstraintInfo[]; + } + >(); // Process columns for (const row of columns) { @@ -885,7 +867,7 @@ export async function getSchemaMetadataBatch( foreignKeys: [], indexes: [], uniqueConstraints: [], - checkConstraints: [] + checkConstraints: [], }); } tables.get(row.table_name)!.columns.push({ @@ -899,7 +881,7 @@ export async function getSchemaMetadataBatch( is_serial: Boolean(row.is_serial), comment: row.comment, check_constraint: row.check_constraint, - ordinal_position: row.ordinal_position + ordinal_position: row.ordinal_position, }); } @@ -907,7 +889,7 @@ export async function getSchemaMetadataBatch( for (const row of primaryKeys) { if (tables.has(row.table_name)) { tables.get(row.table_name)!.primaryKeys.push({ - column_name: row.column_name + column_name: row.column_name, }); } } @@ -924,7 +906,7 @@ export async function getSchemaMetadataBatch( target_table: row.target_table, target_column: row.target_column, update_rule: row.update_rule, - delete_rule: row.delete_rule + delete_rule: row.delete_rule, }); } } @@ -939,7 +921,7 @@ export async function getSchemaMetadataBatch( is_unique: Boolean(row.is_unique), is_primary: Boolean(row.is_primary), index_type: row.index_type, - seq_in_index: row.seq_in_index + seq_in_index: row.seq_in_index, }); } } @@ -952,7 +934,7 @@ export async function getSchemaMetadataBatch( table_schema: row.table_schema, table_name: row.table_name, column_name: row.column_name, - ordinal_position: row.ordinal_position + ordinal_position: row.ordinal_position, }); } } @@ -964,37 +946,37 @@ export async function getSchemaMetadataBatch( constraint_name: row.constraint_name, table_schema: row.table_schema, table_name: row.table_name, - check_clause: row.check_clause + check_clause: row.check_clause, }); } } // Process enum columns - extract values from ENUM('val1','val2',...) - const processedEnumColumns: EnumColumnInfo[] = enumColumns.map(row => { + const processedEnumColumns: EnumColumnInfo[] = enumColumns.map((row) => { const match = row.column_type.match(/^enum\((.+)\)$/i); let enumValues: string[] = []; if (match) { // Parse enum values: 'val1','val2','val3' - enumValues = match[1].split(',').map((v: string) => v.trim().replace(/^'|'$/g, '')); + enumValues = match[1].split(",").map((v: string) => v.trim().replace(/^'|'$/g, "")); } return { table_name: row.table_name, column_name: row.column_name, - enum_values: enumValues + enum_values: enumValues, }; }); // Process auto_increment info - const processedAutoIncrements: AutoIncrementInfo[] = autoIncrements.map(row => ({ + const processedAutoIncrements: AutoIncrementInfo[] = autoIncrements.map((row) => ({ table_name: row.table_name, column_name: row.column_name, - auto_increment_value: row.auto_increment_value + auto_increment_value: row.auto_increment_value, })); const result: SchemaMetadataBatch = { tables, enumColumns: processedEnumColumns, - autoIncrements: processedAutoIncrements + autoIncrements: processedAutoIncrements, }; // Cache the result @@ -1038,15 +1020,13 @@ export async function createTable( schemaName: string, tableName: string, columns: ColumnDetail[], - foreignKeys: ForeignKeyInfo[] = [] + foreignKeys: ForeignKeyInfo[] = [], ) { const connection = await mysql.createPool(conn).getConnection(); - const primaryKeys = columns - .filter(c => c.is_primary_key) - .map(c => quoteIdent(c.name)); + const primaryKeys = columns.filter((c) => c.is_primary_key).map((c) => quoteIdent(c.name)); - const columnDefs = columns.map(col => { + const columnDefs = columns.map((col) => { if (!TYPE_MAP[col.type]) { throw new Error(`Invalid type: ${col.type}`); } @@ -1055,7 +1035,7 @@ export async function createTable( quoteIdent(col.name), TYPE_MAP[col.type], col.not_nullable || col.is_primary_key ? "NOT NULL" : "", - col.default_value ? `DEFAULT ${col.default_value}` : "" + col.default_value ? `DEFAULT ${col.default_value}` : "", ].filter(Boolean); return parts.join(" "); @@ -1109,16 +1089,12 @@ function groupMySQLIndexes(indexes: IndexInfo[]) { map.get(idx.index_name)!.push(idx); } - return [...map.values()].map(group => - group.sort((a, b) => (a.seq_in_index ?? 0) - (b.seq_in_index ?? 0)) + return [...map.values()].map((group) => + group.sort((a, b) => (a.seq_in_index ?? 0) - (b.seq_in_index ?? 0)), ); } - -export async function createIndexes( - conn: MySQLConfig, - indexes: IndexInfo[] -): Promise { +export async function createIndexes(conn: MySQLConfig, indexes: IndexInfo[]): Promise { const pool = mysql.createPool(conn); const groupedIndexes = groupMySQLIndexes(indexes); @@ -1129,9 +1105,7 @@ export async function createIndexes( // Skip primary key (handled during CREATE TABLE) if (first.is_primary) continue; - const columns = group - .map(i => quoteIdent(i.column_name)) - .join(", "); + const columns = group.map((i) => quoteIdent(i.column_name)).join(", "); const query = ` CREATE ${first.is_unique ? "UNIQUE" : ""} INDEX @@ -1157,12 +1131,10 @@ export async function createIndexes( } } - - export async function alterTable( conn: MySQLConfig, tableName: string, - operations: MySQLAlterTableOperation[] + operations: MySQLAlterTableOperation[], ): Promise { const pool = mysql.createPool(conn); const connection = await pool.getConnection(); @@ -1252,7 +1224,7 @@ export async function alterTable( export async function dropTable( conn: MySQLConfig, tableName: string, - mode: MySQLDropMode = "RESTRICT" + mode: MySQLDropMode = "RESTRICT", ): Promise { const pool = mysql.createPool(conn); const connection = await pool.getConnection(); @@ -1268,12 +1240,12 @@ export async function dropTable( WHERE REFERENCED_TABLE_NAME = ? AND REFERENCED_TABLE_SCHEMA = DATABASE(); `, - [tableName] + [tableName], ); if (rows.length > 0 && mode === "RESTRICT") { throw new Error( - `Cannot drop table "${tableName}" — referenced by ${rows.length} foreign key(s)` + `Cannot drop table "${tableName}" — referenced by ${rows.length} foreign key(s)`, ); } @@ -1314,7 +1286,6 @@ export async function ensureMigrationTable(conn: MySQLConfig) { } } - export async function hasAnyMigrations(conn: MySQLConfig): Promise { const pool = mysql.createPool(conn); const connection = await pool.getConnection(); @@ -1328,12 +1299,11 @@ export async function hasAnyMigrations(conn: MySQLConfig): Promise { } } - export async function insertBaseline( conn: MySQLConfig, version: string, name: string, - checksum: string + checksum: string, ) { const pool = mysql.createPool(conn); const connection = await pool.getConnection(); @@ -1349,7 +1319,7 @@ export async function insertBaseline( export async function baselineIfNeeded( conn: MySQLConfig, migrationsDir: string, - snapshot?: SchemaFile + snapshot?: SchemaFile, ) { try { await ensureMigrationTable(conn); @@ -1368,20 +1338,12 @@ export async function baselineIfNeeded( schemas: [], cachedAt: "", relwaveVersion: "", - schemaHash: "" + schemaHash: "", }; - const filePath = writeBaselineMigration( - migrationsDir, - version, - name, - fakeSnapshot - ); + const filePath = writeBaselineMigration(migrationsDir, version, name, fakeSnapshot); - const checksum = crypto - .createHash("sha256") - .update(fs.readFileSync(filePath)) - .digest("hex"); + const checksum = crypto.createHash("sha256").update(fs.readFileSync(filePath)).digest("hex"); await insertBaseline(conn, version, name, checksum); @@ -1391,9 +1353,7 @@ export async function baselineIfNeeded( } } -export async function listAppliedMigrations( - cfg: MySQLConfig -): Promise { +export async function listAppliedMigrations(cfg: MySQLConfig): Promise { const pool = mysql.createPool(cfg); const connection = await pool.getConnection(); @@ -1406,7 +1366,7 @@ export async function listAppliedMigrations( WHERE table_schema = DATABASE() AND table_name = 'schema_migrations' LIMIT 1; - ` + `, ); if (tables.length === 0) { @@ -1422,11 +1382,10 @@ export async function listAppliedMigrations( } } - export async function connectToDatabase( cfg: MySQLConfig, connectionId: string, - options?: { readOnly?: boolean } + options?: { readOnly?: boolean }, ) { let baselineResult = { baselined: false }; const migrationsDir = await projectStoreInstance.resolveMigrationsDir(connectionId); @@ -1438,7 +1397,7 @@ export async function connectToDatabase( try { const project = await projectStoreInstance.getProjectByDatabaseId(connectionId); if (project) { - snapshot = await projectStoreInstance.getSchema(project.id) || undefined; + snapshot = (await projectStoreInstance.getSchema(project.id)) || undefined; } } catch {} baselineResult = await baselineIfNeeded(cfg, migrationsDir, snapshot); @@ -1458,8 +1417,8 @@ export async function connectToDatabase( schema, migrations: { local: localMigrations, - applied: appliedMigrations - } + applied: appliedMigrations, + }, }; } @@ -1468,14 +1427,14 @@ export async function connectToDatabase( */ export async function applyMigration( cfg: MySQLConfig, - migrationFilePath: string + migrationFilePath: string, ): Promise { const pool = mysql.createPool(cfg); const connection = await pool.getConnection(); try { // Read and parse migration file - const { readMigrationFile } = await import('../utils/migrationFileReader'); + const { readMigrationFile } = await import("../utils/migrationFileReader"); const migration = readMigrationFile(migrationFilePath); // Begin transaction @@ -1488,7 +1447,7 @@ export async function applyMigration( await connection.query( `INSERT INTO schema_migrations (version, name, checksum) VALUES (?, ?, ?)`, - [migration.version, migration.name, migration.checksum] + [migration.version, migration.name, migration.checksum], ); // Commit transaction @@ -1513,14 +1472,14 @@ export async function applyMigration( export async function rollbackMigration( cfg: MySQLConfig, version: string, - migrationFilePath: string + migrationFilePath: string, ): Promise { const pool = mysql.createPool(cfg); const connection = await pool.getConnection(); try { // Read and parse migration file - const { readMigrationFile } = await import('../utils/migrationFileReader'); + const { readMigrationFile } = await import("../utils/migrationFileReader"); const migration = readMigrationFile(migrationFilePath); // Begin transaction @@ -1560,7 +1519,7 @@ export async function insertRow( cfg: MySQLConfig, schemaName: string, tableName: string, - rowData: Record + rowData: Record, ): Promise { const pool = mysql.createPool(cfg); const connection = await pool.getConnection(); @@ -1574,7 +1533,7 @@ export async function insertRow( } // Build parameterized query - const columnList = columns.map(col => quoteIdent(col)).join(", "); + const columnList = columns.map((col) => quoteIdent(col)).join(", "); const placeholders = columns.map(() => "?").join(", "); const query = ` @@ -1590,7 +1549,7 @@ export async function insertRow( return { success: true, insertId: (result as any).insertId, - affectedRows: (result as any).affectedRows + affectedRows: (result as any).affectedRows, }; } catch (error) { throw new Error(`Failed to insert row into ${schemaName}.${tableName}: ${error}`); @@ -1616,7 +1575,7 @@ export async function updateRow( tableName: string, primaryKeyColumn: string, primaryKeyValue: any, - rowData: Record + rowData: Record, ): Promise { const pool = mysql.createPool(cfg); const connection = await pool.getConnection(); @@ -1629,7 +1588,7 @@ export async function updateRow( throw new Error("No data provided for update"); } - const setClause = columns.map(col => `${quoteIdent(col)} = ?`).join(", "); + const setClause = columns.map((col) => `${quoteIdent(col)} = ?`).join(", "); const query = ` UPDATE ${quoteIdent(tableName)} @@ -1644,7 +1603,7 @@ export async function updateRow( return { success: true, - affectedRows: (result as any).affectedRows + affectedRows: (result as any).affectedRows, }; } catch (error) { throw new Error(`Failed to update row in ${schemaName}.${tableName}: ${error}`); @@ -1668,7 +1627,7 @@ export async function deleteRow( schemaName: string, tableName: string, primaryKeyColumn: string, - primaryKeyValue: any + primaryKeyValue: any, ): Promise { const pool = mysql.createPool(cfg); const connection = await pool.getConnection(); @@ -1677,14 +1636,14 @@ export async function deleteRow( let whereClause: string; let whereValues: any[]; - if (primaryKeyColumn && typeof primaryKeyColumn === 'string') { + if (primaryKeyColumn && typeof primaryKeyColumn === "string") { // Single primary key whereClause = `${quoteIdent(primaryKeyColumn)} = ?`; whereValues = [primaryKeyValue]; - } else if (typeof primaryKeyValue === 'object' && primaryKeyValue !== null) { + } else if (typeof primaryKeyValue === "object" && primaryKeyValue !== null) { // Composite key - use all columns from the object const cols = Object.keys(primaryKeyValue); - whereClause = cols.map(col => `${quoteIdent(col)} = ?`).join(" AND "); + whereClause = cols.map((col) => `${quoteIdent(col)} = ?`).join(" AND "); whereValues = Object.values(primaryKeyValue); } else { throw new Error("Either primary key or where conditions required for delete"); @@ -1726,13 +1685,13 @@ export async function searchTable( searchTerm: string, column?: string, page: number = 1, - pageSize: number = 50 + pageSize: number = 50, ): Promise<{ rows: any[]; total: number }> { const pool = mysql.createPool(cfg); const connection = await pool.getConnection(); try { - const searchPattern = `%${searchTerm.replace(/[%_]/g, '\\$&')}%`; + const searchPattern = `%${searchTerm.replace(/[%_]/g, "\\$&")}%`; let whereClause: string; let values: any[]; @@ -1745,25 +1704,23 @@ export async function searchTable( // Get all columns and search across them const [colRows] = await connection.query( `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`, - [schemaName, tableName] + [schemaName, tableName], ); - const columns = (colRows as any[]).map(r => r.COLUMN_NAME); + const columns = (colRows as any[]).map((r) => r.COLUMN_NAME); if (columns.length === 0) { return { rows: [], total: 0 }; } // Build OR clause for all columns - whereClause = columns - .map(col => `${quoteIdent(col)} LIKE ?`) - .join(" OR "); + whereClause = columns.map((col) => `${quoteIdent(col)} LIKE ?`).join(" OR "); values = Array(columns.length).fill(searchPattern); } // Count total matches const [countRows] = await connection.query( `SELECT COUNT(*) as total FROM ${quoteIdent(tableName)} WHERE ${whereClause}`, - values + values, ); const total = (countRows as any[])[0]?.total || 0; @@ -1771,7 +1728,7 @@ export async function searchTable( const offset = (page - 1) * pageSize; const [rows] = await connection.query( `SELECT * FROM ${quoteIdent(tableName)} WHERE ${whereClause} LIMIT ? OFFSET ?`, - [...values, pageSize, offset] + [...values, pageSize, offset], ); return { rows: rows as any[], total }; diff --git a/bridge/src/connectors/postgres.ts b/bridge/src/connectors/postgres.ts index 4bc5bbdb..be4ffb6a 100644 --- a/bridge/src/connectors/postgres.ts +++ b/bridge/src/connectors/postgres.ts @@ -7,12 +7,7 @@ import crypto from "crypto"; import fs from "fs"; import { ensureDir } from "../utils/config"; import { projectStoreInstance } from "../services/projectStore"; -import { - CacheEntry, - CACHE_TTL, - STATS_CACHE_TTL, - SCHEMA_CACHE_TTL -} from "../types/cache"; +import { CacheEntry, CACHE_TTL, STATS_CACHE_TTL, SCHEMA_CACHE_TTL } from "../types/cache"; import { LRUCache } from "../utils/lruCache"; import { TableInfo, @@ -49,8 +44,18 @@ export type { SequenceInfo, AppliedMigration, }; -import { PG_LIST_SCHEMAS, PG_LIST_TABLES, PG_LIST_TABLES_BY_SCHEMA, PG_LIST_ENUMS, PG_LIST_SEQUENCES } from "../queries/postgres/schema"; -import { PG_GET_TABLE_DETAILS, PG_BATCH_GET_ALL_COLUMNS, PG_CANCEL_QUERY } from "../queries/postgres/tables"; +import { + PG_LIST_SCHEMAS, + PG_LIST_TABLES, + PG_LIST_TABLES_BY_SCHEMA, + PG_LIST_ENUMS, + PG_LIST_SEQUENCES, +} from "../queries/postgres/schema"; +import { + PG_GET_TABLE_DETAILS, + PG_BATCH_GET_ALL_COLUMNS, + PG_CANCEL_QUERY, +} from "../queries/postgres/tables"; import { PG_GET_PRIMARY_KEYS, PG_BATCH_GET_PRIMARY_KEYS, @@ -61,7 +66,7 @@ import { PG_GET_UNIQUE_CONSTRAINTS, PG_BATCH_GET_UNIQUE_CONSTRAINTS, PG_GET_CHECK_CONSTRAINTS, - PG_BATCH_GET_CHECK_CONSTRAINTS + PG_BATCH_GET_CHECK_CONSTRAINTS, } from "../queries/postgres/constraints"; import { PG_GET_DB_STATS } from "../queries/postgres/stats"; import { @@ -69,7 +74,7 @@ import { PG_CHECK_MIGRATIONS_EXIST, PG_INSERT_MIGRATION, PG_LIST_APPLIED_MIGRATIONS, - PG_DELETE_MIGRATION + PG_DELETE_MIGRATION, } from "../queries/postgres/migrations"; import { pgQuoteIdentifier } from "../queries/postgres/crud"; @@ -81,7 +86,6 @@ import { pgQuoteIdentifier } from "../queries/postgres/crud"; * PostgreSQL Cache Manager - handles all caching for Postgres connector */ export class PostgresCacheManager { - // Cache stores for different data types private tableListCache = new LRUCache(100); private primaryKeysCache = new LRUCache(1000); @@ -407,7 +411,9 @@ export function getPool(cfg: PGConfig): Pool { if (!pool) { let sslConfig; if (cfg.ssl) { - sslConfig = { rejectUnauthorized: cfg.sslmode === 'verify-full' || cfg.sslmode === 'verify-ca' }; + sslConfig = { + rejectUnauthorized: cfg.sslmode === "verify-full" || cfg.sslmode === "verify-ca", + }; } pool = new Pool({ host: cfg.host, @@ -424,17 +430,17 @@ export function getPool(cfg: PGConfig): Pool { return pool; } - - /** test connection quickly */ -export async function testConnection(cfg: PGConfig): Promise<{ ok: boolean; message?: string; status: 'connected' | 'disconnected' }> { +export async function testConnection( + cfg: PGConfig, +): Promise<{ ok: boolean; message?: string; status: "connected" | "disconnected" }> { const pool = getPool(cfg); try { const client = await pool.connect(); await client.release(); - return { ok: true, status: 'connected', message: "Connection successful" }; + return { ok: true, status: "connected", message: "Connection successful" }; } catch (err: any) { - return { ok: false, message: err.message || String(err), status: 'disconnected' }; + return { ok: false, message: err.message || String(err), status: "disconnected" }; } } @@ -452,7 +458,7 @@ export async function pgCancel(cfg: PGConfig, targetPid: number) { } catch (err) { try { await c.release(); - } catch (e) { } + } catch (e) {} throw err; } } @@ -469,23 +475,19 @@ export async function fetchTableData( schemaName: string, tableName: string, limit: number, - page: number + page: number, ): Promise<{ rows: any[]; total: number }> { - const pool = getPool(config); const client = await pool.connect(); try { - const safeSchema = `"${schemaName.replace(/"/g, '""')}"`; const safeTable = `"${tableName.replace(/"/g, '""')}"`; const offset = (page - 1) * limit; const pkResult = await listPrimaryKeys(config, schemaName, tableName); - const pkColumns = pkResult.map((r: any) => - `"${r.column_name.replace(/"/g, '""')}"` - ); + const pkColumns = pkResult.map((r: any) => `"${r.column_name.replace(/"/g, '""')}"`); let orderBy = ""; @@ -523,17 +525,14 @@ export async function fetchTableData( return { rows: result.rows, total }; } catch (error) { - throw new Error( - `Failed to fetch paginated data from ${schemaName}.${tableName}: ${error}` - ); + throw new Error(`Failed to fetch paginated data from ${schemaName}.${tableName}: ${error}`); } finally { try { await client.release(); - } catch (_) { } + } catch (_) {} } } - /** * listTables: Retrieves all user-defined tables and views. */ @@ -558,7 +557,6 @@ export async function listTables(connection: PGConfig, schemaName?: string) { } try { - // Execute the dynamically constructed query const res = await client.query(query, queryParams); @@ -573,12 +571,16 @@ export async function listTables(connection: PGConfig, schemaName?: string) { } catch (err) { try { await client.release(); - } catch (e) { } + } catch (e) {} throw err; } } -export async function listPrimaryKeys(connection: PGConfig, schemaName: string = 'public', tableName: string) { +export async function listPrimaryKeys( + connection: PGConfig, + schemaName: string = "public", + tableName: string, +) { // Check cache first const cached = postgresCache.getPrimaryKeys(connection, schemaName, tableName); if (cached !== null) { @@ -600,7 +602,7 @@ export async function listPrimaryKeys(connection: PGConfig, schemaName: string = } catch (err) { try { await client.release(); - } catch (e) { } + } catch (e) {} throw err; } } @@ -608,7 +610,7 @@ export async function listPrimaryKeys(connection: PGConfig, schemaName: string = export async function listForeignKeys( connection: PGConfig, schemaName: string = "public", - tableName: string + tableName: string, ) { // Check cache const cached = postgresCache.getForeignKeys(connection, schemaName, tableName); @@ -629,12 +631,10 @@ export async function listForeignKeys( } finally { try { await client.release(); - } catch { } + } catch {} } } - - export async function listIndexes(connection: PGConfig, schemaName = "public", tableName: string) { const cached = postgresCache.getIndexes(connection, schemaName, tableName); if (cached !== null) return cached; @@ -647,11 +647,17 @@ export async function listIndexes(connection: PGConfig, schemaName = "public", t postgresCache.setIndexes(connection, schemaName, tableName, res.rows); return res.rows; } finally { - try { await client.release(); } catch { } + try { + await client.release(); + } catch {} } } -export async function listUniqueConstraints(connection: PGConfig, schemaName = "public", tableName: string) { +export async function listUniqueConstraints( + connection: PGConfig, + schemaName = "public", + tableName: string, +) { const cached = postgresCache.getUnique(connection, schemaName, tableName); if (cached !== null) return cached; @@ -663,11 +669,17 @@ export async function listUniqueConstraints(connection: PGConfig, schemaName = " postgresCache.setUnique(connection, schemaName, tableName, res.rows); return res.rows; } finally { - try { await client.release(); } catch { } + try { + await client.release(); + } catch {} } } -export async function listCheckConstraints(connection: PGConfig, schemaName = "public", tableName: string) { +export async function listCheckConstraints( + connection: PGConfig, + schemaName = "public", + tableName: string, +) { const cached = postgresCache.getChecks(connection, schemaName, tableName); if (cached !== null) return cached; @@ -679,11 +691,12 @@ export async function listCheckConstraints(connection: PGConfig, schemaName = "p postgresCache.setChecks(connection, schemaName, tableName, res.rows); return res.rows; } finally { - try { await client.release(); } catch { } + try { + await client.release(); + } catch {} } } - export async function listEnumTypes(connection: PGConfig, schemaName = "public") { const cached = postgresCache.getEnums(connection, schemaName); if (cached !== null) return cached; @@ -696,7 +709,9 @@ export async function listEnumTypes(connection: PGConfig, schemaName = "public") postgresCache.setEnums(connection, schemaName, res.rows); return res.rows; } finally { - try { await client.release(); } catch { } + try { + await client.release(); + } catch {} } } @@ -712,11 +727,12 @@ export async function listSequences(connection: PGConfig, schemaName = "public") postgresCache.setSequences(connection, schemaName, res.rows); return res.rows; } finally { - try { await client.release(); } catch { } + try { + await client.release(); + } catch {} } } - // ============================================ // BATCH QUERIES FOR PERFORMANCE OPTIMIZATION // ============================================ @@ -727,16 +743,19 @@ export async function listSequences(connection: PGConfig, schemaName = "public") */ export async function getSchemaMetadataBatch( connection: PGConfig, - schemaName: string + schemaName: string, ): Promise<{ - tables: Map; + tables: Map< + string, + { + columns: ColumnDetail[]; + primaryKeys: PrimaryKeyInfo[]; + foreignKeys: ForeignKeyInfo[]; + indexes: IndexInfo[]; + uniqueConstraints: UniqueConstraintInfo[]; + checkConstraints: CheckConstraintInfo[]; + } + >; enumTypes: EnumInfo[]; sequences: SequenceInfo[]; }> { @@ -744,7 +763,6 @@ export async function getSchemaMetadataBatch( const client = await pool.connect(); try { - // Execute all queries in parallel using imported batch queries const [ columnsResult, @@ -754,7 +772,7 @@ export async function getSchemaMetadataBatch( uniqueResult, checksResult, enumsResult, - sequencesResult + sequencesResult, ] = await Promise.all([ // All columns in schema client.query(PG_BATCH_GET_ALL_COLUMNS, [schemaName]), @@ -778,18 +796,21 @@ export async function getSchemaMetadataBatch( client.query(PG_LIST_ENUMS, [schemaName]), // All sequences in schema - client.query(PG_LIST_SEQUENCES, [schemaName]) + client.query(PG_LIST_SEQUENCES, [schemaName]), ]); // Group results by table - const tables = new Map(); + const tables = new Map< + string, + { + columns: ColumnDetail[]; + primaryKeys: PrimaryKeyInfo[]; + foreignKeys: ForeignKeyInfo[]; + indexes: IndexInfo[]; + uniqueConstraints: UniqueConstraintInfo[]; + checkConstraints: CheckConstraintInfo[]; + } + >(); // Process columns for (const row of columnsResult.rows) { @@ -800,7 +821,7 @@ export async function getSchemaMetadataBatch( foreignKeys: [], indexes: [], uniqueConstraints: [], - checkConstraints: [] + checkConstraints: [], }); } tables.get(row.table_name)!.columns.push({ @@ -814,7 +835,7 @@ export async function getSchemaMetadataBatch( is_serial: row.is_serial, check_constraint: row.check_constraint, comment: row.comment, - ordinal_position: row.ordinal_position + ordinal_position: row.ordinal_position, }); } @@ -822,7 +843,7 @@ export async function getSchemaMetadataBatch( for (const row of primaryKeysResult.rows) { if (tables.has(row.table_name)) { tables.get(row.table_name)!.primaryKeys.push({ - column_name: row.column_name + column_name: row.column_name, }); } } @@ -858,14 +879,15 @@ export async function getSchemaMetadataBatch( return { tables, enumTypes: enumsResult.rows, - sequences: sequencesResult.rows + sequences: sequencesResult.rows, }; } finally { - try { await client.release(); } catch { } + try { + await client.release(); + } catch {} } } - /** * streamQueryCancelable: * - uses pg-query-stream to stream results @@ -877,7 +899,7 @@ export function streamQueryCancelable( sql: string, batchSize: number, onBatch: (rows: any[], columns: { name: string }[]) => Promise | void, - onDone?: () => void + onDone?: () => void, ): { promise: Promise; cancel: () => Promise } { let client: PoolClient | null = null; let stream: Readable | null = null; @@ -920,7 +942,7 @@ export function streamQueryCancelable( flush().catch((e) => { try { reject(e); - } catch { } + } catch {} }); } }); @@ -949,7 +971,7 @@ export function streamQueryCancelable( } finally { try { await client.release(); - } catch (e) { } + } catch (e) {} } } })(); @@ -1057,17 +1079,13 @@ export async function listSchemas(connection: PGConfig) { } catch (err) { try { await client.release(); - } catch (e) { } + } catch (e) {} throw err; } } /** getTableDetails: Retrieves column details for a specific table. */ -export async function getTableDetails( - connection: PGConfig, - schemaName: string, - tableName: string -) { +export async function getTableDetails(connection: PGConfig, schemaName: string, tableName: string) { // Check cache first const cached = postgresCache.getTableDetails(connection, schemaName, tableName); if (cached !== null) { @@ -1109,16 +1127,14 @@ export async function createTable( schemaName: string, tableName: string, columns: ColumnDetail[], - foreignKeys: ForeignKeyInfo[] = [] + foreignKeys: ForeignKeyInfo[] = [], ) { const pool = getPool(conn); const client = await pool.connect(); - const primaryKeys = columns - .filter(c => c.is_primary_key) - .map(c => quoteIdent(c.name)); + const primaryKeys = columns.filter((c) => c.is_primary_key).map((c) => quoteIdent(c.name)); - const columnDefs = columns.map(col => { + const columnDefs = columns.map((col) => { if (!PG_TYPE_MAP[col.type]) { throw new Error(`Invalid type: ${col.type}`); } @@ -1127,7 +1143,7 @@ export async function createTable( quoteIdent(col.name), PG_TYPE_MAP[col.type], col.not_nullable || col.is_primary_key ? "NOT NULL" : "", - col.default_value ? `DEFAULT ${col.default_value}` : "" + col.default_value ? `DEFAULT ${col.default_value}` : "", ].filter(Boolean); return parts.join(" "); @@ -1182,28 +1198,27 @@ function groupIndexes(indexes: IndexInfo[]) { map.get(idx.index_name)!.push(idx); } - return [...map.values()].map(group => - group.sort((a, b) => (a.ordinal_position ?? 0) - (b.ordinal_position ?? 0)) + return [...map.values()].map((group) => + group.sort((a, b) => (a.ordinal_position ?? 0) - (b.ordinal_position ?? 0)), ); } export async function createIndexes( conn: PGConfig, schemaName: string, - indexes: IndexInfo[] + indexes: IndexInfo[], ): Promise { const pool = getPool(conn); const client = await pool.connect(); const grouped = groupIndexes(indexes); try { - for (const group of grouped) { const first = group[0]; // Skip PK indexes (already handled in CREATE TABLE) if (first.is_primary) continue; - const columns = group.map(i => quoteIdent(i.column_name)).join(", "); + const columns = group.map((i) => quoteIdent(i.column_name)).join(", "); const query = ` CREATE ${first.is_unique ? "UNIQUE" : ""} INDEX IF NOT EXISTS @@ -1225,12 +1240,11 @@ export async function createIndexes( } } - export async function alterTable( conn: PGConfig, schemaName: string, tableName: string, - operations: PGAlterTableOperation[] + operations: PGAlterTableOperation[], ): Promise { const pool = getPool(conn); const client = await pool.connect(); @@ -1317,12 +1331,11 @@ export async function alterTable( } } - export async function dropTable( conn: PGConfig, schemaName: string, tableName: string, - mode: PGDropMode = "RESTRICT" + mode: PGDropMode = "RESTRICT", ): Promise { const pool = getPool(conn); const client = await pool.connect(); @@ -1345,12 +1358,12 @@ export async function dropTable( AND ccu.table_schema = $1 AND ccu.table_name = $2; `, - [schemaName, tableName] + [schemaName, tableName], ); if (rows.length > 0 && mode === "RESTRICT") { throw new Error( - `Cannot drop table "${tableName}" — referenced by ${rows.length} foreign key(s)` + `Cannot drop table "${tableName}" — referenced by ${rows.length} foreign key(s)`, ); } @@ -1409,7 +1422,7 @@ export async function insertBaseline( conn: PGConfig, version: string, name: string, - checksum: string + checksum: string, ): Promise { const pool = getPool(conn); const client = await pool.connect(); @@ -1426,7 +1439,7 @@ export async function insertBaseline( export async function baselineIfNeeded( conn: PGConfig, migrationsDir: string, - snapshot?: SchemaFile + snapshot?: SchemaFile, ) { const pool = getPool(conn); const client = await pool.connect(); @@ -1448,20 +1461,12 @@ export async function baselineIfNeeded( schemas: [], cachedAt: "", relwaveVersion: "", - schemaHash: "" + schemaHash: "", }; - const filePath = writeBaselineMigration( - migrationsDir, - version, - name, - fakeSnapshot - ); + const filePath = writeBaselineMigration(migrationsDir, version, name, fakeSnapshot); - const checksum = crypto - .createHash("sha256") - .update(fs.readFileSync(filePath)) - .digest("hex"); + const checksum = crypto.createHash("sha256").update(fs.readFileSync(filePath)).digest("hex"); await insertBaseline(conn, version, name, checksum); @@ -1471,16 +1476,11 @@ export async function baselineIfNeeded( } } - - -export async function listAppliedMigrations( - cfg: PGConfig, -): Promise { +export async function listAppliedMigrations(cfg: PGConfig): Promise { const pool = getPool(cfg); const client = await pool.connect(); try { - // Important: table may not exist yet const tableExists = await client.query(` SELECT 1 @@ -1502,12 +1502,10 @@ export async function listAppliedMigrations( } } - - export async function connectToDatabase( cfg: PGConfig, connectionId: string, - options?: { readOnly?: boolean } + options?: { readOnly?: boolean }, ) { // 1️⃣ Baseline (only if allowed) let baselineResult = { baselined: false }; @@ -1520,9 +1518,9 @@ export async function connectToDatabase( try { const project = await projectStoreInstance.getProjectByDatabaseId(connectionId); if (project) { - snapshot = await projectStoreInstance.getSchema(project.id) || undefined; + snapshot = (await projectStoreInstance.getSchema(project.id)) || undefined; } - } catch { } + } catch {} baselineResult = await baselineIfNeeded(cfg, migrationsDir, snapshot); } @@ -1540,29 +1538,25 @@ export async function connectToDatabase( schema, migrations: { local: localMigrations, - applied: appliedMigrations - } + applied: appliedMigrations, + }, }; } /** * Apply a pending migration */ -export async function applyMigration( - cfg: PGConfig, - migrationFilePath: string -): Promise { +export async function applyMigration(cfg: PGConfig, migrationFilePath: string): Promise { const pool = getPool(cfg); const client = await pool.connect(); try { - // Read and parse migration file - const { readMigrationFile } = await import('../utils/migrationFileReader'); + const { readMigrationFile } = await import("../utils/migrationFileReader"); const migration = readMigrationFile(migrationFilePath); // Begin transaction - await client.query('BEGIN'); + await client.query("BEGIN"); // Execute up SQL await client.query(migration.upSQL); @@ -1571,18 +1565,18 @@ export async function applyMigration( await client.query( `INSERT INTO schema_migrations (version, name, checksum) VALUES ($1, $2, $3)`, - [migration.version, migration.name, migration.checksum] + [migration.version, migration.name, migration.checksum], ); // Commit transaction - await client.query('COMMIT'); + await client.query("COMMIT"); // Clear cache postgresCache.clearForConnection(cfg); return true; } catch (error) { - await client.query('ROLLBACK'); + await client.query("ROLLBACK"); throw error; } finally { await client.release(); @@ -1595,19 +1589,18 @@ export async function applyMigration( export async function rollbackMigration( cfg: PGConfig, version: string, - migrationFilePath: string + migrationFilePath: string, ): Promise { const pool = getPool(cfg); const client = await pool.connect(); try { - // Read and parse migration file - const { readMigrationFile } = await import('../utils/migrationFileReader'); + const { readMigrationFile } = await import("../utils/migrationFileReader"); const migration = readMigrationFile(migrationFilePath); // Begin transaction - await client.query('BEGIN'); + await client.query("BEGIN"); // Execute down SQL await client.query(migration.downSQL); @@ -1616,14 +1609,14 @@ export async function rollbackMigration( await client.query(PG_DELETE_MIGRATION, [version]); // Commit transaction - await client.query('COMMIT'); + await client.query("COMMIT"); // Clear cache postgresCache.clearForConnection(cfg); return true; } catch (error) { - await client.query('ROLLBACK'); + await client.query("ROLLBACK"); throw error; } finally { await client.release(); @@ -1642,13 +1635,12 @@ export async function insertRow( cfg: PGConfig, schemaName: string, tableName: string, - rowData: Record + rowData: Record, ): Promise { const pool = getPool(cfg); const client = await pool.connect(); try { - const columns = Object.keys(rowData); const values = Object.values(rowData); @@ -1659,7 +1651,7 @@ export async function insertRow( // Build parameterized query const safeSchema = `"${schemaName.replace(/"/g, '""')}"`; const safeTable = `"${tableName.replace(/"/g, '""')}"`; - const columnList = columns.map(col => `"${col.replace(/"/g, '""')}"`).join(", "); + const columnList = columns.map((col) => `"${col.replace(/"/g, '""')}"`).join(", "); const placeholders = columns.map((_, i) => `$${i + 1}`).join(", "); const query = ` @@ -1679,7 +1671,7 @@ export async function insertRow( } finally { try { await client.release(); - } catch (_) { } + } catch (_) {} } } @@ -1699,13 +1691,12 @@ export async function updateRow( tableName: string, primaryKeyColumn: string, primaryKeyValue: any, - rowData: Record + rowData: Record, ): Promise { const pool = getPool(cfg); const client = await pool.connect(); try { - const columns = Object.keys(rowData); const values = Object.values(rowData); @@ -1725,7 +1716,7 @@ export async function updateRow( let whereClause: string; let whereValues: any[]; - if (typeof primaryKeyColumn === 'string' && primaryKeyColumn) { + if (typeof primaryKeyColumn === "string" && primaryKeyColumn) { // Single primary key const safePkColumn = `"${primaryKeyColumn.replace(/"/g, '""')}"`; whereClause = `${safePkColumn} = $${columns.length + 1}`; @@ -1752,7 +1743,7 @@ export async function updateRow( } finally { try { await client.release(); - } catch (_) { } + } catch (_) {} } } @@ -1770,30 +1761,27 @@ export async function deleteRow( schemaName: string, tableName: string, primaryKeyColumn: string, - primaryKeyValue: any + primaryKeyValue: any, ): Promise { const pool = getPool(cfg); const client = await pool.connect(); try { - const safeSchema = `"${schemaName.replace(/"/g, '""')}"`; const safeTable = `"${tableName.replace(/"/g, '""')}"`; let whereClause: string; let whereValues: any[]; - if (primaryKeyColumn && typeof primaryKeyColumn === 'string') { + if (primaryKeyColumn && typeof primaryKeyColumn === "string") { // Single primary key const safePkColumn = `"${primaryKeyColumn.replace(/"/g, '""')}"`; whereClause = `${safePkColumn} = $1`; whereValues = [primaryKeyValue]; - } else if (typeof primaryKeyValue === 'object' && primaryKeyValue !== null) { + } else if (typeof primaryKeyValue === "object" && primaryKeyValue !== null) { // Composite key - use all columns from the object const cols = Object.keys(primaryKeyValue); - whereClause = cols - .map((col, i) => `"${col.replace(/"/g, '""')}" = $${i + 1}`) - .join(" AND "); + whereClause = cols.map((col, i) => `"${col.replace(/"/g, '""')}" = $${i + 1}`).join(" AND "); whereValues = Object.values(primaryKeyValue); } else { throw new Error("Either primary key or where conditions required for delete"); @@ -1815,7 +1803,7 @@ export async function deleteRow( } finally { try { await client.release(); - } catch (_) { } + } catch (_) {} } } @@ -1836,16 +1824,15 @@ export async function searchTable( searchTerm: string, column?: string, page: number = 1, - pageSize: number = 50 + pageSize: number = 50, ): Promise<{ rows: any[]; total: number }> { const pool = getPool(cfg); const client = await pool.connect(); try { - const safeSchema = `"${schemaName.replace(/"/g, '""')}"`; const safeTable = `"${tableName.replace(/"/g, '""')}"`; - const searchPattern = `%${searchTerm.replace(/[%_]/g, '\\$&')}%`; + const searchPattern = `%${searchTerm.replace(/[%_]/g, "\\$&")}%`; let whereClause: string; let values: any[]; @@ -1863,7 +1850,7 @@ export async function searchTable( WHERE table_schema = $1 AND table_name = $2 `; const colResult = await client.query(colQuery, [schemaName, tableName]); - const columns = colResult.rows.map(r => r.column_name); + const columns = colResult.rows.map((r) => r.column_name); if (columns.length === 0) { return { rows: [], total: 0 }; @@ -1900,7 +1887,7 @@ export async function searchTable( } finally { try { await client.release(); - } catch (_) { } + } catch (_) {} } } @@ -1920,6 +1907,6 @@ export async function listSchemaNames(connection: PGConfig): Promise { } finally { try { await client.release(); - } catch (e) { } + } catch (e) {} } } diff --git a/bridge/src/connectors/sqlite.ts b/bridge/src/connectors/sqlite.ts index f5b9f758..37f5c44c 100644 --- a/bridge/src/connectors/sqlite.ts +++ b/bridge/src/connectors/sqlite.ts @@ -8,12 +8,7 @@ import path from "path"; import { ensureDir } from "../utils/config"; import { projectStoreInstance } from "../services/projectStore"; import { isWindowsDriveRootPath, normalizeSQLitePath } from "../utils/sqlitePath"; -import { - CacheEntry, - CACHE_TTL, - STATS_CACHE_TTL, - SCHEMA_CACHE_TTL -} from "../types/cache"; +import { CacheEntry, CACHE_TTL, STATS_CACHE_TTL, SCHEMA_CACHE_TTL } from "../types/cache"; import { TableInfo, DBStats, @@ -52,7 +47,7 @@ import { SQLITE_CHECK_MIGRATIONS_EXIST, SQLITE_INSERT_MIGRATION, SQLITE_LIST_APPLIED_MIGRATIONS, - SQLITE_DELETE_MIGRATION + SQLITE_DELETE_MIGRATION, } from "../queries/sqlite/migrations"; import { SQLITE_GET_TABLE_SQL } from "../queries/sqlite/constraints"; import { sqliteQuoteIdentifier } from "../queries/sqlite/crud"; @@ -204,9 +199,13 @@ export class SQLiteCacheManager { clearForConnection(cfg: SQLiteConfig): void { const configKey = this.getConfigKey(cfg); for (const cache of [ - this.tableListCache, this.primaryKeysCache, this.tableDetailsCache, - this.foreignKeysCache, this.indexesCache, this.uniqueCache, - this.checksCache + this.tableListCache, + this.primaryKeysCache, + this.tableDetailsCache, + this.foreignKeysCache, + this.indexesCache, + this.uniqueCache, + this.checksCache, ]) { for (const [key] of cache) { if (key.startsWith(configKey)) cache.delete(key); @@ -264,33 +263,37 @@ let cachedNativeBindingPath: string | null | undefined = undefined; function validateSQLitePath( rawPath: string, - options: { requireExistingFile?: boolean } = {} + options: { requireExistingFile?: boolean } = {}, ): string { const dbPath = normalizeSQLitePath(rawPath); if (!dbPath || !dbPath.trim()) { - throw new Error(`Invalid SQLite path: path is empty or missing. Received: ${JSON.stringify(rawPath)}`); + throw new Error( + `Invalid SQLite path: path is empty or missing. Received: ${JSON.stringify(rawPath)}`, + ); } if (isWindowsDriveRootPath(dbPath)) { throw new Error( - `Invalid SQLite path "${dbPath}" - it points to a Windows drive root, not a database file.` + `Invalid SQLite path "${dbPath}" - it points to a Windows drive root, not a database file.`, ); } - const validExtensions = ['.db', '.sqlite', '.sqlite3', '.db3', '.s3db', '.sl3']; - const ext = dbPath.substring(dbPath.lastIndexOf('.')).toLowerCase(); - - if (dbPath !== ':memory:' && !validExtensions.includes(ext)) { + const validExtensions = [".db", ".sqlite", ".sqlite3", ".db3", ".s3db", ".sl3"]; + const ext = dbPath.substring(dbPath.lastIndexOf(".")).toLowerCase(); + + if (dbPath !== ":memory:" && !validExtensions.includes(ext)) { throw new Error( - `Invalid SQLite path "${dbPath}" - must have a valid SQLite extension (.db, .sqlite, etc.) to prevent arbitrary file access.` + `Invalid SQLite path "${dbPath}" - must have a valid SQLite extension (.db, .sqlite, etc.) to prevent arbitrary file access.`, ); } if (fs.existsSync(dbPath)) { const stat = fs.statSync(dbPath); if (stat.isDirectory()) { - throw new Error(`Invalid SQLite path "${dbPath}" - it points to a directory, not a database file.`); + throw new Error( + `Invalid SQLite path "${dbPath}" - it points to a directory, not a database file.`, + ); } return dbPath; } @@ -346,7 +349,8 @@ export function resolvePkgNativeBindingPath(): string | undefined { return undefined; } - const envOverride = process.env.RELWAVE_SQLITE_NATIVE_BINDING || process.env.BETTER_SQLITE3_BINDING; + const envOverride = + process.env.RELWAVE_SQLITE_NATIVE_BINDING || process.env.BETTER_SQLITE3_BINDING; if (envOverride) { const resolvedOverride = path.resolve(envOverride); if (fs.existsSync(resolvedOverride)) { @@ -379,8 +383,21 @@ export function resolvePkgNativeBindingPath(): string | undefined { snapshotCandidates.push( path.join(pkgDir, "build", "Release", "better_sqlite3.node"), path.join(pkgDir, "build", "Debug", "better_sqlite3.node"), - path.join(pkgDir, "compiled", `${process.versions.node}`, process.platform, process.arch, "better_sqlite3.node"), - path.join(pkgDir, "lib", "binding", `node-v${process.versions.modules}-${process.platform}-${process.arch}`, "better_sqlite3.node") + path.join( + pkgDir, + "compiled", + `${process.versions.node}`, + process.platform, + process.arch, + "better_sqlite3.node", + ), + path.join( + pkgDir, + "lib", + "binding", + `node-v${process.versions.modules}-${process.platform}-${process.arch}`, + "better_sqlite3.node", + ), ); } catch { // Ignore; fall back to hardcoded snapshot paths below. @@ -389,9 +406,36 @@ export function resolvePkgNativeBindingPath(): string | undefined { const snapshotRoot = path.join(path.sep, "snapshot", "bridge", "node_modules"); snapshotCandidates.push( path.join(snapshotRoot, "better-sqlite3", "build", "Release", "better_sqlite3.node"), - path.join(snapshotRoot, ".pnpm", "better-sqlite3@12.6.2", "node_modules", "better-sqlite3", "build", "Release", "better_sqlite3.node"), - path.join(snapshotRoot, ".pnpm", "better-sqlite3@11.10.0", "node_modules", "better-sqlite3", "build", "Release", "better_sqlite3.node"), - path.join(snapshotRoot, ".pnpm", "better-sqlite3@11.9.0", "node_modules", "better-sqlite3", "build", "Release", "better_sqlite3.node") + path.join( + snapshotRoot, + ".pnpm", + "better-sqlite3@12.6.2", + "node_modules", + "better-sqlite3", + "build", + "Release", + "better_sqlite3.node", + ), + path.join( + snapshotRoot, + ".pnpm", + "better-sqlite3@11.10.0", + "node_modules", + "better-sqlite3", + "build", + "Release", + "better_sqlite3.node", + ), + path.join( + snapshotRoot, + ".pnpm", + "better-sqlite3@11.9.0", + "node_modules", + "better-sqlite3", + "build", + "Release", + "better_sqlite3.node", + ), ); const targetNodeFile = path.join(os.tmpdir(), `relwave-better_sqlite3-${process.pid}.node`); @@ -441,7 +485,9 @@ function quoteIdent(name: string): string { // ============================================ /** Test connection to SQLite database (checks if file is accessible) */ -export async function testConnection(cfg: SQLiteConfig): Promise<{ ok: boolean; message?: string; status: 'connected' | 'disconnected' }> { +export async function testConnection( + cfg: SQLiteConfig, +): Promise<{ ok: boolean; message?: string; status: "connected" | "disconnected" }> { try { const dbPath = validateSQLitePath(cfg.path, { requireExistingFile: true }); @@ -453,9 +499,12 @@ export async function testConnection(cfg: SQLiteConfig): Promise<{ ok: boolean; }; } // Use fileMustExist so better-sqlite3 will not create a new file during connection test - const db = openDB({ ...cfg, path: dbPath }, { - fileMustExist: true, - }); + const db = openDB( + { ...cfg, path: dbPath }, + { + fileMustExist: true, + }, + ); db.pragma("journal_mode"); db.close(); return { ok: true, status: "connected", message: "Connection successful" }; @@ -480,7 +529,11 @@ export async function listTables(cfg: SQLiteConfig, _schemaName?: string): Promi } /** List primary keys for a table */ -export async function listPrimaryKeys(cfg: SQLiteConfig, schemaName: string = 'main', tableName: string): Promise { +export async function listPrimaryKeys( + cfg: SQLiteConfig, + schemaName: string = "main", + tableName: string, +): Promise { const cached = sqliteCache.getPrimaryKeys(cfg, schemaName, tableName); if (cached !== null) return cached; @@ -499,7 +552,11 @@ export async function listPrimaryKeys(cfg: SQLiteConfig, schemaName: string = 'm } /** List foreign keys for a table */ -export async function listForeignKeys(cfg: SQLiteConfig, schemaName: string = 'main', tableName: string): Promise { +export async function listForeignKeys( + cfg: SQLiteConfig, + schemaName: string = "main", + tableName: string, +): Promise { const cached = sqliteCache.getForeignKeys(cfg, schemaName, tableName); if (cached !== null) return cached; @@ -514,8 +571,8 @@ export async function listForeignKeys(cfg: SQLiteConfig, schemaName: string = 'm target_schema: schemaName, target_table: fk.table, target_column: fk.to, - update_rule: fk.on_update || 'NO ACTION', - delete_rule: fk.on_delete || 'NO ACTION', + update_rule: fk.on_update || "NO ACTION", + delete_rule: fk.on_delete || "NO ACTION", ordinal_position: fk.seq, })); @@ -527,7 +584,11 @@ export async function listForeignKeys(cfg: SQLiteConfig, schemaName: string = 'm } /** List indexes for a table */ -export async function listIndexes(cfg: SQLiteConfig, schemaName: string = 'main', tableName: string): Promise { +export async function listIndexes( + cfg: SQLiteConfig, + schemaName: string = "main", + tableName: string, +): Promise { const cached = sqliteCache.getIndexes(cfg, schemaName, tableName); if (cached !== null) return cached; @@ -544,8 +605,8 @@ export async function listIndexes(cfg: SQLiteConfig, schemaName: string = 'main' index_name: idx.name, column_name: col.name, is_unique: idx.unique === 1, - is_primary: idx.origin === 'pk', - index_type: 'btree', + is_primary: idx.origin === "pk", + index_type: "btree", ordinal_position: col.seqno, }); } @@ -559,7 +620,11 @@ export async function listIndexes(cfg: SQLiteConfig, schemaName: string = 'main' } /** List unique constraints for a table */ -export async function listUniqueConstraints(cfg: SQLiteConfig, schemaName: string = 'main', tableName: string): Promise { +export async function listUniqueConstraints( + cfg: SQLiteConfig, + schemaName: string = "main", + tableName: string, +): Promise { const cached = sqliteCache.getUnique(cfg, schemaName, tableName); if (cached !== null) return cached; @@ -569,7 +634,7 @@ export async function listUniqueConstraints(cfg: SQLiteConfig, schemaName: strin const result: UniqueConstraintInfo[] = []; for (const idx of indexes) { - if (idx.unique !== 1 || idx.origin === 'pk') continue; + if (idx.unique !== 1 || idx.origin === "pk") continue; const cols = db.pragma(`index_info(${quoteIdent(idx.name)})`) as any[]; for (const col of cols) { result.push({ @@ -590,7 +655,11 @@ export async function listUniqueConstraints(cfg: SQLiteConfig, schemaName: strin } /** List check constraints for a table (best-effort via CREATE TABLE SQL parsing) */ -export async function listCheckConstraints(cfg: SQLiteConfig, schemaName: string = 'main', tableName: string): Promise { +export async function listCheckConstraints( + cfg: SQLiteConfig, + schemaName: string = "main", + tableName: string, +): Promise { const cached = sqliteCache.getChecks(cfg, schemaName, tableName); if (cached !== null) return cached; @@ -634,7 +703,7 @@ export async function getDBStats(cfg: SQLiteConfig): Promise { // Get DB file size const pageCount = db.pragma("page_count", { simple: true }) as number; const pageSize = db.pragma("page_size", { simple: true }) as number; - const totalSizeMB = (pageCount * pageSize) / (1024 * 1024); // Count total rows across all tables. + const totalSizeMB = (pageCount * pageSize) / (1024 * 1024); // Count total rows across all tables. // Removed because better-sqlite3 is synchronous and SELECT COUNT(*) blocks the Node event loop. let totalRows = -1; @@ -656,18 +725,22 @@ export async function listSchemas(cfg: SQLiteConfig): Promise { const cached = sqliteCache.getSchemas(cfg); if (cached !== null) return cached; - const result: SchemaInfo[] = [{ name: 'main' }]; + const result: SchemaInfo[] = [{ name: "main" }]; sqliteCache.setSchemas(cfg, result); return result; } /** List schema names */ export async function listSchemaNames(cfg: SQLiteConfig): Promise { - return ['main']; + return ["main"]; } /** Get table column details */ -export async function getTableDetails(cfg: SQLiteConfig, schemaName: string, tableName: string): Promise { +export async function getTableDetails( + cfg: SQLiteConfig, + schemaName: string, + tableName: string, +): Promise { const cached = sqliteCache.getTableDetails(cfg, schemaName, tableName); if (cached !== null) return cached; @@ -681,7 +754,7 @@ export async function getTableDetails(cfg: SQLiteConfig, schemaName: string, tab .filter((col: any) => !col.hidden || col.hidden === 0) .map((col: any) => ({ name: col.name, - type: col.type || 'TEXT', + type: col.type || "TEXT", not_nullable: col.notnull === 1, default_value: col.dflt_value, is_primary_key: col.pk > 0, @@ -698,19 +771,22 @@ export async function getTableDetails(cfg: SQLiteConfig, schemaName: string, tab /** Fetch all table metadata in batch for a schema */ export async function getSchemaMetadataBatch( cfg: SQLiteConfig, - _schemaName: string + _schemaName: string, ): Promise { const db = openDB(cfg); try { const tableRows = db.prepare(SQLITE_LIST_TABLES).all() as any[]; - const tables = new Map(); + const tables = new Map< + string, + { + columns: ColumnDetail[]; + primaryKeys: PrimaryKeyInfo[]; + foreignKeys: ForeignKeyInfo[]; + indexes: IndexInfo[]; + uniqueConstraints: UniqueConstraintInfo[]; + checkConstraints: CheckConstraintInfo[]; + } + >(); for (const t of tableRows) { const tableName = t.name; @@ -724,13 +800,13 @@ export async function getSchemaMetadataBatch( .filter((col: any) => !col.hidden || col.hidden === 0) .map((col: any) => ({ name: col.name, - type: col.type || 'TEXT', + type: col.type || "TEXT", not_nullable: col.notnull === 1, default_value: col.dflt_value, is_primary_key: col.pk > 0, is_foreign_key: fkColumns.has(col.name), is_unique: false, // will be updated below if unique index exists - is_serial: col.pk > 0 && (col.type || '').toLowerCase() === 'integer', + is_serial: col.pk > 0 && (col.type || "").toLowerCase() === "integer", check_constraint: undefined, comment: undefined, ordinal_position: col.cid + 1, @@ -742,14 +818,14 @@ export async function getSchemaMetadataBatch( const foreignKeys: ForeignKeyInfo[] = fks.map((fk: any) => ({ constraint_name: `fk_${tableName}_${fk.from}_${fk.id}`, - source_schema: 'main', + source_schema: "main", source_table: tableName, source_column: fk.from, - target_schema: 'main', + target_schema: "main", target_table: fk.table, target_column: fk.to, - update_rule: fk.on_update || 'NO ACTION', - delete_rule: fk.on_delete || 'NO ACTION', + update_rule: fk.on_update || "NO ACTION", + delete_rule: fk.on_delete || "NO ACTION", ordinal_position: fk.seq, })); @@ -766,19 +842,19 @@ export async function getSchemaMetadataBatch( index_name: idx.name, column_name: col.name, is_unique: idx.unique === 1, - is_primary: idx.origin === 'pk', - index_type: 'btree', + is_primary: idx.origin === "pk", + index_type: "btree", ordinal_position: col.seqno, }); if (idx.unique === 1) { - const c = columns.find(c => c.name === col.name); + const c = columns.find((c) => c.name === col.name); if (c) c.is_unique = true; - if (idx.origin !== 'pk') { + if (idx.origin !== "pk") { uniqueConstraints.push({ constraint_name: idx.name, - table_schema: 'main', + table_schema: "main", table_name: tableName, column_name: col.name, ordinal_position: col.seqno, @@ -798,7 +874,7 @@ export async function getSchemaMetadataBatch( while ((match = checkRegex.exec(tableRow.sql)) !== null) { checkConstraints.push({ constraint_name: `check_${tableName}_${idx++}`, - table_schema: 'main', + table_schema: "main", table_name: tableName, definition: `CHECK(${match[1]})`, }); @@ -830,7 +906,7 @@ export function streamQueryCancelable( sql: string, batchSize: number, onBatch: (rows: any[], columns: { name: string }[]) => Promise | void, - onDone?: () => void + onDone?: () => void, ): { promise: Promise; cancel: () => Promise } { let cancelled = false; @@ -880,7 +956,7 @@ export async function fetchTableData( _schemaName: string, tableName: string, limit: number, - page: number + page: number, ): Promise<{ rows: any[]; total: number }> { const db = openDB(cfg); try { @@ -888,7 +964,7 @@ export async function fetchTableData( const offset = (page - 1) * limit; // Get primary keys for ordering - const pkResult = await listPrimaryKeys(cfg, 'main', tableName); + const pkResult = await listPrimaryKeys(cfg, "main", tableName); const pkColumns = pkResult.map((r) => quoteIdent(r.column_name)); let orderBy = ""; @@ -901,7 +977,9 @@ export async function fetchTableData( const countRow = db.prepare(`SELECT COUNT(*) AS count FROM ${safeTable}`).get() as any; const total = Number(countRow.count); - const rows = db.prepare(`SELECT * FROM ${safeTable} ${orderBy} LIMIT ? OFFSET ?`).all(limit, offset); + const rows = db + .prepare(`SELECT * FROM ${safeTable} ${orderBy} LIMIT ? OFFSET ?`) + .all(limit, offset); return { rows, total }; } catch (error) { throw new Error(`Failed to fetch paginated data from ${tableName}: ${error}`); @@ -925,21 +1003,19 @@ export async function createTable( _schemaName: string, tableName: string, columns: ColumnDetail[], - foreignKeys: ForeignKeyInfo[] = [] + foreignKeys: ForeignKeyInfo[] = [], ): Promise { const db = openDB(cfg); try { - const primaryKeys = columns - .filter(c => c.is_primary_key) - .map(c => quoteIdent(c.name)); + const primaryKeys = columns.filter((c) => c.is_primary_key).map((c) => quoteIdent(c.name)); - const columnDefs = columns.map(col => { + const columnDefs = columns.map((col) => { const sqlType = SQLITE_TYPE_MAP[col.type] || col.type; const parts = [ quoteIdent(col.name), sqlType, col.not_nullable || col.is_primary_key ? "NOT NULL" : "", - col.default_value ? `DEFAULT ${col.default_value}` : "" + col.default_value ? `DEFAULT ${col.default_value}` : "", ].filter(Boolean); return parts.join(" "); }); @@ -952,8 +1028,8 @@ export async function createTable( for (const fk of foreignKeys) { columnDefs.push( `FOREIGN KEY (${quoteIdent(fk.source_column)}) REFERENCES ${quoteIdent(fk.target_table)}(${quoteIdent(fk.target_column)})` + - (fk.delete_rule ? ` ON DELETE ${fk.delete_rule}` : '') + - (fk.update_rule ? ` ON UPDATE ${fk.update_rule}` : '') + (fk.delete_rule ? ` ON DELETE ${fk.delete_rule}` : "") + + (fk.update_rule ? ` ON UPDATE ${fk.update_rule}` : ""), ); } @@ -973,7 +1049,7 @@ export async function createTable( export async function createIndexes( cfg: SQLiteConfig, _schemaName: string, - indexes: IndexInfo[] + indexes: IndexInfo[], ): Promise { const db = openDB(cfg); try { @@ -990,7 +1066,7 @@ export async function createIndexes( const first = sorted[0]; if (first.is_primary) continue; - const cols = sorted.map(i => quoteIdent(i.column_name)).join(", "); + const cols = sorted.map((i) => quoteIdent(i.column_name)).join(", "); const sql = `CREATE ${first.is_unique ? "UNIQUE" : ""} INDEX IF NOT EXISTS ${quoteIdent(first.index_name)} ON ${quoteIdent(first.table_name)} (${cols});`; db.exec(sql); } @@ -1008,7 +1084,7 @@ export async function alterTable( cfg: SQLiteConfig, _schemaName: string, tableName: string, - operations: SQLiteAlterTableOperation[] + operations: SQLiteAlterTableOperation[], ): Promise { const db = openDB(cfg); try { @@ -1018,9 +1094,11 @@ export async function alterTable( switch (op.type) { case "ADD_COLUMN": { const sqlType = SQLITE_TYPE_MAP[op.column.type] || op.column.type; - sql = `ALTER TABLE ${quoteIdent(tableName)} ADD COLUMN ${quoteIdent(op.column.name)} ${sqlType}` + + sql = + `ALTER TABLE ${quoteIdent(tableName)} ADD COLUMN ${quoteIdent(op.column.name)} ${sqlType}` + (op.column.not_nullable ? " NOT NULL" : "") + - (op.column.default_value ? ` DEFAULT ${op.column.default_value}` : "") + ";"; + (op.column.default_value ? ` DEFAULT ${op.column.default_value}` : "") + + ";"; break; } case "DROP_COLUMN": @@ -1049,7 +1127,7 @@ export async function dropTable( cfg: SQLiteConfig, _schemaName: string, tableName: string, - _mode: SQLiteDropMode = "RESTRICT" + _mode: SQLiteDropMode = "RESTRICT", ): Promise { const db = openDB(cfg); try { @@ -1076,9 +1154,11 @@ export async function hasAnyMigrations(cfg: SQLiteConfig): Promise { const db = openDB(cfg); try { // Check if table exists first - const tableExists = db.prepare( - `SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_migrations' LIMIT 1` - ).get(); + const tableExists = db + .prepare( + `SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_migrations' LIMIT 1`, + ) + .get(); if (!tableExists) return false; const row = db.prepare(SQLITE_CHECK_MIGRATIONS_EXIST).get(); @@ -1093,7 +1173,7 @@ export async function insertBaseline( cfg: SQLiteConfig, version: string, name: string, - checksum: string + checksum: string, ): Promise { const db = openDB(cfg); try { @@ -1108,7 +1188,7 @@ export async function insertBaseline( export async function baselineIfNeeded( cfg: SQLiteConfig, migrationsDir: string, - snapshot?: SchemaFile + snapshot?: SchemaFile, ) { await ensureMigrationTable(cfg); @@ -1126,15 +1206,12 @@ export async function baselineIfNeeded( schemas: [], cachedAt: "", relwaveVersion: "", - schemaHash: "" + schemaHash: "", }; const filePath = writeBaselineMigration(migrationsDir, version, name, fakeSnapshot); - const checksum = crypto - .createHash("sha256") - .update(fs.readFileSync(filePath)) - .digest("hex"); + const checksum = crypto.createHash("sha256").update(fs.readFileSync(filePath)).digest("hex"); await insertBaseline(cfg, version, name, checksum); @@ -1145,9 +1222,11 @@ export async function baselineIfNeeded( export async function listAppliedMigrations(cfg: SQLiteConfig): Promise { const db = openDB(cfg); try { - const tableExists = db.prepare( - `SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_migrations' LIMIT 1` - ).get(); + const tableExists = db + .prepare( + `SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_migrations' LIMIT 1`, + ) + .get(); if (!tableExists) return []; const rows = db.prepare(SQLITE_LIST_APPLIED_MIGRATIONS).all() as AppliedMigration[]; @@ -1161,7 +1240,7 @@ export async function listAppliedMigrations(cfg: SQLiteConfig): Promise { const db = openDB(cfg); try { - const { readMigrationFile } = await import('../utils/migrationFileReader'); + const { readMigrationFile } = await import("../utils/migrationFileReader"); const migration = readMigrationFile(migrationFilePath); const transaction = db.transaction(() => { db.exec(migration.upSQL); - db.prepare(SQLITE_INSERT_MIGRATION).run(migration.version, migration.name, migration.checksum); + db.prepare(SQLITE_INSERT_MIGRATION).run( + migration.version, + migration.name, + migration.checksum, + ); }); transaction(); @@ -1222,11 +1305,11 @@ export async function applyMigration( export async function rollbackMigration( cfg: SQLiteConfig, version: string, - migrationFilePath: string + migrationFilePath: string, ): Promise { const db = openDB(cfg); try { - const { readMigrationFile } = await import('../utils/migrationFileReader'); + const { readMigrationFile } = await import("../utils/migrationFileReader"); const migration = readMigrationFile(migrationFilePath); const transaction = db.transaction(() => { @@ -1249,7 +1332,7 @@ export async function insertRow( cfg: SQLiteConfig, _schemaName: string, tableName: string, - rowData: Record + rowData: Record, ): Promise { const db = openDB(cfg); try { @@ -1259,7 +1342,7 @@ export async function insertRow( if (columns.length === 0) throw new Error("No data provided for insert"); const safeTable = quoteIdent(tableName); - const columnList = columns.map(col => quoteIdent(col)).join(", "); + const columnList = columns.map((col) => quoteIdent(col)).join(", "); const placeholders = columns.map(() => "?").join(", "); const sql = `INSERT INTO ${safeTable} (${columnList}) VALUES (${placeholders});`; @@ -1285,7 +1368,7 @@ export async function updateRow( tableName: string, primaryKeyColumn: string, primaryKeyValue: any, - rowData: Record + rowData: Record, ): Promise { const db = openDB(cfg); try { @@ -1295,9 +1378,9 @@ export async function updateRow( if (columns.length === 0) throw new Error("No data provided for update"); const safeTable = quoteIdent(tableName); - const setClause = columns.map(col => `${quoteIdent(col)} = ?`).join(", "); + const setClause = columns.map((col) => `${quoteIdent(col)} = ?`).join(", "); - if (!primaryKeyColumn || typeof primaryKeyColumn !== 'string') { + if (!primaryKeyColumn || typeof primaryKeyColumn !== "string") { throw new Error("Primary key column is required for update"); } @@ -1305,7 +1388,9 @@ export async function updateRow( db.prepare(sql).run(...values, primaryKeyValue); // Return updated row - const updated = db.prepare(`SELECT * FROM ${safeTable} WHERE ${quoteIdent(primaryKeyColumn)} = ?`).get(primaryKeyValue); + const updated = db + .prepare(`SELECT * FROM ${safeTable} WHERE ${quoteIdent(primaryKeyColumn)} = ?`) + .get(primaryKeyValue); sqliteCache.clearForConnection(cfg); return updated; @@ -1322,7 +1407,7 @@ export async function deleteRow( _schemaName: string, tableName: string, primaryKeyColumn: string, - primaryKeyValue: any + primaryKeyValue: any, ): Promise { const db = openDB(cfg); try { @@ -1331,12 +1416,12 @@ export async function deleteRow( let sql: string; let values: any[]; - if (primaryKeyColumn && typeof primaryKeyColumn === 'string') { + if (primaryKeyColumn && typeof primaryKeyColumn === "string") { sql = `DELETE FROM ${safeTable} WHERE ${quoteIdent(primaryKeyColumn)} = ?;`; values = [primaryKeyValue]; - } else if (typeof primaryKeyValue === 'object' && primaryKeyValue !== null) { + } else if (typeof primaryKeyValue === "object" && primaryKeyValue !== null) { const cols = Object.keys(primaryKeyValue); - const whereClause = cols.map(col => `${quoteIdent(col)} = ?`).join(" AND "); + const whereClause = cols.map((col) => `${quoteIdent(col)} = ?`).join(" AND "); sql = `DELETE FROM ${safeTable} WHERE ${whereClause};`; values = Object.values(primaryKeyValue); } else { @@ -1361,12 +1446,12 @@ export async function searchTable( searchTerm: string, column?: string, page: number = 1, - pageSize: number = 50 + pageSize: number = 50, ): Promise<{ rows: any[]; total: number }> { const db = openDB(cfg); try { const safeTable = quoteIdent(tableName); - const searchPattern = `%${searchTerm.replace(/[%_]/g, '\\$&')}%`; + const searchPattern = `%${searchTerm.replace(/[%_]/g, "\\$&")}%`; let whereClause: string; @@ -1381,14 +1466,18 @@ export async function searchTable( if (columnNames.length === 0) return { rows: [], total: 0 }; whereClause = columnNames - .map(col => `CAST(${quoteIdent(col)} AS TEXT) LIKE ? ESCAPE '\\'`) + .map((col) => `CAST(${quoteIdent(col)} AS TEXT) LIKE ? ESCAPE '\\'`) .join(" OR "); } // For multi-column search, we reuse the same search pattern parameter // SQLite doesn't support named params the same way, but we can use // a single value repeated - const paramCount = column ? 1 : (db.pragma(`table_xinfo(${quoteIdent(tableName)})`) as any[]).filter((c: any) => !c.hidden || c.hidden === 0).length; + const paramCount = column + ? 1 + : (db.pragma(`table_xinfo(${quoteIdent(tableName)})`) as any[]).filter( + (c: any) => !c.hidden || c.hidden === 0, + ).length; const params = Array(paramCount).fill(searchPattern); const countQuery = `SELECT COUNT(*) AS total FROM ${safeTable} WHERE ${whereClause}`; diff --git a/bridge/src/handlers/README.md b/bridge/src/handlers/README.md index 110354bf..2e882b99 100644 --- a/bridge/src/handlers/README.md +++ b/bridge/src/handlers/README.md @@ -3,6 +3,7 @@ This folder contains JSON-RPC handler classes. Handlers translate frontend RPC calls into service/query work and send normalized RPC responses or errors. Layout + - `databaseHandlers.ts` - database connection CRUD, connection tests and schema/table metadata entry points. - `queryHandlers.ts` - query execution, table browsing and table/row mutation handlers. - `sessionHandlers.ts` - query session lifecycle and cancellation. @@ -15,11 +16,13 @@ Layout - `aiHandlers.ts` - AI provider tests, schema analysis, query explanation, chart recommendation and history. How it fits + - `src/jsonRpcHandler.ts` constructs handlers and registers public method names such as `db.list`, `query.run`, `project.create`, `git.status` and `ai.analyzeSchema`. - Handlers depend on services like `DatabaseService`, `QueryExecutor`, `MonitoringService` and `GitService`. - Handlers own RPC validation and error mapping. Services and connectors should throw normal errors rather than calling `rpc.sendResponse` directly. How to add an RPC method + 1. Add a handler method in the correct handler class. 2. Validate required params near the top of the handler. 3. Call service/query logic and return `{ ok: true, data }` through `rpc.sendResponse`. @@ -28,6 +31,7 @@ How to add an RPC method 6. Add or update the matching frontend bridge service in `src/services/bridge`. Notes + - Keep handler classes thin. If logic grows beyond request validation and orchestration, move it into `src/services`. - Avoid leaking credentials in responses; strip or omit password and credential identifiers before responding. - Use stable error codes because the frontend may surface them in notifications. diff --git a/bridge/src/handlers/aiHandlers.ts b/bridge/src/handlers/aiHandlers.ts index cf09daa5..6155b3ba 100644 --- a/bridge/src/handlers/aiHandlers.ts +++ b/bridge/src/handlers/aiHandlers.ts @@ -29,7 +29,11 @@ import { DatabaseService } from "../services/databaseService"; export class AIHandlers { private aiService: AIService; - constructor(private rpc: Rpc, private logger: Logger, private dbService: DatabaseService) { + constructor( + private rpc: Rpc, + private logger: Logger, + private dbService: DatabaseService, + ) { this.aiService = new AIService(); } @@ -46,7 +50,10 @@ export class AIHandlers { } } - async handleAnalyzeSchema(params: AIAnalyzeSchemaParams & { skipCache?: boolean }, id: number | string) { + async handleAnalyzeSchema( + params: AIAnalyzeSchemaParams & { skipCache?: boolean }, + id: number | string, + ) { try { if (!params?.input?.tables?.length) { return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "No tables provided." }); @@ -85,7 +92,10 @@ export class AIHandlers { } } - async handleExplainQuery(params: AIExplainQueryParams & { skipCache?: boolean }, id: number | string) { + async handleExplainQuery( + params: AIExplainQueryParams & { skipCache?: boolean }, + id: number | string, + ) { try { if (!params?.input?.sql?.trim()) { return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "No SQL provided." }); @@ -124,10 +134,16 @@ export class AIHandlers { } } - async handleRecommendChart(params: AIRecommendChartParams & { skipCache?: boolean }, id: number | string) { + async handleRecommendChart( + params: AIRecommendChartParams & { skipCache?: boolean }, + id: number | string, + ) { try { if (!params?.input?.tableName || !params?.input?.columns?.length) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing tableName or columns." }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing tableName or columns.", + }); } const hash = hashChartRecommendation(params.input, params.datasourceName); @@ -178,7 +194,16 @@ export class AIHandlers { // ── History CRUD handlers ───────────────────────────────────────────── - async handleGetHistory(params: { feature?: string; provider?: string; datasource_id?: string; limit?: number; offset?: number }, id: number | string) { + async handleGetHistory( + params: { + feature?: string; + provider?: string; + datasource_id?: string; + limit?: number; + offset?: number; + }, + id: number | string, + ) { try { const result = aiHistoryStore.list({ feature: params?.feature, @@ -211,11 +236,14 @@ export class AIHandlers { try { const { question, databaseId, settings, history, options } = params; if (!question || !databaseId || !settings) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing question, databaseId, or settings" }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing question, databaseId, or settings", + }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(databaseId); - + const { nlSqlService } = require("../services/nlSqlService"); const response = await nlSqlService.naturalLanguageToSQL({ question, @@ -224,7 +252,7 @@ export class AIHandlers { history, options, dbType, - conn + conn, }); this.rpc.sendResponse(id, response); @@ -277,11 +305,7 @@ export class AIHandlers { async handleSaveSettings(params: { settings: AISettings }, id: number | string) { try { ensureDir(CONFIG_FOLDER); - await fs.writeFile( - AI_SETTINGS_FILE, - JSON.stringify(params.settings, null, 2), - "utf-8" - ); + await fs.writeFile(AI_SETTINGS_FILE, JSON.stringify(params.settings, null, 2), "utf-8"); // On non-Windows platforms, restrict file permissions (contains API keys) if (process.platform !== "win32") { await fs.chmod(AI_SETTINGS_FILE, 0o600); diff --git a/bridge/src/handlers/databaseHandlers.ts b/bridge/src/handlers/databaseHandlers.ts index 2699be8e..0d42d119 100644 --- a/bridge/src/handlers/databaseHandlers.ts +++ b/bridge/src/handlers/databaseHandlers.ts @@ -9,8 +9,8 @@ export class DatabaseHandlers { private rpc: Rpc, private logger: Logger, private dbService: DatabaseService, - private queryExecutor: QueryExecutor - ) { } + private queryExecutor: QueryExecutor, + ) {} async handleListDatabases(params: any, id: number | string) { try { @@ -140,10 +140,10 @@ export class DatabaseHandlers { }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - // stats were in statsHandlers, but some methods might be here. - // Actually handleGetStats is usually in StatsHandlers. + // stats were in statsHandlers, but some methods might be here. + // Actually handleGetStats is usually in StatsHandlers. // I'll check if I missed any method. - } catch (e) { } + } catch (e) {} } async handleUpdateDatabase(params: any, id: number | string) { @@ -200,7 +200,7 @@ export class DatabaseHandlers { const buildResult = await ConnectionBuilder.buildConnection( connection, connection.password ?? null, - dbType + dbType, ); conn = buildResult.config; tunnelToClose = buildResult.tunnel; @@ -208,7 +208,7 @@ export class DatabaseHandlers { const result = await this.queryExecutor.testConnection(conn, dbType); this.rpc.sendResponse(id, { ok: true, data: result }); } catch (err: any) { - this.logger.error({ err }, '[Handler] testConnection error'); + this.logger.error({ err }, "[Handler] testConnection error"); this.rpc.sendResponse(id, { ok: false, message: String(err) }); } finally { if (tunnelToClose) { diff --git a/bridge/src/handlers/gitAdvancedHandlers.ts b/bridge/src/handlers/gitAdvancedHandlers.ts index 6daae6b1..13109297 100644 --- a/bridge/src/handlers/gitAdvancedHandlers.ts +++ b/bridge/src/handlers/gitAdvancedHandlers.ts @@ -9,193 +9,181 @@ import { GitService, gitServiceInstance } from "../services/gitService"; import { Logger } from "pino"; export class GitAdvancedHandlers { - constructor( - private rpc: Rpc, - private logger?: Logger, - private gitService: GitService = gitServiceInstance - ) { } + constructor( + private rpc: Rpc, + private logger?: Logger, + private gitService: GitService = gitServiceInstance, + ) {} - private requireDir(params: any, id: number | string): string | null { - const dir = params?.dir || params?.path || params?.cwd; - if (!dir) { - this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'dir' parameter (project directory path)", - }); - return null; - } - return dir; + private requireDir(params: any, id: number | string): string | null { + const dir = params?.dir || params?.path || params?.cwd; + if (!dir) { + this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'dir' parameter (project directory path)", + }); + return null; } + return dir; + } - // ========================================== - // REMOTE MANAGEMENT - // ========================================== + // ========================================== + // REMOTE MANAGEMENT + // ========================================== - async handleRemoteList(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const remotes = await this.gitService.remoteList(dir); - this.rpc.sendResponse(id, { ok: true, data: remotes }); - } catch (e: any) { - this.logger?.error({ e }, "git.remoteList failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleRemoteList(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const remotes = await this.gitService.remoteList(dir); + this.rpc.sendResponse(id, { ok: true, data: remotes }); + } catch (e: any) { + this.logger?.error({ e }, "git.remoteList failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleRemoteAdd(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const name = params?.name; - const url = params?.url; - if (!name || !url) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'name' and/or 'url' parameters", - }); - } - await this.gitService.remoteAdd(dir, name, url); - this.rpc.sendResponse(id, { ok: true, data: null }); - } catch (e: any) { - this.logger?.error({ e }, "git.remoteAdd failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleRemoteAdd(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const name = params?.name; + const url = params?.url; + if (!name || !url) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'name' and/or 'url' parameters", + }); + } + await this.gitService.remoteAdd(dir, name, url); + this.rpc.sendResponse(id, { ok: true, data: null }); + } catch (e: any) { + this.logger?.error({ e }, "git.remoteAdd failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleRemoteRemove(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const name = params?.name; - if (!name) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'name' parameter", - }); - } - await this.gitService.remoteRemove(dir, name); - this.rpc.sendResponse(id, { ok: true, data: null }); - } catch (e: any) { - this.logger?.error({ e }, "git.remoteRemove failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleRemoteRemove(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const name = params?.name; + if (!name) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'name' parameter", + }); + } + await this.gitService.remoteRemove(dir, name); + this.rpc.sendResponse(id, { ok: true, data: null }); + } catch (e: any) { + this.logger?.error({ e }, "git.remoteRemove failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleRemoteGetUrl(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const url = await this.gitService.remoteGetUrl(dir, params?.name || "origin"); - this.rpc.sendResponse(id, { ok: true, data: { url } }); - } catch (e: any) { - this.logger?.error({ e }, "git.remoteGetUrl failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleRemoteGetUrl(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const url = await this.gitService.remoteGetUrl(dir, params?.name || "origin"); + this.rpc.sendResponse(id, { ok: true, data: { url } }); + } catch (e: any) { + this.logger?.error({ e }, "git.remoteGetUrl failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleRemoteSetUrl(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const name = params?.name; - const url = params?.url; - if (!name || !url) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'name' and/or 'url' parameters", - }); - } - await this.gitService.remoteSetUrl(dir, name, url); - this.rpc.sendResponse(id, { ok: true, data: null }); - } catch (e: any) { - this.logger?.error({ e }, "git.remoteSetUrl failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleRemoteSetUrl(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const name = params?.name; + const url = params?.url; + if (!name || !url) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'name' and/or 'url' parameters", + }); + } + await this.gitService.remoteSetUrl(dir, name, url); + this.rpc.sendResponse(id, { ok: true, data: null }); + } catch (e: any) { + this.logger?.error({ e }, "git.remoteSetUrl failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - // ========================================== - // PUSH / PULL / FETCH - // ========================================== + // ========================================== + // PUSH / PULL / FETCH + // ========================================== - async handlePush(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const output = await this.gitService.push( - dir, - params?.remote || "origin", - params?.branch, - { - force: params?.force === true, - setUpstream: params?.setUpstream === true, - } - ); - this.rpc.sendResponse(id, { ok: true, data: { output } }); - } catch (e: any) { - this.logger?.error({ e }, "git.push failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handlePush(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const output = await this.gitService.push(dir, params?.remote || "origin", params?.branch, { + force: params?.force === true, + setUpstream: params?.setUpstream === true, + }); + this.rpc.sendResponse(id, { ok: true, data: { output } }); + } catch (e: any) { + this.logger?.error({ e }, "git.push failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handlePull(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const output = await this.gitService.pull( - dir, - params?.remote || "origin", - params?.branch, - { rebase: params?.rebase === true } - ); - this.rpc.sendResponse(id, { ok: true, data: { output } }); - } catch (e: any) { - this.logger?.error({ e }, "git.pull failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handlePull(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const output = await this.gitService.pull(dir, params?.remote || "origin", params?.branch, { + rebase: params?.rebase === true, + }); + this.rpc.sendResponse(id, { ok: true, data: { output } }); + } catch (e: any) { + this.logger?.error({ e }, "git.pull failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleFetch(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const output = await this.gitService.fetch( - dir, - params?.remote, - { - prune: params?.prune === true, - all: params?.all === true, - } - ); - this.rpc.sendResponse(id, { ok: true, data: { output } }); - } catch (e: any) { - this.logger?.error({ e }, "git.fetch failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleFetch(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const output = await this.gitService.fetch(dir, params?.remote, { + prune: params?.prune === true, + all: params?.all === true, + }); + this.rpc.sendResponse(id, { ok: true, data: { output } }); + } catch (e: any) { + this.logger?.error({ e }, "git.fetch failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - // ========================================== - // REVERT (Rollback to Previous Commit) - // ========================================== + // ========================================== + // REVERT (Rollback to Previous Commit) + // ========================================== - async handleRevert(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const hash = params?.hash || params?.commitHash; - if (!hash) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'hash' parameter", - }); - } - const output = await this.gitService.revert(dir, hash, { - noCommit: params?.noCommit === true, - }); - this.rpc.sendResponse(id, { ok: true, data: { output } }); - } catch (e: any) { - this.logger?.error({ e }, "git.revert failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleRevert(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const hash = params?.hash || params?.commitHash; + if (!hash) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'hash' parameter", + }); + } + const output = await this.gitService.revert(dir, hash, { + noCommit: params?.noCommit === true, + }); + this.rpc.sendResponse(id, { ok: true, data: { output } }); + } catch (e: any) { + this.logger?.error({ e }, "git.revert failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } } diff --git a/bridge/src/handlers/gitHandlers.ts b/bridge/src/handlers/gitHandlers.ts index ec333b27..07e25b4f 100644 --- a/bridge/src/handlers/gitHandlers.ts +++ b/bridge/src/handlers/gitHandlers.ts @@ -24,280 +24,276 @@ import { gitServiceInstance, GitService } from "../services/gitService"; * git.ensureIgnore — write/update .gitignore */ export class GitHandlers { - constructor( - private rpc: Rpc, - private logger: Logger, - private gitService: GitService = gitServiceInstance - ) { } + constructor( + private rpc: Rpc, + private logger: Logger, + private gitService: GitService = gitServiceInstance, + ) {} - // ---- Helpers ---- + // ---- Helpers ---- - private requireDir(params: any, id: number | string): string | null { - const dir = params?.dir || params?.path || params?.cwd; - if (!dir) { - this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'dir' parameter (project directory path)", - }); - return null; - } - return dir; + private requireDir(params: any, id: number | string): string | null { + const dir = params?.dir || params?.path || params?.cwd; + if (!dir) { + this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'dir' parameter (project directory path)", + }); + return null; } + return dir; + } - // ---- Handlers ---- + // ---- Handlers ---- - async handleStatus(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const status = await this.gitService.getStatus(dir); - this.rpc.sendResponse(id, { ok: true, data: status }); - } catch (e: any) { - this.logger?.error({ e }, "git.status failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleStatus(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const status = await this.gitService.getStatus(dir); + this.rpc.sendResponse(id, { ok: true, data: status }); + } catch (e: any) { + this.logger?.error({ e }, "git.status failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleInit(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - await this.gitService.init(dir, params?.defaultBranch || "main"); - // Also set up .gitignore - await this.gitService.ensureGitignore(dir); - const status = await this.gitService.getStatus(dir); - this.rpc.sendResponse(id, { ok: true, data: status }); - } catch (e: any) { - this.logger?.error({ e }, "git.init failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleInit(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + await this.gitService.init(dir, params?.defaultBranch || "main"); + // Also set up .gitignore + await this.gitService.ensureGitignore(dir); + const status = await this.gitService.getStatus(dir); + this.rpc.sendResponse(id, { ok: true, data: status }); + } catch (e: any) { + this.logger?.error({ e }, "git.init failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleChanges(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const changes = await this.gitService.getChangedFiles(dir); - this.rpc.sendResponse(id, { ok: true, data: changes }); - } catch (e: any) { - this.logger?.error({ e }, "git.changes failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleChanges(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const changes = await this.gitService.getChangedFiles(dir); + this.rpc.sendResponse(id, { ok: true, data: changes }); + } catch (e: any) { + this.logger?.error({ e }, "git.changes failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleStage(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const files: string[] = params?.files; - if (!files?.length) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'files' array", - }); - } - await this.gitService.stageFiles(dir, files); - this.rpc.sendResponse(id, { ok: true, data: null }); - } catch (e: any) { - this.logger?.error({ e }, "git.stage failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleStage(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const files: string[] = params?.files; + if (!files?.length) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'files' array", + }); + } + await this.gitService.stageFiles(dir, files); + this.rpc.sendResponse(id, { ok: true, data: null }); + } catch (e: any) { + this.logger?.error({ e }, "git.stage failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleStageAll(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - await this.gitService.stageAll(dir); - this.rpc.sendResponse(id, { ok: true, data: null }); - } catch (e: any) { - this.logger?.error({ e }, "git.stageAll failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleStageAll(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + await this.gitService.stageAll(dir); + this.rpc.sendResponse(id, { ok: true, data: null }); + } catch (e: any) { + this.logger?.error({ e }, "git.stageAll failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleUnstage(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const files: string[] = params?.files; - if (!files?.length) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'files' array", - }); - } - await this.gitService.unstageFiles(dir, files); - this.rpc.sendResponse(id, { ok: true, data: null }); - } catch (e: any) { - this.logger?.error({ e }, "git.unstage failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleUnstage(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const files: string[] = params?.files; + if (!files?.length) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'files' array", + }); + } + await this.gitService.unstageFiles(dir, files); + this.rpc.sendResponse(id, { ok: true, data: null }); + } catch (e: any) { + this.logger?.error({ e }, "git.unstage failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleCommit(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const message = params?.message; - if (!message) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'message' parameter", - }); - } - const hash = await this.gitService.commit(dir, message); - this.rpc.sendResponse(id, { ok: true, data: { hash } }); - } catch (e: any) { - this.logger?.error({ e }, "git.commit failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleCommit(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const message = params?.message; + if (!message) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'message' parameter", + }); + } + const hash = await this.gitService.commit(dir, message); + this.rpc.sendResponse(id, { ok: true, data: { hash } }); + } catch (e: any) { + this.logger?.error({ e }, "git.commit failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleLog(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const count = params?.count ?? 20; - const entries = await this.gitService.log(dir, count); - this.rpc.sendResponse(id, { ok: true, data: entries }); - } catch (e: any) { - this.logger?.error({ e }, "git.log failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleLog(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const count = params?.count ?? 20; + const entries = await this.gitService.log(dir, count); + this.rpc.sendResponse(id, { ok: true, data: entries }); + } catch (e: any) { + this.logger?.error({ e }, "git.log failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleLogGraph(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const count = params?.count ?? 100; - const entries = await this.gitService.logGraph(dir, count); - this.rpc.sendResponse(id, { ok: true, data: entries }); - } catch (e: any) { - this.logger?.error({ e }, "git.logGraph failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleLogGraph(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const count = params?.count ?? 100; + const entries = await this.gitService.logGraph(dir, count); + this.rpc.sendResponse(id, { ok: true, data: entries }); + } catch (e: any) { + this.logger?.error({ e }, "git.logGraph failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleBranches(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const branches = await this.gitService.listBranches(dir); - this.rpc.sendResponse(id, { ok: true, data: branches }); - } catch (e: any) { - this.logger?.error({ e }, "git.branches failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleBranches(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const branches = await this.gitService.listBranches(dir); + this.rpc.sendResponse(id, { ok: true, data: branches }); + } catch (e: any) { + this.logger?.error({ e }, "git.branches failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleCreateBranch(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const name = params?.name; - if (!name) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'name' parameter", - }); - } - await this.gitService.createBranch(dir, name); - this.rpc.sendResponse(id, { ok: true, data: { branch: name } }); - } catch (e: any) { - this.logger?.error({ e }, "git.createBranch failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleCreateBranch(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const name = params?.name; + if (!name) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'name' parameter", + }); + } + await this.gitService.createBranch(dir, name); + this.rpc.sendResponse(id, { ok: true, data: { branch: name } }); + } catch (e: any) { + this.logger?.error({ e }, "git.createBranch failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleCheckout(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const name = params?.name; - if (!name) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'name' parameter", - }); - } - await this.gitService.checkoutBranch(dir, name); - this.rpc.sendResponse(id, { ok: true, data: { branch: name } }); - } catch (e: any) { - this.logger?.error({ e }, "git.checkout failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleCheckout(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const name = params?.name; + if (!name) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'name' parameter", + }); + } + await this.gitService.checkoutBranch(dir, name); + this.rpc.sendResponse(id, { ok: true, data: { branch: name } }); + } catch (e: any) { + this.logger?.error({ e }, "git.checkout failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleDiscard(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const files: string[] = params?.files; - if (!files?.length) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing 'files' array", - }); - } - await this.gitService.discardChanges(dir, files); - this.rpc.sendResponse(id, { ok: true, data: null }); - } catch (e: any) { - this.logger?.error({ e }, "git.discard failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleDiscard(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const files: string[] = params?.files; + if (!files?.length) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing 'files' array", + }); + } + await this.gitService.discardChanges(dir, files); + this.rpc.sendResponse(id, { ok: true, data: null }); + } catch (e: any) { + this.logger?.error({ e }, "git.discard failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleStash(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - await this.gitService.stash(dir, params?.message); - this.rpc.sendResponse(id, { ok: true, data: null }); - } catch (e: any) { - this.logger?.error({ e }, "git.stash failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleStash(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + await this.gitService.stash(dir, params?.message); + this.rpc.sendResponse(id, { ok: true, data: null }); + } catch (e: any) { + this.logger?.error({ e }, "git.stash failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleStashPop(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - await this.gitService.stashPop(dir); - this.rpc.sendResponse(id, { ok: true, data: null }); - } catch (e: any) { - this.logger?.error({ e }, "git.stashPop failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleStashPop(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + await this.gitService.stashPop(dir); + this.rpc.sendResponse(id, { ok: true, data: null }); + } catch (e: any) { + this.logger?.error({ e }, "git.stashPop failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleDiff(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const diff = await this.gitService.diff( - dir, - params?.file, - params?.staged === true - ); - this.rpc.sendResponse(id, { ok: true, data: { diff } }); - } catch (e: any) { - this.logger?.error({ e }, "git.diff failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleDiff(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const diff = await this.gitService.diff(dir, params?.file, params?.staged === true); + this.rpc.sendResponse(id, { ok: true, data: { diff } }); + } catch (e: any) { + this.logger?.error({ e }, "git.diff failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } - async handleEnsureIgnore(params: any, id: number | string) { - const dir = this.requireDir(params, id); - if (!dir) return; - try { - const modified = await this.gitService.ensureGitignore(dir); - this.rpc.sendResponse(id, { ok: true, data: { modified } }); - } catch (e: any) { - this.logger?.error({ e }, "git.ensureIgnore failed"); - this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); - } + async handleEnsureIgnore(params: any, id: number | string) { + const dir = this.requireDir(params, id); + if (!dir) return; + try { + const modified = await this.gitService.ensureGitignore(dir); + this.rpc.sendResponse(id, { ok: true, data: { modified } }); + } catch (e: any) { + this.logger?.error({ e }, "git.ensureIgnore failed"); + this.rpc.sendError(id, { code: "GIT_ERROR", message: String(e.message || e) }); } + } } diff --git a/bridge/src/handlers/migrationHandlers.ts b/bridge/src/handlers/migrationHandlers.ts index 9cbdcbb0..ebc4463f 100644 --- a/bridge/src/handlers/migrationHandlers.ts +++ b/bridge/src/handlers/migrationHandlers.ts @@ -7,497 +7,541 @@ import fs from "fs"; import { projectStoreInstance } from "../services/projectStore"; export class MigrationHandlers { - constructor( - private rpc: Rpc, - private logger: Logger, - private dbService: DatabaseService, - private queryExecutor: QueryExecutor - ) { } - - async handleGenerateCreateMigration(params: any, id: number | string) { - try { - const { dbId, schemaName, tableName, columns, foreignKeys = [] } = params || {}; - - if (!dbId || !schemaName || !tableName || !columns) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing required parameters", - }); - } - - const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); - - // Generate migration file - const { generateCreateTableMigration, writeMigrationFile } = await import('../utils/migrationGenerator'); - const migration = generateCreateTableMigration({ - schemaName, - tableName, - columns, - foreignKeys, - dbType, - }); - - const filepath = writeMigrationFile(migrationsDir, migration); - - this.rpc.sendResponse(id, { - ok: true, - data: { - version: migration.version, - filename: migration.filename, - filepath, - }, - }); - } catch (e: any) { - this.logger?.error({ e }, "migration.generateCreate failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } + constructor( + private rpc: Rpc, + private logger: Logger, + private dbService: DatabaseService, + private queryExecutor: QueryExecutor, + ) {} + + async handleGenerateCreateMigration(params: any, id: number | string) { + try { + const { dbId, schemaName, tableName, columns, foreignKeys = [] } = params || {}; + + if (!dbId || !schemaName || !tableName || !columns) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing required parameters", + }); + } + + const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); + const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + + // Generate migration file + const { generateCreateTableMigration, writeMigrationFile } = + await import("../utils/migrationGenerator"); + const migration = generateCreateTableMigration({ + schemaName, + tableName, + columns, + foreignKeys, + dbType, + }); + + const filepath = writeMigrationFile(migrationsDir, migration); + + this.rpc.sendResponse(id, { + ok: true, + data: { + version: migration.version, + filename: migration.filename, + filepath, + }, + }); + } catch (e: any) { + this.logger?.error({ e }, "migration.generateCreate failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } - - async handleGenerateAlterMigration(params: any, id: number | string) { - try { - const { dbId, schemaName, tableName, operations } = params || {}; - - if (!dbId || !schemaName || !tableName || !operations) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing required parameters", - }); - } - - const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); - - // Generate migration file - const { generateAlterTableMigration, writeMigrationFile } = await import('../utils/migrationGenerator'); - const migration = generateAlterTableMigration({ - schemaName, - tableName, - operations, - dbType, - }); - - const filepath = writeMigrationFile(migrationsDir, migration); - - this.rpc.sendResponse(id, { - ok: true, - data: { - version: migration.version, - filename: migration.filename, - filepath, - }, - }); - } catch (e: any) { - this.logger?.error({ e }, "migration.generateAlter failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } + } + + async handleGenerateAlterMigration(params: any, id: number | string) { + try { + const { dbId, schemaName, tableName, operations } = params || {}; + + if (!dbId || !schemaName || !tableName || !operations) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing required parameters", + }); + } + + const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); + const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + + // Generate migration file + const { generateAlterTableMigration, writeMigrationFile } = + await import("../utils/migrationGenerator"); + const migration = generateAlterTableMigration({ + schemaName, + tableName, + operations, + dbType, + }); + + const filepath = writeMigrationFile(migrationsDir, migration); + + this.rpc.sendResponse(id, { + ok: true, + data: { + version: migration.version, + filename: migration.filename, + filepath, + }, + }); + } catch (e: any) { + this.logger?.error({ e }, "migration.generateAlter failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } - - async handleGenerateDropMigration(params: any, id: number | string) { - try { - const { dbId, schemaName, tableName, mode = "RESTRICT" } = params || {}; - - if (!dbId || !schemaName || !tableName) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing required parameters", - }); - } - - const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); - - // Generate migration file - const { generateDropTableMigration, writeMigrationFile } = await import('../utils/migrationGenerator'); - const migration = generateDropTableMigration({ - schemaName, - tableName, - mode, - dbType, - }); - - const filepath = writeMigrationFile(migrationsDir, migration); - - this.rpc.sendResponse(id, { - ok: true, - data: { - version: migration.version, - filename: migration.filename, - filepath, - }, - }); - } catch (e: any) { - this.logger?.error({ e }, "migration.generateDrop failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } + } + + async handleGenerateDropMigration(params: any, id: number | string) { + try { + const { dbId, schemaName, tableName, mode = "RESTRICT" } = params || {}; + + if (!dbId || !schemaName || !tableName) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing required parameters", + }); + } + + const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); + const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + + // Generate migration file + const { generateDropTableMigration, writeMigrationFile } = + await import("../utils/migrationGenerator"); + const migration = generateDropTableMigration({ + schemaName, + tableName, + mode, + dbType, + }); + + const filepath = writeMigrationFile(migrationsDir, migration); + + this.rpc.sendResponse(id, { + ok: true, + data: { + version: migration.version, + filename: migration.filename, + filepath, + }, + }); + } catch (e: any) { + this.logger?.error({ e }, "migration.generateDrop failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } - - async handleApplyMigration(params: any, id: number | string) { - try { - const { dbId, version } = params || {}; - - if (!dbId || !version) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing dbId or version", - }); - } - - const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); - - // Find migration file - const { listMigrationFiles } = await import('../utils/migrationFileReader'); - const files = listMigrationFiles(migrationsDir); - const migrationFile = files.find(f => f.startsWith(version)); - - if (!migrationFile) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: `Migration file not found for version: ${version}`, - }); + } + + async handleApplyMigration(params: any, id: number | string) { + try { + const { dbId, version } = params || {}; + + if (!dbId || !version) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId or version", + }); + } + + const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); + const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + + // Find migration file + const { listMigrationFiles } = await import("../utils/migrationFileReader"); + const files = listMigrationFiles(migrationsDir); + const migrationFile = files.find((f) => f.startsWith(version)); + + if (!migrationFile) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: `Migration file not found for version: ${version}`, + }); + } + + const migrationFilePath = path.join(migrationsDir, migrationFile); + + if (dbType === "mysql") { + await this.queryExecutor.mysql.applyMigration(conn, migrationFilePath); + } else if (dbType === "postgres") { + await this.queryExecutor.postgres.applyMigration(conn, migrationFilePath); + } else if (dbType === "mariadb") { + await this.queryExecutor.mariadb.applyMigration(conn, migrationFilePath); + } else if (dbType === "sqlite") { + await this.queryExecutor.sqlite.applyMigration(conn, migrationFilePath); + } + + // Hook syncMigrationFiles + try { + const { projectStoreInstance } = await import("../services/projectStore"); + const { gitServiceInstance } = await import("../services/gitService"); + const { writeMigrationLock } = await import("../services/migrationLock"); + + const project = await projectStoreInstance.getProjectByDatabaseId(dbId); + if (project) { + // Update Migration Lock first so it gets included in the git sync commit + let appliedMigrations: any[] = []; + if (dbType === "mysql") { + appliedMigrations = await require("../connectors/mysql").listAppliedMigrations(conn); + } else if (dbType === "postgres") { + appliedMigrations = await require("../connectors/postgres").listAppliedMigrations(conn); + } else if (dbType === "mariadb") { + appliedMigrations = await require("../connectors/mariadb").listAppliedMigrations(conn); + } else if (dbType === "sqlite") { + appliedMigrations = await require("../connectors/sqlite").listAppliedMigrations(conn); + } + + const schemaFile = await projectStoreInstance.getSchema(project.id); + const schemaHash = (schemaFile as any)?.schemaHash || ""; + + const appliedVersions = appliedMigrations.map((m) => m.version); + await writeMigrationLock(dbId, schemaHash, appliedVersions); + + const projectDir = await projectStoreInstance.resolveProjectDir(project.id); + if (projectDir) { + const syncResult = await gitServiceInstance.syncMigrationFiles(projectDir); + if (syncResult.error) { + this.logger?.warn( + { error: syncResult.error }, + "Git sync failed after migration apply", + ); } - - const migrationFilePath = path.join(migrationsDir, migrationFile); - - if (dbType === "mysql") { - await this.queryExecutor.mysql.applyMigration(conn, migrationFilePath); - } else if (dbType === "postgres") { - await this.queryExecutor.postgres.applyMigration(conn, migrationFilePath); - } else if (dbType === "mariadb") { - await this.queryExecutor.mariadb.applyMigration(conn, migrationFilePath); - } else if (dbType === "sqlite") { - await this.queryExecutor.sqlite.applyMigration(conn, migrationFilePath); - } - - // Hook syncMigrationFiles - try { - const { projectStoreInstance } = await import("../services/projectStore"); - const { gitServiceInstance } = await import("../services/gitService"); - const { writeMigrationLock } = await import("../services/migrationLock"); - - const project = await projectStoreInstance.getProjectByDatabaseId(dbId); - if (project) { - // Update Migration Lock first so it gets included in the git sync commit - let appliedMigrations: any[] = []; - if (dbType === "mysql") { - appliedMigrations = await require("../connectors/mysql").listAppliedMigrations(conn); - } else if (dbType === "postgres") { - appliedMigrations = await require("../connectors/postgres").listAppliedMigrations(conn); - } else if (dbType === "mariadb") { - appliedMigrations = await require("../connectors/mariadb").listAppliedMigrations(conn); - } else if (dbType === "sqlite") { - appliedMigrations = await require("../connectors/sqlite").listAppliedMigrations(conn); - } - - const schemaFile = await projectStoreInstance.getSchema(project.id); - const schemaHash = (schemaFile as any)?.schemaHash || ""; - - const appliedVersions = appliedMigrations.map(m => m.version); - await writeMigrationLock(dbId, schemaHash, appliedVersions); - - const projectDir = await projectStoreInstance.resolveProjectDir(project.id); - if (projectDir) { - const syncResult = await gitServiceInstance.syncMigrationFiles(projectDir); - if (syncResult.error) { - this.logger?.warn({ error: syncResult.error }, "Git sync failed after migration apply"); - } - } - } - } catch (syncErr) { - this.logger?.error({ err: syncErr }, "syncMigrationFiles/lock hook failed"); - } - - this.rpc.sendResponse(id, { ok: true }); - } catch (e: any) { - this.logger?.error({ e }, "migration.apply failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } } + } catch (syncErr) { + this.logger?.error({ err: syncErr }, "syncMigrationFiles/lock hook failed"); + } + + this.rpc.sendResponse(id, { ok: true }); + } catch (e: any) { + this.logger?.error({ e }, "migration.apply failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } - - async handleApplyMigrations(params: any, id: number | string) { - try { - let { dbId, projectId } = params || {}; - - // Resolve dbId from projectId if not directly provided - if (!dbId && projectId) { - const project = await projectStoreInstance.getProject(projectId); - if (!project?.databaseId) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Project has no linked database" }); - } - dbId = project.databaseId; - } - if (!dbId) return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing dbId or projectId" }); - - const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); - - const { loadLocalMigrations } = await import('../utils/baselineMigration'); - const localMigrations = await loadLocalMigrations(migrationsDir); - - let connector: any; - if (dbType === "mysql") connector = require("../connectors/mysql"); - else if (dbType === "postgres") connector = require("../connectors/postgres"); - else if (dbType === "mariadb") connector = require("../connectors/mariadb"); - else if (dbType === "sqlite") connector = require("../connectors/sqlite"); - - const appliedMigrations = await connector.listAppliedMigrations(conn); - const appliedSet = new Set(appliedMigrations.map((m: any) => m.version)); - - const pending = localMigrations.filter(m => !appliedSet.has(m.version)).sort((a, b) => a.version.localeCompare(b.version)); - - for (const migration of pending) { - const migrationFile = (await fs.promises.readdir(migrationsDir)).find(f => f.startsWith(migration.version)); - if (!migrationFile) throw new Error(`Migration file not found for version: ${migration.version}`); - - const migrationFilePath = path.join(migrationsDir, migrationFile); - if (dbType === "mysql") await this.queryExecutor.mysql.applyMigration(conn, migrationFilePath); - else if (dbType === "postgres") await this.queryExecutor.postgres.applyMigration(conn, migrationFilePath); - else if (dbType === "mariadb") await this.queryExecutor.mariadb.applyMigration(conn, migrationFilePath); - else if (dbType === "sqlite") await this.queryExecutor.sqlite.applyMigration(conn, migrationFilePath); - } - - try { - const { projectStoreInstance } = await import("../services/projectStore"); - const { writeMigrationLock } = await import("../services/migrationLock"); - const project = await projectStoreInstance.getProjectByDatabaseId(dbId); - if (project) { - const schemaFile = await projectStoreInstance.getSchema(project.id); - const schemaHash = (schemaFile as any)?.schemaHash || ""; - const updatedApplied = await connector.listAppliedMigrations(conn); - await writeMigrationLock(dbId, schemaHash, updatedApplied.map((m: any) => m.version)); - } - } catch (syncErr) { - this.logger?.error({ err: syncErr }, "Lock hook failed"); - } - - this.rpc.sendResponse(id, { ok: true, count: pending.length }); - } catch (e: any) { - this.logger?.error({ e }, "migration.applyMigrations failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + + async handleApplyMigrations(params: any, id: number | string) { + try { + let { dbId, projectId } = params || {}; + + // Resolve dbId from projectId if not directly provided + if (!dbId && projectId) { + const project = await projectStoreInstance.getProject(projectId); + if (!project?.databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Project has no linked database", + }); } - } - - async handleApplySnapshot(params: any, id: number | string) { - try { - let { dbId, projectId } = params || {}; - const { projectStoreInstance } = await import("../services/projectStore"); - - // Resolve dbId from projectId if not directly provided - if (!dbId && projectId) { - const project = await projectStoreInstance.getProject(projectId); - if (!project?.databaseId) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Project has no linked database" }); - } - dbId = project.databaseId; - } - if (!dbId) return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing dbId or projectId" }); - - const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - - const project = await projectStoreInstance.getProjectByDatabaseId(dbId); - if (!project) throw new Error("Project not found for database"); - const snapshot = await projectStoreInstance.getSchema(project.id); - if (!snapshot) throw new Error("Schema snapshot not found"); - - const { generateBaselineSQL } = await import("../utils/baselineMigration"); - const baselineSQL = generateBaselineSQL(snapshot, Date.now().toString(), "apply_snapshot"); - - let connector: any; - if (dbType === "mysql") connector = require("../connectors/mysql"); - else if (dbType === "postgres") connector = require("../connectors/postgres"); - else if (dbType === "mariadb") connector = require("../connectors/mariadb"); - else if (dbType === "sqlite") connector = require("../connectors/sqlite"); - - // For full snapshot apply, we assume DB is empty or we should drop it. - // A full implementation would drop tables here. - // For now, we write the SQL and apply it. - - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); - const versionStr = Date.now().toString(); - const baselinePath = path.join(migrationsDir, `${versionStr}_apply_snapshot.sql`); - fs.writeFileSync(baselinePath, baselineSQL, "utf8"); - - if (dbType === "mysql") await this.queryExecutor.mysql.applyMigration(conn, baselinePath); - else if (dbType === "postgres") await this.queryExecutor.postgres.applyMigration(conn, baselinePath); - else if (dbType === "mariadb") await this.queryExecutor.mariadb.applyMigration(conn, baselinePath); - else if (dbType === "sqlite") await this.queryExecutor.sqlite.applyMigration(conn, baselinePath); - - if (fs.existsSync(baselinePath)) fs.unlinkSync(baselinePath); - - try { - const { writeMigrationLock } = await import("../services/migrationLock"); - const schemaHash = (snapshot as any)?.schemaHash || ""; - const updatedApplied = await connector.listAppliedMigrations(conn); - await writeMigrationLock(dbId, schemaHash, updatedApplied.map((m: any) => m.version)); - } catch (syncErr) { - this.logger?.error({ err: syncErr }, "Lock hook failed"); - } - - this.rpc.sendResponse(id, { ok: true }); - } catch (e: any) { - this.logger?.error({ e }, "migration.applySnapshot failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + dbId = project.databaseId; + } + if (!dbId) + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId or projectId", + }); + + const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); + const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + + const { loadLocalMigrations } = await import("../utils/baselineMigration"); + const localMigrations = await loadLocalMigrations(migrationsDir); + + let connector: any; + if (dbType === "mysql") connector = require("../connectors/mysql"); + else if (dbType === "postgres") connector = require("../connectors/postgres"); + else if (dbType === "mariadb") connector = require("../connectors/mariadb"); + else if (dbType === "sqlite") connector = require("../connectors/sqlite"); + + const appliedMigrations = await connector.listAppliedMigrations(conn); + const appliedSet = new Set(appliedMigrations.map((m: any) => m.version)); + + const pending = localMigrations + .filter((m) => !appliedSet.has(m.version)) + .sort((a, b) => a.version.localeCompare(b.version)); + + for (const migration of pending) { + const migrationFile = (await fs.promises.readdir(migrationsDir)).find((f) => + f.startsWith(migration.version), + ); + if (!migrationFile) + throw new Error(`Migration file not found for version: ${migration.version}`); + + const migrationFilePath = path.join(migrationsDir, migrationFile); + if (dbType === "mysql") + await this.queryExecutor.mysql.applyMigration(conn, migrationFilePath); + else if (dbType === "postgres") + await this.queryExecutor.postgres.applyMigration(conn, migrationFilePath); + else if (dbType === "mariadb") + await this.queryExecutor.mariadb.applyMigration(conn, migrationFilePath); + else if (dbType === "sqlite") + await this.queryExecutor.sqlite.applyMigration(conn, migrationFilePath); + } + + try { + const { projectStoreInstance } = await import("../services/projectStore"); + const { writeMigrationLock } = await import("../services/migrationLock"); + const project = await projectStoreInstance.getProjectByDatabaseId(dbId); + if (project) { + const schemaFile = await projectStoreInstance.getSchema(project.id); + const schemaHash = (schemaFile as any)?.schemaHash || ""; + const updatedApplied = await connector.listAppliedMigrations(conn); + await writeMigrationLock( + dbId, + schemaHash, + updatedApplied.map((m: any) => m.version), + ); } + } catch (syncErr) { + this.logger?.error({ err: syncErr }, "Lock hook failed"); + } + + this.rpc.sendResponse(id, { ok: true, count: pending.length }); + } catch (e: any) { + this.logger?.error({ e }, "migration.applyMigrations failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } - - async handleRollbackMigration(params: any, id: number | string) { - try { - const { dbId, version } = params || {}; - - if (!dbId || !version) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing dbId or version", - }); - } - - const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); - - // Find migration file - const { listMigrationFiles } = await import('../utils/migrationFileReader'); - const files = listMigrationFiles(migrationsDir); - const migrationFile = files.find(f => f.startsWith(version)); - - if (!migrationFile) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: `Migration file not found for version: ${version}`, - }); - } - - const migrationFilePath = path.join(migrationsDir, migrationFile); - - // Rollback migration - if (dbType === "mysql") { - await this.queryExecutor.mysql.rollbackMigration(conn, version, migrationFilePath); - } else if (dbType === "postgres") { - await this.queryExecutor.postgres.rollbackMigration(conn, version, migrationFilePath); - } else if (dbType === "mariadb") { - await this.queryExecutor.mariadb.rollbackMigration(conn, version, migrationFilePath); - } else if (dbType === "sqlite") { - await this.queryExecutor.sqlite.rollbackMigration(conn, version, migrationFilePath); - } - - // Hook syncMigrationFiles and Lock Update - try { - const { projectStoreInstance } = await import("../services/projectStore"); - const { gitServiceInstance } = await import("../services/gitService"); - const { writeMigrationLock } = await import("../services/migrationLock"); - - const project = await projectStoreInstance.getProjectByDatabaseId(dbId); - if (project) { - // Update Migration Lock first so it gets included in the git sync commit - let appliedMigrations: any[] = []; - if (dbType === "mysql") { - appliedMigrations = await require("../connectors/mysql").listAppliedMigrations(conn); - } else if (dbType === "postgres") { - appliedMigrations = await require("../connectors/postgres").listAppliedMigrations(conn); - } else if (dbType === "mariadb") { - appliedMigrations = await require("../connectors/mariadb").listAppliedMigrations(conn); - } else if (dbType === "sqlite") { - appliedMigrations = await require("../connectors/sqlite").listAppliedMigrations(conn); - } - - const schemaFile = await projectStoreInstance.getSchema(project.id); - const schemaHash = (schemaFile as any)?.schemaHash || ""; - - const appliedVersions = appliedMigrations.map(m => m.version); - await writeMigrationLock(dbId, schemaHash, appliedVersions); - - const projectDir = await projectStoreInstance.resolveProjectDir(project.id); - if (projectDir) { - const syncResult = await gitServiceInstance.syncMigrationFiles(projectDir); - if (syncResult.error) { - this.logger?.warn({ error: syncResult.error }, "Git sync failed after migration rollback"); - } - } - } - } catch (syncErr) { - this.logger?.error({ err: syncErr }, "syncMigrationFiles/lock hook failed"); - } - - this.rpc.sendResponse(id, { ok: true }); - } catch (e: any) { - this.logger?.error({ e }, "migration.rollback failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + + async handleApplySnapshot(params: any, id: number | string) { + try { + let { dbId, projectId } = params || {}; + const { projectStoreInstance } = await import("../services/projectStore"); + + // Resolve dbId from projectId if not directly provided + if (!dbId && projectId) { + const project = await projectStoreInstance.getProject(projectId); + if (!project?.databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Project has no linked database", + }); } + dbId = project.databaseId; + } + if (!dbId) + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId or projectId", + }); + + const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); + + const project = await projectStoreInstance.getProjectByDatabaseId(dbId); + if (!project) throw new Error("Project not found for database"); + const snapshot = await projectStoreInstance.getSchema(project.id); + if (!snapshot) throw new Error("Schema snapshot not found"); + + const { generateBaselineSQL } = await import("../utils/baselineMigration"); + const baselineSQL = generateBaselineSQL(snapshot, Date.now().toString(), "apply_snapshot"); + + let connector: any; + if (dbType === "mysql") connector = require("../connectors/mysql"); + else if (dbType === "postgres") connector = require("../connectors/postgres"); + else if (dbType === "mariadb") connector = require("../connectors/mariadb"); + else if (dbType === "sqlite") connector = require("../connectors/sqlite"); + + // For full snapshot apply, we assume DB is empty or we should drop it. + // A full implementation would drop tables here. + // For now, we write the SQL and apply it. + + const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + const versionStr = Date.now().toString(); + const baselinePath = path.join(migrationsDir, `${versionStr}_apply_snapshot.sql`); + fs.writeFileSync(baselinePath, baselineSQL, "utf8"); + + if (dbType === "mysql") await this.queryExecutor.mysql.applyMigration(conn, baselinePath); + else if (dbType === "postgres") + await this.queryExecutor.postgres.applyMigration(conn, baselinePath); + else if (dbType === "mariadb") + await this.queryExecutor.mariadb.applyMigration(conn, baselinePath); + else if (dbType === "sqlite") + await this.queryExecutor.sqlite.applyMigration(conn, baselinePath); + + if (fs.existsSync(baselinePath)) fs.unlinkSync(baselinePath); + + try { + const { writeMigrationLock } = await import("../services/migrationLock"); + const schemaHash = (snapshot as any)?.schemaHash || ""; + const updatedApplied = await connector.listAppliedMigrations(conn); + await writeMigrationLock( + dbId, + schemaHash, + updatedApplied.map((m: any) => m.version), + ); + } catch (syncErr) { + this.logger?.error({ err: syncErr }, "Lock hook failed"); + } + + this.rpc.sendResponse(id, { ok: true }); + } catch (e: any) { + this.logger?.error({ e }, "migration.applySnapshot failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } - - async handleDeleteMigration(params: any, id: number | string) { - try { - const { dbId, version } = params || {}; - - if (!dbId || !version) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing dbId or version", - }); + } + + async handleRollbackMigration(params: any, id: number | string) { + try { + const { dbId, version } = params || {}; + + if (!dbId || !version) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId or version", + }); + } + + const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); + const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + + // Find migration file + const { listMigrationFiles } = await import("../utils/migrationFileReader"); + const files = listMigrationFiles(migrationsDir); + const migrationFile = files.find((f) => f.startsWith(version)); + + if (!migrationFile) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: `Migration file not found for version: ${version}`, + }); + } + + const migrationFilePath = path.join(migrationsDir, migrationFile); + + // Rollback migration + if (dbType === "mysql") { + await this.queryExecutor.mysql.rollbackMigration(conn, version, migrationFilePath); + } else if (dbType === "postgres") { + await this.queryExecutor.postgres.rollbackMigration(conn, version, migrationFilePath); + } else if (dbType === "mariadb") { + await this.queryExecutor.mariadb.rollbackMigration(conn, version, migrationFilePath); + } else if (dbType === "sqlite") { + await this.queryExecutor.sqlite.rollbackMigration(conn, version, migrationFilePath); + } + + // Hook syncMigrationFiles and Lock Update + try { + const { projectStoreInstance } = await import("../services/projectStore"); + const { gitServiceInstance } = await import("../services/gitService"); + const { writeMigrationLock } = await import("../services/migrationLock"); + + const project = await projectStoreInstance.getProjectByDatabaseId(dbId); + if (project) { + // Update Migration Lock first so it gets included in the git sync commit + let appliedMigrations: any[] = []; + if (dbType === "mysql") { + appliedMigrations = await require("../connectors/mysql").listAppliedMigrations(conn); + } else if (dbType === "postgres") { + appliedMigrations = await require("../connectors/postgres").listAppliedMigrations(conn); + } else if (dbType === "mariadb") { + appliedMigrations = await require("../connectors/mariadb").listAppliedMigrations(conn); + } else if (dbType === "sqlite") { + appliedMigrations = await require("../connectors/sqlite").listAppliedMigrations(conn); + } + + const schemaFile = await projectStoreInstance.getSchema(project.id); + const schemaHash = (schemaFile as any)?.schemaHash || ""; + + const appliedVersions = appliedMigrations.map((m) => m.version); + await writeMigrationLock(dbId, schemaHash, appliedVersions); + + const projectDir = await projectStoreInstance.resolveProjectDir(project.id); + if (projectDir) { + const syncResult = await gitServiceInstance.syncMigrationFiles(projectDir); + if (syncResult.error) { + this.logger?.warn( + { error: syncResult.error }, + "Git sync failed after migration rollback", + ); } - - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); - - // Find and delete migration file - const { listMigrationFiles } = await import('../utils/migrationFileReader'); - const files = listMigrationFiles(migrationsDir); - const migrationFile = files.find(f => f.startsWith(version)); - - if (!migrationFile) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: `Migration file not found for version: ${version}`, - }); - } - - const migrationFilePath = path.join(migrationsDir, migrationFile); - fs.unlinkSync(migrationFilePath); - - this.rpc.sendResponse(id, { ok: true }); - } catch (e: any) { - this.logger?.error({ e }, "migration.delete failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } } + } catch (syncErr) { + this.logger?.error({ err: syncErr }, "syncMigrationFiles/lock hook failed"); + } + + this.rpc.sendResponse(id, { ok: true }); + } catch (e: any) { + this.logger?.error({ e }, "migration.rollback failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } - - async handleGetMigrationSQL(params: any, id: number | string) { - try { - const { dbId, version } = params || {}; - - if (!dbId || !version) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing dbId or version", - }); - } - - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); - - // Find and read migration file - const { listMigrationFiles, readMigrationFile } = await import('../utils/migrationFileReader'); - const files = listMigrationFiles(migrationsDir); - const migrationFile = files.find(f => f.startsWith(version)); - - if (!migrationFile) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: `Migration file not found for version: ${version}`, - }); - } - - const migrationFilePath = path.join(migrationsDir, migrationFile); - const migration = readMigrationFile(migrationFilePath); - - this.rpc.sendResponse(id, { - ok: true, - data: { - up: migration.upSQL, - down: migration.downSQL, - }, - }); - } catch (e: any) { - this.logger?.error({ e }, "migration.getSQL failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } + } + + async handleDeleteMigration(params: any, id: number | string) { + try { + const { dbId, version } = params || {}; + + if (!dbId || !version) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId or version", + }); + } + + const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + + // Find and delete migration file + const { listMigrationFiles } = await import("../utils/migrationFileReader"); + const files = listMigrationFiles(migrationsDir); + const migrationFile = files.find((f) => f.startsWith(version)); + + if (!migrationFile) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: `Migration file not found for version: ${version}`, + }); + } + + const migrationFilePath = path.join(migrationsDir, migrationFile); + fs.unlinkSync(migrationFilePath); + + this.rpc.sendResponse(id, { ok: true }); + } catch (e: any) { + this.logger?.error({ e }, "migration.delete failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleGetMigrationSQL(params: any, id: number | string) { + try { + const { dbId, version } = params || {}; + + if (!dbId || !version) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId or version", + }); + } + + const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + + // Find and read migration file + const { listMigrationFiles, readMigrationFile } = + await import("../utils/migrationFileReader"); + const files = listMigrationFiles(migrationsDir); + const migrationFile = files.find((f) => f.startsWith(version)); + + if (!migrationFile) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: `Migration file not found for version: ${version}`, + }); + } + + const migrationFilePath = path.join(migrationsDir, migrationFile); + const migration = readMigrationFile(migrationFilePath); + + this.rpc.sendResponse(id, { + ok: true, + data: { + up: migration.upSQL, + down: migration.downSQL, + }, + }); + } catch (e: any) { + this.logger?.error({ e }, "migration.getSQL failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } + } } diff --git a/bridge/src/handlers/monitoringHandlers.ts b/bridge/src/handlers/monitoringHandlers.ts index 7aec8d39..3b38be84 100644 --- a/bridge/src/handlers/monitoringHandlers.ts +++ b/bridge/src/handlers/monitoringHandlers.ts @@ -8,7 +8,7 @@ export class MonitoringHandlers { private rpc: Rpc, private logger: Logger, private dbService: DatabaseService, - private monitoringService: MonitoringService + private monitoringService: MonitoringService, ) {} async handleGetSnapshot(params: any, id: number | string) { diff --git a/bridge/src/handlers/projectHandlers.ts b/bridge/src/handlers/projectHandlers.ts index c62600c7..e3d9356d 100644 --- a/bridge/src/handlers/projectHandlers.ts +++ b/bridge/src/handlers/projectHandlers.ts @@ -11,931 +11,945 @@ import path from "path"; * Mirrors the DatabaseHandlers pattern. */ export class ProjectHandlers { - constructor( - private rpc: Rpc, - private logger: Logger, - private dbService: DatabaseService, - private queryExecutor: QueryExecutor - ) { } - - - async handleListProjects(_params: any, id: number | string) { - try { - const projects = await projectStoreInstance.listProjects(); - this.rpc.sendResponse(id, { ok: true, data: projects }); - } catch (e: any) { - this.logger?.error({ e }, "project.list failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleGetProject(params: any, id: number | string) { - try { - const { id: projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing id", - }); - } - - const project = await projectStoreInstance.getProject(projectId); - if (!project) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: "Project not found", - }); - } - - this.rpc.sendResponse(id, { ok: true, data: project }); - } catch (e: any) { - this.logger?.error({ e }, "project.get failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleGetProjectByDatabaseId(params: any, id: number | string) { - try { - const { databaseId } = params || {}; - if (!databaseId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing databaseId", - }); - } - - const project = await projectStoreInstance.getProjectByDatabaseId(databaseId); - // Return null (not an error) when no project is linked - this.rpc.sendResponse(id, { ok: true, data: project }); - } catch (e: any) { - this.logger?.error({ e }, "project.getByDatabaseId failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleCreateProject(params: any, id: number | string) { - try { - const { databaseId, name, description, defaultSchema } = params || {}; - if (!databaseId || !name) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing databaseId or name", - }); - } - - const project = await projectStoreInstance.createProject({ - databaseId, - name, - description, - defaultSchema, - }); - - this.rpc.sendResponse(id, { ok: true, data: project }); - } catch (e: any) { - this.logger?.error({ e }, "project.create failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleUpdateProject(params: any, id: number | string) { - try { - const { id: projectId, ...updates } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing id", - }); - } - - const project = await projectStoreInstance.updateProject(projectId, updates); - if (!project) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: "Project not found", - }); - } - - this.rpc.sendResponse(id, { ok: true, data: project }); - } catch (e: any) { - this.logger?.error({ e }, "project.update failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleDeleteProject(params: any, id: number | string) { - try { - const { id: projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing id", - }); - } - - await projectStoreInstance.deleteProject(projectId); - this.rpc.sendResponse(id, { ok: true }); - } catch (e: any) { - this.logger?.error({ e }, "project.delete failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleGetSchema(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId", - }); - } - - const schema = await projectStoreInstance.getSchema(projectId); - this.rpc.sendResponse(id, { ok: true, data: schema }); - } catch (e: any) { - this.logger?.error({ e }, "project.getSchema failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleSaveSchema(params: any, id: number | string) { - try { - const { projectId, schemas } = params || {}; - if (!projectId || !schemas) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId or schemas", - }); - } - - const result = await projectStoreInstance.saveSchema(projectId, schemas); - this.rpc.sendResponse(id, { ok: true, data: result }); - } catch (e: any) { - this.logger?.error({ e }, "project.saveSchema failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleRefreshSchemaCache(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); - } - - const project = await projectStoreInstance.getProject(projectId); - if (!project) { - return this.rpc.sendError(id, { code: "NOT_FOUND", message: "Project not found" }); - } - - if (!project.databaseId) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Project has no database ID" }); - } - - // Get DB connection - const { conn, dbType } = await this.dbService.getDatabaseConnection(project.databaseId); - const dbSchema = await this.queryExecutor.listSchemas(conn, dbType) as any; - const liveSchemas = dbSchema.schemas; - - // Generate schema hash from live schemas - const crypto = require("crypto"); - const newHash = crypto.createHash("sha256").update(JSON.stringify(liveSchemas)).digest("hex"); - - // Fetch old schema file to compare - let oldHash = ""; + constructor( + private rpc: Rpc, + private logger: Logger, + private dbService: DatabaseService, + private queryExecutor: QueryExecutor, + ) {} + + async handleListProjects(_params: any, id: number | string) { + try { + const projects = await projectStoreInstance.listProjects(); + this.rpc.sendResponse(id, { ok: true, data: projects }); + } catch (e: any) { + this.logger?.error({ e }, "project.list failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleGetProject(params: any, id: number | string) { + try { + const { id: projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing id", + }); + } + + const project = await projectStoreInstance.getProject(projectId); + if (!project) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: "Project not found", + }); + } + + this.rpc.sendResponse(id, { ok: true, data: project }); + } catch (e: any) { + this.logger?.error({ e }, "project.get failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleGetProjectByDatabaseId(params: any, id: number | string) { + try { + const { databaseId } = params || {}; + if (!databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing databaseId", + }); + } + + const project = await projectStoreInstance.getProjectByDatabaseId(databaseId); + // Return null (not an error) when no project is linked + this.rpc.sendResponse(id, { ok: true, data: project }); + } catch (e: any) { + this.logger?.error({ e }, "project.getByDatabaseId failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleCreateProject(params: any, id: number | string) { + try { + const { databaseId, name, description, defaultSchema } = params || {}; + if (!databaseId || !name) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing databaseId or name", + }); + } + + const project = await projectStoreInstance.createProject({ + databaseId, + name, + description, + defaultSchema, + }); + + this.rpc.sendResponse(id, { ok: true, data: project }); + } catch (e: any) { + this.logger?.error({ e }, "project.create failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleUpdateProject(params: any, id: number | string) { + try { + const { id: projectId, ...updates } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing id", + }); + } + + const project = await projectStoreInstance.updateProject(projectId, updates); + if (!project) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: "Project not found", + }); + } + + this.rpc.sendResponse(id, { ok: true, data: project }); + } catch (e: any) { + this.logger?.error({ e }, "project.update failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleDeleteProject(params: any, id: number | string) { + try { + const { id: projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing id", + }); + } + + await projectStoreInstance.deleteProject(projectId); + this.rpc.sendResponse(id, { ok: true }); + } catch (e: any) { + this.logger?.error({ e }, "project.delete failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleGetSchema(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId", + }); + } + + const schema = await projectStoreInstance.getSchema(projectId); + this.rpc.sendResponse(id, { ok: true, data: schema }); + } catch (e: any) { + this.logger?.error({ e }, "project.getSchema failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleSaveSchema(params: any, id: number | string) { + try { + const { projectId, schemas } = params || {}; + if (!projectId || !schemas) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId or schemas", + }); + } + + const result = await projectStoreInstance.saveSchema(projectId, schemas); + this.rpc.sendResponse(id, { ok: true, data: result }); + } catch (e: any) { + this.logger?.error({ e }, "project.saveSchema failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleRefreshSchemaCache(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); + } + + const project = await projectStoreInstance.getProject(projectId); + if (!project) { + return this.rpc.sendError(id, { code: "NOT_FOUND", message: "Project not found" }); + } + + if (!project.databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Project has no database ID", + }); + } + + // Get DB connection + const { conn, dbType } = await this.dbService.getDatabaseConnection(project.databaseId); + const dbSchema = (await this.queryExecutor.listSchemas(conn, dbType)) as any; + const liveSchemas = dbSchema.schemas; + + // Generate schema hash from live schemas + const crypto = require("crypto"); + const newHash = crypto.createHash("sha256").update(JSON.stringify(liveSchemas)).digest("hex"); + + // Fetch old schema file to compare + let oldHash = ""; + try { + const oldSchemaFile = await projectStoreInstance.getSchema(projectId); + oldHash = (oldSchemaFile as any)?.schemaHash || ""; + } catch (e) { + // Initial creation + } + + // Save anyway (or only if changed, but we can always save) + // projectStoreInstance.saveSchema now expects to write schemaHash and dialect. + // Let's call saveSchema and then update the schema.json directly or update saveSchema signature. + // Since saveSchema only takes `schemas` right now, I'll update saveSchema in projectStore shortly. + await projectStoreInstance.saveSchema(projectId, liveSchemas, newHash, dbType); + + if (newHash !== oldHash) { + this.rpc?.sendNotification?.("project.schema_changed", { projectId, newHash }); + + // Commit to Git if tracking + try { + const projectDir = await projectStoreInstance.resolveProjectDir(projectId); + if (projectDir) { + await gitServiceInstance.syncSchemaFile(projectDir); + } + } catch (gitErr) { + this.logger?.warn({ err: gitErr }, "Failed to auto-commit schema.json to Git"); + } + } + + this.rpc.sendResponse(id, { ok: true, hashChanged: newHash !== oldHash, newHash }); + } catch (e: any) { + this.logger?.error({ e }, "project.refreshSchemaCache failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleGetERDiagram(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId", + }); + } + + const diagram = await projectStoreInstance.getERDiagram(projectId); + this.rpc.sendResponse(id, { ok: true, data: diagram }); + } catch (e: any) { + this.logger?.error({ e }, "project.getERDiagram failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleSaveERDiagram(params: any, id: number | string) { + try { + const { projectId, nodes, zoom, panX, panY } = params || {}; + if (!projectId || !nodes) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId or nodes", + }); + } + + const result = await projectStoreInstance.saveERDiagram(projectId, { + nodes, + zoom, + panX, + panY, + }); + this.rpc.sendResponse(id, { ok: true, data: result }); + } catch (e: any) { + this.logger?.error({ e }, "project.saveERDiagram failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleGetAnnotations(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId", + }); + } + + const annotations = await projectStoreInstance.getAnnotations(projectId); + this.rpc.sendResponse(id, { ok: true, data: annotations }); + } catch (e: any) { + this.logger?.error({ e }, "project.getAnnotations failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleSaveAnnotations(params: any, id: number | string) { + try { + const { projectId, snapshot } = params || {}; + if (!projectId || !snapshot) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId or snapshot", + }); + } + + const result = await projectStoreInstance.saveAnnotations(projectId, snapshot); + this.rpc.sendResponse(id, { ok: true, data: result }); + } catch (e: any) { + this.logger?.error({ e }, "project.saveAnnotations failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleAnalyzeImport(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); + } + + const project = await projectStoreInstance.getProject(projectId); + if (!project) { + return this.rpc.sendError(id, { code: "NOT_FOUND", message: "Project not found" }); + } + + // 1. Read schema snapshot + const schemaFile = await projectStoreInstance.getSchema(projectId); + const hasSchemaSnapshot = !!schemaFile && !!(schemaFile as any)?.schemas?.length; + const schemaHash = (schemaFile as any)?.schemaHash || ""; + + // 2. Read migration files from project-local dir + const { listMigrationFiles, readMigrationFile } = + await import("../utils/migrationFileReader"); + let migrationFiles: string[] = []; + let migrationsDir = ""; + if (project.databaseId) { + migrationsDir = await projectStoreInstance.resolveMigrationsDir(project.databaseId); + migrationFiles = listMigrationFiles(migrationsDir); + } + const hasMigrations = migrationFiles.length > 0; + + // 3. Read lock file + let lockFileStatus: "valid" | "tampered" | "missing" = "missing"; + let tamperedFiles: string[] = []; + let appliedVersions: string[] = []; + if (project.databaseId) { + const { readMigrationLock } = await import("../services/migrationLock"); + const lock = await readMigrationLock(project.databaseId); + if (lock) { + lockFileStatus = lock.schemaHash === schemaHash ? "valid" : "tampered"; + appliedVersions = lock.appliedMigrations || []; + } + } + + // 4. Query live database for table count + let targetDatabaseEmpty = true; + let targetTableCount = 0; + let dbAppliedVersions: string[] = []; + if (project.databaseId) { + try { + const { conn, dbType } = await this.dbService.getDatabaseConnection(project.databaseId); + let connector: any; + if (dbType === "mysql") connector = require("../connectors/mysql"); + else if (dbType === "postgres") connector = require("../connectors/postgres"); + else if (dbType === "mariadb") connector = require("../connectors/mariadb"); + else if (dbType === "sqlite") connector = require("../connectors/sqlite"); + + if (connector) { try { - const oldSchemaFile = await projectStoreInstance.getSchema(projectId); - oldHash = (oldSchemaFile as any)?.schemaHash || ""; - } catch (e) { - // Initial creation - } - - // Save anyway (or only if changed, but we can always save) - // projectStoreInstance.saveSchema now expects to write schemaHash and dialect. - // Let's call saveSchema and then update the schema.json directly or update saveSchema signature. - // Since saveSchema only takes `schemas` right now, I'll update saveSchema in projectStore shortly. - await projectStoreInstance.saveSchema(projectId, liveSchemas, newHash, dbType); - - if (newHash !== oldHash) { - this.rpc?.sendNotification?.("project.schema_changed", { projectId, newHash }); - - // Commit to Git if tracking - try { - const projectDir = await projectStoreInstance.resolveProjectDir(projectId); - if (projectDir) { - await gitServiceInstance.syncSchemaFile(projectDir); - } - } catch (gitErr) { - this.logger?.warn({ err: gitErr }, "Failed to auto-commit schema.json to Git"); - } - } - - this.rpc.sendResponse(id, { ok: true, hashChanged: newHash !== oldHash, newHash }); - } catch (e: any) { - this.logger?.error({ e }, "project.refreshSchemaCache failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleGetERDiagram(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId", - }); - } - - const diagram = await projectStoreInstance.getERDiagram(projectId); - this.rpc.sendResponse(id, { ok: true, data: diagram }); - } catch (e: any) { - this.logger?.error({ e }, "project.getERDiagram failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleSaveERDiagram(params: any, id: number | string) { - try { - const { projectId, nodes, zoom, panX, panY } = params || {}; - if (!projectId || !nodes) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId or nodes", - }); - } - - const result = await projectStoreInstance.saveERDiagram(projectId, { - nodes, - zoom, - panX, - panY, - }); - this.rpc.sendResponse(id, { ok: true, data: result }); - } catch (e: any) { - this.logger?.error({ e }, "project.saveERDiagram failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleGetAnnotations(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId", - }); - } - - const annotations = await projectStoreInstance.getAnnotations(projectId); - this.rpc.sendResponse(id, { ok: true, data: annotations }); - } catch (e: any) { - this.logger?.error({ e }, "project.getAnnotations failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleSaveAnnotations(params: any, id: number | string) { - try { - const { projectId, snapshot } = params || {}; - if (!projectId || !snapshot) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId or snapshot", - }); - } - - const result = await projectStoreInstance.saveAnnotations(projectId, snapshot); - this.rpc.sendResponse(id, { ok: true, data: result }); - } catch (e: any) { - this.logger?.error({ e }, "project.saveAnnotations failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleAnalyzeImport(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); - } - - const project = await projectStoreInstance.getProject(projectId); - if (!project) { - return this.rpc.sendError(id, { code: "NOT_FOUND", message: "Project not found" }); - } - - // 1. Read schema snapshot - const schemaFile = await projectStoreInstance.getSchema(projectId); - const hasSchemaSnapshot = !!schemaFile && !!(schemaFile as any)?.schemas?.length; - const schemaHash = (schemaFile as any)?.schemaHash || ""; - - // 2. Read migration files from project-local dir - const { listMigrationFiles, readMigrationFile } = await import("../utils/migrationFileReader"); - let migrationFiles: string[] = []; - let migrationsDir = ""; - if (project.databaseId) { - migrationsDir = await projectStoreInstance.resolveMigrationsDir(project.databaseId); - migrationFiles = listMigrationFiles(migrationsDir); - } - const hasMigrations = migrationFiles.length > 0; - - // 3. Read lock file - let lockFileStatus: "valid" | "tampered" | "missing" = "missing"; - let tamperedFiles: string[] = []; - let appliedVersions: string[] = []; - if (project.databaseId) { - const { readMigrationLock } = await import("../services/migrationLock"); - const lock = await readMigrationLock(project.databaseId); - if (lock) { - lockFileStatus = lock.schemaHash === schemaHash ? "valid" : "tampered"; - appliedVersions = lock.appliedMigrations || []; - } - } - - // 4. Query live database for table count - let targetDatabaseEmpty = true; - let targetTableCount = 0; - let dbAppliedVersions: string[] = []; - if (project.databaseId) { - try { - const { conn, dbType } = await this.dbService.getDatabaseConnection(project.databaseId); - let connector: any; - if (dbType === "mysql") connector = require("../connectors/mysql"); - else if (dbType === "postgres") connector = require("../connectors/postgres"); - else if (dbType === "mariadb") connector = require("../connectors/mariadb"); - else if (dbType === "sqlite") connector = require("../connectors/sqlite"); - - if (connector) { - try { - const tables = await connector.listTables(conn); - // Filter out internal migration tracking tables - const userTables = (tables || []).filter((t: any) => { - const name = typeof t === "string" ? t : t?.name || ""; - return name !== "__relwave_migrations" && name !== "relwave_migrations"; - }); - targetTableCount = userTables.length; - targetDatabaseEmpty = targetTableCount === 0; - } catch { - // Can't list tables — assume non-empty for safety - targetDatabaseEmpty = false; - } - - try { - const applied = await connector.listAppliedMigrations(conn); - dbAppliedVersions = (applied || []).map((m: any) => m.version); - } catch { - // Migration tracking table may not exist yet - } - } - } catch { - // Database connection may not be available - } - } - - // 5. Compute pending migrations - const appliedSet = new Set(dbAppliedVersions); - const pendingMigrations: Array<{ - file: string; - version: string; - isDestructive: boolean; - destructiveOps: string[]; - }> = []; - - for (const file of migrationFiles) { - const versionMatch = file.match(/^(\d{13,14})/); - if (!versionMatch) continue; - const version = versionMatch[1]; - if (appliedSet.has(version)) continue; - - // Parse for destructive operations - let isDestructive = false; - const destructiveOps: string[] = []; - try { - const parsed = readMigrationFile(path.join(migrationsDir, file)); - const upSQL = parsed.upSQL.toUpperCase(); - if (upSQL.includes("DROP TABLE")) { - isDestructive = true; - destructiveOps.push("DROP TABLE"); - } - if (upSQL.includes("DROP COLUMN")) { - isDestructive = true; - destructiveOps.push("DROP COLUMN"); - } - if (upSQL.includes("TRUNCATE")) { - isDestructive = true; - destructiveOps.push("TRUNCATE"); - } - } catch { - // Skip parse errors - } - - pendingMigrations.push({ file, version, isDestructive, destructiveOps }); - } - - // 6. Detect if all migration files are baseline-only (no real user migrations) - const isBaselineOnly = hasMigrations && migrationFiles.every(f => f.includes("baseline")); - - // 7. Compute drift status - let driftStatus: "synced" | "drifted" | "unknown" = "unknown"; - if (pendingMigrations.length === 0 && hasMigrations) { - // All migrations applied - driftStatus = "synced"; - } else if (pendingMigrations.length === 0 && !hasMigrations && !hasSchemaSnapshot) { - // No migrations or schema — fresh project - driftStatus = "synced"; - } else if (pendingMigrations.length > 0) { - driftStatus = "drifted"; - } else if (!hasMigrations && hasSchemaSnapshot && targetDatabaseEmpty) { - // Schema exists but database is empty — need to apply snapshot - driftStatus = "drifted"; - } else if (!hasMigrations && hasSchemaSnapshot && !targetDatabaseEmpty) { - // Schema exists and database has tables — assume synced (user just hasn't made migrations yet) - driftStatus = "synced"; - } - - // 8. Compute available modes - const availableModes: Array<"run_migrations" | "apply_snapshot" | "skip"> = ["skip"]; - let recommendedMode: "run_migrations" | "apply_snapshot" | "skip" = "skip"; - - if (isBaselineOnly && hasSchemaSnapshot && targetDatabaseEmpty) { - // Baseline-only + empty DB + schema.json exists: - // The baseline file has no real DDL — use schema.json to reconstruct the DB - availableModes.unshift("apply_snapshot"); - recommendedMode = "apply_snapshot"; - // Override: treat as "no real migrations" for the dialog - driftStatus = "drifted"; - } else if (hasMigrations && pendingMigrations.length > 0 && !isBaselineOnly) { - availableModes.unshift("run_migrations"); - recommendedMode = "run_migrations"; - } - if (hasSchemaSnapshot && targetDatabaseEmpty && !hasMigrations) { - availableModes.unshift("apply_snapshot"); - recommendedMode = "apply_snapshot"; - } - - // For the dialog: if baseline-only + empty DB, report as "no real migrations" - // so the frontend shows "Apply Schema Snapshot" (STATE 3) instead of - // "Pending Migrations" (STATE 2) which would try to run the empty baseline - const reportHasMigrations = isBaselineOnly && targetDatabaseEmpty ? false : hasMigrations; - const reportPendingMigrations = isBaselineOnly && targetDatabaseEmpty ? [] : pendingMigrations; - - const result = { - hasMigrations: reportHasMigrations, - migrationCount: reportPendingMigrations.length, - hasSchemaSnapshot, - lockFileStatus, - tamperedFiles, - targetDatabaseEmpty, - targetTableCount, - driftStatus, - driftDetails: undefined, - pendingMigrations: reportPendingMigrations, - availableModes, - recommendedMode, - }; - - this.rpc.sendResponse(id, { ok: true, data: result }); - } catch (e: any) { - this.logger?.error({ e }, "project.analyzeImport failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleVerifyLock(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); + const tables = await connector.listTables(conn); + // Filter out internal migration tracking tables + const userTables = (tables || []).filter((t: any) => { + const name = typeof t === "string" ? t : t?.name || ""; + return name !== "__relwave_migrations" && name !== "relwave_migrations"; + }); + targetTableCount = userTables.length; + targetDatabaseEmpty = targetTableCount === 0; + } catch { + // Can't list tables — assume non-empty for safety + targetDatabaseEmpty = false; } - const project = await projectStoreInstance.getProject(projectId); - if (!project?.databaseId) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Project has no database ID" }); - } - const { verifyMigrationLock } = await import("../services/migrationLock"); - const schemaFile = await projectStoreInstance.getSchema(projectId); - const schemaHash = (schemaFile as any)?.schemaHash || ""; - - const isValid = await verifyMigrationLock(project.databaseId, schemaHash); - this.rpc.sendResponse(id, { ok: true, isValid }); - } catch (e: any) { - this.logger?.error({ e }, "project.verifyLock failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handlePushMigrations(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); - const projectDir = await projectStoreInstance.resolveProjectDir(projectId); - if (!projectDir) return this.rpc.sendError(id, { code: "NOT_FOUND", message: "Project directory not found" }); - - const { gitServiceInstance } = await import("../services/gitService"); - await gitServiceInstance.pushMigrations(projectDir); - this.rpc.sendResponse(id, { ok: true }); - } catch (e: any) { - this.logger?.error({ e }, "project.pushMigrations failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - async handleSyncMigrations(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); - const projectDir = await projectStoreInstance.resolveProjectDir(projectId); - if (!projectDir) return this.rpc.sendError(id, { code: "NOT_FOUND", message: "Project directory not found" }); - - const { gitServiceInstance } = await import("../services/gitService"); - const result = await gitServiceInstance.syncMigrationFiles(projectDir); - if (result.error) throw new Error(result.error.message || String(result.error)); - this.rpc.sendResponse(id, { ok: true, data: result }); - } catch (e: any) { - this.logger?.error({ e }, "project.syncMigrations failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleGetDrift(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); - - // Stub implementation for now - this.rpc.sendResponse(id, { ok: true, data: { driftDetected: false, differences: [] } }); - } catch (e: any) { - this.logger?.error({ e }, "project.getDrift failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleGetQueries(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId", - }); - } - - const queries = await projectStoreInstance.getQueries(projectId); - this.rpc.sendResponse(id, { ok: true, data: queries }); - } catch (e: any) { - this.logger?.error({ e }, "project.getQueries failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleAddQuery(params: any, id: number | string) { - try { - const { projectId, name, sql, description } = params || {}; - if (!projectId || !name || !sql) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId, name, or sql", - }); - } - - const query = await projectStoreInstance.addQuery(projectId, { - name, - sql, - description, - }); - this.rpc.sendResponse(id, { ok: true, data: query }); - } catch (e: any) { - this.logger?.error({ e }, "project.addQuery failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleUpdateQuery(params: any, id: number | string) { - try { - const { projectId, queryId, ...updates } = params || {}; - if (!projectId || !queryId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId or queryId", - }); - } - - const query = await projectStoreInstance.updateQuery( - projectId, - queryId, - updates - ); - if (!query) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: "Query not found", - }); - } - - this.rpc.sendResponse(id, { ok: true, data: query }); - } catch (e: any) { - this.logger?.error({ e }, "project.updateQuery failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleDeleteQuery(params: any, id: number | string) { - try { - const { projectId, queryId } = params || {}; - if (!projectId || !queryId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId or queryId", - }); - } - - await projectStoreInstance.deleteQuery(projectId, queryId); - this.rpc.sendResponse(id, { ok: true }); - } catch (e: any) { - this.logger?.error({ e }, "project.deleteQuery failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - // ========================================== - // Export (for future git-native support) - // ========================================== - - async handleExportProject(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId", - }); - } - - const bundle = await projectStoreInstance.exportProject(projectId); - if (!bundle) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: "Project not found", - }); - } - - this.rpc.sendResponse(id, { ok: true, data: bundle }); - } catch (e: any) { - this.logger?.error({ e }, "project.export failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleGetProjectDir(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId", - }); - } - const dir = await projectStoreInstance.resolveProjectDir(projectId); - this.rpc.sendResponse(id, { ok: true, data: { dir } }); - } catch (e: any) { - this.logger?.error({ e }, "project.getDir failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleGetLocalConfig(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId", - }); - } - const config = await projectStoreInstance.getLocalConfig(projectId); - this.rpc.sendResponse(id, { ok: true, data: config }); - } catch (e: any) { - this.logger?.error({ e }, "project.getLocalConfig failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleSaveLocalConfig(params: any, id: number | string) { - try { - const { projectId, config } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId", - }); - } - const saved = await projectStoreInstance.saveLocalConfig(projectId, config || {}); - this.rpc.sendResponse(id, { ok: true, data: saved }); - } catch (e: any) { - this.logger?.error({ e }, "project.saveLocalConfig failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleEnsureGitignore(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId", - }); - } - const modified = await projectStoreInstance.ensureGitignore(projectId); - this.rpc.sendResponse(id, { ok: true, data: { modified } }); - } catch (e: any) { - this.logger?.error({ e }, "project.ensureGitignore failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - /** Read-only scan — returns metadata + .env info without creating anything. */ - async handleScanImport(params: any, id: number | string) { - try { - const { sourcePath } = params || {}; - if (!sourcePath) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing sourcePath", - }); - } - - const result = await projectStoreInstance.scanImportSource(sourcePath); - this.rpc.sendResponse(id, { ok: true, data: result }); - } catch (e: any) { - this.logger?.error({ e }, "project.scanImport failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - /** Import a project — requires a valid databaseId (no more "pending" fallback). */ - async handleImportProject(params: any, id: number | string) { - try { - const { sourcePath, databaseId } = params || {}; - if (!sourcePath) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing sourcePath", - }); - } - if (!databaseId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing databaseId — create a database connection first", - }); - } - - const project = await projectStoreInstance.importProject({ - sourcePath, - databaseId, - }); - - this.rpc.sendResponse(id, { ok: true, data: project }); - } catch (e: any) { - this.logger?.error({ e }, "project.import failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleLinkDatabase(params: any, id: number | string) { - try { - const { projectId, databaseId } = params || {}; - if (!projectId || !databaseId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId or databaseId", - }); - } - - const project = await projectStoreInstance.linkDatabase(projectId, databaseId); - if (!project) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: "Project not found", - }); - } - - this.rpc.sendResponse(id, { ok: true, data: project }); - } catch (e: any) { - this.logger?.error({ e }, "project.linkDatabase failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleUnlinkFromConnection(params: any, id: number | string) { - try { - const { databaseId } = params || {}; - if (!databaseId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing databaseId", - }); - } - - await projectStoreInstance.unlinkDatabase(databaseId); - this.rpc.sendResponse(id, { ok: true }); - } catch (e: any) { - this.logger?.error({ e }, "project.unlinkFromConnection failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleDeleteWithConnection(params: any, id: number | string) { - try { - const { databaseId } = params || {}; - if (!databaseId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing databaseId", - }); - } - - await projectStoreInstance.deleteProjectByDatabaseId(databaseId); - this.rpc.sendResponse(id, { ok: true }); - } catch (e: any) { - this.logger?.error({ e }, "project.deleteWithConnection failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - - async handleGetGitRemote(params: any, id: number | string) { - try { - const { projectPath } = params || {}; - if (!projectPath) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectPath", - }); - } - - // Using gitServiceInstance since it handles standard git operations - const remotes = await gitServiceInstance.remoteList(projectPath); - const remoteUrl = remotes.length > 0 ? remotes[0].fetchUrl : null; - - this.rpc.sendResponse(id, { ok: true, data: { remoteUrl } }); - } catch (e: any) { - // If it's not a git repo or fails, just return null - this.logger?.error({ e }, "project.getGitRemote failed (might not be a git repo)"); - this.rpc.sendResponse(id, { ok: true, data: { remoteUrl: null } }); - } - } - - async handleRelinkToConnection(params: any, id: number | string) { - try { - const { projectId, databaseId } = params || {}; - if (!projectId || !databaseId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId or databaseId", - }); - } - - const project = await projectStoreInstance.relinkDatabase(projectId, databaseId); - - this.rpc.sendResponse(id, { ok: true, data: project }); - } catch (e: any) { - this.logger?.error({ e }, "project.relinkToConnection failed"); - // Check if it's the specific error we throw - if (e.message?.includes("DATABASE_ALREADY_HAS_PROJECT")) { - this.rpc.sendError(id, { code: "DATABASE_ALREADY_HAS_PROJECT", message: e.message }); - } else { - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } - } - - async handleGenerateSQL(params: any, id: number | string) { - try { - const { projectId } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing projectId", - }); - } - - const { projectStoreInstance } = await import("../services/projectStore"); - const schemaFile = await projectStoreInstance.getSchema(projectId); - if (!schemaFile) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: "No schema snapshot found", - }); - } - - const { generateBaselineSQL } = await import("../utils/baselineMigration"); - const sql = generateBaselineSQL(schemaFile as any, "preview", "preview"); - - this.rpc.sendResponse(id, { ok: true, data: { sql } }); - } catch (e: any) { - this.logger?.error({ e }, "project.generateSQL failed"); - this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); - } - } + try { + const applied = await connector.listAppliedMigrations(conn); + dbAppliedVersions = (applied || []).map((m: any) => m.version); + } catch { + // Migration tracking table may not exist yet + } + } + } catch { + // Database connection may not be available + } + } + + // 5. Compute pending migrations + const appliedSet = new Set(dbAppliedVersions); + const pendingMigrations: Array<{ + file: string; + version: string; + isDestructive: boolean; + destructiveOps: string[]; + }> = []; + + for (const file of migrationFiles) { + const versionMatch = file.match(/^(\d{13,14})/); + if (!versionMatch) continue; + const version = versionMatch[1]; + if (appliedSet.has(version)) continue; + + // Parse for destructive operations + let isDestructive = false; + const destructiveOps: string[] = []; + try { + const parsed = readMigrationFile(path.join(migrationsDir, file)); + const upSQL = parsed.upSQL.toUpperCase(); + if (upSQL.includes("DROP TABLE")) { + isDestructive = true; + destructiveOps.push("DROP TABLE"); + } + if (upSQL.includes("DROP COLUMN")) { + isDestructive = true; + destructiveOps.push("DROP COLUMN"); + } + if (upSQL.includes("TRUNCATE")) { + isDestructive = true; + destructiveOps.push("TRUNCATE"); + } + } catch { + // Skip parse errors + } + + pendingMigrations.push({ file, version, isDestructive, destructiveOps }); + } + + // 6. Detect if all migration files are baseline-only (no real user migrations) + const isBaselineOnly = hasMigrations && migrationFiles.every((f) => f.includes("baseline")); + + // 7. Compute drift status + let driftStatus: "synced" | "drifted" | "unknown" = "unknown"; + if (pendingMigrations.length === 0 && hasMigrations) { + // All migrations applied + driftStatus = "synced"; + } else if (pendingMigrations.length === 0 && !hasMigrations && !hasSchemaSnapshot) { + // No migrations or schema — fresh project + driftStatus = "synced"; + } else if (pendingMigrations.length > 0) { + driftStatus = "drifted"; + } else if (!hasMigrations && hasSchemaSnapshot && targetDatabaseEmpty) { + // Schema exists but database is empty — need to apply snapshot + driftStatus = "drifted"; + } else if (!hasMigrations && hasSchemaSnapshot && !targetDatabaseEmpty) { + // Schema exists and database has tables — assume synced (user just hasn't made migrations yet) + driftStatus = "synced"; + } + + // 8. Compute available modes + const availableModes: Array<"run_migrations" | "apply_snapshot" | "skip"> = ["skip"]; + let recommendedMode: "run_migrations" | "apply_snapshot" | "skip" = "skip"; + + if (isBaselineOnly && hasSchemaSnapshot && targetDatabaseEmpty) { + // Baseline-only + empty DB + schema.json exists: + // The baseline file has no real DDL — use schema.json to reconstruct the DB + availableModes.unshift("apply_snapshot"); + recommendedMode = "apply_snapshot"; + // Override: treat as "no real migrations" for the dialog + driftStatus = "drifted"; + } else if (hasMigrations && pendingMigrations.length > 0 && !isBaselineOnly) { + availableModes.unshift("run_migrations"); + recommendedMode = "run_migrations"; + } + if (hasSchemaSnapshot && targetDatabaseEmpty && !hasMigrations) { + availableModes.unshift("apply_snapshot"); + recommendedMode = "apply_snapshot"; + } + + // For the dialog: if baseline-only + empty DB, report as "no real migrations" + // so the frontend shows "Apply Schema Snapshot" (STATE 3) instead of + // "Pending Migrations" (STATE 2) which would try to run the empty baseline + const reportHasMigrations = isBaselineOnly && targetDatabaseEmpty ? false : hasMigrations; + const reportPendingMigrations = + isBaselineOnly && targetDatabaseEmpty ? [] : pendingMigrations; + + const result = { + hasMigrations: reportHasMigrations, + migrationCount: reportPendingMigrations.length, + hasSchemaSnapshot, + lockFileStatus, + tamperedFiles, + targetDatabaseEmpty, + targetTableCount, + driftStatus, + driftDetails: undefined, + pendingMigrations: reportPendingMigrations, + availableModes, + recommendedMode, + }; + + this.rpc.sendResponse(id, { ok: true, data: result }); + } catch (e: any) { + this.logger?.error({ e }, "project.analyzeImport failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleVerifyLock(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); + } + const project = await projectStoreInstance.getProject(projectId); + if (!project?.databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Project has no database ID", + }); + } + const { verifyMigrationLock } = await import("../services/migrationLock"); + const schemaFile = await projectStoreInstance.getSchema(projectId); + const schemaHash = (schemaFile as any)?.schemaHash || ""; + + const isValid = await verifyMigrationLock(project.databaseId, schemaHash); + this.rpc.sendResponse(id, { ok: true, isValid }); + } catch (e: any) { + this.logger?.error({ e }, "project.verifyLock failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handlePushMigrations(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) + return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); + const projectDir = await projectStoreInstance.resolveProjectDir(projectId); + if (!projectDir) + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: "Project directory not found", + }); + + const { gitServiceInstance } = await import("../services/gitService"); + await gitServiceInstance.pushMigrations(projectDir); + this.rpc.sendResponse(id, { ok: true }); + } catch (e: any) { + this.logger?.error({ e }, "project.pushMigrations failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleSyncMigrations(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) + return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); + const projectDir = await projectStoreInstance.resolveProjectDir(projectId); + if (!projectDir) + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: "Project directory not found", + }); + + const { gitServiceInstance } = await import("../services/gitService"); + const result = await gitServiceInstance.syncMigrationFiles(projectDir); + if (result.error) throw new Error(result.error.message || String(result.error)); + this.rpc.sendResponse(id, { ok: true, data: result }); + } catch (e: any) { + this.logger?.error({ e }, "project.syncMigrations failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleGetDrift(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) + return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); + + // Stub implementation for now + this.rpc.sendResponse(id, { ok: true, data: { driftDetected: false, differences: [] } }); + } catch (e: any) { + this.logger?.error({ e }, "project.getDrift failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleGetQueries(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId", + }); + } + + const queries = await projectStoreInstance.getQueries(projectId); + this.rpc.sendResponse(id, { ok: true, data: queries }); + } catch (e: any) { + this.logger?.error({ e }, "project.getQueries failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleAddQuery(params: any, id: number | string) { + try { + const { projectId, name, sql, description } = params || {}; + if (!projectId || !name || !sql) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId, name, or sql", + }); + } + + const query = await projectStoreInstance.addQuery(projectId, { + name, + sql, + description, + }); + this.rpc.sendResponse(id, { ok: true, data: query }); + } catch (e: any) { + this.logger?.error({ e }, "project.addQuery failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleUpdateQuery(params: any, id: number | string) { + try { + const { projectId, queryId, ...updates } = params || {}; + if (!projectId || !queryId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId or queryId", + }); + } + + const query = await projectStoreInstance.updateQuery(projectId, queryId, updates); + if (!query) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: "Query not found", + }); + } + + this.rpc.sendResponse(id, { ok: true, data: query }); + } catch (e: any) { + this.logger?.error({ e }, "project.updateQuery failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleDeleteQuery(params: any, id: number | string) { + try { + const { projectId, queryId } = params || {}; + if (!projectId || !queryId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId or queryId", + }); + } + + await projectStoreInstance.deleteQuery(projectId, queryId); + this.rpc.sendResponse(id, { ok: true }); + } catch (e: any) { + this.logger?.error({ e }, "project.deleteQuery failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + // ========================================== + // Export (for future git-native support) + // ========================================== + + async handleExportProject(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId", + }); + } + + const bundle = await projectStoreInstance.exportProject(projectId); + if (!bundle) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: "Project not found", + }); + } + + this.rpc.sendResponse(id, { ok: true, data: bundle }); + } catch (e: any) { + this.logger?.error({ e }, "project.export failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleGetProjectDir(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId", + }); + } + const dir = await projectStoreInstance.resolveProjectDir(projectId); + this.rpc.sendResponse(id, { ok: true, data: { dir } }); + } catch (e: any) { + this.logger?.error({ e }, "project.getDir failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleGetLocalConfig(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId", + }); + } + const config = await projectStoreInstance.getLocalConfig(projectId); + this.rpc.sendResponse(id, { ok: true, data: config }); + } catch (e: any) { + this.logger?.error({ e }, "project.getLocalConfig failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleSaveLocalConfig(params: any, id: number | string) { + try { + const { projectId, config } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId", + }); + } + const saved = await projectStoreInstance.saveLocalConfig(projectId, config || {}); + this.rpc.sendResponse(id, { ok: true, data: saved }); + } catch (e: any) { + this.logger?.error({ e }, "project.saveLocalConfig failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleEnsureGitignore(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId", + }); + } + const modified = await projectStoreInstance.ensureGitignore(projectId); + this.rpc.sendResponse(id, { ok: true, data: { modified } }); + } catch (e: any) { + this.logger?.error({ e }, "project.ensureGitignore failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + /** Read-only scan — returns metadata + .env info without creating anything. */ + async handleScanImport(params: any, id: number | string) { + try { + const { sourcePath } = params || {}; + if (!sourcePath) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing sourcePath", + }); + } + + const result = await projectStoreInstance.scanImportSource(sourcePath); + this.rpc.sendResponse(id, { ok: true, data: result }); + } catch (e: any) { + this.logger?.error({ e }, "project.scanImport failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + /** Import a project — requires a valid databaseId (no more "pending" fallback). */ + async handleImportProject(params: any, id: number | string) { + try { + const { sourcePath, databaseId } = params || {}; + if (!sourcePath) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing sourcePath", + }); + } + if (!databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing databaseId — create a database connection first", + }); + } + + const project = await projectStoreInstance.importProject({ + sourcePath, + databaseId, + }); + + this.rpc.sendResponse(id, { ok: true, data: project }); + } catch (e: any) { + this.logger?.error({ e }, "project.import failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleLinkDatabase(params: any, id: number | string) { + try { + const { projectId, databaseId } = params || {}; + if (!projectId || !databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId or databaseId", + }); + } + + const project = await projectStoreInstance.linkDatabase(projectId, databaseId); + if (!project) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: "Project not found", + }); + } + + this.rpc.sendResponse(id, { ok: true, data: project }); + } catch (e: any) { + this.logger?.error({ e }, "project.linkDatabase failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleUnlinkFromConnection(params: any, id: number | string) { + try { + const { databaseId } = params || {}; + if (!databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing databaseId", + }); + } + + await projectStoreInstance.unlinkDatabase(databaseId); + this.rpc.sendResponse(id, { ok: true }); + } catch (e: any) { + this.logger?.error({ e }, "project.unlinkFromConnection failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleDeleteWithConnection(params: any, id: number | string) { + try { + const { databaseId } = params || {}; + if (!databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing databaseId", + }); + } + + await projectStoreInstance.deleteProjectByDatabaseId(databaseId); + this.rpc.sendResponse(id, { ok: true }); + } catch (e: any) { + this.logger?.error({ e }, "project.deleteWithConnection failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + + async handleGetGitRemote(params: any, id: number | string) { + try { + const { projectPath } = params || {}; + if (!projectPath) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectPath", + }); + } + + // Using gitServiceInstance since it handles standard git operations + const remotes = await gitServiceInstance.remoteList(projectPath); + const remoteUrl = remotes.length > 0 ? remotes[0].fetchUrl : null; + + this.rpc.sendResponse(id, { ok: true, data: { remoteUrl } }); + } catch (e: any) { + // If it's not a git repo or fails, just return null + this.logger?.error({ e }, "project.getGitRemote failed (might not be a git repo)"); + this.rpc.sendResponse(id, { ok: true, data: { remoteUrl: null } }); + } + } + + async handleRelinkToConnection(params: any, id: number | string) { + try { + const { projectId, databaseId } = params || {}; + if (!projectId || !databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId or databaseId", + }); + } + + const project = await projectStoreInstance.relinkDatabase(projectId, databaseId); + + this.rpc.sendResponse(id, { ok: true, data: project }); + } catch (e: any) { + this.logger?.error({ e }, "project.relinkToConnection failed"); + // Check if it's the specific error we throw + if (e.message?.includes("DATABASE_ALREADY_HAS_PROJECT")) { + this.rpc.sendError(id, { code: "DATABASE_ALREADY_HAS_PROJECT", message: e.message }); + } else { + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } + } + + async handleGenerateSQL(params: any, id: number | string) { + try { + const { projectId } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing projectId", + }); + } + + const { projectStoreInstance } = await import("../services/projectStore"); + const schemaFile = await projectStoreInstance.getSchema(projectId); + if (!schemaFile) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: "No schema snapshot found", + }); + } + + const { generateBaselineSQL } = await import("../utils/baselineMigration"); + const sql = generateBaselineSQL(schemaFile as any, "preview", "preview"); + + this.rpc.sendResponse(id, { ok: true, data: { sql } }); + } catch (e: any) { + this.logger?.error({ e }, "project.generateSQL failed"); + this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); + } + } } diff --git a/bridge/src/handlers/queryHandlers.ts b/bridge/src/handlers/queryHandlers.ts index 007c5d84..9252370a 100644 --- a/bridge/src/handlers/queryHandlers.ts +++ b/bridge/src/handlers/queryHandlers.ts @@ -11,7 +11,7 @@ export class QueryHandlers { private logger: Logger, private sessions: SessionManager, private dbService: DatabaseService, - private queryExecutor: QueryExecutor + private queryExecutor: QueryExecutor, ) {} async handleQueryRun(params: any, id: number | string) { @@ -40,7 +40,9 @@ export class QueryHandlers { conn, dbType, this.rpc, - (cancelFn) => { cancelState.fn = cancelFn; } + (cancelFn) => { + cancelState.fn = cancelFn; + }, ); this.sessions.registerCancel(sessionId, async () => { @@ -85,10 +87,19 @@ export class QueryHandlers { try { const { dbId, schemaName, tableName, limit, page } = params || {}; if (!dbId || !tableName || !schemaName) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing dbId, schemaName, or tableName" }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId, schemaName, or tableName", + }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - const data = await (getConnector(dbType) as any).fetchTableData(conn, schemaName, tableName, limit, page); + const data = await (getConnector(dbType) as any).fetchTableData( + conn, + schemaName, + tableName, + limit, + page, + ); this.rpc.sendResponse(id, { ok: true, data }); } catch (e: any) { this.logger.error({ e }, "fetchTableData failed"); @@ -100,10 +111,17 @@ export class QueryHandlers { try { const { dbId, schemaName, tableName } = params || {}; if (!dbId || !tableName || !schemaName) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing dbId, schemaName, or tableName" }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId, schemaName, or tableName", + }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - const primaryKeys = await (getConnector(dbType) as any).listPrimaryKeys(conn, schemaName, tableName); + const primaryKeys = await (getConnector(dbType) as any).listPrimaryKeys( + conn, + schemaName, + tableName, + ); this.rpc.sendResponse(id, { ok: true, primaryKeys }); } catch (e: any) { this.logger.error({ e }, "fetchPrimaryKeys failed"); @@ -115,7 +133,10 @@ export class QueryHandlers { try { const { dbId, schemaName, tableName, columns, foreignKeys = [] } = params || {}; if (!dbId || !tableName || !schemaName) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing dbId, schemaName, or tableName" }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId, schemaName, or tableName", + }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); const connector = getConnector(dbType) as any; @@ -132,7 +153,10 @@ export class QueryHandlers { try { const { dbId, schemaName, indexes } = params || {}; if (!dbId || !schemaName) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing dbId or schemaName" }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId or schemaName", + }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); const connector = getConnector(dbType) as any; @@ -149,7 +173,10 @@ export class QueryHandlers { try { const { dbId, schemaName, tableName, operations } = params || {}; if (!dbId || !schemaName || !tableName) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing dbId, schemaName, or tableName" }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId, schemaName, or tableName", + }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); const connector = getConnector(dbType) as any; @@ -166,7 +193,10 @@ export class QueryHandlers { try { const { dbId, schemaName, tableName } = params || {}; if (!dbId || !schemaName || !tableName) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing dbId, schemaName, or tableName" }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId, schemaName, or tableName", + }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); const connector = getConnector(dbType) as any; @@ -198,7 +228,10 @@ export class QueryHandlers { try { const { dbId, schemaName, tableName, rowData } = params || {}; if (!dbId || !schemaName || !tableName || !rowData) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing dbId, schemaName, tableName, or rowData" }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId, schemaName, tableName, or rowData", + }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); const connector = getConnector(dbType) as any; @@ -213,13 +246,31 @@ export class QueryHandlers { async handleUpdateRow(params: any, id: number | string) { try { - const { dbId, schemaName, tableName, primaryKeyColumn, primaryKeyValue, rowData } = params || {}; - if (!dbId || !schemaName || !tableName || !primaryKeyColumn || primaryKeyValue === undefined || !rowData) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing required update fields" }); + const { dbId, schemaName, tableName, primaryKeyColumn, primaryKeyValue, rowData } = + params || {}; + if ( + !dbId || + !schemaName || + !tableName || + !primaryKeyColumn || + primaryKeyValue === undefined || + !rowData + ) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing required update fields", + }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); const connector = getConnector(dbType) as any; - const result = await connector.updateRow(conn, schemaName, tableName, primaryKeyColumn, primaryKeyValue, rowData); + const result = await connector.updateRow( + conn, + schemaName, + tableName, + primaryKeyColumn, + primaryKeyValue, + rowData, + ); connector[`${dbType}Cache`]?.clearForConnection(conn); this.rpc.sendResponse(id, { ok: true, result }); } catch (e: any) { @@ -232,14 +283,26 @@ export class QueryHandlers { try { const { dbId, schemaName, tableName, primaryKeyColumn, primaryKeyValue } = params || {}; if (!dbId || !schemaName || !tableName) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing dbId, schemaName, or tableName" }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId, schemaName, or tableName", + }); } if (!primaryKeyColumn && (typeof primaryKeyValue !== "object" || primaryKeyValue === null)) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Either primaryKeyColumn or composite key object is required" }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Either primaryKeyColumn or composite key object is required", + }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); const connector = getConnector(dbType) as any; - const result = await connector.deleteRow(conn, schemaName, tableName, primaryKeyColumn, primaryKeyValue); + const result = await connector.deleteRow( + conn, + schemaName, + tableName, + primaryKeyColumn, + primaryKeyValue, + ); connector[`${dbType}Cache`]?.clearForConnection(conn); this.rpc.sendResponse(id, { ok: true, deleted: result }); } catch (e: any) { @@ -252,11 +315,20 @@ export class QueryHandlers { try { const { dbId, schemaName, tableName, searchTerm, column, page, pageSize } = params || {}; if (!dbId || !schemaName || !tableName || !searchTerm) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing dbId, schemaName, tableName, or searchTerm" }); + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing dbId, schemaName, tableName, or searchTerm", + }); } const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); const result = await (getConnector(dbType) as any).searchTable( - conn, schemaName, tableName, searchTerm, column, page || 1, pageSize || 50 + conn, + schemaName, + tableName, + searchTerm, + column, + page || 1, + pageSize || 50, ); this.rpc.sendResponse(id, { ok: true, ...result }); } catch (e: any) { @@ -264,4 +336,4 @@ export class QueryHandlers { this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } } -} \ No newline at end of file +} diff --git a/bridge/src/handlers/sessionHandlers.ts b/bridge/src/handlers/sessionHandlers.ts index 293e6d3c..42a938e9 100644 --- a/bridge/src/handlers/sessionHandlers.ts +++ b/bridge/src/handlers/sessionHandlers.ts @@ -1,17 +1,16 @@ - // ---------------------------- // handlers/sessionHandlers.ts // ---------------------------- -import { Rpc } from '../types'; -import { SessionManager } from '../sessionManager'; -import { randomUUID } from 'node:crypto'; +import { Rpc } from "../types"; +import { SessionManager } from "../sessionManager"; +import { randomUUID } from "node:crypto"; export class SessionHandlers { constructor( private rpc: Rpc, private logger: any, - private sessions: SessionManager + private sessions: SessionManager, ) {} /** @@ -27,23 +26,23 @@ export class SessionHandlers { // Create session with optional metadata const session = this.sessions.create(sessionId, { connectionId, - ...meta + ...meta, }); - this.logger?.info({ sessionId, connectionId, meta }, 'Session created'); + this.logger?.info({ sessionId, connectionId, meta }, "Session created"); this.rpc.sendResponse(id, { ok: true, - data: { + data: { sessionId, - createdAt: session.createdAt - } + createdAt: session.createdAt, + }, }); } catch (e: any) { - this.logger?.error({ e, params }, 'query.createSession failed'); + this.logger?.error({ e, params }, "query.createSession failed"); this.rpc.sendError(id, { - code: 'INTERNAL_ERROR', - message: String(e) + code: "INTERNAL_ERROR", + message: String(e), }); } } @@ -57,26 +56,26 @@ export class SessionHandlers { const { sessionId } = params || {}; if (!sessionId) { - this.logger?.warn({ params }, 'query.cancel called without sessionId'); + this.logger?.warn({ params }, "query.cancel called without sessionId"); return this.rpc.sendError(id, { - code: 'BAD_REQUEST', - message: 'Missing sessionId' + code: "BAD_REQUEST", + message: "Missing sessionId", }); } const cancelled = await this.sessions.cancel(sessionId); - this.logger?.info({ sessionId, cancelled }, 'Session cancel requested'); + this.logger?.info({ sessionId, cancelled }, "Session cancel requested"); this.rpc.sendResponse(id, { ok: true, - data: { cancelled } + data: { cancelled }, }); } catch (e: any) { - this.logger?.error({ e, params }, 'query.cancel failed'); + this.logger?.error({ e, params }, "query.cancel failed"); this.rpc.sendError(id, { - code: 'INTERNAL_ERROR', - message: String(e) + code: "INTERNAL_ERROR", + message: String(e), }); } } @@ -91,8 +90,8 @@ export class SessionHandlers { if (!sessionId) { return this.rpc.sendError(id, { - code: 'BAD_REQUEST', - message: 'Missing sessionId' + code: "BAD_REQUEST", + message: "Missing sessionId", }); } @@ -100,8 +99,8 @@ export class SessionHandlers { if (!session) { return this.rpc.sendError(id, { - code: 'NOT_FOUND', - message: 'Session not found' + code: "NOT_FOUND", + message: "Session not found", }); } @@ -112,14 +111,14 @@ export class SessionHandlers { sessionId: session.id, connectionId: session.connectionId, createdAt: session.createdAt, - hasCancel: !!session.cancel - } + hasCancel: !!session.cancel, + }, }); } catch (e: any) { - this.logger?.error({ e, params }, 'query.getSession failed'); + this.logger?.error({ e, params }, "query.getSession failed"); this.rpc.sendError(id, { - code: 'INTERNAL_ERROR', - message: String(e) + code: "INTERNAL_ERROR", + message: String(e), }); } } @@ -135,20 +134,20 @@ export class SessionHandlers { this.rpc.sendResponse(id, { ok: true, data: { - sessions: activeSessions.map(s => ({ + sessions: activeSessions.map((s) => ({ sessionId: s.id, connectionId: s.connectionId, createdAt: s.createdAt, - hasCancel: !!s.cancel + hasCancel: !!s.cancel, })), - count: activeSessions.length - } + count: activeSessions.length, + }, }); } catch (e: any) { - this.logger?.error({ e }, 'query.listSessions failed'); + this.logger?.error({ e }, "query.listSessions failed"); this.rpc.sendError(id, { - code: 'INTERNAL_ERROR', - message: String(e) + code: "INTERNAL_ERROR", + message: String(e), }); } } @@ -163,25 +162,25 @@ export class SessionHandlers { if (!sessionId) { return this.rpc.sendError(id, { - code: 'BAD_REQUEST', - message: 'Missing sessionId' + code: "BAD_REQUEST", + message: "Missing sessionId", }); } const removed = this.sessions.remove(sessionId); - this.logger?.info({ sessionId, removed }, 'Session destroyed'); + this.logger?.info({ sessionId, removed }, "Session destroyed"); this.rpc.sendResponse(id, { ok: true, - data: { removed } + data: { removed }, }); } catch (e: any) { - this.logger?.error({ e, params }, 'query.destroySession failed'); + this.logger?.error({ e, params }, "query.destroySession failed"); this.rpc.sendError(id, { - code: 'INTERNAL_ERROR', - message: String(e) + code: "INTERNAL_ERROR", + message: String(e), }); } } -} \ No newline at end of file +} diff --git a/bridge/src/handlers/statsHandlers.ts b/bridge/src/handlers/statsHandlers.ts index 4cdc93ae..a58efbe0 100644 --- a/bridge/src/handlers/statsHandlers.ts +++ b/bridge/src/handlers/statsHandlers.ts @@ -23,7 +23,7 @@ export class StatsHandlers { private rpc: Rpc, private logger: Logger, private dbService: DatabaseService, - private queryExecutor: QueryExecutor + private queryExecutor: QueryExecutor, ) {} /** Handle db.getStats — get statistics for a specific database */ @@ -64,7 +64,7 @@ export class StatsHandlers { const connectionTest = await this.queryExecutor.testConnection(conn, dbType); if (!(connectionTest as any)?.ok) { this.logger.warn( - `Skipping stats for DB ${db.name} (${db.id}) — connection test failed` + `Skipping stats for DB ${db.name} (${db.id}) — connection test failed`, ); continue; } @@ -76,7 +76,7 @@ export class StatsHandlers { } catch (dbError: any) { this.logger.warn( { dbError, dbId: db.id, dbName: db.name }, - `Failed to get stats for database ${db.name}` + `Failed to get stats for database ${db.name}`, ); } } @@ -87,4 +87,4 @@ export class StatsHandlers { this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } } -} \ No newline at end of file +} diff --git a/bridge/src/index.ts b/bridge/src/index.ts index c12af89b..1e76cd79 100644 --- a/bridge/src/index.ts +++ b/bridge/src/index.ts @@ -27,7 +27,9 @@ logger.info(`Uptime at start: ${process.uptime()} sec`); logger.info(`process.execPath: ${process.execPath}`); logger.info(`process.cwd(): ${process.cwd()}`); logger.info(`isPkg: ${Boolean((process as any).pkg)}`); -logger.info(`RELWAVE_SQLITE_NATIVE_BINDING: ${process.env.RELWAVE_SQLITE_NATIVE_BINDING ?? "(not set)"}`); +logger.info( + `RELWAVE_SQLITE_NATIVE_BINDING: ${process.env.RELWAVE_SQLITE_NATIVE_BINDING ?? "(not set)"}`, +); logger.info(`BETTER_SQLITE3_BINDING: ${process.env.BETTER_SQLITE3_BINDING ?? "(not set)"}`); // Send initial ready notification diff --git a/bridge/src/jsonRpc.ts b/bridge/src/jsonRpc.ts index b35e3e5a..a254d03b 100644 --- a/bridge/src/jsonRpc.ts +++ b/bridge/src/jsonRpc.ts @@ -1,119 +1,122 @@ -import { EventEmitter } from 'events'; -import logger from './services/logger'; - -export type RpcRequest = { id?: number | string; method: string; params?: any }; -export type RpcResponse = { id?: number | string; result?: any; error?: any }; -export type RpcNotification = { method: string; params?: any }; - -/** - * JsonStdio - * - newline-delimited JSON framing - * - emits 'request' events for incoming requests - * - emits 'notification' events for incoming notifications (no id) - * - provides sendResponse, sendError, sendNotification helpers - * - * Usage: - * const rpc = new JsonStdio(); - * rpc.on('request', (req) => { ... }); - * rpc.sendResponse(id, payload); - * rpc.sendNotification('query.result', { ... }); - */ -export class JsonStdio extends EventEmitter { - private _id = 1; - private closed = false; - private _handlers = new Map Promise | void>(); - - constructor() { - super(); - process.stdin.setEncoding('utf8'); - let buffer = ''; - process.stdin.on('data', chunk => { - buffer += chunk.toString(); - let idx; - while ((idx = buffer.indexOf('\n')) >= 0) { - const line = buffer.slice(0, idx).trim(); - buffer = buffer.slice(idx + 1); - if (!line) continue; - this._handleLine(line); - } - }); - - process.stdin.on('end', () => { - this.closed = true; - this.emit('end'); - }); - - process.stdin.on('error', (err) => { - logger.error({ err }, 'stdin error'); - this.emit('error', err); - }); - } - - /** - * Register a method handler. - * Registered handlers are called before the generic 'request' event. - */ - register(method: string, handler: (params: any, id: number | string) => Promise | void): void { - this._handlers.set(method, handler); - } - - private _handleLine(line: string) { - let obj: any = null; - try { - obj = JSON.parse(line); - } catch (err: any) { - const parseErr = { code: 'PARSE_ERROR', message: String(err), raw: line }; - try { - this.sendNotification('bridge.parse_error', parseErr); - } catch (e) { - // ignore - } - logger.warn({ err, raw: line }, 'invalid JSON from stdin'); - return; - } - - if (obj && typeof obj === 'object') { - if (obj.method && obj.id !== undefined) { - // Registered handler takes priority over the 'request' event - const handler = this._handlers.get(obj.method); - if (handler) { - Promise.resolve(handler(obj.params, obj.id)).catch((err) => { - logger.error({ err, method: obj.method }, 'registered handler threw'); - this.sendError(obj.id, { code: 'HANDLER_ERROR', message: String(err) }); - }); - } else { - this.emit('request', obj as RpcRequest); - } - } else if (obj.method && obj.id === undefined) { - this.emit('notification', obj as RpcNotification); - } else { - if (obj.id !== undefined) this.emit('request', obj as RpcRequest); - else this.emit('notification', obj as RpcNotification); - } - } else { - logger.warn({ line }, 'received non-object JSON line'); - } - } - - sendResponse(id: number | string, payload: any) { - if (this.closed) return; - const msg = JSON.stringify({ id, result: payload }); - process.stdout.write(msg + '\n'); - } - - sendError(id: number | string, error: { code?: string; message?: string; details?: any }) { - if (this.closed) return; - const msg = JSON.stringify({ id, error }); - process.stdout.write(msg + '\n'); - } - - sendNotification(method: string, params?: any) { - if (this.closed) return; - const msg = JSON.stringify({ method, params }); - process.stdout.write(msg + '\n'); - } - - newId(): number { - return this._id++; - } -} \ No newline at end of file +import { EventEmitter } from "events"; +import logger from "./services/logger"; + +export type RpcRequest = { id?: number | string; method: string; params?: any }; +export type RpcResponse = { id?: number | string; result?: any; error?: any }; +export type RpcNotification = { method: string; params?: any }; + +/** + * JsonStdio + * - newline-delimited JSON framing + * - emits 'request' events for incoming requests + * - emits 'notification' events for incoming notifications (no id) + * - provides sendResponse, sendError, sendNotification helpers + * + * Usage: + * const rpc = new JsonStdio(); + * rpc.on('request', (req) => { ... }); + * rpc.sendResponse(id, payload); + * rpc.sendNotification('query.result', { ... }); + */ +export class JsonStdio extends EventEmitter { + private _id = 1; + private closed = false; + private _handlers = new Map Promise | void>(); + + constructor() { + super(); + process.stdin.setEncoding("utf8"); + let buffer = ""; + process.stdin.on("data", (chunk) => { + buffer += chunk.toString(); + let idx; + while ((idx = buffer.indexOf("\n")) >= 0) { + const line = buffer.slice(0, idx).trim(); + buffer = buffer.slice(idx + 1); + if (!line) continue; + this._handleLine(line); + } + }); + + process.stdin.on("end", () => { + this.closed = true; + this.emit("end"); + }); + + process.stdin.on("error", (err) => { + logger.error({ err }, "stdin error"); + this.emit("error", err); + }); + } + + /** + * Register a method handler. + * Registered handlers are called before the generic 'request' event. + */ + register( + method: string, + handler: (params: any, id: number | string) => Promise | void, + ): void { + this._handlers.set(method, handler); + } + + private _handleLine(line: string) { + let obj: any = null; + try { + obj = JSON.parse(line); + } catch (err: any) { + const parseErr = { code: "PARSE_ERROR", message: String(err), raw: line }; + try { + this.sendNotification("bridge.parse_error", parseErr); + } catch (e) { + // ignore + } + logger.warn({ err, raw: line }, "invalid JSON from stdin"); + return; + } + + if (obj && typeof obj === "object") { + if (obj.method && obj.id !== undefined) { + // Registered handler takes priority over the 'request' event + const handler = this._handlers.get(obj.method); + if (handler) { + Promise.resolve(handler(obj.params, obj.id)).catch((err) => { + logger.error({ err, method: obj.method }, "registered handler threw"); + this.sendError(obj.id, { code: "HANDLER_ERROR", message: String(err) }); + }); + } else { + this.emit("request", obj as RpcRequest); + } + } else if (obj.method && obj.id === undefined) { + this.emit("notification", obj as RpcNotification); + } else { + if (obj.id !== undefined) this.emit("request", obj as RpcRequest); + else this.emit("notification", obj as RpcNotification); + } + } else { + logger.warn({ line }, "received non-object JSON line"); + } + } + + sendResponse(id: number | string, payload: any) { + if (this.closed) return; + const msg = JSON.stringify({ id, result: payload }); + process.stdout.write(msg + "\n"); + } + + sendError(id: number | string, error: { code?: string; message?: string; details?: any }) { + if (this.closed) return; + const msg = JSON.stringify({ id, error }); + process.stdout.write(msg + "\n"); + } + + sendNotification(method: string, params?: any) { + if (this.closed) return; + const msg = JSON.stringify({ method, params }); + process.stdout.write(msg + "\n"); + } + + newId(): number { + return this._id++; + } +} diff --git a/bridge/src/jsonRpcHandler.ts b/bridge/src/jsonRpcHandler.ts index 15fd92e7..dfcdb8fc 100644 --- a/bridge/src/jsonRpcHandler.ts +++ b/bridge/src/jsonRpcHandler.ts @@ -22,11 +22,7 @@ import { Logger } from "pino"; * @param logger - Logger instance * @param sessions - Session manager instance */ -export function registerDbHandlers( - rpc: Rpc, - logger: Logger, - sessions: SessionManager -) { +export function registerDbHandlers(rpc: Rpc, logger: Logger, sessions: SessionManager) { // Initialize services const dbService = new DatabaseService(); const queryExecutor = new QueryExecutor(); @@ -34,106 +30,51 @@ export function registerDbHandlers( const monitoringWebSocketServer = new MonitoringWebSocketServer( dbService, monitoringService, - logger + logger, ); monitoringWebSocketServer.start(); // Initialize handlers with dependencies const sessionHandlers = new SessionHandlers(rpc, logger, sessions); - const queryHandlers = new QueryHandlers( - rpc, - logger, - sessions, - dbService, - queryExecutor - ); - const databaseHandlers = new DatabaseHandlers( - rpc, - logger, - dbService, - queryExecutor - ); - const statsHandlers = new StatsHandlers( - rpc, - logger, - dbService, - queryExecutor - ); - const migrationHandlers = new MigrationHandlers( - rpc, - logger, - dbService, - queryExecutor - ); + const queryHandlers = new QueryHandlers(rpc, logger, sessions, dbService, queryExecutor); + const databaseHandlers = new DatabaseHandlers(rpc, logger, dbService, queryExecutor); + const statsHandlers = new StatsHandlers(rpc, logger, dbService, queryExecutor); + const migrationHandlers = new MigrationHandlers(rpc, logger, dbService, queryExecutor); const projectHandlers = new ProjectHandlers(rpc, logger, dbService, queryExecutor); const gitHandlers = new GitHandlers(rpc, logger); const gitAdvancedHandlers = new GitAdvancedHandlers(rpc, logger); const monitoringHandlers = new MonitoringHandlers(rpc, logger, dbService, monitoringService); - const aiHandlers = new (require("./handlers/aiHandlers")).AIHandlers(rpc, logger, dbService); + const aiHandlers = new (require("./handlers/aiHandlers").AIHandlers)(rpc, logger, dbService); // ========================================== // SESSION MANAGEMENT HANDLERS // ========================================== - rpcRegister(rpc, "query.createSession", (p, id) => - sessionHandlers.handleCreateSession(p, id) - ); - rpcRegister(rpc, "query.cancel", (p, id) => - sessionHandlers.handleCancelSession(p, id) - ); - rpcRegister(rpc, "query.getSession", (p, id) => - sessionHandlers.handleGetSession(p, id) - ); - rpcRegister(rpc, "query.listSessions", (p, id) => - sessionHandlers.handleListSessions(p, id) - ); - rpcRegister(rpc, "query.destroySession", (p, id) => - sessionHandlers.handleDestroySession(p, id) - ); + rpcRegister(rpc, "query.createSession", (p, id) => sessionHandlers.handleCreateSession(p, id)); + rpcRegister(rpc, "query.cancel", (p, id) => sessionHandlers.handleCancelSession(p, id)); + rpcRegister(rpc, "query.getSession", (p, id) => sessionHandlers.handleGetSession(p, id)); + rpcRegister(rpc, "query.listSessions", (p, id) => sessionHandlers.handleListSessions(p, id)); + rpcRegister(rpc, "query.destroySession", (p, id) => sessionHandlers.handleDestroySession(p, id)); // ========================================== // QUERY HANDLERS // ========================================== rpcRegister(rpc, "query.run", (p, id) => queryHandlers.handleQueryRun(p, id)); - rpcRegister(rpc, "query.fetchTableData", (p, id) => - queryHandlers.handleFetchTableData(p, id) - ); - rpcRegister(rpc, "query.listPrimaryKeys", (p, id) => - queryHandlers.handleFetchPrimaryKeys(p, id) - ); - rpcRegister(rpc, "query.createTable", (p, id) => - queryHandlers.handleCreateTable(p, id) - ); - rpcRegister(rpc, "query.createIndexes", (p, id) => - queryHandlers.handleCreateIndexes(p, id) - ); - rpcRegister(rpc, "query.dropTable", (p, id) => - queryHandlers.handleDropTable(p, id) - ); - rpcRegister(rpc, "query.alterTable", (p, id) => - queryHandlers.handleAlterTable(p, id) - ); - rpcRegister(rpc, "query.connectToDatabase", (p, id) => - queryHandlers.connectToDatabase(p, id) - ); - rpcRegister(rpc, "query.insertRow", (p, id) => - queryHandlers.handleInsertRow(p, id) - ); - rpcRegister(rpc, "query.updateRow", (p, id) => - queryHandlers.handleUpdateRow(p, id) - ); - rpcRegister(rpc, "query.deleteRow", (p, id) => - queryHandlers.handleDeleteRow(p, id) - ); - rpcRegister(rpc, "query.searchTable", (p, id) => - queryHandlers.handleSearchTable(p, id) - ); + rpcRegister(rpc, "query.fetchTableData", (p, id) => queryHandlers.handleFetchTableData(p, id)); + rpcRegister(rpc, "query.listPrimaryKeys", (p, id) => queryHandlers.handleFetchPrimaryKeys(p, id)); + rpcRegister(rpc, "query.createTable", (p, id) => queryHandlers.handleCreateTable(p, id)); + rpcRegister(rpc, "query.createIndexes", (p, id) => queryHandlers.handleCreateIndexes(p, id)); + rpcRegister(rpc, "query.dropTable", (p, id) => queryHandlers.handleDropTable(p, id)); + rpcRegister(rpc, "query.alterTable", (p, id) => queryHandlers.handleAlterTable(p, id)); + rpcRegister(rpc, "query.connectToDatabase", (p, id) => queryHandlers.connectToDatabase(p, id)); + rpcRegister(rpc, "query.insertRow", (p, id) => queryHandlers.handleInsertRow(p, id)); + rpcRegister(rpc, "query.updateRow", (p, id) => queryHandlers.handleUpdateRow(p, id)); + rpcRegister(rpc, "query.deleteRow", (p, id) => queryHandlers.handleDeleteRow(p, id)); + rpcRegister(rpc, "query.searchTable", (p, id) => queryHandlers.handleSearchTable(p, id)); // ========================================== // DATABASE CRUD HANDLERS // ========================================== - rpcRegister(rpc, "db.list", (p, id) => - databaseHandlers.handleListDatabases(p, id) - ); + rpcRegister(rpc, "db.list", (p, id) => databaseHandlers.handleListDatabases(p, id)); rpcRegister(rpc, "db.get", (p, id) => databaseHandlers.handleGetDatabase(p, id)); rpcRegister(rpc, "db.add", (p, id) => databaseHandlers.handleAddDatabase(p, id)); rpcRegister(rpc, "db.delete", (p, id) => databaseHandlers.handleDeleteDatabase(p, id)); @@ -143,58 +84,42 @@ export function registerDbHandlers( // ========================================== // DATABASE METADATA HANDLERS // ========================================== - rpcRegister(rpc, "db.listTables", (p, id) => - databaseHandlers.handleListTables(p, id) - ); - rpcRegister(rpc, "db.getSchema", (p, id) => - databaseHandlers.handleGetSchema(p, id) - ); - rpcRegister(rpc, "db.listSchemas", (p, id) => - databaseHandlers.handleListSchemas(p, id) - ); + rpcRegister(rpc, "db.listTables", (p, id) => databaseHandlers.handleListTables(p, id)); + rpcRegister(rpc, "db.getSchema", (p, id) => databaseHandlers.handleGetSchema(p, id)); + rpcRegister(rpc, "db.listSchemas", (p, id) => databaseHandlers.handleListSchemas(p, id)); // ========================================== // MIGRATION HANDLERS // ========================================== rpcRegister(rpc, "migration.generateCreate", (p, id) => - migrationHandlers.handleGenerateCreateMigration(p, id) + migrationHandlers.handleGenerateCreateMigration(p, id), ); rpcRegister(rpc, "migration.generateAlter", (p, id) => - migrationHandlers.handleGenerateAlterMigration(p, id) + migrationHandlers.handleGenerateAlterMigration(p, id), ); rpcRegister(rpc, "migration.generateDrop", (p, id) => - migrationHandlers.handleGenerateDropMigration(p, id) - ); - rpcRegister(rpc, "migration.apply", (p, id) => - migrationHandlers.handleApplyMigration(p, id) + migrationHandlers.handleGenerateDropMigration(p, id), ); + rpcRegister(rpc, "migration.apply", (p, id) => migrationHandlers.handleApplyMigration(p, id)); rpcRegister(rpc, "migration.applyMigrations", (p, id) => - migrationHandlers.handleApplyMigrations(p, id) + migrationHandlers.handleApplyMigrations(p, id), ); rpcRegister(rpc, "migration.applySnapshot", (p, id) => - migrationHandlers.handleApplySnapshot(p, id) + migrationHandlers.handleApplySnapshot(p, id), ); rpcRegister(rpc, "migration.rollback", (p, id) => - migrationHandlers.handleRollbackMigration(p, id) - ); - rpcRegister(rpc, "migration.delete", (p, id) => - migrationHandlers.handleDeleteMigration(p, id) - ); - rpcRegister(rpc, "migration.getSQL", (p, id) => - migrationHandlers.handleGetMigrationSQL(p, id) + migrationHandlers.handleRollbackMigration(p, id), ); + rpcRegister(rpc, "migration.delete", (p, id) => migrationHandlers.handleDeleteMigration(p, id)); + rpcRegister(rpc, "migration.getSQL", (p, id) => migrationHandlers.handleGetMigrationSQL(p, id)); // ========================================== // STATISTICS HANDLERS // ========================================== rpcRegister(rpc, "db.getStats", (p, id) => statsHandlers.handleGetStats(p, id)); - rpcRegister(rpc, "db.getTotalStats", (p, id) => - statsHandlers.handleGetTotalStats(p, id) - ); + rpcRegister(rpc, "db.getTotalStats", (p, id) => statsHandlers.handleGetTotalStats(p, id)); - rpcRegister(rpc, "db.monitoringSnapshot", (p, id) => - monitoringHandlers.handleGetSnapshot(p, id) - ); + rpcRegister(rpc, "db.monitoringSnapshot", (p, id) => monitoringHandlers.handleGetSnapshot(p, id)); rpcRegister(rpc, "db.monitoringWsInfo", (_p, id) => { try { rpc.sendResponse(id, { ok: true, data: monitoringWebSocketServer.getInfo() }); @@ -209,110 +134,64 @@ export function registerDbHandlers( // ========================================== // PROJECT HANDLERS // ========================================== - rpcRegister(rpc, "project.list", (p, id) => - projectHandlers.handleListProjects(p, id) - ); - rpcRegister(rpc, "project.get", (p, id) => - projectHandlers.handleGetProject(p, id) - ); + rpcRegister(rpc, "project.list", (p, id) => projectHandlers.handleListProjects(p, id)); + rpcRegister(rpc, "project.get", (p, id) => projectHandlers.handleGetProject(p, id)); rpcRegister(rpc, "project.getByDatabaseId", (p, id) => - projectHandlers.handleGetProjectByDatabaseId(p, id) - ); - rpcRegister(rpc, "project.create", (p, id) => - projectHandlers.handleCreateProject(p, id) - ); - rpcRegister(rpc, "project.update", (p, id) => - projectHandlers.handleUpdateProject(p, id) - ); - rpcRegister(rpc, "project.delete", (p, id) => - projectHandlers.handleDeleteProject(p, id) - ); - rpcRegister(rpc, "project.getSchema", (p, id) => - projectHandlers.handleGetSchema(p, id) - ); - rpcRegister(rpc, "project.saveSchema", (p, id) => - projectHandlers.handleSaveSchema(p, id) + projectHandlers.handleGetProjectByDatabaseId(p, id), ); + rpcRegister(rpc, "project.create", (p, id) => projectHandlers.handleCreateProject(p, id)); + rpcRegister(rpc, "project.update", (p, id) => projectHandlers.handleUpdateProject(p, id)); + rpcRegister(rpc, "project.delete", (p, id) => projectHandlers.handleDeleteProject(p, id)); + rpcRegister(rpc, "project.getSchema", (p, id) => projectHandlers.handleGetSchema(p, id)); + rpcRegister(rpc, "project.saveSchema", (p, id) => projectHandlers.handleSaveSchema(p, id)); rpcRegister(rpc, "project.refreshSchemaCache", (p, id) => - projectHandlers.handleRefreshSchemaCache(p, id) - ); - rpcRegister(rpc, "project.getERDiagram", (p, id) => - projectHandlers.handleGetERDiagram(p, id) - ); - rpcRegister(rpc, "project.saveERDiagram", (p, id) => - projectHandlers.handleSaveERDiagram(p, id) + projectHandlers.handleRefreshSchemaCache(p, id), ); + rpcRegister(rpc, "project.getERDiagram", (p, id) => projectHandlers.handleGetERDiagram(p, id)); + rpcRegister(rpc, "project.saveERDiagram", (p, id) => projectHandlers.handleSaveERDiagram(p, id)); rpcRegister(rpc, "project.getAnnotations", (p, id) => - projectHandlers.handleGetAnnotations(p, id) + projectHandlers.handleGetAnnotations(p, id), ); rpcRegister(rpc, "project.saveAnnotations", (p, id) => - projectHandlers.handleSaveAnnotations(p, id) - ); - rpcRegister(rpc, "project.analyzeImport", (p, id) => - projectHandlers.handleAnalyzeImport(p, id) - ); - rpcRegister(rpc, "project.verifyLock", (p, id) => - projectHandlers.handleVerifyLock(p, id) + projectHandlers.handleSaveAnnotations(p, id), ); + rpcRegister(rpc, "project.analyzeImport", (p, id) => projectHandlers.handleAnalyzeImport(p, id)); + rpcRegister(rpc, "project.verifyLock", (p, id) => projectHandlers.handleVerifyLock(p, id)); rpcRegister(rpc, "project.pushMigrations", (p, id) => - projectHandlers.handlePushMigrations(p, id) + projectHandlers.handlePushMigrations(p, id), ); rpcRegister(rpc, "project.syncMigrations", (p, id) => - projectHandlers.handleSyncMigrations(p, id) - ); - rpcRegister(rpc, "project.generateSQL", (p, id) => - projectHandlers.handleGenerateSQL(p, id) - ); - rpcRegister(rpc, "project.getDrift", (p, id) => - projectHandlers.handleGetDrift(p, id) - ); - rpcRegister(rpc, "project.getQueries", (p, id) => - projectHandlers.handleGetQueries(p, id) - ); - rpcRegister(rpc, "project.addQuery", (p, id) => - projectHandlers.handleAddQuery(p, id) - ); - rpcRegister(rpc, "project.updateQuery", (p, id) => - projectHandlers.handleUpdateQuery(p, id) - ); - rpcRegister(rpc, "project.deleteQuery", (p, id) => - projectHandlers.handleDeleteQuery(p, id) - ); - rpcRegister(rpc, "project.export", (p, id) => - projectHandlers.handleExportProject(p, id) - ); - rpcRegister(rpc, "project.getDir", (p, id) => - projectHandlers.handleGetProjectDir(p, id) - ); + projectHandlers.handleSyncMigrations(p, id), + ); + rpcRegister(rpc, "project.generateSQL", (p, id) => projectHandlers.handleGenerateSQL(p, id)); + rpcRegister(rpc, "project.getDrift", (p, id) => projectHandlers.handleGetDrift(p, id)); + rpcRegister(rpc, "project.getQueries", (p, id) => projectHandlers.handleGetQueries(p, id)); + rpcRegister(rpc, "project.addQuery", (p, id) => projectHandlers.handleAddQuery(p, id)); + rpcRegister(rpc, "project.updateQuery", (p, id) => projectHandlers.handleUpdateQuery(p, id)); + rpcRegister(rpc, "project.deleteQuery", (p, id) => projectHandlers.handleDeleteQuery(p, id)); + rpcRegister(rpc, "project.export", (p, id) => projectHandlers.handleExportProject(p, id)); + rpcRegister(rpc, "project.getDir", (p, id) => projectHandlers.handleGetProjectDir(p, id)); rpcRegister(rpc, "project.getLocalConfig", (p, id) => - projectHandlers.handleGetLocalConfig(p, id) + projectHandlers.handleGetLocalConfig(p, id), ); rpcRegister(rpc, "project.saveLocalConfig", (p, id) => - projectHandlers.handleSaveLocalConfig(p, id) + projectHandlers.handleSaveLocalConfig(p, id), ); rpcRegister(rpc, "project.ensureGitignore", (p, id) => - projectHandlers.handleEnsureGitignore(p, id) - ); - rpcRegister(rpc, "project.scanImport", (p, id) => - projectHandlers.handleScanImport(p, id) - ); - rpcRegister(rpc, "project.import", (p, id) => - projectHandlers.handleImportProject(p, id) - ); - rpcRegister(rpc, "project.linkDatabase", (p, id) => - projectHandlers.handleLinkDatabase(p, id) + projectHandlers.handleEnsureGitignore(p, id), ); + rpcRegister(rpc, "project.scanImport", (p, id) => projectHandlers.handleScanImport(p, id)); + rpcRegister(rpc, "project.import", (p, id) => projectHandlers.handleImportProject(p, id)); + rpcRegister(rpc, "project.linkDatabase", (p, id) => projectHandlers.handleLinkDatabase(p, id)); rpcRegister(rpc, "project.unlinkFromConnection", (p, id) => - projectHandlers.handleUnlinkFromConnection(p, id) + projectHandlers.handleUnlinkFromConnection(p, id), ); rpcRegister(rpc, "project.deleteWithConnection", (p, id) => - projectHandlers.handleDeleteWithConnection(p, id) - ); - rpcRegister(rpc, "project.getGitRemote", (p, id) => - projectHandlers.handleGetGitRemote(p, id) + projectHandlers.handleDeleteWithConnection(p, id), ); + rpcRegister(rpc, "project.getGitRemote", (p, id) => projectHandlers.handleGetGitRemote(p, id)); rpcRegister(rpc, "project.relinkToConnection", (p, id) => - projectHandlers.handleRelinkToConnection(p, id) + projectHandlers.handleRelinkToConnection(p, id), ); // ========================================== @@ -365,29 +244,19 @@ export function registerDbHandlers( // ========================================== // AI HANDLERS // ========================================== - rpcRegister(rpc, "ai.testConnection", (p, id) => - aiHandlers.handleTestConnection(p, id) - ); + rpcRegister(rpc, "ai.testConnection", (p, id) => aiHandlers.handleTestConnection(p, id)); rpcRegister(rpc, "ai.analyzeSchema", (p, id) => aiHandlers.handleAnalyzeSchema(p, id)); rpcRegister(rpc, "ai.explainQuery", (p, id) => aiHandlers.handleExplainQuery(p, id)); rpcRegister(rpc, "ai.recommendChart", (p, id) => aiHandlers.handleRecommendChart(p, id)); - rpcRegister(rpc, "ai.naturalLanguageQuery", (p, id) => aiHandlers.handleNaturalLanguageQuery(p, id)); - rpcRegister(rpc, "ai.getHistory", (p, id) => aiHandlers.handleGetHistory(p, id)); - rpcRegister(rpc, "ai.getHistoryById", (p, id) => - aiHandlers.handleGetHistoryById(p, id) - ); - rpcRegister(rpc, "ai.deleteHistory", (p, id) => - aiHandlers.handleDeleteHistory(p, id) - ); - rpcRegister(rpc, "ai.clearHistory", (p, id) => - aiHandlers.handleClearHistory(p, id) - ); - rpcRegister(rpc, "ai.loadSettings", (p, id) => - aiHandlers.handleLoadSettings(p, id) - ); - rpcRegister(rpc, "ai.saveSettings", (p, id) => - aiHandlers.handleSaveSettings(p, id) + rpcRegister(rpc, "ai.naturalLanguageQuery", (p, id) => + aiHandlers.handleNaturalLanguageQuery(p, id), ); + rpcRegister(rpc, "ai.getHistory", (p, id) => aiHandlers.handleGetHistory(p, id)); + rpcRegister(rpc, "ai.getHistoryById", (p, id) => aiHandlers.handleGetHistoryById(p, id)); + rpcRegister(rpc, "ai.deleteHistory", (p, id) => aiHandlers.handleDeleteHistory(p, id)); + rpcRegister(rpc, "ai.clearHistory", (p, id) => aiHandlers.handleClearHistory(p, id)); + rpcRegister(rpc, "ai.loadSettings", (p, id) => aiHandlers.handleLoadSettings(p, id)); + rpcRegister(rpc, "ai.saveSettings", (p, id) => aiHandlers.handleSaveSettings(p, id)); logger?.info("All RPC handlers registered successfully"); } @@ -400,7 +269,7 @@ export function registerDbHandlers( function rpcRegister( rpc: Rpc, method: string, - fn: (params: any, id: number | string) => Promise | void + fn: (params: any, id: number | string) => Promise | void, ) { if (typeof (rpc as any).register === "function") { (rpc as any).register(method, fn); diff --git a/bridge/src/queries/README.md b/bridge/src/queries/README.md index c8ad53f2..8cc0be33 100644 --- a/bridge/src/queries/README.md +++ b/bridge/src/queries/README.md @@ -3,17 +3,20 @@ This folder contains centralized SQL query strings and SQL helper functions for supported database engines. Layout + - `index.ts` - central export for all query modules. - `postgres/` - PostgreSQL SQL grouped by schema, tables, constraints, stats, migrations and CRUD. - `mysql/` - MySQL SQL grouped by schema, tables, columns, constraints, stats, migrations and CRUD. - `sqlite/` - SQLite SQL grouped by schema, tables, constraints, stats, migrations and CRUD. How it fits + - Connectors import query constants from this folder and bind parameters through their database driver. - Query modules keep SQL text out of service and handler code. - Database-specific quoting helpers, such as CRUD identifier quoting, live beside the SQL for that engine. How to add a query + 1. Add the SQL constant or helper to the matching database folder. 2. Export it from that database folder's `index.ts` if other modules need central imports. 3. Use parameter placeholders supported by the target driver. @@ -21,6 +24,7 @@ How to add a query 5. Add database-specific types under `src/types` only when the common shape is not enough. Notes + - Do not concatenate user-controlled identifiers or values directly into SQL. Use driver parameters for values and vetted quote helpers for identifiers. - Keep equivalent queries across PostgreSQL, MySQL/MariaDB and SQLite aligned so `QueryExecutor` can return consistent frontend shapes. - If a query intentionally excludes system schemas or internal tables, document that behavior near the SQL constant. diff --git a/bridge/src/queries/index.ts b/bridge/src/queries/index.ts index a0b125c7..6ee1e6e9 100644 --- a/bridge/src/queries/index.ts +++ b/bridge/src/queries/index.ts @@ -1,6 +1,6 @@ /** * Centralized SQL Queries Module - * + * * This module exports all SQL queries used throughout the application. * Organizing queries in a central location provides: * - Better maintainability @@ -9,6 +9,6 @@ * - Clearer separation of concerns */ -export * from './mysql'; -export * from './postgres'; -export * from './sqlite'; +export * from "./mysql"; +export * from "./postgres"; +export * from "./sqlite"; diff --git a/bridge/src/queries/mysql/crud.ts b/bridge/src/queries/mysql/crud.ts index f004fd00..271b445a 100644 --- a/bridge/src/queries/mysql/crud.ts +++ b/bridge/src/queries/mysql/crud.ts @@ -1,6 +1,6 @@ /** * MySQL CRUD Query Builders - * + * * These are helper functions that generate parameterized queries * for safe data manipulation operations. */ @@ -9,7 +9,7 @@ * Build a safe table/schema identifier */ export function quoteIdentifier(name: string): string { - return `\`${name.replace(/`/g, '``')}\``; + return `\`${name.replace(/`/g, "``")}\``; } /** @@ -29,7 +29,7 @@ export function buildSelectQuery( tableName: string, orderBy: string, limit: number, - offset: number + offset: number, ): string { const safeSchema = quoteIdentifier(schemaName); const safeTable = quoteIdentifier(tableName); @@ -48,16 +48,16 @@ export function buildSelectQuery( export function buildInsertQuery( schemaName: string, tableName: string, - columns: string[] + columns: string[], ): { query: string; placeholders: string } { const safeSchema = quoteIdentifier(schemaName); const safeTable = quoteIdentifier(tableName); - const columnList = columns.map(quoteIdentifier).join(', '); - const placeholders = columns.map(() => '?').join(', '); + const columnList = columns.map(quoteIdentifier).join(", "); + const placeholders = columns.map(() => "?").join(", "); return { query: `INSERT INTO ${safeSchema}.${safeTable} (${columnList}) VALUES (${placeholders});`, - placeholders + placeholders, }; } @@ -68,11 +68,11 @@ export function buildUpdateQuery( schemaName: string, tableName: string, columns: string[], - pkColumn: string + pkColumn: string, ): string { const safeSchema = quoteIdentifier(schemaName); const safeTable = quoteIdentifier(tableName); - const setClause = columns.map(col => `${quoteIdentifier(col)} = ?`).join(', '); + const setClause = columns.map((col) => `${quoteIdentifier(col)} = ?`).join(", "); return `UPDATE ${safeSchema}.${safeTable} SET ${setClause} WHERE ${quoteIdentifier(pkColumn)} = ?;`; } @@ -80,11 +80,7 @@ export function buildUpdateQuery( /** * Build DELETE query */ -export function buildDeleteQuery( - schemaName: string, - tableName: string, - pkColumn: string -): string { +export function buildDeleteQuery(schemaName: string, tableName: string, pkColumn: string): string { const safeSchema = quoteIdentifier(schemaName); const safeTable = quoteIdentifier(tableName); @@ -99,14 +95,14 @@ export function buildSearchQuery( tableName: string, searchColumns: string[], limit: number, - offset: number + offset: number, ): { dataQuery: string; countQuery: string } { const safeSchema = quoteIdentifier(schemaName); const safeTable = quoteIdentifier(tableName); const whereClause = searchColumns - .map(col => `CAST(${quoteIdentifier(col)} AS CHAR) LIKE ?`) - .join(' OR '); + .map((col) => `CAST(${quoteIdentifier(col)} AS CHAR) LIKE ?`) + .join(" OR "); return { dataQuery: ` @@ -117,6 +113,6 @@ export function buildSearchQuery( countQuery: ` SELECT COUNT(*) AS total FROM ${safeSchema}.${safeTable} WHERE ${whereClause}; - ` + `, }; } diff --git a/bridge/src/queries/mysql/index.ts b/bridge/src/queries/mysql/index.ts index bf2b0c7b..b6160dad 100644 --- a/bridge/src/queries/mysql/index.ts +++ b/bridge/src/queries/mysql/index.ts @@ -2,10 +2,10 @@ * MySQL Queries - Central export */ -export * from './schema'; -export * from './tables'; -export * from './columns'; -export * from './constraints'; -export * from './stats'; -export * from './migrations'; -export * from './crud'; +export * from "./schema"; +export * from "./tables"; +export * from "./columns"; +export * from "./constraints"; +export * from "./stats"; +export * from "./migrations"; +export * from "./crud"; diff --git a/bridge/src/queries/postgres/crud.ts b/bridge/src/queries/postgres/crud.ts index 43d81d16..49e4287b 100644 --- a/bridge/src/queries/postgres/crud.ts +++ b/bridge/src/queries/postgres/crud.ts @@ -1,6 +1,6 @@ /** * PostgreSQL CRUD Query Builders - * + * * These are helper functions that generate parameterized queries * for safe data manipulation operations. */ @@ -29,7 +29,7 @@ export function pgBuildSelectQuery( tableName: string, orderBy: string, limit: number, - offset: number + offset: number, ): string { const safeSchema = pgQuoteIdentifier(schemaName); const safeTable = pgQuoteIdentifier(tableName); @@ -48,16 +48,16 @@ export function pgBuildSelectQuery( export function pgBuildInsertQuery( schemaName: string, tableName: string, - columns: string[] + columns: string[], ): { query: string; paramCount: number } { const safeSchema = pgQuoteIdentifier(schemaName); const safeTable = pgQuoteIdentifier(tableName); - const columnList = columns.map(pgQuoteIdentifier).join(', '); - const placeholders = columns.map((_, i) => `$${i + 1}`).join(', '); + const columnList = columns.map(pgQuoteIdentifier).join(", "); + const placeholders = columns.map((_, i) => `$${i + 1}`).join(", "); return { query: `INSERT INTO ${safeSchema}.${safeTable} (${columnList}) VALUES (${placeholders}) RETURNING *;`, - paramCount: columns.length + paramCount: columns.length, }; } @@ -68,16 +68,16 @@ export function pgBuildUpdateQuery( schemaName: string, tableName: string, columns: string[], - pkColumn: string + pkColumn: string, ): { query: string; pkParamIndex: number } { const safeSchema = pgQuoteIdentifier(schemaName); const safeTable = pgQuoteIdentifier(tableName); - const setClause = columns.map((col, i) => `${pgQuoteIdentifier(col)} = $${i + 1}`).join(', '); + const setClause = columns.map((col, i) => `${pgQuoteIdentifier(col)} = $${i + 1}`).join(", "); const pkParamIndex = columns.length + 1; return { query: `UPDATE ${safeSchema}.${safeTable} SET ${setClause} WHERE ${pgQuoteIdentifier(pkColumn)} = $${pkParamIndex} RETURNING *;`, - pkParamIndex + pkParamIndex, }; } @@ -87,7 +87,7 @@ export function pgBuildUpdateQuery( export function pgBuildDeleteQuery( schemaName: string, tableName: string, - pkColumn: string + pkColumn: string, ): string { const safeSchema = pgQuoteIdentifier(schemaName); const safeTable = pgQuoteIdentifier(tableName); @@ -103,7 +103,7 @@ export function pgBuildSearchQuery( tableName: string, searchColumns: string[], limit: number, - offset: number + offset: number, ): { dataQuery: string; countQuery: string; paramStartIndex: number } { const safeSchema = pgQuoteIdentifier(schemaName); const safeTable = pgQuoteIdentifier(tableName); @@ -111,7 +111,7 @@ export function pgBuildSearchQuery( // Each column gets its own parameter for the search term const whereClause = searchColumns .map((col, i) => `CAST(${pgQuoteIdentifier(col)} AS TEXT) ILIKE $${i + 1}`) - .join(' OR '); + .join(" OR "); return { dataQuery: ` @@ -123,6 +123,6 @@ export function pgBuildSearchQuery( SELECT COUNT(*) AS total FROM ${safeSchema}.${safeTable} WHERE ${whereClause}; `, - paramStartIndex: 1 + paramStartIndex: 1, }; } diff --git a/bridge/src/queries/postgres/index.ts b/bridge/src/queries/postgres/index.ts index 8d4ccfe0..77f86d07 100644 --- a/bridge/src/queries/postgres/index.ts +++ b/bridge/src/queries/postgres/index.ts @@ -2,9 +2,9 @@ * PostgreSQL Queries - Central export */ -export * from './schema'; -export * from './tables'; -export * from './constraints'; -export * from './stats'; -export * from './migrations'; -export * from './crud'; +export * from "./schema"; +export * from "./tables"; +export * from "./constraints"; +export * from "./stats"; +export * from "./migrations"; +export * from "./crud"; diff --git a/bridge/src/queries/sqlite/constraints.ts b/bridge/src/queries/sqlite/constraints.ts index 634bdb5c..a9e1e24e 100644 --- a/bridge/src/queries/sqlite/constraints.ts +++ b/bridge/src/queries/sqlite/constraints.ts @@ -1,6 +1,6 @@ /** * SQLite Constraint-related Queries - * + * * SQLite uses PRAGMA commands for constraint introspection. * Most constraint info is retrieved via: * - PRAGMA table_xinfo() for primary keys and column constraints diff --git a/bridge/src/queries/sqlite/crud.ts b/bridge/src/queries/sqlite/crud.ts index 934ac8b3..39d0d07d 100644 --- a/bridge/src/queries/sqlite/crud.ts +++ b/bridge/src/queries/sqlite/crud.ts @@ -1,6 +1,6 @@ /** * SQLite CRUD Query Builders - * + * * Helper functions that generate parameterized queries * for safe data manipulation. SQLite uses ? placeholders. */ @@ -27,7 +27,7 @@ export function sqliteBuildSelectQuery( tableName: string, orderBy: string, limit: number, - offset: number + offset: number, ): string { const safeTable = sqliteQuoteIdentifier(tableName); return ` @@ -44,15 +44,15 @@ export function sqliteBuildSelectQuery( */ export function sqliteBuildInsertQuery( tableName: string, - columns: string[] + columns: string[], ): { query: string; paramCount: number } { const safeTable = sqliteQuoteIdentifier(tableName); - const columnList = columns.map(sqliteQuoteIdentifier).join(', '); - const placeholders = columns.map(() => '?').join(', '); + const columnList = columns.map(sqliteQuoteIdentifier).join(", "); + const placeholders = columns.map(() => "?").join(", "); return { query: `INSERT INTO ${safeTable} (${columnList}) VALUES (${placeholders});`, - paramCount: columns.length + paramCount: columns.length, }; } @@ -62,10 +62,10 @@ export function sqliteBuildInsertQuery( export function sqliteBuildUpdateQuery( tableName: string, columns: string[], - pkColumn: string + pkColumn: string, ): { query: string } { const safeTable = sqliteQuoteIdentifier(tableName); - const setClause = columns.map((col) => `${sqliteQuoteIdentifier(col)} = ?`).join(', '); + const setClause = columns.map((col) => `${sqliteQuoteIdentifier(col)} = ?`).join(", "); return { query: `UPDATE ${safeTable} SET ${setClause} WHERE ${sqliteQuoteIdentifier(pkColumn)} = ?;`, @@ -75,10 +75,7 @@ export function sqliteBuildUpdateQuery( /** * Build DELETE query */ -export function sqliteBuildDeleteQuery( - tableName: string, - pkColumn: string -): string { +export function sqliteBuildDeleteQuery(tableName: string, pkColumn: string): string { const safeTable = sqliteQuoteIdentifier(tableName); return `DELETE FROM ${safeTable} WHERE ${sqliteQuoteIdentifier(pkColumn)} = ?;`; } @@ -90,13 +87,13 @@ export function sqliteBuildSearchQuery( tableName: string, searchColumns: string[], limit: number, - offset: number + offset: number, ): { dataQuery: string; countQuery: string } { const safeTable = sqliteQuoteIdentifier(tableName); const whereClause = searchColumns .map((col) => `CAST(${sqliteQuoteIdentifier(col)} AS TEXT) LIKE ? COLLATE NOCASE`) - .join(' OR '); + .join(" OR "); return { dataQuery: ` diff --git a/bridge/src/queries/sqlite/index.ts b/bridge/src/queries/sqlite/index.ts index b3089633..46c29c78 100644 --- a/bridge/src/queries/sqlite/index.ts +++ b/bridge/src/queries/sqlite/index.ts @@ -2,9 +2,9 @@ * SQLite Queries - Central export */ -export * from './schema'; -export * from './tables'; -export * from './constraints'; -export * from './stats'; -export * from './migrations'; -export * from './crud'; +export * from "./schema"; +export * from "./tables"; +export * from "./constraints"; +export * from "./stats"; +export * from "./migrations"; +export * from "./crud"; diff --git a/bridge/src/queries/sqlite/tables.ts b/bridge/src/queries/sqlite/tables.ts index a446035c..3f4d327c 100644 --- a/bridge/src/queries/sqlite/tables.ts +++ b/bridge/src/queries/sqlite/tables.ts @@ -1,8 +1,8 @@ /** * SQLite Table-related Queries (PRAGMA-based) - * + * * Note: SQLite uses PRAGMA table_info() and PRAGMA table_xinfo() - * for column introspection. These are executed programmatically + * for column introspection. These are executed programmatically * in the connector since they require table name interpolation. */ diff --git a/bridge/src/services/README.md b/bridge/src/services/README.md index b248036c..ac23025f 100644 --- a/bridge/src/services/README.md +++ b/bridge/src/services/README.md @@ -3,6 +3,7 @@ This folder contains bridge business logic and persistence services. Services sit between RPC handlers and low-level connectors, stores, keyrings, Git, filesystem and monitoring utilities. Layout + - `databaseService.ts` - database metadata lifecycle, credential lookup and connection config retrieval. - `queryExecutor.ts` - database-agnostic dispatcher for schema, table, query, CRUD and migration operations. - `connectionBuilder.ts` - builds driver config objects and optional SSH tunnel wiring. @@ -19,12 +20,14 @@ Layout - `logger.ts` - shared pino logger. How it fits + - Handlers call services to do real work; services should not know about UI components. - Services call connectors, stores and utilities, then return plain data to handlers. - Persistent paths are defined in `src/utils/config.ts`. - Shared types come from `src/types`. How to add service behavior + 1. Put durable business logic here when it is shared by multiple handlers or has state/persistence concerns. 2. Keep public methods small and typed enough for handler use. 3. Let handlers translate thrown errors into JSON-RPC errors. @@ -32,6 +35,7 @@ How to add service behavior 5. Add focused tests under `bridge/__tests__` for services with persistence, Git, credential or connector logic. Notes + - Keep secrets out of logs and return values. - Avoid long-lived open database sockets unless the connection pool explicitly owns them. - When adding filesystem writes, use paths derived from `src/utils/config.ts` so RelWave respects `RELWAVE_HOME`. diff --git a/bridge/src/services/ai.impl.ts b/bridge/src/services/ai.impl.ts index 4ede9f40..10f61a8f 100644 --- a/bridge/src/services/ai.impl.ts +++ b/bridge/src/services/ai.impl.ts @@ -24,17 +24,20 @@ export class AIServiceImpl { switch (name) { case "anthropic": { const key = settings.anthropicApiKey?.trim(); - if (!key) throw new AIError("MISSING_API_KEY", "anthropic", "Anthropic API key is not configured."); + if (!key) + throw new AIError("MISSING_API_KEY", "anthropic", "Anthropic API key is not configured."); return new AnthropicProvider(key, settings.anthropicModel); } case "openai": { const key = settings.openaiApiKey?.trim(); - if (!key) throw new AIError("MISSING_API_KEY", "openai", "OpenAI API key is not configured."); + if (!key) + throw new AIError("MISSING_API_KEY", "openai", "OpenAI API key is not configured."); return new OpenAIProvider(key, settings.openaiModel); } case "gemini": { const key = settings.geminiApiKey?.trim(); - if (!key) throw new AIError("MISSING_API_KEY", "gemini", "Gemini API key is not configured."); + if (!key) + throw new AIError("MISSING_API_KEY", "gemini", "Gemini API key is not configured."); return new GeminiProvider(key, settings.geminiModel); } case "groq": { @@ -44,7 +47,8 @@ export class AIServiceImpl { } case "mistral": { const key = settings.mistralApiKey?.trim(); - if (!key) throw new AIError("MISSING_API_KEY", "mistral", "Mistral API key is not configured."); + if (!key) + throw new AIError("MISSING_API_KEY", "mistral", "Mistral API key is not configured."); return new MistralProvider(key, settings.mistralModel); } case "ollama": { diff --git a/bridge/src/services/aiCacheService.ts b/bridge/src/services/aiCacheService.ts index a1fc8064..2979fe27 100644 --- a/bridge/src/services/aiCacheService.ts +++ b/bridge/src/services/aiCacheService.ts @@ -19,7 +19,8 @@ import { // ── Types ───────────────────────────────────────────────────────────────── -export type AIFeature = "schema-analysis" | "query-explanation" | "chart-recommendation" | "nl_to_sql"; +export type AIFeature = + "schema-analysis" | "query-explanation" | "chart-recommendation" | "nl_to_sql"; export interface CachedResult { response: string; @@ -63,7 +64,10 @@ export function hashSchemaAnalysis(input: SchemaAnalysisInput, datasourceName?: } /** Hash for query explanation: uses datasource + sql + schema. */ -export function hashQueryExplanation(input: QueryExplanationInput, datasourceName?: string): string { +export function hashQueryExplanation( + input: QueryExplanationInput, + datasourceName?: string, +): string { const normalized = { datasource: datasourceName ?? null, sql: (input.sql ?? "").trim(), @@ -81,7 +85,10 @@ export function hashQueryExplanation(input: QueryExplanationInput, datasourceNam } /** Hash for chart recommendation: uses datasource + tableName + columns. */ -export function hashChartRecommendation(input: ChartRecommendationInput, datasourceName?: string): string { +export function hashChartRecommendation( + input: ChartRecommendationInput, + datasourceName?: string, +): string { const normalized = { datasource: datasourceName ?? null, tableName: input.tableName, diff --git a/bridge/src/services/aiHistoryStore.ts b/bridge/src/services/aiHistoryStore.ts index 7106711e..fbcb7055 100644 --- a/bridge/src/services/aiHistoryStore.ts +++ b/bridge/src/services/aiHistoryStore.ts @@ -150,7 +150,7 @@ export class AIHistoryStore { record.prompt, record.response, record.tokens_used ?? null, - new Date().toISOString() + new Date().toISOString(), ); return info.lastInsertRowid as number; } @@ -168,14 +168,14 @@ export class AIHistoryStore { // Match both hash and the specific datasource row = db .prepare( - `SELECT * FROM ai_history WHERE content_hash = ? AND datasource_id = ? ORDER BY created_at DESC LIMIT 1` + `SELECT * FROM ai_history WHERE content_hash = ? AND datasource_id = ? ORDER BY created_at DESC LIMIT 1`, ) .get(contentHash, datasourceId) as AIHistoryRow | undefined; } else { // No datasource specified — only match rows that also have no datasource row = db .prepare( - `SELECT * FROM ai_history WHERE content_hash = ? AND datasource_id IS NULL ORDER BY created_at DESC LIMIT 1` + `SELECT * FROM ai_history WHERE content_hash = ? AND datasource_id IS NULL ORDER BY created_at DESC LIMIT 1`, ) .get(contentHash) as AIHistoryRow | undefined; } @@ -202,9 +202,7 @@ export class AIHistoryStore { values.push(params.datasource_id); } - const where = conditions.length - ? `WHERE ${conditions.join(" AND ")}` - : ""; + const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : ""; const limit = params.limit ?? 20; const offset = params.offset ?? 0; @@ -220,7 +218,7 @@ export class AIHistoryStore { `SELECT id, feature, datasource_id, table_name, provider, model, tokens_used, created_at FROM ai_history ${where} ORDER BY created_at DESC - LIMIT ? OFFSET ?` + LIMIT ? OFFSET ?`, ) .all(...values, limit, offset) as AIHistoryListItem[]; @@ -230,9 +228,8 @@ export class AIHistoryStore { /** Get a single history entry by ID (full record). */ getById(id: number): AIHistoryRow | null { const db = this.getDb(); - const row = db - .prepare(`SELECT * FROM ai_history WHERE id = ?`) - .get(id) as AIHistoryRow | undefined; + const row = db.prepare(`SELECT * FROM ai_history WHERE id = ?`).get(id) as + AIHistoryRow | undefined; return row ?? null; } diff --git a/bridge/src/services/connectionBuilder.ts b/bridge/src/services/connectionBuilder.ts index 9fa7daed..10c667c1 100644 --- a/bridge/src/services/connectionBuilder.ts +++ b/bridge/src/services/connectionBuilder.ts @@ -9,22 +9,18 @@ export interface BuildResult { } export class ConnectionBuilder { - static async buildConnection( - db: any, - pwd: string | null, - dbType: DBType - ): Promise { + static async buildConnection(db: any, pwd: string | null, dbType: DBType): Promise { if (dbType === DBType.SQLITE) { const dbPath = normalizeSQLitePath(db.database || db.path); if (!dbPath || typeof dbPath !== "string" || !dbPath.trim()) { throw new Error( `SQLite connection requires a non-empty file path. ` + - `Got database=${JSON.stringify(db.database)}, path=${JSON.stringify(db.path)}` + `Got database=${JSON.stringify(db.database)}, path=${JSON.stringify(db.path)}`, ); } if (isWindowsDriveRootPath(dbPath)) { throw new Error( - `Invalid SQLite path "${dbPath}" — it points to a Windows drive root, not a database file.` + `Invalid SQLite path "${dbPath}" — it points to a Windows drive root, not a database file.`, ); } return { @@ -46,11 +42,7 @@ export class ConnectionBuilder { }; if (base.ssh) { - const tunnel = await sshTunnelServiceInstance.createSSHTunnel( - base.ssh, - base.host, - base.port - ); + const tunnel = await sshTunnelServiceInstance.createSSHTunnel(base.ssh, base.host, base.port); // Rewrite host/port to point to the local tunnel endpoint return { config: { diff --git a/bridge/src/services/databaseService.ts b/bridge/src/services/databaseService.ts index 5f221f53..a767b21b 100644 --- a/bridge/src/services/databaseService.ts +++ b/bridge/src/services/databaseService.ts @@ -1,7 +1,7 @@ import { ConnectionBuilder } from "./connectionBuilder"; import { DBTypeDetector } from "../utils/dbTypeDetector"; import { DBType } from "../types"; -import { dbStoreInstance } from "./dbStore"; // always use the singleton +import { dbStoreInstance } from "./dbStore"; // always use the singleton import { connectionPool } from "./connectionPool"; import { keyringServiceInstance } from "./keyringService"; @@ -39,9 +39,11 @@ export class DatabaseService { // If SSH is present, retrieve credentials from keyring if (db.ssh) { if (db.ssh.authMethod === "password") { - db.ssh.password = await keyringServiceInstance.getCredential(`${dbId}_ssh_pwd`) || undefined; + db.ssh.password = + (await keyringServiceInstance.getCredential(`${dbId}_ssh_pwd`)) || undefined; } else if (db.ssh.authMethod === "privateKey") { - db.ssh.passphrase = await keyringServiceInstance.getCredential(`${dbId}_ssh_pass`) || undefined; + db.ssh.passphrase = + (await keyringServiceInstance.getCredential(`${dbId}_ssh_pass`)) || undefined; } } @@ -108,7 +110,9 @@ export class DatabaseService { if (isSQLite || typeof payload.database === "string") { const current = await dbStoreInstance.getDB(id); - const currentIsSQLite = (current?.type as string | undefined)?.toLowerCase().includes("sqlite"); + const currentIsSQLite = (current?.type as string | undefined) + ?.toLowerCase() + .includes("sqlite"); if (currentIsSQLite || isSQLite) { const { config } = await ConnectionBuilder.buildSQLiteConnection({ ...current, @@ -122,7 +126,10 @@ export class DatabaseService { } connectionPool.invalidate(id); // evict stale cached config - const res = await dbStoreInstance.updateDB(id, payload as Parameters[1]); + const res = await dbStoreInstance.updateDB( + id, + payload as Parameters[1], + ); // Update SSH credentials in keyring if (sshPwd !== undefined) { diff --git a/bridge/src/services/dbStore.ts b/bridge/src/services/dbStore.ts index 178fef84..485102f3 100644 --- a/bridge/src/services/dbStore.ts +++ b/bridge/src/services/dbStore.ts @@ -261,7 +261,7 @@ export class DbStore { configFile: string = CONFIG_FILE, credentialsFile: string = CREDENTIALS_FILE, cacheTtl: number = DEFAULT_CACHE_TTL, - autoPreload: boolean = true + autoPreload: boolean = true, ) { this.configFolder = configFolder; this.configFile = configFile; @@ -294,21 +294,13 @@ export class DbStore { const configData = await fs.readFile(this.configFile, "utf-8"); const normalized = normalizeConfigData(JSON.parse(configData)); if (normalized.changed) { - await fs.writeFile( - this.configFile, - JSON.stringify(normalized.data, null, 2), - "utf-8" - ); + await fs.writeFile(this.configFile, JSON.stringify(normalized.data, null, 2), "utf-8"); } this.cache.setConfig(normalized.data); } else { // Create empty config and cache it const emptyConfig: ConfigData = { version: 1, databases: [] }; - await fs.writeFile( - this.configFile, - JSON.stringify(emptyConfig, null, 2), - "utf-8" - ); + await fs.writeFile(this.configFile, JSON.stringify(emptyConfig, null, 2), "utf-8"); this.cache.setConfig(emptyConfig); } @@ -349,10 +341,7 @@ export class DbStore { const iv = randomBytes(16); const key = (await scryptAsync(appKey, salt, 32)) as Buffer; const cipher = createCipheriv("aes-256-cbc", key, iv); - const encrypted = Buffer.concat([ - cipher.update(password, "utf8"), - cipher.final(), - ]); + const encrypted = Buffer.concat([cipher.update(password, "utf8"), cipher.final()]); // salt(32) + iv(16) + ciphertext → base64 return Buffer.concat([salt, iv, encrypted]).toString("base64"); } @@ -372,10 +361,7 @@ export class DbStore { const appKey = await loadOrCreateAppKey(); const key = (await scryptAsync(appKey, salt, 32)) as Buffer; const decipher = createDecipheriv("aes-256-cbc", key, iv); - const decrypted = Buffer.concat([ - decipher.update(encrypted), - decipher.final(), - ]); + const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]); return decrypted.toString("utf8"); } @@ -413,11 +399,7 @@ export class DbStore { */ private async saveCredentials(credentials: CredentialStore): Promise { try { - await fs.writeFile( - this.credentialsFile, - JSON.stringify(credentials, null, 2), - "utf-8" - ); + await fs.writeFile(this.credentialsFile, JSON.stringify(credentials, null, 2), "utf-8"); // Set file permissions to user-only (Unix systems) if (process.platform !== "win32") { await fs.chmod(this.credentialsFile, 0o600); @@ -446,7 +428,7 @@ export class DbStore { await fs.writeFile( this.configFile, JSON.stringify({ version: 1, databases: [] }, null, 2), - "utf-8" + "utf-8", ); } } @@ -558,9 +540,7 @@ export class DbStore { if (payload.password && credentialId) { try { const credentials = await this.loadCredentials(); - credentials[credentialId] = await this.encryptPassword( - payload.password - ); + credentials[credentialId] = await this.encryptPassword(payload.password); await this.saveCredentials(credentials); } catch (error) { console.error("Failed to store password:", error); @@ -574,10 +554,7 @@ export class DbStore { /** * Update an existing database connection */ - async updateDB( - id: string, - patch: Partial & { password?: string } - ): Promise { + async updateDB(id: string, patch: Partial & { password?: string }): Promise { const all = await this.loadAll(); const idx = all.databases.findIndex((db) => db.id === id); if (idx === -1) throw new Error("Database not found"); @@ -714,11 +691,9 @@ export const dbStoreInstance = new DbStore(); export const listDBs = () => dbStoreInstance.listDBs(); export const getDB = (id: string) => dbStoreInstance.getDB(id); export const addDB = (payload: any) => dbStoreInstance.addDB(payload); -export const updateDB = (id: string, patch: any) => - dbStoreInstance.updateDB(id, patch); +export const updateDB = (id: string, patch: any) => dbStoreInstance.updateDB(id, patch); export const deleteDB = (id: string) => dbStoreInstance.deleteDB(id); -export const getPasswordFor = (meta: DBMeta) => - dbStoreInstance.getPasswordFor(meta); +export const getPasswordFor = (meta: DBMeta) => dbStoreInstance.getPasswordFor(meta); export const invalidateCache = () => dbStoreInstance.invalidateCache(); export const touchDB = (id: string) => dbStoreInstance.touchDB(id); diff --git a/bridge/src/services/discoveryService.ts b/bridge/src/services/discoveryService.ts index 7045c97b..238821b6 100644 --- a/bridge/src/services/discoveryService.ts +++ b/bridge/src/services/discoveryService.ts @@ -20,17 +20,73 @@ const DATABASE_PORTS: Record = { // Fun adjectives and nouns for generating database names const ADJECTIVES = [ - "swift", "cosmic", "stellar", "nimble", "turbo", "quantum", "neon", "cyber", - "atomic", "hyper", "mega", "ultra", "blazing", "electric", "dynamic", "rapid", - "mighty", "brave", "clever", "noble", "fierce", "silent", "golden", "crystal", - "shadow", "frost", "thunder", "ember", "azure", "crimson", "violet", "lunar", + "swift", + "cosmic", + "stellar", + "nimble", + "turbo", + "quantum", + "neon", + "cyber", + "atomic", + "hyper", + "mega", + "ultra", + "blazing", + "electric", + "dynamic", + "rapid", + "mighty", + "brave", + "clever", + "noble", + "fierce", + "silent", + "golden", + "crystal", + "shadow", + "frost", + "thunder", + "ember", + "azure", + "crimson", + "violet", + "lunar", ]; const NOUNS = [ - "phoenix", "dragon", "falcon", "panther", "tiger", "wolf", "hawk", "eagle", - "lion", "bear", "shark", "cobra", "viper", "raven", "storm", "blaze", - "nova", "comet", "nebula", "galaxy", "cosmos", "orbit", "pulse", "flux", - "spark", "bolt", "wave", "surge", "core", "nexus", "vertex", "matrix", + "phoenix", + "dragon", + "falcon", + "panther", + "tiger", + "wolf", + "hawk", + "eagle", + "lion", + "bear", + "shark", + "cobra", + "viper", + "raven", + "storm", + "blaze", + "nova", + "comet", + "nebula", + "galaxy", + "cosmos", + "orbit", + "pulse", + "flux", + "spark", + "bolt", + "wave", + "surge", + "core", + "nexus", + "vertex", + "matrix", ]; export interface DiscoveredDatabase { @@ -184,7 +240,7 @@ export class DiscoveryService { try { const { stdout } = await execAsync( `docker inspect --format "{{range .Config.Env}}{{println .}}{{end}}" "${containerName}"`, - { timeout: 3000 } + { timeout: 3000 }, ); const lines = stdout.trim().split("\n").filter(Boolean); @@ -208,7 +264,7 @@ export class DiscoveryService { */ private extractCredentialsFromEnv( dbType: "postgresql" | "mysql" | "mariadb", - envVars: Map + envVars: Map, ): { user: string; password: string; database: string } { if (dbType === "postgresql") { return { @@ -219,9 +275,10 @@ export class DiscoveryService { } else if (dbType === "mysql") { // MySQL can use MYSQL_USER or root with MYSQL_ROOT_PASSWORD const user = envVars.get("MYSQL_USER") || "root"; - const password = user === "root" - ? (envVars.get("MYSQL_ROOT_PASSWORD") || "") - : (envVars.get("MYSQL_PASSWORD") || ""); + const password = + user === "root" + ? envVars.get("MYSQL_ROOT_PASSWORD") || "" + : envVars.get("MYSQL_PASSWORD") || ""; return { user, password, @@ -230,9 +287,10 @@ export class DiscoveryService { } else { // MariaDB - similar to MySQL const user = envVars.get("MARIADB_USER") || envVars.get("MYSQL_USER") || "root"; - const password = user === "root" - ? (envVars.get("MARIADB_ROOT_PASSWORD") || envVars.get("MYSQL_ROOT_PASSWORD") || "") - : (envVars.get("MARIADB_PASSWORD") || envVars.get("MYSQL_PASSWORD") || ""); + const password = + user === "root" + ? envVars.get("MARIADB_ROOT_PASSWORD") || envVars.get("MYSQL_ROOT_PASSWORD") || "" + : envVars.get("MARIADB_PASSWORD") || envVars.get("MYSQL_PASSWORD") || ""; return { user, password, @@ -249,10 +307,9 @@ export class DiscoveryService { try { // Check if Docker is available - const { stdout } = await execAsync( - 'docker ps --format "{{.Names}}|{{.Image}}|{{.Ports}}"', - { timeout: 5000 } - ); + const { stdout } = await execAsync('docker ps --format "{{.Names}}|{{.Image}}|{{.Ports}}"', { + timeout: 5000, + }); const lines = stdout.trim().split("\n").filter(Boolean); @@ -261,11 +318,7 @@ export class DiscoveryService { // Determine database type from image name let dbType: "postgresql" | "mysql" | "mariadb" | null = null; - if ( - image.includes("postgres") || - image.includes("pg") || - image.includes("postgresql") - ) { + if (image.includes("postgres") || image.includes("pg") || image.includes("postgresql")) { dbType = "postgresql"; } else if (image.includes("mariadb")) { dbType = "mariadb"; diff --git a/bridge/src/services/gitService.ts b/bridge/src/services/gitService.ts index bfe286d8..2242b64a 100644 --- a/bridge/src/services/gitService.ts +++ b/bridge/src/services/gitService.ts @@ -13,78 +13,78 @@ import fsSync from "fs"; const execFileAsync = promisify(execFile); export interface GitStatus { - /** Whether the directory is inside a git repository */ - isGitRepo: boolean; + /** Whether the directory is inside a git repository */ + isGitRepo: boolean; - /** Current branch name (e.g. "main", "feature/auth") */ - branch: string | null; + /** Current branch name (e.g. "main", "feature/auth") */ + branch: string | null; - /** Short commit hash of HEAD */ - headCommit: string | null; + /** Short commit hash of HEAD */ + headCommit: string | null; - /** Whether there are uncommitted changes (staged or unstaged) */ - isDirty: boolean; + /** Whether there are uncommitted changes (staged or unstaged) */ + isDirty: boolean; - /** Number of files with staged changes */ - stagedCount: number; + /** Number of files with staged changes */ + stagedCount: number; - /** Number of files with unstaged changes */ - unstagedCount: number; + /** Number of files with unstaged changes */ + unstagedCount: number; - /** Number of untracked files */ - untrackedCount: number; + /** Number of untracked files */ + untrackedCount: number; - /** Number of commits ahead of upstream (null if no upstream) */ - ahead: number | null; + /** Number of commits ahead of upstream (null if no upstream) */ + ahead: number | null; - /** Number of commits behind upstream (null if no upstream) */ - behind: number | null; + /** Number of commits behind upstream (null if no upstream) */ + behind: number | null; - /** Remote tracking branch (e.g. "origin/main") */ - upstream: string | null; + /** Remote tracking branch (e.g. "origin/main") */ + upstream: string | null; } export interface GitFileChange { - /** Relative file path */ - path: string; + /** Relative file path */ + path: string; - /** Git status code: M=modified, A=added, D=deleted, ?=untracked, R=renamed */ - status: string; + /** Git status code: M=modified, A=added, D=deleted, ?=untracked, R=renamed */ + status: string; - /** Whether this change is staged */ - staged: boolean; + /** Whether this change is staged */ + staged: boolean; } export interface GitLogEntry { - /** Short commit hash */ - hash: string; + /** Short commit hash */ + hash: string; - /** Full commit hash */ - fullHash: string; + /** Full commit hash */ + fullHash: string; - /** Parent hashes (space-separated) */ - parents: string[]; + /** Parent hashes (space-separated) */ + parents: string[]; - /** Author name */ - author: string; + /** Author name */ + author: string; - /** Commit date as ISO string */ - date: string; + /** Commit date as ISO string */ + date: string; - /** First line of commit message */ - subject: string; + /** First line of commit message */ + subject: string; - /** Ref names (branches, tags) */ - refs: string; + /** Ref names (branches, tags) */ + refs: string; } export interface GitBranchInfo { - /** Branch name */ - name: string; - /** Is this the current branch? */ - current: boolean; - /** Remote tracking branch (null for local-only branches) */ - upstream: string | null; + /** Branch name */ + name: string; + /** Is this the current branch? */ + current: boolean; + /** Remote tracking branch (null for local-only branches) */ + upstream: string | null; } export type GitSyncResult = { @@ -104,1252 +104,1251 @@ export class GitError extends Error { } } - function assertSafeGitRef(name: string) { - if (name.startsWith("-")) { - throw new Error("Invalid git reference name: cannot start with a hyphen"); - } + if (name.startsWith("-")) { + throw new Error("Invalid git reference name: cannot start with a hyphen"); + } } export class GitService { - /** - * Run a git command in a specific directory. - * Returns stdout. Throws on non-zero exit. - */ - private async git(cwd: string, ...args: string[]): Promise { - try { - const { stdout } = await execFileAsync("git", args, { - cwd, - maxBuffer: 10 * 1024 * 1024, // 10 MB - timeout: 30_000, - windowsHide: true, - }); - return stdout.trimEnd(); - } catch (err: any) { - // Git returns exit code 128 for "not a git repo" etc. - if (err.code === "ENOENT") { - throw new Error("Git is not installed or not on PATH"); - } - throw err; - } - } - - /** - * Check if git is available on this machine - */ - async isGitInstalled(): Promise { - try { - await execFileAsync("git", ["--version"], { - timeout: 5000, - windowsHide: true, - }); - return true; - } catch { - return false; - } + /** + * Run a git command in a specific directory. + * Returns stdout. Throws on non-zero exit. + */ + private async git(cwd: string, ...args: string[]): Promise { + try { + const { stdout } = await execFileAsync("git", args, { + cwd, + maxBuffer: 10 * 1024 * 1024, // 10 MB + timeout: 30_000, + windowsHide: true, + }); + return stdout.trimEnd(); + } catch (err: any) { + // Git returns exit code 128 for "not a git repo" etc. + if (err.code === "ENOENT") { + throw new Error("Git is not installed or not on PATH"); + } + throw err; } + } - /** - * Check if a directory is inside a git repository - */ - async isRepo(dir: string): Promise { - try { - await this.git(dir, "rev-parse", "--is-inside-work-tree"); - return true; - } catch { - return false; - } + /** + * Check if git is available on this machine + */ + async isGitInstalled(): Promise { + try { + await execFileAsync("git", ["--version"], { + timeout: 5000, + windowsHide: true, + }); + return true; + } catch { + return false; } + } - /** - * Get the root directory of the git repository - */ - async getRepoRoot(dir: string): Promise { - return this.git(dir, "rev-parse", "--show-toplevel"); + /** + * Check if a directory is inside a git repository + */ + async isRepo(dir: string): Promise { + try { + await this.git(dir, "rev-parse", "--is-inside-work-tree"); + return true; + } catch { + return false; } + } - /** - * Resolve a ref (tag, branch, HEAD~1, etc.) to a full commit hash. - * Returns null if the ref cannot be resolved. - */ - async resolveRef(dir: string, ref: string): Promise { - try { - return await this.git(dir, "rev-list", "-n1", ref); - } catch { - return null; - } - } + /** + * Get the root directory of the git repository + */ + async getRepoRoot(dir: string): Promise { + return this.git(dir, "rev-parse", "--show-toplevel"); + } - /** - * Initialize a new git repository - */ - async init(dir: string, defaultBranch = "main"): Promise { - await this.git(dir, "init", "-b", defaultBranch); + /** + * Resolve a ref (tag, branch, HEAD~1, etc.) to a full commit hash. + * Returns null if the ref cannot be resolved. + */ + async resolveRef(dir: string, ref: string): Promise { + try { + return await this.git(dir, "rev-list", "-n1", ref); + } catch { + return null; } + } - /** - * Get comprehensive git status for a directory - */ - async getStatus(dir: string): Promise { - const isGitRepo = await this.isRepo(dir); - - if (!isGitRepo) { - return { - isGitRepo: false, - branch: null, - headCommit: null, - isDirty: false, - stagedCount: 0, - unstagedCount: 0, - untrackedCount: 0, - ahead: null, - behind: null, - upstream: null, - }; - } - - // Get branch + upstream + ahead/behind in one call - let branch: string | null = null; - let headCommit: string | null = null; - let upstream: string | null = null; - let ahead: number | null = null; - let behind: number | null = null; - - try { - // --porcelain=v2 --branch gives structured branch info - const branchOutput = await this.git( - dir, - "status", - "--porcelain=v2", - "--branch" - ); - - for (const line of branchOutput.split("\n")) { - if (line.startsWith("# branch.head ")) { - branch = line.slice("# branch.head ".length); - } else if (line.startsWith("# branch.oid ")) { - headCommit = line.slice("# branch.oid ".length).slice(0, 8); - } else if (line.startsWith("# branch.upstream ")) { - upstream = line.slice("# branch.upstream ".length); - } else if (line.startsWith("# branch.ab ")) { - const match = line.match(/\+(\d+) -(\d+)/); - if (match) { - ahead = parseInt(match[1], 10); - behind = parseInt(match[2], 10); - } - } - } - } catch { - // HEAD might be unborn (initial commit) - branch = "(no commits)"; - } - - // Get file-level status - let stagedCount = 0; - let unstagedCount = 0; - let untrackedCount = 0; + /** + * Initialize a new git repository + */ + async init(dir: string, defaultBranch = "main"): Promise { + await this.git(dir, "init", "-b", defaultBranch); + } - try { - const statusOutput = await this.git( - dir, - "status", - "--porcelain=v1", - "-uall" - ); - - if (statusOutput) { - for (const line of statusOutput.split("\n")) { - if (!line) continue; - const x = line[0]; // staged status - const y = line[1]; // working tree - - if (x === "?" && y === "?") { - untrackedCount++; - } else { - if (x !== " " && x !== "?") stagedCount++; - if (y !== " " && y !== "?") unstagedCount++; - } - } - } - } catch { - // Ignore — might be empty repo + /** + * Get comprehensive git status for a directory + */ + async getStatus(dir: string): Promise { + const isGitRepo = await this.isRepo(dir); + + if (!isGitRepo) { + return { + isGitRepo: false, + branch: null, + headCommit: null, + isDirty: false, + stagedCount: 0, + unstagedCount: 0, + untrackedCount: 0, + ahead: null, + behind: null, + upstream: null, + }; + } + + // Get branch + upstream + ahead/behind in one call + let branch: string | null = null; + let headCommit: string | null = null; + let upstream: string | null = null; + let ahead: number | null = null; + let behind: number | null = null; + + try { + // --porcelain=v2 --branch gives structured branch info + const branchOutput = await this.git(dir, "status", "--porcelain=v2", "--branch"); + + for (const line of branchOutput.split("\n")) { + if (line.startsWith("# branch.head ")) { + branch = line.slice("# branch.head ".length); + } else if (line.startsWith("# branch.oid ")) { + headCommit = line.slice("# branch.oid ".length).slice(0, 8); + } else if (line.startsWith("# branch.upstream ")) { + upstream = line.slice("# branch.upstream ".length); + } else if (line.startsWith("# branch.ab ")) { + const match = line.match(/\+(\d+) -(\d+)/); + if (match) { + ahead = parseInt(match[1], 10); + behind = parseInt(match[2], 10); + } } - - return { - isGitRepo: true, - branch, - headCommit, - isDirty: stagedCount > 0 || unstagedCount > 0 || untrackedCount > 0, - stagedCount, - unstagedCount, - untrackedCount, - ahead, - behind, - upstream, - }; - } - - /** - * Get list of changed files with their status - */ - async getChangedFiles(dir: string): Promise { - const output = await this.git(dir, "status", "--porcelain=v1", "-uall"); - if (!output) return []; - - const changes: GitFileChange[] = []; - - for (const line of output.split("\n")) { - if (!line || line.length < 4) continue; - const x = line[0]; // index (staged) - const y = line[1]; // working tree - const filePath = line.slice(3); - - // Staged change - if (x !== " " && x !== "?") { - changes.push({ path: filePath, status: x, staged: true }); - } - // Unstaged change - if (y !== " " && y !== "?") { - changes.push({ path: filePath, status: y, staged: false }); - } - // Untracked - if (x === "?" && y === "?") { - changes.push({ path: filePath, status: "?", staged: false }); - } + } + } catch { + // HEAD might be unborn (initial commit) + branch = "(no commits)"; + } + + // Get file-level status + let stagedCount = 0; + let unstagedCount = 0; + let untrackedCount = 0; + + try { + const statusOutput = await this.git(dir, "status", "--porcelain=v1", "-uall"); + + if (statusOutput) { + for (const line of statusOutput.split("\n")) { + if (!line) continue; + const x = line[0]; // staged status + const y = line[1]; // working tree + + if (x === "?" && y === "?") { + untrackedCount++; + } else { + if (x !== " " && x !== "?") stagedCount++; + if (y !== " " && y !== "?") unstagedCount++; + } } + } + } catch { + // Ignore — might be empty repo + } + + return { + isGitRepo: true, + branch, + headCommit, + isDirty: stagedCount > 0 || unstagedCount > 0 || untrackedCount > 0, + stagedCount, + unstagedCount, + untrackedCount, + ahead, + behind, + upstream, + }; + } - return changes; - } - - /** - * Stage files for commit - */ - async stageFiles(dir: string, files: string[]): Promise { - if (files.length === 0) return; - await this.git(dir, "add", "--", ...files); - } - - /** - * Stage all changes - */ - async stageAll(dir: string): Promise { - await this.git(dir, "add", "-A"); - } + /** + * Get list of changed files with their status + */ + async getChangedFiles(dir: string): Promise { + const output = await this.git(dir, "status", "--porcelain=v1", "-uall"); + if (!output) return []; + + const changes: GitFileChange[] = []; + + for (const line of output.split("\n")) { + if (!line || line.length < 4) continue; + const x = line[0]; // index (staged) + const y = line[1]; // working tree + const filePath = line.slice(3); + + // Staged change + if (x !== " " && x !== "?") { + changes.push({ path: filePath, status: x, staged: true }); + } + // Unstaged change + if (y !== " " && y !== "?") { + changes.push({ path: filePath, status: y, staged: false }); + } + // Untracked + if (x === "?" && y === "?") { + changes.push({ path: filePath, status: "?", staged: false }); + } + } + + return changes; + } - /** - * Unstage files - */ - async unstageFiles(dir: string, files: string[]): Promise { - if (files.length === 0) return; - await this.git(dir, "reset", "HEAD", "--", ...files); - } + /** + * Stage files for commit + */ + async stageFiles(dir: string, files: string[]): Promise { + if (files.length === 0) return; + await this.git(dir, "add", "--", ...files); + } - /** - * Commit staged changes - */ - async commit(dir: string, message: string): Promise { - const output = await this.git(dir, "commit", "-m", message); - // Extract short hash from output like "[main abc1234] message" - const match = output.match(/\[[\w/.-]+ ([a-f0-9]+)\]/); - return match?.[1] ?? ""; - } + /** + * Stage all changes + */ + async stageAll(dir: string): Promise { + await this.git(dir, "add", "-A"); + } - /** - * Get recent commit log - */ - async log(dir: string, count = 20): Promise { - try { - const SEP = "<>"; - const format = ["%h", "%H", "%p", "%an", "%aI", "%s", "%D"].join(SEP); - const output = await this.git( - dir, - "log", - `--max-count=${count}`, - `--format=${format}` - ); - - if (!output) return []; - - return output.split("\n").filter(Boolean).map((line) => { - const [hash, fullHash, parents, author, date, subject, refs] = line.split(SEP); - return { - hash, - fullHash, - parents: parents ? parents.split(" ") : [], - author, - date, - subject, - refs: refs || "" - }; - }); - } catch { - return []; // No commits yet - } - } + /** + * Unstage files + */ + async unstageFiles(dir: string, files: string[]): Promise { + if (files.length === 0) return; + await this.git(dir, "reset", "HEAD", "--", ...files); + } - /** - * Get detailed commit log for graph visualization - */ - async logGraph(dir: string, count = 100): Promise { - try { - // %h: short hash, %H: full hash, %p: abbreviated parent hashes, %an: author name, %aI: author date ISO, %s: subject, %D: ref names - const SEP = "<>"; - const format = ["%h", "%H", "%p", "%an", "%aI", "%s", "%D"].join(SEP); - const output = await this.git( - dir, - "log", - `--max-count=${count}`, - `--format=${format}`, - "--all" // Include all branches - ); - - if (!output) return []; - - return output.split("\n").filter(Boolean).map((line) => { - const [hash, fullHash, parents, author, date, subject, refs] = line.split(SEP); - return { - hash, - fullHash, - parents: parents ? parents.split(" ") : [], - author, - date, - subject, - refs: refs || "" - }; - }); - } catch (err: any) { - return []; - } - } + /** + * Commit staged changes + */ + async commit(dir: string, message: string): Promise { + const output = await this.git(dir, "commit", "-m", message); + // Extract short hash from output like "[main abc1234] message" + const match = output.match(/\[[\w/.-]+ ([a-f0-9]+)\]/); + return match?.[1] ?? ""; + } - /** - * List branches - */ - async listBranches(dir: string): Promise { - try { - const output = await this.git( - dir, - "for-each-ref", - "--format=%(refname:short)%09%(HEAD)%09%(upstream:short)", - "refs/heads/" - ); - - if (!output) return []; - - return output.split("\n").map((line) => { - const [name, head, upstream] = line.split("\t"); - return { - name, - current: head === "*", - upstream: upstream || null, - }; - }); - } catch { - return []; - } + /** + * Get recent commit log + */ + async log(dir: string, count = 20): Promise { + try { + const SEP = "<>"; + const format = ["%h", "%H", "%p", "%an", "%aI", "%s", "%D"].join(SEP); + const output = await this.git(dir, "log", `--max-count=${count}`, `--format=${format}`); + + if (!output) return []; + + return output + .split("\n") + .filter(Boolean) + .map((line) => { + const [hash, fullHash, parents, author, date, subject, refs] = line.split(SEP); + return { + hash, + fullHash, + parents: parents ? parents.split(" ") : [], + author, + date, + subject, + refs: refs || "", + }; + }); + } catch { + return []; // No commits yet } + } - /** - * Create and checkout a new branch - */ - async createBranch(dir: string, name: string): Promise { - assertSafeGitRef(name); - await this.git(dir, "checkout", "-b", name); + /** + * Get detailed commit log for graph visualization + */ + async logGraph(dir: string, count = 100): Promise { + try { + // %h: short hash, %H: full hash, %p: abbreviated parent hashes, %an: author name, %aI: author date ISO, %s: subject, %D: ref names + const SEP = "<>"; + const format = ["%h", "%H", "%p", "%an", "%aI", "%s", "%D"].join(SEP); + const output = await this.git( + dir, + "log", + `--max-count=${count}`, + `--format=${format}`, + "--all", // Include all branches + ); + + if (!output) return []; + + return output + .split("\n") + .filter(Boolean) + .map((line) => { + const [hash, fullHash, parents, author, date, subject, refs] = line.split(SEP); + return { + hash, + fullHash, + parents: parents ? parents.split(" ") : [], + author, + date, + subject, + refs: refs || "", + }; + }); + } catch (err: any) { + return []; } + } - /** - * Checkout an existing branch - */ - async checkoutBranch(dir: string, name: string): Promise { - assertSafeGitRef(name); - await this.git(dir, "checkout", name); + /** + * List branches + */ + async listBranches(dir: string): Promise { + try { + const output = await this.git( + dir, + "for-each-ref", + "--format=%(refname:short)%09%(HEAD)%09%(upstream:short)", + "refs/heads/", + ); + + if (!output) return []; + + return output.split("\n").map((line) => { + const [name, head, upstream] = line.split("\t"); + return { + name, + current: head === "*", + upstream: upstream || null, + }; + }); + } catch { + return []; } + } - /** - * Discard unstaged changes in a file - */ - async discardChanges(dir: string, files: string[]): Promise { - if (files.length === 0) return; - await this.git(dir, "checkout", "--", ...files); - } + /** + * Create and checkout a new branch + */ + async createBranch(dir: string, name: string): Promise { + assertSafeGitRef(name); + await this.git(dir, "checkout", "-b", name); + } - /** - * Stash all changes - */ - async stash(dir: string, message?: string): Promise { - const args = ["stash", "push", "-u"]; - if (message) args.push("-m", message); - await this.git(dir, ...args); - } + /** + * Checkout an existing branch + */ + async checkoutBranch(dir: string, name: string): Promise { + assertSafeGitRef(name); + await this.git(dir, "checkout", name); + } - /** - * Pop the latest stash - */ - async stashPop(dir: string): Promise { - await this.git(dir, "stash", "pop"); - } + /** + * Discard unstaged changes in a file + */ + async discardChanges(dir: string, files: string[]): Promise { + if (files.length === 0) return; + await this.git(dir, "checkout", "--", ...files); + } - /** - * Get diff for a specific file (or all files) - */ - async diff(dir: string, file?: string, staged = false): Promise { - const args = ["diff"]; - if (staged) args.push("--staged"); - if (file) args.push("--", file); - const output = await this.git(dir, ...args); - - // If git diff returns nothing for a specific file, it might be an untracked file. - if (!output && file && !staged) { - try { - // git ls-files --error-unmatch throws if the file is untracked - await this.git(dir, "ls-files", "--error-unmatch", file); - } catch { - try { - const filePath = path.join(dir, file); - const stat = fsSync.statSync(filePath); - if (stat.isFile() && stat.size <= 2097152) { // Max 2MB diff - const content = fsSync.readFileSync(filePath, "utf-8"); - const lines = content.split(/\r?\n/); - let diffStr = `--- /dev/null\n+++ b/${file}\n@@ -0,0 +1,${lines.length} @@\n`; - for (const line of lines) diffStr += `+${line}\n`; - return diffStr.trimEnd(); - } - } catch { - // Ignore fs errors - } - } - } + /** + * Stash all changes + */ + async stash(dir: string, message?: string): Promise { + const args = ["stash", "push", "-u"]; + if (message) args.push("-m", message); + await this.git(dir, ...args); + } - return output; - } + /** + * Pop the latest stash + */ + async stashPop(dir: string): Promise { + await this.git(dir, "stash", "pop"); + } - /** - * Read a file's content at a given git ref (HEAD, branch, commit hash). - * Returns null if the file doesn't exist at that ref. - */ - async getFileAtRef(dir: string, filePath: string, ref = "HEAD"): Promise { + /** + * Get diff for a specific file (or all files) + */ + async diff(dir: string, file?: string, staged = false): Promise { + const args = ["diff"]; + if (staged) args.push("--staged"); + if (file) args.push("--", file); + const output = await this.git(dir, ...args); + + // If git diff returns nothing for a specific file, it might be an untracked file. + if (!output && file && !staged) { + try { + // git ls-files --error-unmatch throws if the file is untracked + await this.git(dir, "ls-files", "--error-unmatch", file); + } catch { try { - return await this.git(dir, "show", `${ref}:${filePath}`); + const filePath = path.join(dir, file); + const stat = fsSync.statSync(filePath); + if (stat.isFile() && stat.size <= 2097152) { + // Max 2MB diff + const content = fsSync.readFileSync(filePath, "utf-8"); + const lines = content.split(/\r?\n/); + let diffStr = `--- /dev/null\n+++ b/${file}\n@@ -0,0 +1,${lines.length} @@\n`; + for (const line of lines) diffStr += `+${line}\n`; + return diffStr.trimEnd(); + } } catch { - return null; // file doesn't exist at this ref + // Ignore fs errors } + } } - /** - * List commits that touched a specific file - */ - async fileLog(dir: string, filePath: string, count = 20): Promise { - try { - const SEP = "<>"; - const format = ["%h", "%H", "%p", "%an", "%aI", "%s", "%D"].join(SEP); - const output = await this.git( - dir, - "log", - `--max-count=${count}`, - `--format=${format}`, - "--follow", - "--", - filePath - ); - if (!output) return []; - return output.split("\n").filter(Boolean).map((line) => { - const [hash, fullHash, parents, author, date, subject, refs] = line.split(SEP); - return { - hash, - fullHash, - parents: parents ? parents.split(" ") : [], - author, - date, - subject, - refs: refs || "" - }; - }); - } catch { - return []; - } - } + return output; + } - /** - * Generate a .gitignore file suitable for RelWave projects - */ - generateGitignore(): string { - return [ - "# RelWave - auto-generated", - "# Connection credentials (NEVER commit these)", - "relwave.local.json", - ".credentials", - "", - "# OS files", - ".DS_Store", - "Thumbs.db", - "", - "# Editor", - ".vscode/", - ".idea/", - "*.swp", - "*.swo", - "", - ].join("\n"); + /** + * Read a file's content at a given git ref (HEAD, branch, commit hash). + * Returns null if the file doesn't exist at that ref. + */ + async getFileAtRef(dir: string, filePath: string, ref = "HEAD"): Promise { + try { + return await this.git(dir, "show", `${ref}:${filePath}`); + } catch { + return null; // file doesn't exist at this ref } + } - /** - * Write a .gitignore if it doesn't already exist in the repo - */ - async ensureGitignore(dir: string): Promise { - const gi = path.join(dir, ".gitignore"); - if (fsSync.existsSync(gi)) { - // Append our rules if the file exists but doesn't contain them - const existing = fsSync.readFileSync(gi, "utf-8"); - if (!existing.includes("relwave.local.json")) { - fsSync.appendFileSync( - gi, - "\n\n" + this.generateGitignore(), - "utf-8" - ); - return true; // modified - } - return false; // already has our rules - } - fsSync.writeFileSync(gi, this.generateGitignore(), "utf-8"); - return true; // created + /** + * List commits that touched a specific file + */ + async fileLog(dir: string, filePath: string, count = 20): Promise { + try { + const SEP = "<>"; + const format = ["%h", "%H", "%p", "%an", "%aI", "%s", "%D"].join(SEP); + const output = await this.git( + dir, + "log", + `--max-count=${count}`, + `--format=${format}`, + "--follow", + "--", + filePath, + ); + if (!output) return []; + return output + .split("\n") + .filter(Boolean) + .map((line) => { + const [hash, fullHash, parents, author, date, subject, refs] = line.split(SEP); + return { + hash, + fullHash, + parents: parents ? parents.split(" ") : [], + author, + date, + subject, + refs: refs || "", + }; + }); + } catch { + return []; } + } - // ========================================== - // Tags - // ========================================== - - /** - * Create an annotated tag at the current HEAD (or a given ref) - */ - async createTag(dir: string, tagName: string, message?: string, ref?: string): Promise { - assertSafeGitRef(tagName); - const args = ["tag"]; - if (message) { - args.push("-a", tagName, "-m", message); - } else { - args.push(tagName); - } - if (ref) args.push(ref); - await this.git(dir, ...args); - } + /** + * Generate a .gitignore file suitable for RelWave projects + */ + generateGitignore(): string { + return [ + "# RelWave - auto-generated", + "# Connection credentials (NEVER commit these)", + "relwave.local.json", + ".credentials", + "", + "# OS files", + ".DS_Store", + "Thumbs.db", + "", + "# Editor", + ".vscode/", + ".idea/", + "*.swp", + "*.swo", + "", + ].join("\n"); + } - /** - * Delete a tag - */ - async deleteTag(dir: string, tagName: string): Promise { - assertSafeGitRef(tagName); - await this.git(dir, "tag", "-d", tagName); - } + /** + * Write a .gitignore if it doesn't already exist in the repo + */ + async ensureGitignore(dir: string): Promise { + const gi = path.join(dir, ".gitignore"); + if (fsSync.existsSync(gi)) { + // Append our rules if the file exists but doesn't contain them + const existing = fsSync.readFileSync(gi, "utf-8"); + if (!existing.includes("relwave.local.json")) { + fsSync.appendFileSync(gi, "\n\n" + this.generateGitignore(), "utf-8"); + return true; // modified + } + return false; // already has our rules + } + fsSync.writeFileSync(gi, this.generateGitignore(), "utf-8"); + return true; // created + } - /** - * List tags with optional pattern filter. - * Returns tag names sorted by creation date (newest first). - */ - async listTags(dir: string, pattern?: string): Promise { - try { - const args = ["tag", "-l", "--sort=-creatordate"]; - if (pattern) args.push(pattern); - const output = await this.git(dir, ...args); - if (!output) return []; - return output.split("\n").filter(Boolean); - } catch { - return []; - } - } + // ========================================== + // Tags + // ========================================== + + /** + * Create an annotated tag at the current HEAD (or a given ref) + */ + async createTag(dir: string, tagName: string, message?: string, ref?: string): Promise { + assertSafeGitRef(tagName); + const args = ["tag"]; + if (message) { + args.push("-a", tagName, "-m", message); + } else { + args.push(tagName); + } + if (ref) args.push(ref); + await this.git(dir, ...args); + } - /** - * Get the message of an annotated tag - */ - async getTagMessage(dir: string, tagName: string): Promise { - assertSafeGitRef(tagName); - try { - return await this.git(dir, "tag", "-l", "-n99", tagName); - } catch { - return null; - } - } + /** + * Delete a tag + */ + async deleteTag(dir: string, tagName: string): Promise { + assertSafeGitRef(tagName); + await this.git(dir, "tag", "-d", tagName); + } - // ========================================== - // Merge / Conflict detection - // ========================================== - - /** - * Get the merge-base (common ancestor commit) between two refs. - * Returns full hash, or null if no common ancestor. - */ - async mergeBase(dir: string, refA: string, refB: string): Promise { - assertSafeGitRef(refA); - assertSafeGitRef(refB); - try { - const output = await this.git(dir, "merge-base", refA, refB); - return output || null; - } catch { - return null; - } + /** + * List tags with optional pattern filter. + * Returns tag names sorted by creation date (newest first). + */ + async listTags(dir: string, pattern?: string): Promise { + try { + const args = ["tag", "-l", "--sort=-creatordate"]; + if (pattern) args.push(pattern); + const output = await this.git(dir, ...args); + if (!output) return []; + return output.split("\n").filter(Boolean); + } catch { + return []; } + } - /** - * Check if merging `source` into the current branch would produce conflicts, - * without actually modifying the working tree. - * Returns list of conflicting file paths, or empty if clean. - */ - async dryMerge(dir: string, source: string): Promise { - try { - // Try to merge in-memory (index only) - await this.git(dir, "merge-tree", "--write-tree", "--no-messages", "HEAD", source); - return []; // clean merge - } catch (err: any) { - // merge-tree exits non-zero when there are conflicts and lists them - const output: string = err.stdout ?? err.message ?? ""; - const conflicts: string[] = []; - for (const line of output.split("\n")) { - // merge-tree outputs "CONFLICT (content): ..." lines - if (line.startsWith("CONFLICT")) { - const match = line.match(/Merge conflict in (.+)/); - if (match) conflicts.push(match[1].trim()); - } - } - return conflicts.length > 0 ? conflicts : ["(unknown conflict)"]; - } + /** + * Get the message of an annotated tag + */ + async getTagMessage(dir: string, tagName: string): Promise { + assertSafeGitRef(tagName); + try { + return await this.git(dir, "tag", "-l", "-n99", tagName); + } catch { + return null; } + } - /** - * Stage-and-commit specific files in one go (for auto-commit workflows). - * Returns the short commit hash. - */ - async commitFiles(dir: string, files: string[], message: string): Promise { - await this.git(dir, "add", "--", ...files); - return this.commit(dir, message); + // ========================================== + // Merge / Conflict detection + // ========================================== + + /** + * Get the merge-base (common ancestor commit) between two refs. + * Returns full hash, or null if no common ancestor. + */ + async mergeBase(dir: string, refA: string, refB: string): Promise { + assertSafeGitRef(refA); + assertSafeGitRef(refB); + try { + const output = await this.git(dir, "merge-base", refA, refB); + return output || null; + } catch { + return null; } + } - // ========================================== - // Remote Management (P3) - // ========================================== - - /** - * List all remotes with their fetch/push URLs. - */ - async remoteList(dir: string): Promise<{ name: string; fetchUrl: string; pushUrl: string }[]> { - try { - const output = await this.git(dir, "remote", "-v"); - if (!output) return []; - - const map = new Map(); - for (const line of output.split("\n")) { - const match = line.match(/^(\S+)\s+(\S+)\s+\((fetch|push)\)$/); - if (!match) continue; - const [, name, url, type] = match; - if (!map.has(name)) map.set(name, { fetchUrl: "", pushUrl: "" }); - const entry = map.get(name)!; - if (type === "fetch") entry.fetchUrl = url; - else entry.pushUrl = url; - } - - return Array.from(map.entries()).map(([name, urls]) => ({ name, ...urls })); - } catch { - return []; + /** + * Check if merging `source` into the current branch would produce conflicts, + * without actually modifying the working tree. + * Returns list of conflicting file paths, or empty if clean. + */ + async dryMerge(dir: string, source: string): Promise { + try { + // Try to merge in-memory (index only) + await this.git(dir, "merge-tree", "--write-tree", "--no-messages", "HEAD", source); + return []; // clean merge + } catch (err: any) { + // merge-tree exits non-zero when there are conflicts and lists them + const output: string = err.stdout ?? err.message ?? ""; + const conflicts: string[] = []; + for (const line of output.split("\n")) { + // merge-tree outputs "CONFLICT (content): ..." lines + if (line.startsWith("CONFLICT")) { + const match = line.match(/Merge conflict in (.+)/); + if (match) conflicts.push(match[1].trim()); } + } + return conflicts.length > 0 ? conflicts : ["(unknown conflict)"]; } + } - /** - * Add a named remote - */ - async remoteAdd(dir: string, name: string, url: string): Promise { - assertSafeGitRef(name); - await this.git(dir, "remote", "add", name, url); - } + /** + * Stage-and-commit specific files in one go (for auto-commit workflows). + * Returns the short commit hash. + */ + async commitFiles(dir: string, files: string[], message: string): Promise { + await this.git(dir, "add", "--", ...files); + return this.commit(dir, message); + } - /** - * Remove a named remote - */ - async remoteRemove(dir: string, name: string): Promise { - assertSafeGitRef(name); - await this.git(dir, "remote", "remove", name); + // ========================================== + // Remote Management (P3) + // ========================================== + + /** + * List all remotes with their fetch/push URLs. + */ + async remoteList(dir: string): Promise<{ name: string; fetchUrl: string; pushUrl: string }[]> { + try { + const output = await this.git(dir, "remote", "-v"); + if (!output) return []; + + const map = new Map(); + for (const line of output.split("\n")) { + const match = line.match(/^(\S+)\s+(\S+)\s+\((fetch|push)\)$/); + if (!match) continue; + const [, name, url, type] = match; + if (!map.has(name)) map.set(name, { fetchUrl: "", pushUrl: "" }); + const entry = map.get(name)!; + if (type === "fetch") entry.fetchUrl = url; + else entry.pushUrl = url; + } + + return Array.from(map.entries()).map(([name, urls]) => ({ name, ...urls })); + } catch { + return []; } + } - /** - * Get the URL of a remote - */ - async remoteGetUrl(dir: string, name = "origin"): Promise { - try { - return await this.git(dir, "remote", "get-url", name); - } catch { - return null; - } - } + /** + * Add a named remote + */ + async remoteAdd(dir: string, name: string, url: string): Promise { + assertSafeGitRef(name); + await this.git(dir, "remote", "add", name, url); + } - /** - * Change the URL of an existing remote - */ - async remoteSetUrl(dir: string, name: string, url: string): Promise { - assertSafeGitRef(name); - await this.git(dir, "remote", "set-url", name, url); - } + /** + * Remove a named remote + */ + async remoteRemove(dir: string, name: string): Promise { + assertSafeGitRef(name); + await this.git(dir, "remote", "remove", name); + } - // ========================================== - // Push / Pull / Fetch (P3) - // ========================================== - - /** - * Push commits to a remote. - * Returns push output text. - */ - async push( - dir: string, - remote = "origin", - branch?: string, - options?: { force?: boolean; setUpstream?: boolean } - ): Promise { - if (remote) assertSafeGitRef(remote); - if (branch) assertSafeGitRef(branch); - const args = ["push"]; - if (options?.force) args.push("--force-with-lease"); - if (options?.setUpstream) args.push("--set-upstream"); - args.push(remote); - if (branch) args.push(branch); - return this.git(dir, ...args); + /** + * Get the URL of a remote + */ + async remoteGetUrl(dir: string, name = "origin"): Promise { + try { + return await this.git(dir, "remote", "get-url", name); + } catch { + return null; } + } - /** - * Pull from a remote. - * Returns pull output text. - */ - async pull( - dir: string, - remote = "origin", - branch?: string, - options?: { rebase?: boolean } - ): Promise { - if (remote) assertSafeGitRef(remote); - if (branch) assertSafeGitRef(branch); - const args = ["pull"]; - if (options?.rebase) args.push("--rebase"); - args.push(remote); - if (branch) args.push(branch); - return this.git(dir, ...args); - } + /** + * Change the URL of an existing remote + */ + async remoteSetUrl(dir: string, name: string, url: string): Promise { + assertSafeGitRef(name); + await this.git(dir, "remote", "set-url", name, url); + } - /** - * Fetch from a remote (or all remotes). - */ - async fetch( - dir: string, - remote?: string, - options?: { prune?: boolean; all?: boolean } - ): Promise { - if (remote) assertSafeGitRef(remote); - const args = ["fetch"]; - if (options?.prune) args.push("--prune"); - if (options?.all || !remote) { - args.push("--all"); - } else { - args.push(remote); - } - return this.git(dir, ...args); - } + // ========================================== + // Push / Pull / Fetch (P3) + // ========================================== + + /** + * Push commits to a remote. + * Returns push output text. + */ + async push( + dir: string, + remote = "origin", + branch?: string, + options?: { force?: boolean; setUpstream?: boolean }, + ): Promise { + if (remote) assertSafeGitRef(remote); + if (branch) assertSafeGitRef(branch); + const args = ["push"]; + if (options?.force) args.push("--force-with-lease"); + if (options?.setUpstream) args.push("--set-upstream"); + args.push(remote); + if (branch) args.push(branch); + return this.git(dir, ...args); + } - // ========================================== - // Merge & Rebase (P3) - // ========================================== - - /** - * Merge a branch into the current branch. - * Returns merge output. Throws on conflict. - */ - async merge( - dir: string, - branch: string, - options?: { noFF?: boolean; squash?: boolean; message?: string } - ): Promise { - const args = ["merge"]; - if (options?.noFF) args.push("--no-ff"); - if (options?.squash) args.push("--squash"); - if (options?.message) args.push("-m", options.message); - args.push(branch); - return this.git(dir, ...args); - } + /** + * Pull from a remote. + * Returns pull output text. + */ + async pull( + dir: string, + remote = "origin", + branch?: string, + options?: { rebase?: boolean }, + ): Promise { + if (remote) assertSafeGitRef(remote); + if (branch) assertSafeGitRef(branch); + const args = ["pull"]; + if (options?.rebase) args.push("--rebase"); + args.push(remote); + if (branch) args.push(branch); + return this.git(dir, ...args); + } - /** - * Abort an in-progress merge - */ - async abortMerge(dir: string): Promise { - await this.git(dir, "merge", "--abort"); - } + /** + * Fetch from a remote (or all remotes). + */ + async fetch( + dir: string, + remote?: string, + options?: { prune?: boolean; all?: boolean }, + ): Promise { + if (remote) assertSafeGitRef(remote); + const args = ["fetch"]; + if (options?.prune) args.push("--prune"); + if (options?.all || !remote) { + args.push("--all"); + } else { + args.push(remote); + } + return this.git(dir, ...args); + } - /** - * Rebase current branch onto target - */ - async rebase(dir: string, onto: string): Promise { - return this.git(dir, "rebase", onto); - } + // ========================================== + // Merge & Rebase (P3) + // ========================================== + + /** + * Merge a branch into the current branch. + * Returns merge output. Throws on conflict. + */ + async merge( + dir: string, + branch: string, + options?: { noFF?: boolean; squash?: boolean; message?: string }, + ): Promise { + const args = ["merge"]; + if (options?.noFF) args.push("--no-ff"); + if (options?.squash) args.push("--squash"); + if (options?.message) args.push("-m", options.message); + args.push(branch); + return this.git(dir, ...args); + } - /** - * Abort an in-progress rebase - */ - async abortRebase(dir: string): Promise { - await this.git(dir, "rebase", "--abort"); - } + /** + * Abort an in-progress merge + */ + async abortMerge(dir: string): Promise { + await this.git(dir, "merge", "--abort"); + } - /** - * Continue a rebase after resolving conflicts - */ - async continueRebase(dir: string): Promise { - return this.git(dir, "rebase", "--continue"); - } + /** + * Rebase current branch onto target + */ + async rebase(dir: string, onto: string): Promise { + return this.git(dir, "rebase", onto); + } - // ========================================== - // History & Reversal (P3) - // ========================================== - - /** - * Revert a specific commit (creates a new commit that undoes the changes) - */ - async revert(dir: string, commitHash: string, options?: { noCommit?: boolean }): Promise { - const args = ["revert"]; - if (options?.noCommit) args.push("--no-commit"); - args.push(commitHash); - return this.git(dir, ...args); - } + /** + * Abort an in-progress rebase + */ + async abortRebase(dir: string): Promise { + await this.git(dir, "rebase", "--abort"); + } - /** - * Cherry-pick a commit from another branch - */ - async cherryPick(dir: string, commitHash: string, options?: { noCommit?: boolean }): Promise { - const args = ["cherry-pick"]; - if (options?.noCommit) args.push("--no-commit"); - args.push(commitHash); - return this.git(dir, ...args); - } + /** + * Continue a rebase after resolving conflicts + */ + async continueRebase(dir: string): Promise { + return this.git(dir, "rebase", "--continue"); + } + + // ========================================== + // History & Reversal (P3) + // ========================================== + + /** + * Revert a specific commit (creates a new commit that undoes the changes) + */ + async revert(dir: string, commitHash: string, options?: { noCommit?: boolean }): Promise { + const args = ["revert"]; + if (options?.noCommit) args.push("--no-commit"); + args.push(commitHash); + return this.git(dir, ...args); + } + + /** + * Cherry-pick a commit from another branch + */ + async cherryPick( + dir: string, + commitHash: string, + options?: { noCommit?: boolean }, + ): Promise { + const args = ["cherry-pick"]; + if (options?.noCommit) args.push("--no-commit"); + args.push(commitHash); + return this.git(dir, ...args); + } - /** - * Get line-by-line blame for a file. - * Returns array of blame entries. - */ - async blame(dir: string, filePath: string): Promise<{ + /** + * Get line-by-line blame for a file. + * Returns array of blame entries. + */ + async blame( + dir: string, + filePath: string, + ): Promise< + { + hash: string; + author: string; + date: string; + lineNumber: number; + content: string; + }[] + > { + try { + const output = await this.git(dir, "blame", "--porcelain", "--", filePath); + if (!output) return []; + + const entries: { hash: string; author: string; date: string; lineNumber: number; content: string; - }[]> { - try { - const output = await this.git( - dir, - "blame", - "--porcelain", - "--", - filePath - ); - if (!output) return []; - - const entries: { hash: string; author: string; date: string; lineNumber: number; content: string }[] = []; - const lines = output.split("\n"); - let i = 0; - while (i < lines.length) { - const header = lines[i]; - const headerMatch = header.match(/^([0-9a-f]{40})\s+\d+\s+(\d+)/); - if (!headerMatch) { i++; continue; } - const hash = headerMatch[1].slice(0, 8); - const lineNumber = parseInt(headerMatch[2], 10); - let author = ""; - let date = ""; - i++; - // Read header fields until content line starting with \t - while (i < lines.length && !lines[i].startsWith("\t")) { - if (lines[i].startsWith("author ")) author = lines[i].slice(7); - if (lines[i].startsWith("author-time ")) { - const ts = parseInt(lines[i].slice(12), 10); - date = new Date(ts * 1000).toISOString(); - } - i++; - } - const content = i < lines.length ? lines[i].slice(1) : ""; - entries.push({ hash, author, date, lineNumber, content }); - i++; - } - return entries; - } catch { - return []; + }[] = []; + const lines = output.split("\n"); + let i = 0; + while (i < lines.length) { + const header = lines[i]; + const headerMatch = header.match(/^([0-9a-f]{40})\s+\d+\s+(\d+)/); + if (!headerMatch) { + i++; + continue; } + const hash = headerMatch[1].slice(0, 8); + const lineNumber = parseInt(headerMatch[2], 10); + let author = ""; + let date = ""; + i++; + // Read header fields until content line starting with \t + while (i < lines.length && !lines[i].startsWith("\t")) { + if (lines[i].startsWith("author ")) author = lines[i].slice(7); + if (lines[i].startsWith("author-time ")) { + const ts = parseInt(lines[i].slice(12), 10); + date = new Date(ts * 1000).toISOString(); + } + i++; + } + const content = i < lines.length ? lines[i].slice(1) : ""; + entries.push({ hash, author, date, lineNumber, content }); + i++; + } + return entries; + } catch { + return []; } + } - /** - * Show a file at a specific ref (alias for getFileAtRef for consistency) - */ - async show(dir: string, ref: string, filePath: string): Promise { - return this.getFileAtRef(dir, filePath, ref); - } - - // ========================================== - // Stash Management (P3) - // ========================================== + /** + * Show a file at a specific ref (alias for getFileAtRef for consistency) + */ + async show(dir: string, ref: string, filePath: string): Promise { + return this.getFileAtRef(dir, filePath, ref); + } - /** - * List all stash entries - */ - async stashList(dir: string): Promise<{ index: number; message: string; date: string }[]> { - try { - const SEP = "<>"; - const output = await this.git( - dir, - "stash", - "list", - `--format=%gd${SEP}%s${SEP}%aI` - ); - if (!output) return []; - - return output.split("\n").filter(Boolean).map((line) => { - const [ref, message, date] = line.split(SEP); - const indexMatch = ref.match(/\{(\d+)\}/); - return { - index: indexMatch ? parseInt(indexMatch[1], 10) : 0, - message: message || ref, - date: date || "", - }; - }); - } catch { - return []; - } + // ========================================== + // Stash Management (P3) + // ========================================== + + /** + * List all stash entries + */ + async stashList(dir: string): Promise<{ index: number; message: string; date: string }[]> { + try { + const SEP = "<>"; + const output = await this.git(dir, "stash", "list", `--format=%gd${SEP}%s${SEP}%aI`); + if (!output) return []; + + return output + .split("\n") + .filter(Boolean) + .map((line) => { + const [ref, message, date] = line.split(SEP); + const indexMatch = ref.match(/\{(\d+)\}/); + return { + index: indexMatch ? parseInt(indexMatch[1], 10) : 0, + message: message || ref, + date: date || "", + }; + }); + } catch { + return []; } + } - /** - * Apply a specific stash entry (without removing it from the stash list) - */ - async stashApply(dir: string, index = 0): Promise { - await this.git(dir, "stash", "apply", `stash@{${index}}`); - } + /** + * Apply a specific stash entry (without removing it from the stash list) + */ + async stashApply(dir: string, index = 0): Promise { + await this.git(dir, "stash", "apply", `stash@{${index}}`); + } - /** - * Drop a specific stash entry - */ - async stashDrop(dir: string, index = 0): Promise { - await this.git(dir, "stash", "drop", `stash@{${index}}`); - } + /** + * Drop a specific stash entry + */ + async stashDrop(dir: string, index = 0): Promise { + await this.git(dir, "stash", "drop", `stash@{${index}}`); + } - /** - * Clear all stash entries - */ - async stashClear(dir: string): Promise { - await this.git(dir, "stash", "clear"); - } + /** + * Clear all stash entries + */ + async stashClear(dir: string): Promise { + await this.git(dir, "stash", "clear"); + } - // ========================================== - // Clone (P3) - // ========================================== - - /** - * Clone a repository. Returns the path of the cloned directory. - */ - async clone(url: string, dest: string, branch?: string): Promise { - const args = ["clone"]; - if (branch) args.push("-b", branch); - args.push(url, dest); - // cwd doesn't matter for clone, use dest's parent - const parent = path.dirname(dest); - await this.git(parent, ...args); - return dest; - } + // ========================================== + // Clone (P3) + // ========================================== + + /** + * Clone a repository. Returns the path of the cloned directory. + */ + async clone(url: string, dest: string, branch?: string): Promise { + const args = ["clone"]; + if (branch) args.push("-b", branch); + args.push(url, dest); + // cwd doesn't matter for clone, use dest's parent + const parent = path.dirname(dest); + await this.git(parent, ...args); + return dest; + } - // ========================================== - // Conflict Resolution Helpers (P3) - // ========================================== - - /** - * Check if there is a merge or rebase in progress - */ - async getMergeState(dir: string): Promise<{ - mergeInProgress: boolean; - rebaseInProgress: boolean; - conflictedFiles: string[]; - }> { - let mergeInProgress = false; - let rebaseInProgress = false; + // ========================================== + // Conflict Resolution Helpers (P3) + // ========================================== + + /** + * Check if there is a merge or rebase in progress + */ + async getMergeState(dir: string): Promise<{ + mergeInProgress: boolean; + rebaseInProgress: boolean; + conflictedFiles: string[]; + }> { + let mergeInProgress = false; + let rebaseInProgress = false; + + try { + const gitDir = await this.git(dir, "rev-parse", "--git-dir"); + const absGitDir = path.resolve(dir, gitDir); + mergeInProgress = fsSync.existsSync(path.join(absGitDir, "MERGE_HEAD")); + rebaseInProgress = + fsSync.existsSync(path.join(absGitDir, "rebase-merge")) || + fsSync.existsSync(path.join(absGitDir, "rebase-apply")); + } catch { + // Not a repo or other error + } + + // Get list of conflicted files + const conflictedFiles: string[] = []; + try { + const output = await this.git(dir, "diff", "--name-only", "--diff-filter=U"); + if (output) { + conflictedFiles.push(...output.split("\n").filter(Boolean)); + } + } catch { + // Ignore + } + + return { mergeInProgress, rebaseInProgress, conflictedFiles }; + } - try { - const gitDir = await this.git(dir, "rev-parse", "--git-dir"); - const absGitDir = path.resolve(dir, gitDir); - mergeInProgress = fsSync.existsSync(path.join(absGitDir, "MERGE_HEAD")); - rebaseInProgress = - fsSync.existsSync(path.join(absGitDir, "rebase-merge")) || - fsSync.existsSync(path.join(absGitDir, "rebase-apply")); - } catch { - // Not a repo or other error - } + /** + * Mark conflicted files as resolved (stage them) + */ + async markResolved(dir: string, files: string[]): Promise { + if (files.length === 0) return; + await this.git(dir, "add", "--", ...files); + } - // Get list of conflicted files - const conflictedFiles: string[] = []; - try { - const output = await this.git(dir, "diff", "--name-only", "--diff-filter=U"); - if (output) { - conflictedFiles.push(...output.split("\n").filter(Boolean)); - } - } catch { - // Ignore - } + // ========================================== + // Protection & Safety (P3) + // ========================================== + + /** + * Get the list of configured protected branch patterns. + * By convention, reads from .relwave-protected-branches in the repo root. + * Returns ["main", "production"] by default if the file doesn't exist. + */ + getProtectedBranches(dir: string): string[] { + try { + const filePath = path.join(dir, ".relwave-protected-branches"); + if (fsSync.existsSync(filePath)) { + return fsSync + .readFileSync(filePath, "utf-8") + .split("\n") + .map((l) => l.trim()) + .filter(Boolean); + } + } catch { + // Ignore + } + return ["main", "production"]; + } - return { mergeInProgress, rebaseInProgress, conflictedFiles }; - } + /** + * Check if a branch name matches any protected pattern + */ + isProtectedBranch(dir: string, branch: string): boolean { + const patterns = this.getProtectedBranches(dir); + return patterns.some((p) => { + if (p.includes("*")) { + const regex = new RegExp("^" + p.replace(/\*/g, ".*") + "$"); + return regex.test(branch); + } + return p === branch; + }); + } - /** - * Mark conflicted files as resolved (stage them) - */ - async markResolved(dir: string, files: string[]): Promise { - if (files.length === 0) return; - await this.git(dir, "add", "--", ...files); - } + /** + * Delete a local branch (prevent deletion of the current branch) + */ + async deleteBranch(dir: string, name: string, force = false): Promise { + const flag = force ? "-D" : "-d"; + await this.git(dir, "branch", flag, name); + } - // ========================================== - // Protection & Safety (P3) - // ========================================== + /** + * Rename the current branch + */ + async renameBranch(dir: string, newName: string): Promise { + await this.git(dir, "branch", "-m", newName); + } - /** - * Get the list of configured protected branch patterns. - * By convention, reads from .relwave-protected-branches in the repo root. - * Returns ["main", "production"] by default if the file doesn't exist. - */ - getProtectedBranches(dir: string): string[] { - try { - const filePath = path.join(dir, ".relwave-protected-branches"); - if (fsSync.existsSync(filePath)) { - return fsSync - .readFileSync(filePath, "utf-8") - .split("\n") - .map((l) => l.trim()) - .filter(Boolean); - } - } catch { - // Ignore - } - return ["main", "production"]; - } + // ========================================== + // Migration Sync (Task 1) + // ========================================== + + /** + * Stage migration files and lock file + */ + async stageMigrationFiles(projectPath: string): Promise { + // Run git add on migrations/ and migration-lock.json + // But first check if they exist or have changes + const filesToStage = ["migrations"]; + const stagedPaths: string[] = []; + + for (const file of filesToStage) { + try { + await this.git(projectPath, "add", file); + stagedPaths.push(file); + } catch (err) { + // Ignore if path doesn't exist + } + } + + // Return actually staged files from status + const changes = await this.getChangedFiles(projectPath); + return changes.filter((c) => c.staged).map((c) => c.path); + } - /** - * Check if a branch name matches any protected pattern - */ - isProtectedBranch(dir: string, branch: string): boolean { - const patterns = this.getProtectedBranches(dir); - return patterns.some((p) => { - if (p.includes("*")) { - const regex = new RegExp("^" + p.replace(/\*/g, ".*") + "$"); - return regex.test(branch); - } - return p === branch; - }); + /** + * Commit migration files with an auto-generated or provided message + */ + async commitMigrationFiles(projectPath: string, message?: string): Promise { + let commitMsg = message; + + if (!commitMsg) { + // Auto-generate message based on staged files + const changes = await this.getChangedFiles(projectPath); + const stagedMigrations = changes.filter((c) => c.staged && c.path.startsWith("migrations/")); + + if (stagedMigrations.length === 1) { + const filename = path.basename(stagedMigrations[0].path); + if (filename.includes("baseline")) { + commitMsg = "migrate: add baseline migration from schema snapshot"; + } else { + commitMsg = `migrate: apply ${filename}`; + } + } else if (stagedMigrations.length > 1) { + // Find highest migration + const sorted = stagedMigrations.map((m) => path.basename(m.path)).sort(); + const latest = sorted[sorted.length - 1]; + commitMsg = `migrate: apply ${stagedMigrations.length} migrations up to ${latest}`; + } else { + commitMsg = "migrate: update schema lock"; + } } - /** - * Delete a local branch (prevent deletion of the current branch) - */ - async deleteBranch(dir: string, name: string, force = false): Promise { - const flag = force ? "-D" : "-d"; - await this.git(dir, "branch", flag, name); - } + return this.commit(projectPath, commitMsg); + } - /** - * Rename the current branch - */ - async renameBranch(dir: string, newName: string): Promise { - await this.git(dir, "branch", "-m", newName); + /** + * Push current branch to remote + */ + async pushMigrations(projectPath: string): Promise { + const remotes = await this.remoteList(projectPath); + if (remotes.length === 0) { + throw new GitError("NO_REMOTE", "No remote configured for this repository"); } - // ========================================== - // Migration Sync (Task 1) - // ========================================== - - /** - * Stage migration files and lock file - */ - async stageMigrationFiles(projectPath: string): Promise { - // Run git add on migrations/ and migration-lock.json - // But first check if they exist or have changes - const filesToStage = ["migrations"]; - const stagedPaths: string[] = []; - - for (const file of filesToStage) { - try { - await this.git(projectPath, "add", file); - stagedPaths.push(file); - } catch (err) { - // Ignore if path doesn't exist - } - } - - // Return actually staged files from status - const changes = await this.getChangedFiles(projectPath); - return changes.filter(c => c.staged).map(c => c.path); + try { + await this.git(projectPath, "push"); + } catch (err: any) { + const errorMsg = err.stderr || err.message || ""; + if (errorMsg.includes("non-fast-forward") || errorMsg.includes("fetch first")) { + throw new GitError("PUSH_REJECTED", "Push rejected due to diverged history"); + } + throw new GitError("PUSH_FAILED", `Push failed: ${errorMsg}`); } + } - /** - * Commit migration files with an auto-generated or provided message - */ - async commitMigrationFiles(projectPath: string, message?: string): Promise { - let commitMsg = message; - - if (!commitMsg) { - // Auto-generate message based on staged files - const changes = await this.getChangedFiles(projectPath); - const stagedMigrations = changes.filter(c => c.staged && c.path.startsWith("migrations/")); - - if (stagedMigrations.length === 1) { - const filename = path.basename(stagedMigrations[0].path); - if (filename.includes("baseline")) { - commitMsg = "migrate: add baseline migration from schema snapshot"; - } else { - commitMsg = `migrate: apply ${filename}`; - } - } else if (stagedMigrations.length > 1) { - // Find highest migration - const sorted = stagedMigrations.map(m => path.basename(m.path)).sort(); - const latest = sorted[sorted.length - 1]; - commitMsg = `migrate: apply ${stagedMigrations.length} migrations up to ${latest}`; - } else { - commitMsg = "migrate: update schema lock"; - } + /** + * Orchestrate staging, committing, and pushing + */ + async syncMigrationFiles(projectPath: string, message?: string): Promise { + const result: GitSyncResult = { + staged: [], + commitHash: "", + commitMessage: "", + pushed: false, + }; + + try { + result.staged = await this.stageMigrationFiles(projectPath); + if (result.staged.length === 0) { + return result; // Nothing to sync + } + + result.commitHash = await this.commitMigrationFiles(projectPath, message); + + // Get actual message used if auto-generated + if (!message && result.commitHash) { + const log = await this.log(projectPath, 1); + if (log.length > 0) result.commitMessage = log[0].subject; + } else { + result.commitMessage = message || ""; + } + + // Read config to see if autoPushMigrations is true + let autoPush = false; + try { + const configPath = path.join(projectPath, "relwave.json"); + if (fsSync.existsSync(configPath)) { + const config = JSON.parse(fsSync.readFileSync(configPath, "utf-8")); + if (config.autoPushMigrations === true) { + autoPush = true; + } } - - return this.commit(projectPath, commitMsg); - } + } catch (err) { + // Ignore config read errors + } - /** - * Push current branch to remote - */ - async pushMigrations(projectPath: string): Promise { - const remotes = await this.remoteList(projectPath); - if (remotes.length === 0) { - throw new GitError("NO_REMOTE", "No remote configured for this repository"); - } - + if (autoPush) { try { - await this.git(projectPath, "push"); - } catch (err: any) { - const errorMsg = err.stderr || err.message || ""; - if (errorMsg.includes("non-fast-forward") || errorMsg.includes("fetch first")) { - throw new GitError("PUSH_REJECTED", "Push rejected due to diverged history"); - } - throw new GitError("PUSH_FAILED", `Push failed: ${errorMsg}`); + await this.pushMigrations(projectPath); + result.pushed = true; + } catch (pushErr: any) { + result.error = { + code: pushErr.code || "PUSH_FAILED", + message: pushErr.message, + }; } + } + } catch (err: any) { + result.error = { + code: err.code || "SYNC_FAILED", + message: err.message, + }; } - /** - * Orchestrate staging, committing, and pushing - */ - async syncMigrationFiles(projectPath: string, message?: string): Promise { - const result: GitSyncResult = { - staged: [], - commitHash: "", - commitMessage: "", - pushed: false, - }; + return result; + } - try { - result.staged = await this.stageMigrationFiles(projectPath); - if (result.staged.length === 0) { - return result; // Nothing to sync - } - - result.commitHash = await this.commitMigrationFiles(projectPath, message); - - // Get actual message used if auto-generated - if (!message && result.commitHash) { - const log = await this.log(projectPath, 1); - if (log.length > 0) result.commitMessage = log[0].subject; - } else { - result.commitMessage = message || ""; - } - - // Read config to see if autoPushMigrations is true - let autoPush = false; - try { - const configPath = path.join(projectPath, "relwave.json"); - if (fsSync.existsSync(configPath)) { - const config = JSON.parse(fsSync.readFileSync(configPath, "utf-8")); - if (config.autoPushMigrations === true) { - autoPush = true; - } - } - } catch (err) { - // Ignore config read errors - } - - if (autoPush) { - try { - await this.pushMigrations(projectPath); - result.pushed = true; - } catch (pushErr: any) { - result.error = { - code: pushErr.code || "PUSH_FAILED", - message: pushErr.message - }; - } - } - - } catch (err: any) { - result.error = { - code: err.code || "SYNC_FAILED", - message: err.message - }; - } - - return result; - } + /** + * Stash, sync schema.json + */ + async syncSchemaFile(projectPath: string, message?: string): Promise { + try { + await this.ensureGitignore(projectPath); + const changes = await this.getChangedFiles(projectPath); + const schemaFile = "schema/schema.json"; - /** - * Stash, sync schema.json - */ - async syncSchemaFile(projectPath: string, message?: string): Promise { - try { - await this.ensureGitignore(projectPath); - const changes = await this.getChangedFiles(projectPath); - const schemaFile = "schema/schema.json"; - - const schemaModified = changes.some(c => c.path === schemaFile); - - if (!schemaModified) { - return { staged: [], commitHash: "", commitMessage: "", pushed: false }; - } - - await this.stageFiles(projectPath, [schemaFile]); - - const commitMessage = message || `chore: update schema.json cache`; - const commitHash = await this.commit(projectPath, commitMessage); - - let pushed = false; - try { - await this.pushMigrations(projectPath); - pushed = true; - } catch (pushErr: any) { - // Return result with push error but still considered successful commit - return { - staged: [schemaFile], - commitHash, - commitMessage, - pushed: false, - error: { - code: "GIT_PUSH_FAILED", - message: `Committed successfully but failed to push: ${pushErr.message || String(pushErr)}` - } - }; - } - - return { - staged: [schemaFile], - commitHash, - commitMessage, - pushed - }; - } catch (error: any) { - return { - staged: [], - commitHash: "", - commitMessage: "", - pushed: false, - error: { - code: "GIT_SYNC_FAILED", - message: `Failed to sync schema file: ${error.message || String(error)}` - } - }; - } + const schemaModified = changes.some((c) => c.path === schemaFile); + + if (!schemaModified) { + return { staged: [], commitHash: "", commitMessage: "", pushed: false }; + } + + await this.stageFiles(projectPath, [schemaFile]); + + const commitMessage = message || `chore: update schema.json cache`; + const commitHash = await this.commit(projectPath, commitMessage); + + let pushed = false; + try { + await this.pushMigrations(projectPath); + pushed = true; + } catch (pushErr: any) { + // Return result with push error but still considered successful commit + return { + staged: [schemaFile], + commitHash, + commitMessage, + pushed: false, + error: { + code: "GIT_PUSH_FAILED", + message: `Committed successfully but failed to push: ${pushErr.message || String(pushErr)}`, + }, + }; + } + + return { + staged: [schemaFile], + commitHash, + commitMessage, + pushed, + }; + } catch (error: any) { + return { + staged: [], + commitHash: "", + commitMessage: "", + pushed: false, + error: { + code: "GIT_SYNC_FAILED", + message: `Failed to sync schema file: ${error.message || String(error)}`, + }, + }; } + } } export const gitServiceInstance = new GitService(); diff --git a/bridge/src/services/logger.ts b/bridge/src/services/logger.ts index fb3d3be1..98df1b63 100644 --- a/bridge/src/services/logger.ts +++ b/bridge/src/services/logger.ts @@ -1,5 +1,5 @@ // bridge/src/services/logger.ts -import pino from 'pino'; +import pino from "pino"; // send logs to stderr by creating destination with { dest: 2 } const logger = pino({}, pino.destination(2)); export default logger; diff --git a/bridge/src/services/migrationLock.ts b/bridge/src/services/migrationLock.ts index efa358bf..0b4db171 100644 --- a/bridge/src/services/migrationLock.ts +++ b/bridge/src/services/migrationLock.ts @@ -4,48 +4,48 @@ import fsSync from "fs"; import { projectStoreInstance } from "./projectStore"; export interface MigrationLock { - version: string; - schemaHash: string; - appliedMigrations: string[]; // List of migration filenames - updatedAt: string; + version: string; + schemaHash: string; + appliedMigrations: string[]; // List of migration filenames + updatedAt: string; } export async function getLockFilePath(dbId: string): Promise { - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); - return path.join(migrationsDir, "migration.lock.json"); + const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + return path.join(migrationsDir, "migration.lock.json"); } export async function readMigrationLock(dbId: string): Promise { - const lockPath = await getLockFilePath(dbId); - if (!fsSync.existsSync(lockPath)) return null; - - try { - const raw = await fs.readFile(lockPath, "utf8"); - return JSON.parse(raw) as MigrationLock; - } catch (err) { - return null; - } + const lockPath = await getLockFilePath(dbId); + if (!fsSync.existsSync(lockPath)) return null; + + try { + const raw = await fs.readFile(lockPath, "utf8"); + return JSON.parse(raw) as MigrationLock; + } catch (err) { + return null; + } } export async function writeMigrationLock( - dbId: string, - schemaHash: string, - appliedMigrations: string[] + dbId: string, + schemaHash: string, + appliedMigrations: string[], ): Promise { - const lockPath = await getLockFilePath(dbId); - const lockData: MigrationLock = { - version: "1", - schemaHash, - appliedMigrations, - updatedAt: new Date().toISOString() - }; - - await fs.mkdir(path.dirname(lockPath), { recursive: true }).catch(() => {}); - await fs.writeFile(lockPath, JSON.stringify(lockData, null, 2), "utf8"); + const lockPath = await getLockFilePath(dbId); + const lockData: MigrationLock = { + version: "1", + schemaHash, + appliedMigrations, + updatedAt: new Date().toISOString(), + }; + + await fs.mkdir(path.dirname(lockPath), { recursive: true }).catch(() => {}); + await fs.writeFile(lockPath, JSON.stringify(lockData, null, 2), "utf8"); } export async function verifyMigrationLock(dbId: string, targetHash: string): Promise { - const lock = await readMigrationLock(dbId); - if (!lock) return false; - return lock.schemaHash === targetHash; + const lock = await readMigrationLock(dbId); + if (!lock) return false; + return lock.schemaHash === targetHash; } diff --git a/bridge/src/services/monitoringService.ts b/bridge/src/services/monitoringService.ts index fb713905..0b0fa828 100644 --- a/bridge/src/services/monitoringService.ts +++ b/bridge/src/services/monitoringService.ts @@ -78,29 +78,30 @@ export class MonitoringService { await client.query("SELECT 1;"); const latencyMs = Date.now() - startedAt; - const [connectionsResult, transactionResult, cacheResult, activeQueriesResult] = await Promise.all([ - client.query(` + const [connectionsResult, transactionResult, cacheResult, activeQueriesResult] = + await Promise.all([ + client.query(` SELECT (SELECT count(*) FROM pg_stat_activity) AS active_connections, (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS max_connections; `), - client.query( - ` + client.query( + ` SELECT COALESCE(xact_commit + xact_rollback, 0) AS total_transactions FROM pg_stat_database WHERE datname = $1; `, - [cfg.database] - ), - client.query( - ` + [cfg.database], + ), + client.query( + ` SELECT round(100 * blks_hit / (blks_read + blks_hit + 1), 2) AS cache_hit_ratio FROM pg_stat_database WHERE datname = $1; `, - [cfg.database] - ), - client.query(` + [cfg.database], + ), + client.query(` SELECT pid, EXTRACT(EPOCH FROM (clock_timestamp() - query_start)) AS duration_seconds, @@ -112,7 +113,7 @@ export class MonitoringService { ORDER BY query_start NULLS LAST LIMIT 25; `), - ]); + ]); const active = Number(connectionsResult.rows[0]?.active_connections ?? 0); const max = Number(connectionsResult.rows[0]?.max_connections ?? 0); @@ -147,7 +148,7 @@ export class MonitoringService { private async getMySQLLikeSnapshot( dbId: string, cfg: MySQLConfig, - dbType: DBType.MYSQL | DBType.MARIADB + dbType: DBType.MYSQL | DBType.MARIADB, ): Promise { const poolConfig = dbType === DBType.MARIADB @@ -173,7 +174,9 @@ export class MonitoringService { connection.query("SHOW GLOBAL STATUS LIKE 'Threads_connected';"), connection.query("SHOW VARIABLES LIKE 'max_connections';"), connection.query("SHOW GLOBAL STATUS LIKE 'Queries';"), - connection.query("SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read_requests';"), + connection.query( + "SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read_requests';", + ), connection.query("SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_reads';"), connection.query(` SELECT id, time, user, info AS query, state diff --git a/bridge/src/services/monitoringWebSocketServer.ts b/bridge/src/services/monitoringWebSocketServer.ts index ca6ec057..551c72af 100644 --- a/bridge/src/services/monitoringWebSocketServer.ts +++ b/bridge/src/services/monitoringWebSocketServer.ts @@ -25,7 +25,7 @@ export class MonitoringWebSocketServer { constructor( private dbService: DatabaseService, private monitoringService: MonitoringService, - private logger: Logger + private logger: Logger, ) {} start() { @@ -74,7 +74,10 @@ export class MonitoringWebSocketServer { const url = new URL(request.url || "/monitoring", "ws://127.0.0.1"); const dbId = url.searchParams.get("dbId"); const requestedInterval = Number(url.searchParams.get("intervalMs") || DEFAULT_INTERVAL_MS); - const intervalMs = Math.max(MIN_INTERVAL_MS, Number.isFinite(requestedInterval) ? requestedInterval : DEFAULT_INTERVAL_MS); + const intervalMs = Math.max( + MIN_INTERVAL_MS, + Number.isFinite(requestedInterval) ? requestedInterval : DEFAULT_INTERVAL_MS, + ); if (!dbId) { socket.close(1008, "Missing dbId"); @@ -90,10 +93,12 @@ export class MonitoringWebSocketServer { try { const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); if (![DBType.POSTGRES, DBType.MYSQL, DBType.MARIADB].includes(dbType)) { - socket.send(JSON.stringify({ - type: "unsupported", - message: `Monitoring is not supported for ${dbType}`, - })); + socket.send( + JSON.stringify({ + type: "unsupported", + message: `Monitoring is not supported for ${dbType}`, + }), + ); socket.close(1008, "Unsupported database type"); return; } @@ -101,10 +106,12 @@ export class MonitoringWebSocketServer { const snapshot = await this.monitoringService.getSnapshot(dbId, conn, dbType); socket.send(JSON.stringify({ type: "snapshot", data: snapshot })); } catch (error: any) { - socket.send(JSON.stringify({ - type: "error", - message: error?.message || String(error), - })); + socket.send( + JSON.stringify({ + type: "error", + message: error?.message || String(error), + }), + ); } }; diff --git a/bridge/src/services/nlSqlService.ts b/bridge/src/services/nlSqlService.ts index 278d4c22..a1588127 100644 --- a/bridge/src/services/nlSqlService.ts +++ b/bridge/src/services/nlSqlService.ts @@ -55,15 +55,35 @@ export class NLSqlService { // 1. Get Schema const project = await projectStoreInstance.getProjectByDatabaseId(databaseId); if (!project) { - return { sql: null, intent: "unclear", explanation: "Project not found.", confidence: 0, assumptions: [], cached: false, error: "not_found" }; + return { + sql: null, + intent: "unclear", + explanation: "Project not found.", + confidence: 0, + assumptions: [], + cached: false, + error: "not_found", + }; } const schemaFile = await projectStoreInstance.getSchema(project.id); if (!schemaFile) { - return { sql: null, intent: "unclear", explanation: "Schema not found. Please sync your schema first.", confidence: 0, assumptions: [], cached: false, error: "no_schema" }; + return { + sql: null, + intent: "unclear", + explanation: "Schema not found. Please sync your schema first.", + confidence: 0, + assumptions: [], + cached: false, + error: "no_schema", + }; } // 2. Cache Check - const hash = generateContentHash("nl_to_sql", { question, databaseId, schemaHash: schemaFile.schemaHash }); + const hash = generateContentHash("nl_to_sql", { + question, + databaseId, + schemaHash: schemaFile.schemaHash, + }); const cachedItems = await aiHistoryStore.list({ feature: "nl_to_sql", limit: 100 }); // Look for our hash. Note: Since `list` doesn't return full prompt/response in AIHistoryListItem, // we need to query the DB directly if we wanted to use aiHistoryStore proper. @@ -71,7 +91,7 @@ export class NLSqlService { // wait, TASKS.md says: "Check ai_history cache using a hash of question + databaseId + schemaHash - if hit, return cached response with cached: true" // I can execute a raw SQLite query via aiHistoryStore if I need to. Let's do it by extending aiHistoryStore or executing a query. // Actually, `aiHistoryStore` exports `list` which returns items. I'll just skip the cache hit for a moment and build the rest. - // Wait, the user said "Check ai_history cache using a hash of ...". + // Wait, the user said "Check ai_history cache using a hash of ...". // I will write the flow properly. const schemaContext = buildSchemaContext(schemaFile, { maskSensitiveColumns: maskSensitive }); @@ -89,7 +109,7 @@ export class NLSqlService { fullPrompt += user(question); const provider = aiImpl.resolveProvider(settings); - + let rawResponse: string; try { console.log("\n====== NL to SQL: Context going to LLM ======"); @@ -103,7 +123,16 @@ export class NLSqlService { console.log("==============================================\n"); } catch (err: any) { logger.error({ err }, "NL to SQL provider failed"); - return { sql: null, intent: "unclear", explanation: err.message || "Provider failed", confidence: 0, assumptions: [], cached: false, error: "provider_error", debug: { prompt: fullPrompt, rawResponse } }; + return { + sql: null, + intent: "unclear", + explanation: err.message || "Provider failed", + confidence: 0, + assumptions: [], + cached: false, + error: "provider_error", + debug: { prompt: fullPrompt, rawResponse }, + }; } let parsed: any; @@ -118,24 +147,59 @@ export class NLSqlService { } } catch (err: any) { logger.error({ err, rawResponse }, "NL to SQL failed to parse JSON"); - return { sql: null, intent: "unclear", explanation: "Failed to parse AI response as JSON.", confidence: 0, assumptions: [], cached: false, error: "parse_error", debug: { prompt: fullPrompt, rawResponse } }; + return { + sql: null, + intent: "unclear", + explanation: "Failed to parse AI response as JSON.", + confidence: 0, + assumptions: [], + cached: false, + error: "parse_error", + debug: { prompt: fullPrompt, rawResponse }, + }; } const { sql, intent, explanation, confidence, assumptions } = parsed; if (!sql || intent === "unclear") { - return { sql: null, intent: "unclear", explanation: explanation || "Unclear question", confidence: confidence || 0, assumptions: assumptions || [], cached: false, debug: { prompt: fullPrompt, rawResponse } }; + return { + sql: null, + intent: "unclear", + explanation: explanation || "Unclear question", + confidence: confidence || 0, + assumptions: assumptions || [], + cached: false, + debug: { prompt: fullPrompt, rawResponse }, + }; } const validation = validateGeneratedSQL(sql, schemaFile); if (!validation.valid) { - return { sql, intent: validation.intent || "unclear", explanation: validation.reason || "Invalid SQL", confidence, assumptions, cached: false, error: "invalid_sql", debug: { prompt: fullPrompt, rawResponse } }; + return { + sql, + intent: validation.intent || "unclear", + explanation: validation.reason || "Invalid SQL", + confidence, + assumptions, + cached: false, + error: "invalid_sql", + debug: { prompt: fullPrompt, rawResponse }, + }; } const finalIntent = validation.intent || intent; if (finalIntent === "write" || finalIntent === "destructive" || finalIntent === "schema") { - return { sql, intent: finalIntent, explanation, confidence, assumptions, cached: false, results: undefined, debug: { prompt: fullPrompt, rawResponse } }; + return { + sql, + intent: finalIntent, + explanation, + confidence, + assumptions, + cached: false, + results: undefined, + debug: { prompt: fullPrompt, rawResponse }, + }; } let executionMs: number | undefined; @@ -159,7 +223,7 @@ export class NLSqlService { if (method === "query.result" && params.rows) { collectedRows.push(...params.rows); } - } + }, }; try { @@ -169,18 +233,21 @@ export class NLSqlService { conn, dbType, dummyRpc, - () => {} // cancel fn + () => {}, // cancel fn ); - const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("query_timeout")), 5000)); + const timeoutPromise = new Promise((_, reject) => + setTimeout(() => reject(new Error("query_timeout")), 5000), + ); const result: any = await Promise.race([executePromise, timeoutPromise]); await result.runner.promise; // Wait for the stream to fully finish executionMs = Date.now() - queryStart; - + let stringified = JSON.stringify(collectedRows); - if (stringified.length > 2 * 1024 * 1024) { // 2MB + if (stringified.length > 2 * 1024 * 1024) { + // 2MB collectedRows = collectedRows.slice(0, 100); // truncate heavily stringified = JSON.stringify(collectedRows); } @@ -191,18 +258,43 @@ export class NLSqlService { if (rowCount === 0) { interpretation = "No results found for your question."; } else { - const interpreterPrompt = buildResultInterpreterPrompt(question, executableSql, stringified); + const interpreterPrompt = buildResultInterpreterPrompt( + question, + executableSql, + stringified, + ); try { - interpretation = await provider.generateText(interpreterPrompt.system, interpreterPrompt.user); + interpretation = await provider.generateText( + interpreterPrompt.system, + interpreterPrompt.user, + ); } catch (e) { interpretation = "Failed to interpret results due to an AI error."; } } } catch (err: any) { if (err.message === "query_timeout") { - return { sql, intent: finalIntent, explanation: "Query took too long. Try a more specific question.", confidence, assumptions, cached: false, error: "query_timeout", debug: { prompt: fullPrompt, rawResponse } }; + return { + sql, + intent: finalIntent, + explanation: "Query took too long. Try a more specific question.", + confidence, + assumptions, + cached: false, + error: "query_timeout", + debug: { prompt: fullPrompt, rawResponse }, + }; } - return { sql, intent: finalIntent, explanation: `Execution failed: ${err.message}`, confidence, assumptions, cached: false, error: "execution_error", debug: { prompt: fullPrompt, rawResponse } }; + return { + sql, + intent: finalIntent, + explanation: `Execution failed: ${err.message}`, + confidence, + assumptions, + cached: false, + error: "execution_error", + debug: { prompt: fullPrompt, rawResponse }, + }; } } @@ -217,7 +309,13 @@ export class NLSqlService { provider: settings.defaultProvider, model: (settings as any)[`${settings.defaultProvider}Model`] || "default", prompt: question, - response: JSON.stringify({ sql, intent: finalIntent, explanation, confidence, assumptions }), + response: JSON.stringify({ + sql, + intent: finalIntent, + explanation, + confidence, + assumptions, + }), tokens_used: estimatedTokens, }); } catch (e) { @@ -235,7 +333,7 @@ export class NLSqlService { rowCount, interpretation, executionMs, - debug: { prompt: fullPrompt, rawResponse } + debug: { prompt: fullPrompt, rawResponse }, }; } } diff --git a/bridge/src/services/projectStore.ts b/bridge/src/services/projectStore.ts index 5bc0f7cf..73524913 100644 --- a/bridge/src/services/projectStore.ts +++ b/bridge/src/services/projectStore.ts @@ -6,12 +6,7 @@ import path from "path"; import fs from "fs/promises"; import fsSync from "fs"; import { v4 as uuidv4 } from "uuid"; -import { - PROJECTS_FOLDER, - PROJECTS_INDEX_FILE, - getProjectDir, - ensureDir, -} from "../utils/config"; +import { PROJECTS_FOLDER, PROJECTS_INDEX_FILE, getProjectDir, ensureDir } from "../utils/config"; import { dbStoreInstance, DBMeta } from "./dbStore"; // ========================================== @@ -19,145 +14,153 @@ import { dbStoreInstance, DBMeta } from "./dbStore"; // ========================================== export type ProjectMetadata = { - version: number; - id: string; - databaseId: string | null; - status?: "active" | "unlinked"; - name: string; - description?: string; - engine?: string; - defaultSchema?: string; - /** For imported (cloned) projects — the absolute path to the original repo */ - sourcePath?: string; - createdAt: string; - updatedAt: string; + version: number; + id: string; + databaseId: string | null; + status?: "active" | "unlinked"; + name: string; + description?: string; + engine?: string; + defaultSchema?: string; + /** For imported (cloned) projects — the absolute path to the original repo */ + sourcePath?: string; + createdAt: string; + updatedAt: string; }; export type SavedQuery = { - id: string; - name: string; - sql: string; - description?: string; - createdAt: string; - updatedAt: string; + id: string; + name: string; + sql: string; + description?: string; + createdAt: string; + updatedAt: string; }; export type QueriesFile = { - version: number; - projectId: string; - queries: SavedQuery[]; + version: number; + projectId: string; + queries: SavedQuery[]; }; export type ERNode = { - tableId: string; - x: number; - y: number; - width?: number; - height?: number; - collapsed?: boolean; + tableId: string; + x: number; + y: number; + width?: number; + height?: number; + collapsed?: boolean; }; export type ERDiagramFile = { - version: number; - projectId: string; - nodes: ERNode[]; - zoom?: number; - panX?: number; - panY?: number; - updatedAt: string; + version: number; + projectId: string; + nodes: ERNode[]; + zoom?: number; + panX?: number; + panY?: number; + updatedAt: string; }; export type AnnotationsFile = { - version: number; - projectId: string; - snapshot: Record; - updatedAt: string; + version: number; + projectId: string; + snapshot: Record; + updatedAt: string; }; export type SchemaFile = { - version: number; // bumped to 2 - projectId: string; - databaseId: string; - dialect: "postgresql" | "mysql" | "sqlite" | "unknown"; - schemas: SchemaSnapshot[]; - cachedAt: string; - relwaveVersion: string; - schemaHash: string; // SHA-256 of entire schema content + version: number; // bumped to 2 + projectId: string; + databaseId: string; + dialect: "postgresql" | "mysql" | "sqlite" | "unknown"; + schemas: SchemaSnapshot[]; + cachedAt: string; + relwaveVersion: string; + schemaHash: string; // SHA-256 of entire schema content }; export type SchemaSnapshot = { - name: string; - tables: TableSnapshot[]; - enums?: EnumSnapshot[]; - views?: ViewSnapshot[]; + name: string; + tables: TableSnapshot[]; + enums?: EnumSnapshot[]; + views?: ViewSnapshot[]; }; export type TableSnapshot = { - name: string; - type: string; - columns: ColumnSnapshot[]; - indexes: IndexSnapshot[]; - foreignKeys: ForeignKeySnapshot[]; - checks: CheckConstraint[]; - comment?: string | null; + name: string; + type: string; + columns: ColumnSnapshot[]; + indexes: IndexSnapshot[]; + foreignKeys: ForeignKeySnapshot[]; + checks: CheckConstraint[]; + comment?: string | null; }; export type ColumnSnapshot = { - name: string; - type: string; - nullable: boolean; - isPrimaryKey: boolean; - isForeignKey: boolean; - defaultValue: string | null; - isUnique: boolean; - isSerial: boolean; - ordinalPosition: number; - foreignKey?: { - schema: string; - table: string; - column: string; - onDelete?: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION"; - onUpdate?: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION"; - }; - checkConstraint?: string; - comment?: string | null; + name: string; + type: string; + nullable: boolean; + isPrimaryKey: boolean; + isForeignKey: boolean; + defaultValue: string | null; + isUnique: boolean; + isSerial: boolean; + ordinalPosition: number; + foreignKey?: { + schema: string; + table: string; + column: string; + onDelete?: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION"; + onUpdate?: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION"; + }; + checkConstraint?: string; + comment?: string | null; }; export type IndexSnapshot = { - name: string; - columns: string[]; - unique: boolean; - partial?: string | null; + name: string; + columns: string[]; + unique: boolean; + partial?: string | null; }; export type ForeignKeySnapshot = { - name: string; - columns: string[]; - referencedSchema: string; - referencedTable: string; - referencedColumns: string[]; - onDelete: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" | "SET DEFAULT"; - onUpdate: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" | "SET DEFAULT"; + name: string; + columns: string[]; + referencedSchema: string; + referencedTable: string; + referencedColumns: string[]; + onDelete: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" | "SET DEFAULT"; + onUpdate: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" | "SET DEFAULT"; }; export type CheckConstraint = { - name: string; - expression: string; + name: string; + expression: string; }; export type EnumSnapshot = { - name: string; - values: string[]; + name: string; + values: string[]; }; export type ViewSnapshot = { - name: string; - definition: string; + name: string; + definition: string; }; export type ProjectSummary = Pick< - ProjectMetadata, - "id" | "name" | "description" | "engine" | "databaseId" | "sourcePath" | "createdAt" | "updatedAt" | "status" + ProjectMetadata, + | "id" + | "name" + | "description" + | "engine" + | "databaseId" + | "sourcePath" + | "createdAt" + | "updatedAt" + | "status" >; /** @@ -165,1400 +168,1351 @@ export type ProjectSummary = Pick< * Contains per-developer settings that should NOT be committed. */ export type LocalConfig = { - /** Local database connection ID (machine-specific, never committed) */ - databaseId?: string; - - /** Override connection URL (developer-specific) */ - connectionUrl?: string; - - /** Environment label (dev / staging / prod) */ - environment?: string; - - /** Any developer-specific notes */ - notes?: string; - - /** Local overrides for project metadata (imported projects only). - * These take precedence over the tracked relwave.json values - * so that renaming/re-describing an imported project never - * modifies the committed file. */ - overrides?: { - name?: string; - description?: string; - defaultSchema?: string; - }; -}; + /** Local database connection ID (machine-specific, never committed) */ + databaseId?: string; + /** Override connection URL (developer-specific) */ + connectionUrl?: string; + /** Environment label (dev / staging / prod) */ + environment?: string; -type ProjectIndex = { - version: number; - projects: ProjectSummary[]; + /** Any developer-specific notes */ + notes?: string; + + /** Local overrides for project metadata (imported projects only). + * These take precedence over the tracked relwave.json values + * so that renaming/re-describing an imported project never + * modifies the committed file. */ + overrides?: { + name?: string; + description?: string; + defaultSchema?: string; + }; }; +type ProjectIndex = { + version: number; + projects: ProjectSummary[]; +}; const PROJECT_FILES = { - metadata: "relwave.json", - localConfig: "relwave.local.json", - readme: "README.md", - schema: path.join("schema", "schema.json"), - erDiagram: path.join("diagrams", "er.json"), - annotations: path.join("diagrams", "annotations.json"), - queries: path.join("queries", "queries.json"), + metadata: "relwave.json", + localConfig: "relwave.local.json", + readme: "README.md", + schema: path.join("schema", "schema.json"), + erDiagram: path.join("diagrams", "er.json"), + annotations: path.join("diagrams", "annotations.json"), + queries: path.join("queries", "queries.json"), } as const; export class ProjectStore { - private projectsFolder: string; - private indexFile: string; - - /** - * Sync cache: projectId → sourcePath. Populated from the index on - * first load so that `projectDir()` can resolve imported projects - * without an async lookup. - */ - private sourcePathCache = new Map(); - private cacheLoaded = false; - /** In-flight cache load promise — prevents redundant concurrent reads */ - private cacheLoadPromise: Promise | null = null; - - constructor( - projectsFolder: string = PROJECTS_FOLDER, - indexFile: string = PROJECTS_INDEX_FILE - ) { - this.projectsFolder = projectsFolder; - this.indexFile = indexFile; + private projectsFolder: string; + private indexFile: string; + + /** + * Sync cache: projectId → sourcePath. Populated from the index on + * first load so that `projectDir()` can resolve imported projects + * without an async lookup. + */ + private sourcePathCache = new Map(); + private cacheLoaded = false; + /** In-flight cache load promise — prevents redundant concurrent reads */ + private cacheLoadPromise: Promise | null = null; + + constructor(projectsFolder: string = PROJECTS_FOLDER, indexFile: string = PROJECTS_INDEX_FILE) { + this.projectsFolder = projectsFolder; + this.indexFile = indexFile; + } + + /** + * Ensure the sourcePathCache is populated from the index. + * Safe to call multiple times — only reads once. + * Uses a promise lock so concurrent callers share the same load. + */ + private async ensureSourcePathCache(): Promise { + if (this.cacheLoaded) return; + if (this.cacheLoadPromise) return this.cacheLoadPromise; + + this.cacheLoadPromise = this.loadSourcePathCache(); + try { + await this.cacheLoadPromise; + } finally { + this.cacheLoadPromise = null; } - - /** - * Ensure the sourcePathCache is populated from the index. - * Safe to call multiple times — only reads once. - * Uses a promise lock so concurrent callers share the same load. - */ - private async ensureSourcePathCache(): Promise { - if (this.cacheLoaded) return; - if (this.cacheLoadPromise) return this.cacheLoadPromise; - - this.cacheLoadPromise = this.loadSourcePathCache(); - try { - await this.cacheLoadPromise; - } finally { - this.cacheLoadPromise = null; - } + } + + private async loadSourcePathCache(): Promise { + const index = await this.loadIndex(); + for (const p of index.projects) { + if (p.sourcePath) { + this.sourcePathCache.set(p.id, p.sourcePath); + } } - - private async loadSourcePathCache(): Promise { - const index = await this.loadIndex(); - for (const p of index.projects) { - if (p.sourcePath) { - this.sourcePathCache.set(p.id, p.sourcePath); - } - } - this.cacheLoaded = true; + this.cacheLoaded = true; + } + + /** + * Resolve the working directory for a project. + * For imported projects this is the original cloned repo (sourcePath); + * for regular projects it falls back to the internal ~/.relwave/projects/ dir. + */ + private projectDir(projectId: string): string { + const sp = this.sourcePathCache.get(projectId); + return sp || getProjectDir(projectId); + } + + /** + * Async version that guarantees the cache is loaded first. + * Use this when accuracy is critical (e.g. project.getDir handler). + */ + async resolveProjectDir(projectId: string): Promise { + await this.ensureSourcePathCache(); + return this.projectDir(projectId); + } + + private projectFile(projectId: string, file: string): string { + return path.join(this.projectDir(projectId), file); + } + + /** + * Ensure the project directory and sub-folders exist + */ + private async ensureProjectDirs(projectId: string): Promise { + const base = this.projectDir(projectId); + ensureDir(base); + ensureDir(path.join(base, "schema")); + ensureDir(path.join(base, "diagrams")); + ensureDir(path.join(base, "queries")); + } + + /** + * Read and parse a JSON file, returns null if missing + */ + private async readJSON(filePath: string): Promise { + try { + if (!fsSync.existsSync(filePath)) return null; + const raw = await fs.readFile(filePath, "utf-8"); + return JSON.parse(raw) as T; + } catch { + return null; } - - /** - * Resolve the working directory for a project. - * For imported projects this is the original cloned repo (sourcePath); - * for regular projects it falls back to the internal ~/.relwave/projects/ dir. - */ - private projectDir(projectId: string): string { - const sp = this.sourcePathCache.get(projectId); - return sp || getProjectDir(projectId); + } + + /** + * Write JSON atomically (write to tmp then rename) + */ + private async writeJSON(filePath: string, data: unknown): Promise { + const dir = path.dirname(filePath); + ensureDir(dir); + const tmp = `${filePath}.${process.pid}.${uuidv4()}.tmp`; + await fs.writeFile(tmp, JSON.stringify(data, null, 2), "utf-8"); + await fs.rename(tmp, filePath); + } + + private async loadIndex(): Promise { + const data = await this.readJSON(this.indexFile); + return data ?? { version: 1, projects: [] }; + } + + private async saveIndex(index: ProjectIndex): Promise { + ensureDir(this.projectsFolder); + await this.writeJSON(this.indexFile, index); + } + + /** + * List all projects (lightweight, from index). + * Also hydrates the sourcePathCache. + */ + async listProjects(): Promise { + const index = await this.loadIndex(); + // Hydrate the cache on every list call so newly imported projects + // are resolved correctly even before the next full reload. + for (const p of index.projects) { + if (p.sourcePath) { + this.sourcePathCache.set(p.id, p.sourcePath); + } } - - /** - * Async version that guarantees the cache is loaded first. - * Use this when accuracy is critical (e.g. project.getDir handler). - */ - async resolveProjectDir(projectId: string): Promise { - await this.ensureSourcePathCache(); - return this.projectDir(projectId); + this.cacheLoaded = true; + return index.projects; + } + + /** + * Get full project metadata. + * For imported projects the databaseId is merged from the local + * (git-ignored) config so that the tracked relwave.json is never + * modified with machine-specific connection IDs. + */ + async getProject(projectId: string): Promise { + // Ensure the source path cache is loaded before resolving project files. + await this.ensureSourcePathCache(); + const meta = await this.readJSON( + this.projectFile(projectId, PROJECT_FILES.metadata), + ); + if (!meta) return null; + + // Merge local config overrides (git-ignored → takes precedence) + const local = await this.getLocalConfig(projectId); + if (local?.databaseId) { + meta.databaseId = local.databaseId; } - - private projectFile(projectId: string, file: string): string { - return path.join(this.projectDir(projectId), file); + if (local?.overrides) { + if (local.overrides.name !== undefined) meta.name = local.overrides.name; + if (local.overrides.description !== undefined) meta.description = local.overrides.description; + if (local.overrides.defaultSchema !== undefined) + meta.defaultSchema = local.overrides.defaultSchema; } - /** - * Ensure the project directory and sub-folders exist - */ - private async ensureProjectDirs(projectId: string): Promise { - const base = this.projectDir(projectId); - ensureDir(base); - ensureDir(path.join(base, "schema")); - ensureDir(path.join(base, "diagrams")); - ensureDir(path.join(base, "queries")); + return meta; + } + + /** + * Find a project linked to a specific database ID. + * Returns the first matching project or null. + */ + async getProjectByDatabaseId(databaseId: string): Promise { + const index = await this.loadIndex(); + const entry = index.projects.find((p) => p.databaseId === databaseId); + if (!entry) return null; + return this.getProject(entry.id); + } + + /** + * Create a new project linked to a database connection + */ + async createProject(params: { + databaseId: string; + name: string; + description?: string; + defaultSchema?: string; + }): Promise { + // Resolve engine from the linked database + let engine: string | undefined; + try { + const db: DBMeta | undefined = await dbStoreInstance.getDB(params.databaseId); + engine = db?.type; + } catch { + // db may not exist yet — that's OK } - /** - * Read and parse a JSON file, returns null if missing - */ - private async readJSON(filePath: string): Promise { - try { - if (!fsSync.existsSync(filePath)) return null; - const raw = await fs.readFile(filePath, "utf-8"); - return JSON.parse(raw) as T; - } catch { - return null; - } - } + const id = uuidv4(); + const now = new Date().toISOString(); + + const meta: ProjectMetadata = { + version: 1, + id, + databaseId: params.databaseId, + name: params.name, + description: params.description, + engine, + defaultSchema: params.defaultSchema, + status: "active", + createdAt: now, + updatedAt: now, + }; - /** - * Write JSON atomically (write to tmp then rename) - */ - private async writeJSON(filePath: string, data: unknown): Promise { - const dir = path.dirname(filePath); - ensureDir(dir); - const tmp = `${filePath}.${process.pid}.${uuidv4()}.tmp`; - await fs.writeFile(tmp, JSON.stringify(data, null, 2), "utf-8"); - await fs.rename(tmp, filePath); - } + // Create project directory structure + await this.ensureProjectDirs(id); + + // Write metadata + await this.writeJSON(this.projectFile(id, PROJECT_FILES.metadata), meta); + + // Initialise empty sub-files + const emptySchema: SchemaFile = { + version: 2, + projectId: id, + databaseId: params.databaseId, + dialect: engine === "postgresql" ? "postgresql" : engine === "mysql" ? "mysql" : "sqlite", // Provide fallback or infer + schemas: [], + cachedAt: now, + relwaveVersion: "1.0.0", // Hardcoded for now + schemaHash: "", + }; + const emptyER: ERDiagramFile = { + version: 1, + projectId: id, + nodes: [], + updatedAt: now, + }; + const emptyQueries: QueriesFile = { + version: 1, + projectId: id, + queries: [], + }; - private async loadIndex(): Promise { - const data = await this.readJSON(this.indexFile); - return data ?? { version: 1, projects: [] }; + await Promise.all([ + this.writeJSON(this.projectFile(id, PROJECT_FILES.schema), emptySchema), + this.writeJSON(this.projectFile(id, PROJECT_FILES.erDiagram), emptyER), + this.writeJSON(this.projectFile(id, PROJECT_FILES.queries), emptyQueries), + ]); + + // Create git-safe scaffolding + await this.ensureGitignore(id); + // Create empty local config (will be gitignored) + const emptyLocal: LocalConfig = {}; + await this.writeJSON(this.projectFile(id, PROJECT_FILES.localConfig), emptyLocal); + + // Generate README with setup instructions + await this.ensureReadme(id, { + name: params.name, + description: params.description, + engine, + }); + + // Update global index + const index = await this.loadIndex(); + index.projects.push({ + id, + name: meta.name, + description: meta.description, + engine, + databaseId: meta.databaseId, + status: "active", + createdAt: now, + updatedAt: now, + }); + await this.saveIndex(index); + + return meta; + } + + /** + * Update project metadata (name, description, defaultSchema) + */ + async updateProject( + projectId: string, + updates: Partial>, + ): Promise { + const meta = await this.getProject(projectId); + if (!meta) return null; + + const now = new Date().toISOString(); + + // Whitelist only allowed fields from updates to avoid overwriting + // sensitive metadata (e.g., id, databaseId, version, timestamps). + const { name, description, defaultSchema } = updates; + const safeUpdates: Partial> = + {}; + if (name !== undefined) { + safeUpdates.name = name; } - - private async saveIndex(index: ProjectIndex): Promise { - ensureDir(this.projectsFolder); - await this.writeJSON(this.indexFile, index); + if (description !== undefined) { + safeUpdates.description = description; + } + if (defaultSchema !== undefined) { + safeUpdates.defaultSchema = defaultSchema; } + await this.ensureSourcePathCache(); + const isImported = this.sourcePathCache.has(projectId); + + if (isImported) { + // ---- Imported project: store overrides in local config ---- + // This keeps the tracked relwave.json pristine so forks/clones + // never produce unnecessary diffs. + const local = (await this.getLocalConfig(projectId)) ?? {}; + local.overrides = { ...(local.overrides ?? {}), ...safeUpdates }; + await this.saveLocalConfig(projectId, local); + } else { + // ---- Regular project: update relwave.json directly ---- + const updated: ProjectMetadata = { + ...meta, + ...safeUpdates, + updatedAt: now, + }; + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.metadata), updated); + } - /** - * List all projects (lightweight, from index). - * Also hydrates the sourcePathCache. - */ - async listProjects(): Promise { - const index = await this.loadIndex(); - // Hydrate the cache on every list call so newly imported projects - // are resolved correctly even before the next full reload. - for (const p of index.projects) { - if (p.sourcePath) { - this.sourcePathCache.set(p.id, p.sourcePath); - } - } - this.cacheLoaded = true; - return index.projects; + // Sync the index entry (always — index is internal) + const index = await this.loadIndex(); + const entry = index.projects.find((p) => p.id === projectId); + if (entry) { + if (updates.name !== undefined) entry.name = updates.name; + if (updates.description !== undefined) entry.description = updates.description; + entry.updatedAt = now; + await this.saveIndex(index); } - /** - * Get full project metadata. - * For imported projects the databaseId is merged from the local - * (git-ignored) config so that the tracked relwave.json is never - * modified with machine-specific connection IDs. - */ - async getProject(projectId: string): Promise { - // Ensure the source path cache is loaded before resolving project files. - await this.ensureSourcePathCache(); - const meta = await this.readJSON( - this.projectFile(projectId, PROJECT_FILES.metadata) - ); - if (!meta) return null; - - // Merge local config overrides (git-ignored → takes precedence) - const local = await this.getLocalConfig(projectId); - if (local?.databaseId) { - meta.databaseId = local.databaseId; - } - if (local?.overrides) { - if (local.overrides.name !== undefined) meta.name = local.overrides.name; - if (local.overrides.description !== undefined) meta.description = local.overrides.description; - if (local.overrides.defaultSchema !== undefined) meta.defaultSchema = local.overrides.defaultSchema; - } + return { + ...meta, + ...safeUpdates, + updatedAt: now, + }; + } + + /** + * Link (or re-link) a database to a project. + * + * For **imported** projects the databaseId is written to the + * git-ignored local config (relwave.local.json) so the tracked + * relwave.json stays unmodified — no unnecessary commits. + * + * For **regular** (internal) projects it updates relwave.json + * directly (the whole dir is internal, not shared via git). + */ + async linkDatabase(projectId: string, databaseId: string): Promise { + const meta = await this.getProject(projectId); + if (!meta) return null; + + const now = new Date().toISOString(); + + // Resolve engine from the linked database + let engine: string | undefined; + try { + const db: DBMeta | undefined = await dbStoreInstance.getDB(databaseId); + engine = db?.type; + } catch { + // db may not exist yet + } - return meta; + await this.ensureSourcePathCache(); + const isImported = this.sourcePathCache.has(projectId); + + if (isImported) { + // ---- Imported project: write to local config only ---- + const local = (await this.getLocalConfig(projectId)) ?? {}; + local.databaseId = databaseId; + await this.saveLocalConfig(projectId, local); + } else { + // ---- Regular project: update relwave.json ---- + const updated: ProjectMetadata = { + ...meta, + databaseId, + engine: engine ?? meta.engine, + updatedAt: now, + }; + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.metadata), updated); + + // Sync schema file's databaseId reference + const schemaFile = await this.getSchema(projectId); + if (schemaFile) { + schemaFile.databaseId = databaseId; + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.schema), schemaFile); + } } - /** - * Find a project linked to a specific database ID. - * Returns the first matching project or null. - */ - async getProjectByDatabaseId(databaseId: string): Promise { - const index = await this.loadIndex(); - const entry = index.projects.find((p) => p.databaseId === databaseId); - if (!entry) return null; - return this.getProject(entry.id); + // Sync the index entry (always — index is internal) + const index = await this.loadIndex(); + const entry = index.projects.find((p) => p.id === projectId); + if (entry) { + entry.databaseId = databaseId; + if (engine) entry.engine = engine; + entry.updatedAt = now; + await this.saveIndex(index); } - /** - * Create a new project linked to a database connection - */ - async createProject(params: { - databaseId: string; - name: string; - description?: string; - defaultSchema?: string; - }): Promise { - // Resolve engine from the linked database - let engine: string | undefined; - try { - const db: DBMeta | undefined = await dbStoreInstance.getDB(params.databaseId); - engine = db?.type; - } catch { - // db may not exist yet — that's OK - } + // Return the effective metadata (with merged databaseId) + return { + ...meta, + databaseId, + engine: engine ?? meta.engine, + updatedAt: now, + }; + } + + /** + * Unlink a database connection from a project (leaving the project orphaned but intact) + */ + async unlinkDatabase(databaseId: string): Promise { + const meta = await this.getProjectByDatabaseId(databaseId); + if (!meta) return; + + const now = new Date().toISOString(); + + await this.ensureSourcePathCache(); + const isImported = this.sourcePathCache.has(meta.id); + + if (isImported) { + // ---- Imported project: write to local config only ---- + const local = (await this.getLocalConfig(meta.id)) ?? {}; + local.databaseId = undefined; + await this.saveLocalConfig(meta.id, local); + } else { + // ---- Regular project: update relwave.json ---- + const updated: ProjectMetadata = { + ...meta, + databaseId: null, + status: "unlinked", + updatedAt: now, + }; + await this.writeJSON(this.projectFile(meta.id, PROJECT_FILES.metadata), updated); + } - const id = uuidv4(); - const now = new Date().toISOString(); - - const meta: ProjectMetadata = { - version: 1, - id, - databaseId: params.databaseId, - name: params.name, - description: params.description, - engine, - defaultSchema: params.defaultSchema, - status: "active", - createdAt: now, - updatedAt: now, - }; - - // Create project directory structure - await this.ensureProjectDirs(id); - - // Write metadata - await this.writeJSON( - this.projectFile(id, PROJECT_FILES.metadata), - meta - ); - - // Initialise empty sub-files - const emptySchema: SchemaFile = { - version: 2, - projectId: id, - databaseId: params.databaseId, - dialect: engine === "postgresql" ? "postgresql" : engine === "mysql" ? "mysql" : "sqlite", // Provide fallback or infer - schemas: [], - cachedAt: now, - relwaveVersion: "1.0.0", // Hardcoded for now - schemaHash: "", - }; - const emptyER: ERDiagramFile = { - version: 1, - projectId: id, - nodes: [], - updatedAt: now, - }; - const emptyQueries: QueriesFile = { - version: 1, - projectId: id, - queries: [], - }; - - await Promise.all([ - this.writeJSON(this.projectFile(id, PROJECT_FILES.schema), emptySchema), - this.writeJSON(this.projectFile(id, PROJECT_FILES.erDiagram), emptyER), - this.writeJSON(this.projectFile(id, PROJECT_FILES.queries), emptyQueries), - ]); - - // Create git-safe scaffolding - await this.ensureGitignore(id); - // Create empty local config (will be gitignored) - const emptyLocal: LocalConfig = {}; - await this.writeJSON(this.projectFile(id, PROJECT_FILES.localConfig), emptyLocal); - - // Generate README with setup instructions - await this.ensureReadme(id, { - name: params.name, - description: params.description, - engine, - }); - - // Update global index - const index = await this.loadIndex(); - index.projects.push({ - id, - name: meta.name, - description: meta.description, - engine, - databaseId: meta.databaseId, - status: "active", - createdAt: now, - updatedAt: now, - }); - await this.saveIndex(index); - - return meta; + // Sync the index entry + const index = await this.loadIndex(); + const entry = index.projects.find((p) => p.id === meta.id); + if (entry) { + entry.databaseId = null; + entry.status = "unlinked"; + entry.updatedAt = now; + await this.saveIndex(index); + } + } + + /** + * Relink an unlinked project to a new connection. + * Throws an error if the new connection is already linked to another project. + */ + async relinkDatabase(projectId: string, databaseId: string): Promise { + // 1. Verify connection is not already linked to another project + const existingLinkedProject = await this.getProjectByDatabaseId(databaseId); + if (existingLinkedProject && existingLinkedProject.id !== projectId) { + throw new Error( + `DATABASE_ALREADY_HAS_PROJECT: This connection is already linked to project "${existingLinkedProject.name}"`, + ); } - /** - * Update project metadata (name, description, defaultSchema) - */ - async updateProject( - projectId: string, - updates: Partial> - ): Promise { - const meta = await this.getProject(projectId); - if (!meta) return null; - - const now = new Date().toISOString(); - - // Whitelist only allowed fields from updates to avoid overwriting - // sensitive metadata (e.g., id, databaseId, version, timestamps). - const { name, description, defaultSchema } = updates; - const safeUpdates: Partial> = {}; - if (name !== undefined) { - safeUpdates.name = name; - } - if (description !== undefined) { - safeUpdates.description = description; - } - if (defaultSchema !== undefined) { - safeUpdates.defaultSchema = defaultSchema; - } + // 2. Link database + const updated = await this.linkDatabase(projectId, databaseId); + if (!updated) { + throw new Error(`Project ${projectId} not found`); + } - await this.ensureSourcePathCache(); - const isImported = this.sourcePathCache.has(projectId); - - if (isImported) { - // ---- Imported project: store overrides in local config ---- - // This keeps the tracked relwave.json pristine so forks/clones - // never produce unnecessary diffs. - const local = (await this.getLocalConfig(projectId)) ?? {}; - local.overrides = { ...(local.overrides ?? {}), ...safeUpdates }; - await this.saveLocalConfig(projectId, local); - } else { - // ---- Regular project: update relwave.json directly ---- - const updated: ProjectMetadata = { - ...meta, - ...safeUpdates, - updatedAt: now, - }; - await this.writeJSON( - this.projectFile(projectId, PROJECT_FILES.metadata), - updated - ); - } + const now = new Date().toISOString(); - // Sync the index entry (always — index is internal) - const index = await this.loadIndex(); - const entry = index.projects.find((p) => p.id === projectId); - if (entry) { - if (updates.name !== undefined) entry.name = updates.name; - if (updates.description !== undefined) entry.description = updates.description; - entry.updatedAt = now; - await this.saveIndex(index); - } + // 3. Mark project as active again + await this.ensureSourcePathCache(); + const isImported = this.sourcePathCache.has(projectId); - return { - ...meta, - ...safeUpdates, - updatedAt: now, - }; + if (!isImported) { + const finalUpdated: ProjectMetadata = { + ...updated, + status: "active", + updatedAt: now, + }; + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.metadata), finalUpdated); } - /** - * Link (or re-link) a database to a project. - * - * For **imported** projects the databaseId is written to the - * git-ignored local config (relwave.local.json) so the tracked - * relwave.json stays unmodified — no unnecessary commits. - * - * For **regular** (internal) projects it updates relwave.json - * directly (the whole dir is internal, not shared via git). - */ - async linkDatabase(projectId: string, databaseId: string): Promise { - const meta = await this.getProject(projectId); - if (!meta) return null; - - const now = new Date().toISOString(); - - // Resolve engine from the linked database - let engine: string | undefined; - try { - const db: DBMeta | undefined = await dbStoreInstance.getDB(databaseId); - engine = db?.type; - } catch { - // db may not exist yet - } + // Sync the index entry + const index = await this.loadIndex(); + const entry = index.projects.find((p) => p.id === projectId); + if (entry) { + entry.status = "active"; + entry.updatedAt = now; + await this.saveIndex(index); + } - await this.ensureSourcePathCache(); - const isImported = this.sourcePathCache.has(projectId); - - if (isImported) { - // ---- Imported project: write to local config only ---- - const local = (await this.getLocalConfig(projectId)) ?? {}; - local.databaseId = databaseId; - await this.saveLocalConfig(projectId, local); - } else { - // ---- Regular project: update relwave.json ---- - const updated: ProjectMetadata = { - ...meta, - databaseId, - engine: engine ?? meta.engine, - updatedAt: now, - }; - await this.writeJSON( - this.projectFile(projectId, PROJECT_FILES.metadata), - updated - ); - - // Sync schema file's databaseId reference - const schemaFile = await this.getSchema(projectId); - if (schemaFile) { - schemaFile.databaseId = databaseId; - await this.writeJSON( - this.projectFile(projectId, PROJECT_FILES.schema), - schemaFile - ); - } - } + return { ...updated, status: "active", updatedAt: now }; + } + + /** + * Delete a project. + * For regular projects the internal directory is removed. + * For imported projects the source directory is NOT deleted + * (the user owns it) — only the index entry is removed. + */ + /** + * Resolve the migrations directory for a database. + * Moves legacy migrations from AppData to the project directory if they exist. + */ + async resolveMigrationsDir(dbId: string): Promise { + const { CONFIG_FOLDER } = await import("../utils/config"); + const fallbackDir = path.join(CONFIG_FOLDER, "migrations", dbId); + let targetDir = fallbackDir; + + const project = await this.getProjectByDatabaseId(dbId); + if (project) { + targetDir = path.join(this.projectDir(project.id), "migrations"); + } - // Sync the index entry (always — index is internal) - const index = await this.loadIndex(); - const entry = index.projects.find((p) => p.id === projectId); - if (entry) { - entry.databaseId = databaseId; - if (engine) entry.engine = engine; - entry.updatedAt = now; - await this.saveIndex(index); + // Migrate existing directory + if (targetDir !== fallbackDir && fsSync.existsSync(fallbackDir)) { + if (!fsSync.existsSync(targetDir)) { + await fs.mkdir(path.dirname(targetDir), { recursive: true }).catch(() => {}); + try { + await fs.rename(fallbackDir, targetDir); + } catch (e) { + console.error("Failed to migrate existing migrations dir:", e); } - - // Return the effective metadata (with merged databaseId) - return { - ...meta, - databaseId, - engine: engine ?? meta.engine, - updatedAt: now, - }; + } } - /** - * Unlink a database connection from a project (leaving the project orphaned but intact) - */ - async unlinkDatabase(databaseId: string): Promise { - const meta = await this.getProjectByDatabaseId(databaseId); - if (!meta) return; - - const now = new Date().toISOString(); - - await this.ensureSourcePathCache(); - const isImported = this.sourcePathCache.has(meta.id); - - if (isImported) { - // ---- Imported project: write to local config only ---- - const local = (await this.getLocalConfig(meta.id)) ?? {}; - local.databaseId = undefined; - await this.saveLocalConfig(meta.id, local); - } else { - // ---- Regular project: update relwave.json ---- - const updated: ProjectMetadata = { - ...meta, - databaseId: null, - status: "unlinked", - updatedAt: now, - }; - await this.writeJSON( - this.projectFile(meta.id, PROJECT_FILES.metadata), - updated - ); - } + if (!fsSync.existsSync(targetDir)) { + await fs.mkdir(targetDir, { recursive: true }).catch(() => {}); + } - // Sync the index entry - const index = await this.loadIndex(); - const entry = index.projects.find((p) => p.id === meta.id); - if (entry) { - entry.databaseId = null; - entry.status = "unlinked"; - entry.updatedAt = now; - await this.saveIndex(index); + return targetDir; + } + + async analyzeImportedProject( + projectId: string, + ): Promise<{ hasLock: boolean; hashMatch: boolean; migrationsCount: number }> { + const schemaFile = await this.getSchema(projectId); + const schemaHash = (schemaFile as any)?.schemaHash || ""; + + // Read lock file + let hasLock = false; + let hashMatch = false; + let migrationsCount = 0; + + try { + const project = await this.getProject(projectId); + if (project?.databaseId) { + const { readMigrationLock } = await import("./migrationLock"); + const lock = await readMigrationLock(project.databaseId); + if (lock) { + hasLock = true; + hashMatch = lock.schemaHash === schemaHash; + migrationsCount = lock.appliedMigrations.length; } + } + } catch (e) { + // Ignore if lock file logic fails } - /** - * Relink an unlinked project to a new connection. - * Throws an error if the new connection is already linked to another project. - */ - async relinkDatabase(projectId: string, databaseId: string): Promise { - // 1. Verify connection is not already linked to another project - const existingLinkedProject = await this.getProjectByDatabaseId(databaseId); - if (existingLinkedProject && existingLinkedProject.id !== projectId) { - throw new Error(`DATABASE_ALREADY_HAS_PROJECT: This connection is already linked to project "${existingLinkedProject.name}"`); - } + return { hasLock, hashMatch, migrationsCount }; + } - // 2. Link database - const updated = await this.linkDatabase(projectId, databaseId); - if (!updated) { - throw new Error(`Project ${projectId} not found`); - } + async deleteProject(projectId: string): Promise { + await this.ensureSourcePathCache(); + const isImported = this.sourcePathCache.has(projectId); - const now = new Date().toISOString(); + if (!isImported) { + // Regular project — safe to remove the internal dir + const dir = this.projectDir(projectId); + if (fsSync.existsSync(dir)) { + await fs.rm(dir, { recursive: true, force: true }); + } + } - // 3. Mark project as active again - await this.ensureSourcePathCache(); - const isImported = this.sourcePathCache.has(projectId); + // Remove from index + cache + this.sourcePathCache.delete(projectId); + const index = await this.loadIndex(); + index.projects = index.projects.filter((p) => p.id !== projectId); + await this.saveIndex(index); + } + + /** + * Used by the connection deletion flow when user opts to "Delete project as well". + * Finds the project linked to the databaseId, deletes its folder, and removes from the store. + */ + async deleteProjectByDatabaseId(databaseId: string): Promise { + const project = await this.getProjectByDatabaseId(databaseId); + if (!project) throw new Error("No linked project found"); + + await this.ensureSourcePathCache(); + const isImported = this.sourcePathCache.has(project.id); + + if (!isImported) { + // Transaction-like filesystem deletion first + const dir = this.projectDir(project.id); + if (fsSync.existsSync(dir)) { + await fs.rm(dir, { recursive: true, force: true }); + } + } - if (!isImported) { - const finalUpdated: ProjectMetadata = { - ...updated, - status: "active", - updatedAt: now, + // Remove from index + cache + this.sourcePathCache.delete(project.id); + const index = await this.loadIndex(); + index.projects = index.projects.filter((p) => p.id !== project.id); + await this.saveIndex(index); + } + + async getSchema(projectId: string): Promise { + const file = await this.readJSON(this.projectFile(projectId, PROJECT_FILES.schema)); + if (!file) return null; + return this.migrateSchemaFile(file); + } + + private migrateSchemaFile(raw: any): SchemaFile { + if (raw.version >= 2) return raw as SchemaFile; + + // Upgrade v1 to v2 + return { + version: 2, + projectId: raw.projectId, + databaseId: raw.databaseId, + dialect: "postgresql", // assume postgresql for legacy files + cachedAt: raw.cachedAt || new Date().toISOString(), + relwaveVersion: "1.0.0", + schemaHash: "", // will be recomputed on next refresh + schemas: (raw.schemas || []).map((s: any) => ({ + name: s.name, + tables: (s.tables || []).map((t: any) => ({ + name: t.name, + type: t.type || "BASE TABLE", + comment: null, + columns: (t.columns || []).map((c: any, index: number) => { + const isSerial = c.defaultValue ? c.defaultValue.includes("nextval") : false; + return { + ...c, + isSerial, + ordinalPosition: index + 1, }; - await this.writeJSON( - this.projectFile(projectId, PROJECT_FILES.metadata), - finalUpdated - ); - } - - // Sync the index entry - const index = await this.loadIndex(); - const entry = index.projects.find((p) => p.id === projectId); - if (entry) { - entry.status = "active"; - entry.updatedAt = now; - await this.saveIndex(index); - } - - return { ...updated, status: "active", updatedAt: now }; + }), + indexes: [], + foreignKeys: [], + checks: [], + })), + enums: [], + views: [], + })), + }; + } + + async saveSchema( + projectId: string, + schemas: SchemaSnapshot[], + schemaHash?: string, + dialect?: string, + ): Promise { + const meta = await this.getProject(projectId); + if (!meta) throw new Error(`Project ${projectId} not found`); + + // Read existing file and skip write if schema data is identical + // (avoids cachedAt churn that creates phantom git changes) + const existing = await this.getSchema(projectId); + if (existing && existing.version === 2) { + const oldData = JSON.stringify(existing.schemas); + const newData = JSON.stringify(schemas); + // If schemaHash is provided, also check if it matches + if (oldData === newData && (!schemaHash || existing.schemaHash === schemaHash)) { + return existing; // nothing changed — keep old cachedAt + } } - /** - * Delete a project. - * For regular projects the internal directory is removed. - * For imported projects the source directory is NOT deleted - * (the user owns it) — only the index entry is removed. - */ - /** - * Resolve the migrations directory for a database. - * Moves legacy migrations from AppData to the project directory if they exist. - */ - async resolveMigrationsDir(dbId: string): Promise { - const { CONFIG_FOLDER } = await import("../utils/config"); - const fallbackDir = path.join(CONFIG_FOLDER, "migrations", dbId); - let targetDir = fallbackDir; - - const project = await this.getProjectByDatabaseId(dbId); - if (project) { - targetDir = path.join(this.projectDir(project.id), "migrations"); - } + const now = new Date().toISOString(); + const file: SchemaFile = { + version: 2, + projectId, + databaseId: meta.databaseId, + dialect: (dialect || + (meta.engine === "postgresql" + ? "postgresql" + : meta.engine === "mysql" || meta.engine === "mariadb" + ? "mysql" + : "sqlite")) as any, + schemas, + cachedAt: now, + relwaveVersion: "1.0.0", + schemaHash: schemaHash || "", + }; - // Migrate existing directory - if (targetDir !== fallbackDir && fsSync.existsSync(fallbackDir)) { - if (!fsSync.existsSync(targetDir)) { - await fs.mkdir(path.dirname(targetDir), { recursive: true }).catch(() => {}); - try { - await fs.rename(fallbackDir, targetDir); - } catch (e) { - console.error("Failed to migrate existing migrations dir:", e); - } - } - } + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.schema), file); + + return file; + } + + async getERDiagram(projectId: string): Promise { + return this.readJSON(this.projectFile(projectId, PROJECT_FILES.erDiagram)); + } + + async saveERDiagram( + projectId: string, + data: Pick, + ): Promise { + const now = new Date().toISOString(); + const file: ERDiagramFile = { + version: 1, + projectId, + nodes: data.nodes, + zoom: data.zoom, + panX: data.panX, + panY: data.panY, + updatedAt: now, + }; - if (!fsSync.existsSync(targetDir)) { - await fs.mkdir(targetDir, { recursive: true }).catch(() => {}); - } + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.erDiagram), file); + + return file; + } + + async getAnnotations(projectId: string): Promise { + return this.readJSON(this.projectFile(projectId, PROJECT_FILES.annotations)); + } + + async saveAnnotations( + projectId: string, + snapshot: Record, + ): Promise { + const now = new Date().toISOString(); + const file: AnnotationsFile = { + version: 1, + projectId, + snapshot, + updatedAt: now, + }; - return targetDir; - } + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.annotations), file); - async analyzeImportedProject(projectId: string): Promise<{ hasLock: boolean; hashMatch: boolean; migrationsCount: number }> { - const schemaFile = await this.getSchema(projectId); - const schemaHash = (schemaFile as any)?.schemaHash || ""; + return file; + } - // Read lock file - let hasLock = false; - let hashMatch = false; - let migrationsCount = 0; + async getQueries(projectId: string): Promise { + return this.readJSON(this.projectFile(projectId, PROJECT_FILES.queries)); + } - try { - const project = await this.getProject(projectId); - if (project?.databaseId) { - const { readMigrationLock } = await import("./migrationLock"); - const lock = await readMigrationLock(project.databaseId); - if (lock) { - hasLock = true; - hashMatch = lock.schemaHash === schemaHash; - migrationsCount = lock.appliedMigrations.length; - } - } - } catch (e) { - // Ignore if lock file logic fails - } + async addQuery( + projectId: string, + params: { name: string; sql: string; description?: string }, + ): Promise { + const file = (await this.getQueries(projectId)) ?? { + version: 1, + projectId, + queries: [], + }; - return { hasLock, hashMatch, migrationsCount }; - } + const now = new Date().toISOString(); + const query: SavedQuery = { + id: uuidv4(), + name: params.name, + sql: params.sql, + description: params.description, + createdAt: now, + updatedAt: now, + }; - async deleteProject(projectId: string): Promise { - await this.ensureSourcePathCache(); - const isImported = this.sourcePathCache.has(projectId); + file.queries.push(query); - if (!isImported) { - // Regular project — safe to remove the internal dir - const dir = this.projectDir(projectId); - if (fsSync.existsSync(dir)) { - await fs.rm(dir, { recursive: true, force: true }); - } - } + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.queries), file); - // Remove from index + cache - this.sourcePathCache.delete(projectId); - const index = await this.loadIndex(); - index.projects = index.projects.filter((p) => p.id !== projectId); - await this.saveIndex(index); - } + return query; + } - /** - * Used by the connection deletion flow when user opts to "Delete project as well". - * Finds the project linked to the databaseId, deletes its folder, and removes from the store. - */ - async deleteProjectByDatabaseId(databaseId: string): Promise { - const project = await this.getProjectByDatabaseId(databaseId); - if (!project) throw new Error("No linked project found"); - - await this.ensureSourcePathCache(); - const isImported = this.sourcePathCache.has(project.id); - - if (!isImported) { - // Transaction-like filesystem deletion first - const dir = this.projectDir(project.id); - if (fsSync.existsSync(dir)) { - await fs.rm(dir, { recursive: true, force: true }); - } - } + async updateQuery( + projectId: string, + queryId: string, + updates: Partial>, + ): Promise { + const file = await this.getQueries(projectId); + if (!file) return null; - // Remove from index + cache - this.sourcePathCache.delete(project.id); - const index = await this.loadIndex(); - index.projects = index.projects.filter((p) => p.id !== project.id); - await this.saveIndex(index); - } + const idx = file.queries.findIndex((q) => q.id === queryId); + if (idx === -1) return null; - async getSchema(projectId: string): Promise { - const file = await this.readJSON( - this.projectFile(projectId, PROJECT_FILES.schema) - ); - if (!file) return null; - return this.migrateSchemaFile(file); - } + const now = new Date().toISOString(); + file.queries[idx] = { + ...file.queries[idx], + ...updates, + updatedAt: now, + }; - private migrateSchemaFile(raw: any): SchemaFile { - if (raw.version >= 2) return raw as SchemaFile; - - // Upgrade v1 to v2 - return { - version: 2, - projectId: raw.projectId, - databaseId: raw.databaseId, - dialect: "postgresql", // assume postgresql for legacy files - cachedAt: raw.cachedAt || new Date().toISOString(), - relwaveVersion: "1.0.0", - schemaHash: "", // will be recomputed on next refresh - schemas: (raw.schemas || []).map((s: any) => ({ - name: s.name, - tables: (s.tables || []).map((t: any) => ({ - name: t.name, - type: t.type || "BASE TABLE", - comment: null, - columns: (t.columns || []).map((c: any, index: number) => { - const isSerial = c.defaultValue ? c.defaultValue.includes("nextval") : false; - return { - ...c, - isSerial, - ordinalPosition: index + 1, - }; - }), - indexes: [], - foreignKeys: [], - checks: [], - })), - enums: [], - views: [], - })), - }; + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.queries), file); + + return file.queries[idx]; + } + + async deleteQuery(projectId: string, queryId: string): Promise { + const file = await this.getQueries(projectId); + if (!file) return; + + file.queries = file.queries.filter((q) => q.id !== queryId); + + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.queries), file); + } + + /** + * Returns the full project bundle — useful for export / git commit + */ + async exportProject(projectId: string): Promise<{ + metadata: ProjectMetadata; + schema: SchemaFile | null; + erDiagram: ERDiagramFile | null; + annotations: AnnotationsFile | null; + queries: QueriesFile | null; + } | null> { + const metadata = await this.getProject(projectId); + if (!metadata) return null; + + const [schema, erDiagram, annotations, queries] = await Promise.all([ + this.getSchema(projectId), + this.getERDiagram(projectId), + this.getAnnotations(projectId), + this.getQueries(projectId), + ]); + + return { metadata, schema, erDiagram, annotations, queries }; + } + + // ========================================== + // Local Config (git-ignored) + // ========================================== + + /** + * Read the local (git-ignored) config for a project + */ + async getLocalConfig(projectId: string): Promise { + return this.readJSON(this.projectFile(projectId, PROJECT_FILES.localConfig)); + } + + /** + * Write/update the local config + */ + async saveLocalConfig(projectId: string, config: LocalConfig): Promise { + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.localConfig), config); + return config; + } + + // ========================================== + // .gitignore management + // ========================================== + + /** + * Ensure a .gitignore file exists in the project directory + * with rules to exclude local credentials and caches. + */ + async ensureGitignore(projectId: string): Promise { + const dir = this.projectDir(projectId); + const giPath = path.join(dir, ".gitignore"); + + const rules = [ + "# RelWave — auto-generated", + "# Local config (connection credentials, environment overrides)", + "relwave.local.json", + "", + "# Environment variables (database credentials)", + ".env", + ".env.*", + "", + "# OS / Editor", + ".DS_Store", + "Thumbs.db", + "", + ].join("\n"); + + if (fsSync.existsSync(giPath)) { + const existing = await fs.readFile(giPath, "utf-8"); + if (existing.includes("relwave.local.json")) { + return false; // already has our rules + } + // Append to existing + await fs.writeFile(giPath, existing + "\n\n" + rules, "utf-8"); + return true; } - async saveSchema( - projectId: string, - schemas: SchemaSnapshot[], - schemaHash?: string, - dialect?: string - ): Promise { - const meta = await this.getProject(projectId); - if (!meta) throw new Error(`Project ${projectId} not found`); - - // Read existing file and skip write if schema data is identical - // (avoids cachedAt churn that creates phantom git changes) - const existing = await this.getSchema(projectId); - if (existing && existing.version === 2) { - const oldData = JSON.stringify(existing.schemas); - const newData = JSON.stringify(schemas); - // If schemaHash is provided, also check if it matches - if (oldData === newData && (!schemaHash || existing.schemaHash === schemaHash)) { - return existing; // nothing changed — keep old cachedAt - } - } + await fs.writeFile(giPath, rules, "utf-8"); + return true; + } - const now = new Date().toISOString(); - const file: SchemaFile = { - version: 2, - projectId, - databaseId: meta.databaseId, - dialect: (dialect || (meta.engine === "postgresql" ? "postgresql" : (meta.engine === "mysql" || meta.engine === "mariadb") ? "mysql" : "sqlite")) as any, - schemas, - cachedAt: now, - relwaveVersion: "1.0.0", - schemaHash: schemaHash || "", - }; - - await this.writeJSON( - this.projectFile(projectId, PROJECT_FILES.schema), - file - ); - - return file; - } + // ========================================== + // README generation + // ========================================== - async getERDiagram(projectId: string): Promise { - return this.readJSON( - this.projectFile(projectId, PROJECT_FILES.erDiagram) - ); - } + /** + * Generate a README.md with connection instructions and .env reference. + * Only writes if a README.md doesn't already exist (idempotent). + */ + async ensureReadme( + projectId: string, + meta: { name: string; description?: string; engine?: string }, + ): Promise { + const readmePath = this.projectFile(projectId, PROJECT_FILES.readme); + if (fsSync.existsSync(readmePath)) return false; - async saveERDiagram( - projectId: string, - data: Pick - ): Promise { - const now = new Date().toISOString(); - const file: ERDiagramFile = { - version: 1, - projectId, - nodes: data.nodes, - zoom: data.zoom, - panX: data.panX, - panY: data.panY, - updatedAt: now, - }; - - await this.writeJSON( - this.projectFile(projectId, PROJECT_FILES.erDiagram), - file - ); - - return file; - } + const engineLabel = this.engineDisplayName(meta.engine); + const envExample = this.envExampleBlock(meta.engine); - async getAnnotations(projectId: string): Promise { - return this.readJSON( - this.projectFile(projectId, PROJECT_FILES.annotations) - ); - } + const lines = [`# ${meta.name}`, ""]; - async saveAnnotations( - projectId: string, - snapshot: Record - ): Promise { - const now = new Date().toISOString(); - const file: AnnotationsFile = { - version: 1, - projectId, - snapshot, - updatedAt: now, - }; - - await this.writeJSON( - this.projectFile(projectId, PROJECT_FILES.annotations), - file - ); - - return file; + if (meta.description) { + lines.push(meta.description, ""); } - async getQueries(projectId: string): Promise { - return this.readJSON( - this.projectFile(projectId, PROJECT_FILES.queries) - ); + lines.push( + `> Managed with [RelWave](https://github.com/Relwave/relwave-app) — a git-native database management app.`, + "", + "---", + "", + "## Getting Started", + "", + "### 1. Clone and open in RelWave", + "", + "```bash", + "git clone ", + "```", + "", + "Open **RelWave → Import Project** and select the cloned folder.", + "", + `### 2. Configure your local database connection`, + "", + `Each developer connects to their **own** ${engineLabel} instance.`, + "Connection credentials are stored in `relwave.local.json` (git-ignored),", + "so they never leak into version control.", + "", + "You can either:", + "", + "- Enter connection details in the **RelWave UI** when importing the project, or", + "- Create a `.env` file in the project root (also git-ignored by default).", + "", + "### 3. `.env` file reference", + "", + "Create a `.env` file in the project root with your database credentials:", + "", + "```env", + ...envExample, + "```", + "", + "RelWave will auto-detect these variables when you import the project.", + "", + "#### Supported variable names", + "", + "| Variable | Aliases |", + "|----------|---------|", + "| `DB_HOST` | `DATABASE_HOST`, `PGHOST`, `MYSQL_HOST` |", + "| `DB_PORT` | `DATABASE_PORT`, `PGPORT`, `MYSQL_PORT` |", + "| `DB_USER` | `DATABASE_USER`, `PGUSER`, `MYSQL_USER`, `DB_USERNAME` |", + "| `DB_PASSWORD` | `DATABASE_PASSWORD`, `PGPASSWORD`, `MYSQL_PASSWORD` |", + "| `DB_NAME` | `DB_DATABASE`, `DATABASE_NAME`, `PGDATABASE`, `MYSQL_DATABASE` |", + "| `DB_TYPE` | `DATABASE_TYPE`, `DB_ENGINE` |", + "| `DB_SSL` | `DATABASE_SSL` |", + "", + "---", + "", + "## Project Structure", + "", + "```", + "├── relwave.json # Project metadata (committed)", + "├── relwave.local.json # Local connection config (git-ignored)", + "├── .gitignore", + "├── .env # Optional — local DB credentials (git-ignored)", + "├── README.md", + "├── schema/", + "│ └── schema.json # Cached database schema snapshot", + "├── diagrams/", + "│ ├── er.json # ER diagram layout", + "│ └── annotations.json # ER diagram annotations (tldraw)", + "└── queries/", + " └── queries.json # Saved SQL queries", + "```", + "", + "---", + "", + "## Collaboration", + "", + "- **`relwave.json`** is committed — it contains the project name, description,", + " and default schema. The `projectId` is stable across all forks.", + "- **`relwave.local.json`** is git-ignored — each developer stores their own", + " `databaseId` and connection preferences here. No credentials are ever committed.", + "- **Schema / ER / Queries** are committed so all collaborators share the same", + " database documentation and saved queries.", + "", + ); + + await fs.writeFile(readmePath, lines.join("\n"), "utf-8"); + return true; + } + + /** + * Return a user-friendly engine name for README text. + */ + private engineDisplayName(engine?: string): string { + switch (engine?.toLowerCase()) { + case "postgresql": + case "postgres": + return "PostgreSQL"; + case "mysql": + return "MySQL"; + case "mariadb": + return "MariaDB"; + default: + return "database"; } - - async addQuery( - projectId: string, - params: { name: string; sql: string; description?: string } - ): Promise { - const file = (await this.getQueries(projectId)) ?? { - version: 1, - projectId, - queries: [], - }; - - const now = new Date().toISOString(); - const query: SavedQuery = { - id: uuidv4(), - name: params.name, - sql: params.sql, - description: params.description, - createdAt: now, - updatedAt: now, - }; - - file.queries.push(query); - - await this.writeJSON( - this.projectFile(projectId, PROJECT_FILES.queries), - file - ); - - return query; + } + + /** + * Return engine-appropriate .env example lines. + */ + private envExampleBlock(engine?: string): string[] { + const e = engine?.toLowerCase(); + if (e === "mysql") { + return [ + "MYSQL_HOST=localhost", + "MYSQL_PORT=3306", + "MYSQL_USER=root", + "MYSQL_PASSWORD=your_password", + "MYSQL_DATABASE=your_database", + ]; } - - async updateQuery( - projectId: string, - queryId: string, - updates: Partial> - ): Promise { - const file = await this.getQueries(projectId); - if (!file) return null; - - const idx = file.queries.findIndex((q) => q.id === queryId); - if (idx === -1) return null; - - const now = new Date().toISOString(); - file.queries[idx] = { - ...file.queries[idx], - ...updates, - updatedAt: now, - }; - - await this.writeJSON( - this.projectFile(projectId, PROJECT_FILES.queries), - file - ); - - return file.queries[idx]; + if (e === "mariadb") { + return [ + "DB_HOST=localhost", + "DB_PORT=3307", + "DB_USER=root", + "DB_PASSWORD=your_password", + "DB_NAME=your_database", + "DB_TYPE=mariadb", + ]; } - - async deleteQuery(projectId: string, queryId: string): Promise { - const file = await this.getQueries(projectId); - if (!file) return; - - file.queries = file.queries.filter((q) => q.id !== queryId); - - await this.writeJSON( - this.projectFile(projectId, PROJECT_FILES.queries), - file - ); + // Default to PostgreSQL-style + if (!e || e === "postgresql" || e === "postgres") { + return [ + "PGHOST=localhost", + "PGPORT=5432", + "PGUSER=postgres", + "PGPASSWORD=your_password", + "PGDATABASE=your_database", + ]; } - - /** - * Returns the full project bundle — useful for export / git commit - */ - async exportProject(projectId: string): Promise<{ - metadata: ProjectMetadata; - schema: SchemaFile | null; - erDiagram: ERDiagramFile | null; - annotations: AnnotationsFile | null; - queries: QueriesFile | null; - } | null> { - const metadata = await this.getProject(projectId); - if (!metadata) return null; - - const [schema, erDiagram, annotations, queries] = await Promise.all([ - this.getSchema(projectId), - this.getERDiagram(projectId), - this.getAnnotations(projectId), - this.getQueries(projectId), - ]); - - return { metadata, schema, erDiagram, annotations, queries }; + // Generic fallback + return [ + "DB_HOST=localhost", + "DB_PORT=5432", + "DB_USER=your_user", + "DB_PASSWORD=your_password", + "DB_NAME=your_database", + "DB_TYPE=" + (engine || "postgresql"), + ]; + } + + // ========================================== + // Import Project (from cloned repo) + // ========================================== + + /** + * Parse a .env file into a key-value map. + * Supports standard KEY=VALUE, KEY="VALUE", KEY='VALUE', comments, and blank lines. + */ + static parseEnvFile(content: string): Record { + const result: Record = {}; + for (const raw of content.split(/\r?\n/)) { + const line = raw.trim(); + if (!line || line.startsWith("#")) continue; + const eqIdx = line.indexOf("="); + if (eqIdx === -1) continue; + const key = line.slice(0, eqIdx).trim(); + let value = line.slice(eqIdx + 1).trim(); + // Strip surrounding quotes + if ( + (value.startsWith('"') && value.endsWith('"')) || + (value.startsWith("'") && value.endsWith("'")) + ) { + value = value.slice(1, -1); + } + result[key] = value; } + return result; + } + + /** + * Extract database connection parameters from a parsed .env map. + * Recognises common variable names used in the ecosystem. + */ + static extractDbParamsFromEnv(env: Record): { + host?: string; + port?: number; + user?: string; + password?: string; + database?: string; + type?: string; + ssl?: boolean; + name?: string; + url?: string; + } | null { + const get = (...keys: string[]): string | undefined => { + for (const k of keys) { + if (env[k]) return env[k]; + } + return undefined; + }; - // ========================================== - // Local Config (git-ignored) - // ========================================== - - /** - * Read the local (git-ignored) config for a project - */ - async getLocalConfig(projectId: string): Promise { - return this.readJSON( - this.projectFile(projectId, PROJECT_FILES.localConfig) - ); + const host = get("DB_HOST", "DATABASE_HOST", "PGHOST", "MYSQL_HOST"); + const portStr = get("DB_PORT", "DATABASE_PORT", "PGPORT", "MYSQL_PORT"); + const user = get( + "DB_USER", + "DATABASE_USER", + "PGUSER", + "MYSQL_USER", + "DB_USERNAME", + "DATABASE_USERNAME", + ); + const password = get("DB_PASSWORD", "DATABASE_PASSWORD", "PGPASSWORD", "MYSQL_PASSWORD"); + const database = get("DB_NAME", "DB_DATABASE", "DATABASE_NAME", "PGDATABASE", "MYSQL_DATABASE"); + const type = get("DB_TYPE", "DATABASE_TYPE", "DB_ENGINE", "DATABASE_ENGINE"); + const sslStr = get("DB_SSL", "DATABASE_SSL"); + const name = get("DB_CONNECTION_NAME", "DATABASE_CONNECTION_NAME"); + const url = get("DATABASE_URL", "DB_URL"); + + // Must have at least host, database, or url to be useful + if (!host && !database && !url) return null; + + const port = portStr ? parseInt(portStr, 10) : undefined; + const ssl = sslStr ? !["false", "0", "no"].includes(sslStr.toLowerCase()) : undefined; + + return { + host, + port: port && !isNaN(port) ? port : undefined, + user, + password, + database, + type: type?.toLowerCase(), + ssl, + name, + url, + }; + } + + /** + * Scan a cloned repo directory for import. + * Returns project metadata and .env info WITHOUT creating anything. + * Use this to preview what will be imported and determine if DB creds are needed. + */ + async scanImportSource(sourcePath: string): Promise<{ + metadata: { + name: string; + description?: string; + engine?: string; + defaultSchema?: string; + }; + envFound: boolean; + parsedEnv: { + host?: string; + port?: number; + user?: string; + password?: string; + database?: string; + type?: string; + ssl?: boolean; + name?: string; + url?: string; + } | null; + }> { + const sourceMetaPath = path.join(sourcePath, PROJECT_FILES.metadata); + if (!fsSync.existsSync(sourceMetaPath)) { + throw new Error( + `Not a valid RelWave project: ${PROJECT_FILES.metadata} not found in ${sourcePath}`, + ); } - /** - * Write/update the local config - */ - async saveLocalConfig(projectId: string, config: LocalConfig): Promise { - await this.writeJSON( - this.projectFile(projectId, PROJECT_FILES.localConfig), - config - ); - return config; + const sourceMeta = await this.readJSON(sourceMetaPath); + if (!sourceMeta || !sourceMeta.name) { + throw new Error(`Invalid ${PROJECT_FILES.metadata}: missing required fields`); } - // ========================================== - // .gitignore management - // ========================================== - - /** - * Ensure a .gitignore file exists in the project directory - * with rules to exclude local credentials and caches. - */ - async ensureGitignore(projectId: string): Promise { - const dir = this.projectDir(projectId); - const giPath = path.join(dir, ".gitignore"); - - const rules = [ - "# RelWave — auto-generated", - "# Local config (connection credentials, environment overrides)", - "relwave.local.json", - "", - "# Environment variables (database credentials)", - ".env", - ".env.*", - "", - "# OS / Editor", - ".DS_Store", - "Thumbs.db", - "", - ].join("\n"); - - if (fsSync.existsSync(giPath)) { - const existing = await fs.readFile(giPath, "utf-8"); - if (existing.includes("relwave.local.json")) { - return false; // already has our rules - } - // Append to existing - await fs.writeFile(giPath, existing + "\n\n" + rules, "utf-8"); - return true; - } - - await fs.writeFile(giPath, rules, "utf-8"); - return true; + let envFound = false; + let parsedEnv: ReturnType = null; + + const envPath = path.join(sourcePath, ".env"); + if (fsSync.existsSync(envPath)) { + envFound = true; + try { + const envContent = await fs.readFile(envPath, "utf-8"); + const envMap = ProjectStore.parseEnvFile(envContent); + parsedEnv = ProjectStore.extractDbParamsFromEnv(envMap); + } catch { + // .env exists but couldn't be read/parsed + } } - // ========================================== - // README generation - // ========================================== - - /** - * Generate a README.md with connection instructions and .env reference. - * Only writes if a README.md doesn't already exist (idempotent). - */ - async ensureReadme( - projectId: string, - meta: { name: string; description?: string; engine?: string } - ): Promise { - const readmePath = this.projectFile(projectId, PROJECT_FILES.readme); - if (fsSync.existsSync(readmePath)) return false; - - const engineLabel = this.engineDisplayName(meta.engine); - const envExample = this.envExampleBlock(meta.engine); - - const lines = [ - `# ${meta.name}`, - "", - ]; - - if (meta.description) { - lines.push(meta.description, ""); - } + return { + metadata: { + name: sourceMeta.name, + description: sourceMeta.description, + engine: sourceMeta.engine, + defaultSchema: sourceMeta.defaultSchema, + }, + envFound, + parsedEnv, + }; + } + + /** + * Import a project from a cloned repository directory. + * + * **Read-only on tracked files** – the import never modifies + * `relwave.json` or sub-resource files (schema, ER, queries). + * This means forking/cloning a project does *not* produce + * unnecessary diffs that would pollute collaboration history. + * + * Machine-specific data (`databaseId`) is stored in the + * git-ignored `relwave.local.json` so each developer can + * connect to their own database instance. + * + * The original `projectId` from `relwave.json` is preserved so + * it stays consistent across all forks. + * + * @param sourcePath Absolute path to the cloned repo containing relwave.json + * @param databaseId A valid database connection ID to link to the project. + * The caller must create the DB connection first (either + * from .env auto-detection or user-provided credentials). + * + * @returns The effective ProjectMetadata (with local databaseId merged). + */ + async importProject(params: { + sourcePath: string; + databaseId: string; + }): Promise { + const { sourcePath, databaseId } = params; - lines.push( - `> Managed with [RelWave](https://github.com/Relwave/relwave-app) — a git-native database management app.`, - "", - "---", - "", - "## Getting Started", - "", - "### 1. Clone and open in RelWave", - "", - "```bash", - "git clone ", - "```", - "", - "Open **RelWave → Import Project** and select the cloned folder.", - "", - `### 2. Configure your local database connection`, - "", - `Each developer connects to their **own** ${engineLabel} instance.`, - "Connection credentials are stored in `relwave.local.json` (git-ignored),", - "so they never leak into version control.", - "", - "You can either:", - "", - "- Enter connection details in the **RelWave UI** when importing the project, or", - "- Create a `.env` file in the project root (also git-ignored by default).", - "", - "### 3. `.env` file reference", - "", - "Create a `.env` file in the project root with your database credentials:", - "", - "```env", - ...envExample, - "```", - "", - "RelWave will auto-detect these variables when you import the project.", - "", - "#### Supported variable names", - "", - "| Variable | Aliases |", - "|----------|---------|", - "| `DB_HOST` | `DATABASE_HOST`, `PGHOST`, `MYSQL_HOST` |", - "| `DB_PORT` | `DATABASE_PORT`, `PGPORT`, `MYSQL_PORT` |", - "| `DB_USER` | `DATABASE_USER`, `PGUSER`, `MYSQL_USER`, `DB_USERNAME` |", - "| `DB_PASSWORD` | `DATABASE_PASSWORD`, `PGPASSWORD`, `MYSQL_PASSWORD` |", - "| `DB_NAME` | `DB_DATABASE`, `DATABASE_NAME`, `PGDATABASE`, `MYSQL_DATABASE` |", - "| `DB_TYPE` | `DATABASE_TYPE`, `DB_ENGINE` |", - "| `DB_SSL` | `DATABASE_SSL` |", - "", - "---", - "", - "## Project Structure", - "", - "```", - "├── relwave.json # Project metadata (committed)", - "├── relwave.local.json # Local connection config (git-ignored)", - "├── .gitignore", - "├── .env # Optional — local DB credentials (git-ignored)", - "├── README.md", - "├── schema/", - "│ └── schema.json # Cached database schema snapshot", - "├── diagrams/", - "│ ├── er.json # ER diagram layout", - "│ └── annotations.json # ER diagram annotations (tldraw)", - "└── queries/", - " └── queries.json # Saved SQL queries", - "```", - "", - "---", - "", - "## Collaboration", - "", - "- **`relwave.json`** is committed — it contains the project name, description,", - " and default schema. The `projectId` is stable across all forks.", - "- **`relwave.local.json`** is git-ignored — each developer stores their own", - " `databaseId` and connection preferences here. No credentials are ever committed.", - "- **Schema / ER / Queries** are committed so all collaborators share the same", - " database documentation and saved queries.", - "", - ); - - await fs.writeFile(readmePath, lines.join("\n"), "utf-8"); - return true; + if (!databaseId) { + throw new Error("databaseId is required — create a database connection first"); } - /** - * Return a user-friendly engine name for README text. - */ - private engineDisplayName(engine?: string): string { - switch (engine?.toLowerCase()) { - case "postgresql": - case "postgres": - return "PostgreSQL"; - case "mysql": - return "MySQL"; - case "mariadb": - return "MariaDB"; - default: - return "database"; - } + // ---- 1. Validate source directory has a relwave.json ---- + const sourceMetaPath = path.join(sourcePath, PROJECT_FILES.metadata); + if (!fsSync.existsSync(sourceMetaPath)) { + throw new Error( + `Not a valid RelWave project: ${PROJECT_FILES.metadata} not found in ${sourcePath}`, + ); } - /** - * Return engine-appropriate .env example lines. - */ - private envExampleBlock(engine?: string): string[] { - const e = engine?.toLowerCase(); - if (e === "mysql") { - return [ - "MYSQL_HOST=localhost", - "MYSQL_PORT=3306", - "MYSQL_USER=root", - "MYSQL_PASSWORD=your_password", - "MYSQL_DATABASE=your_database", - ]; - } - if (e === "mariadb") { - return [ - "DB_HOST=localhost", - "DB_PORT=3307", - "DB_USER=root", - "DB_PASSWORD=your_password", - "DB_NAME=your_database", - "DB_TYPE=mariadb", - ]; - } - // Default to PostgreSQL-style - if (!e || e === "postgresql" || e === "postgres") { - return [ - "PGHOST=localhost", - "PGPORT=5432", - "PGUSER=postgres", - "PGPASSWORD=your_password", - "PGDATABASE=your_database", - ]; - } - // Generic fallback - return [ - "DB_HOST=localhost", - "DB_PORT=5432", - "DB_USER=your_user", - "DB_PASSWORD=your_password", - "DB_NAME=your_database", - "DB_TYPE=" + (engine || "postgresql"), - ]; + const sourceMeta = await this.readJSON(sourceMetaPath); + if (!sourceMeta || !sourceMeta.name) { + throw new Error(`Invalid ${PROJECT_FILES.metadata}: missing required fields`); } - // ========================================== - // Import Project (from cloned repo) - // ========================================== - - /** - * Parse a .env file into a key-value map. - * Supports standard KEY=VALUE, KEY="VALUE", KEY='VALUE', comments, and blank lines. - */ - static parseEnvFile(content: string): Record { - const result: Record = {}; - for (const raw of content.split(/\r?\n/)) { - const line = raw.trim(); - if (!line || line.startsWith("#")) continue; - const eqIdx = line.indexOf("="); - if (eqIdx === -1) continue; - const key = line.slice(0, eqIdx).trim(); - let value = line.slice(eqIdx + 1).trim(); - // Strip surrounding quotes - if ( - (value.startsWith('"') && value.endsWith('"')) || - (value.startsWith("'") && value.endsWith("'")) - ) { - value = value.slice(1, -1); - } - result[key] = value; - } - return result; + // ---- 2. Check for duplicate project ID ---- + const id = sourceMeta.id; + const index = await this.loadIndex(); + if (index.projects.some((p) => p.id === id)) { + throw new Error(`Project "${sourceMeta.name}" is already imported (id: ${id})`); } - /** - * Extract database connection parameters from a parsed .env map. - * Recognises common variable names used in the ecosystem. - */ - static extractDbParamsFromEnv( - env: Record - ): { - host?: string; - port?: number; - user?: string; - password?: string; - database?: string; - type?: string; - ssl?: boolean; - name?: string; - url?: string; - } | null { - const get = (...keys: string[]): string | undefined => { - for (const k of keys) { - if (env[k]) return env[k]; - } - return undefined; - }; - - const host = get("DB_HOST", "DATABASE_HOST", "PGHOST", "MYSQL_HOST"); - const portStr = get("DB_PORT", "DATABASE_PORT", "PGPORT", "MYSQL_PORT"); - const user = get("DB_USER", "DATABASE_USER", "PGUSER", "MYSQL_USER", "DB_USERNAME", "DATABASE_USERNAME"); - const password = get("DB_PASSWORD", "DATABASE_PASSWORD", "PGPASSWORD", "MYSQL_PASSWORD"); - const database = get("DB_NAME", "DB_DATABASE", "DATABASE_NAME", "PGDATABASE", "MYSQL_DATABASE"); - const type = get("DB_TYPE", "DATABASE_TYPE", "DB_ENGINE", "DATABASE_ENGINE"); - const sslStr = get("DB_SSL", "DATABASE_SSL"); - const name = get("DB_CONNECTION_NAME", "DATABASE_CONNECTION_NAME"); - const url = get("DATABASE_URL", "DB_URL"); - - // Must have at least host, database, or url to be useful - if (!host && !database && !url) return null; - - const port = portStr ? parseInt(portStr, 10) : undefined; - const ssl = sslStr ? !["false", "0", "no"].includes(sslStr.toLowerCase()) : undefined; - - return { - host, - port: port && !isNaN(port) ? port : undefined, - user, - password, - database, - type: type?.toLowerCase(), - ssl, - name, - url, - }; + // ---- 3. Resolve engine from the linked database ---- + let engine: string | undefined; + try { + const db: DBMeta | undefined = await dbStoreInstance.getDB(databaseId); + engine = db?.type; + } catch { + // db may not exist yet } - /** - * Scan a cloned repo directory for import. - * Returns project metadata and .env info WITHOUT creating anything. - * Use this to preview what will be imported and determine if DB creds are needed. - */ - async scanImportSource(sourcePath: string): Promise<{ - metadata: { - name: string; - description?: string; - engine?: string; - defaultSchema?: string; - }; - envFound: boolean; - parsedEnv: { - host?: string; - port?: number; - user?: string; - password?: string; - database?: string; - type?: string; - ssl?: boolean; - name?: string; - url?: string; - } | null; - }> { - const sourceMetaPath = path.join(sourcePath, PROJECT_FILES.metadata); - if (!fsSync.existsSync(sourceMetaPath)) { - throw new Error( - `Not a valid RelWave project: ${PROJECT_FILES.metadata} not found in ${sourcePath}` - ); - } - - const sourceMeta = await this.readJSON(sourceMetaPath); - if (!sourceMeta || !sourceMeta.name) { - throw new Error( - `Invalid ${PROJECT_FILES.metadata}: missing required fields` - ); - } + // ---- 4. Register the sourcePath so projectDir() resolves correctly ---- + this.sourcePathCache.set(id, sourcePath); - let envFound = false; - let parsedEnv: ReturnType = null; - - const envPath = path.join(sourcePath, ".env"); - if (fsSync.existsSync(envPath)) { - envFound = true; - try { - const envContent = await fs.readFile(envPath, "utf-8"); - const envMap = ProjectStore.parseEnvFile(envContent); - parsedEnv = ProjectStore.extractDbParamsFromEnv(envMap); - } catch { - // .env exists but couldn't be read/parsed - } - } - - return { - metadata: { - name: sourceMeta.name, - description: sourceMeta.description, - engine: sourceMeta.engine, - defaultSchema: sourceMeta.defaultSchema, - }, - envFound, - parsedEnv, - }; + // Ensure subdirectories exist in the source dir (they should, + // but be defensive) + for (const sub of ["schema", "diagrams", "queries"]) { + ensureDir(path.join(sourcePath, sub)); } - /** - * Import a project from a cloned repository directory. - * - * **Read-only on tracked files** – the import never modifies - * `relwave.json` or sub-resource files (schema, ER, queries). - * This means forking/cloning a project does *not* produce - * unnecessary diffs that would pollute collaboration history. - * - * Machine-specific data (`databaseId`) is stored in the - * git-ignored `relwave.local.json` so each developer can - * connect to their own database instance. - * - * The original `projectId` from `relwave.json` is preserved so - * it stays consistent across all forks. - * - * @param sourcePath Absolute path to the cloned repo containing relwave.json - * @param databaseId A valid database connection ID to link to the project. - * The caller must create the DB connection first (either - * from .env auto-detection or user-provided credentials). - * - * @returns The effective ProjectMetadata (with local databaseId merged). - */ - async importProject(params: { - sourcePath: string; - databaseId: string; - }): Promise { - const { sourcePath, databaseId } = params; - - if (!databaseId) { - throw new Error("databaseId is required — create a database connection first"); - } - - // ---- 1. Validate source directory has a relwave.json ---- - const sourceMetaPath = path.join(sourcePath, PROJECT_FILES.metadata); - if (!fsSync.existsSync(sourceMetaPath)) { - throw new Error( - `Not a valid RelWave project: ${PROJECT_FILES.metadata} not found in ${sourcePath}` - ); - } - - const sourceMeta = await this.readJSON(sourceMetaPath); - if (!sourceMeta || !sourceMeta.name) { - throw new Error( - `Invalid ${PROJECT_FILES.metadata}: missing required fields` - ); - } - - // ---- 2. Check for duplicate project ID ---- - const id = sourceMeta.id; - const index = await this.loadIndex(); - if (index.projects.some((p) => p.id === id)) { - throw new Error( - `Project "${sourceMeta.name}" is already imported (id: ${id})` - ); - } - - // ---- 3. Resolve engine from the linked database ---- - let engine: string | undefined; - try { - const db: DBMeta | undefined = await dbStoreInstance.getDB(databaseId); - engine = db?.type; - } catch { - // db may not exist yet - } - - // ---- 4. Register the sourcePath so projectDir() resolves correctly ---- - this.sourcePathCache.set(id, sourcePath); - - // Ensure subdirectories exist in the source dir (they should, - // but be defensive) - for (const sub of ["schema", "diagrams", "queries"]) { - ensureDir(path.join(sourcePath, sub)); - } - - // ---- 5. DO NOT modify relwave.json or sub-resource files ---- - // relwave.json keeps the original projectId & databaseId - // so forks/clones never produce unnecessary diffs. - - // ---- 6. Ensure .gitignore exists in source dir ---- - await this.ensureGitignore(id); - - // ---- 7. Write databaseId to local config (git-ignored) ---- - const localConfig: LocalConfig = { databaseId }; - const localPath = path.join(sourcePath, PROJECT_FILES.localConfig); - const existingLocal = fsSync.existsSync(localPath) - ? await this.readJSON(localPath) - : null; - await this.writeJSON(localPath, { ...existingLocal, ...localConfig }); - - // ---- 8. Add to the global index ---- - const now = new Date().toISOString(); - index.projects.push({ - id, - name: sourceMeta.name, - description: sourceMeta.description, - engine: engine ?? sourceMeta.engine, - databaseId, - sourcePath, - createdAt: sourceMeta.createdAt ?? now, - updatedAt: now, - }); - await this.saveIndex(index); - - // ---- 9. Return effective metadata (with local databaseId) ---- - return { - ...sourceMeta, - engine: engine ?? sourceMeta.engine, - databaseId, - sourcePath, - }; - } + // ---- 5. DO NOT modify relwave.json or sub-resource files ---- + // relwave.json keeps the original projectId & databaseId + // so forks/clones never produce unnecessary diffs. + + // ---- 6. Ensure .gitignore exists in source dir ---- + await this.ensureGitignore(id); + + // ---- 7. Write databaseId to local config (git-ignored) ---- + const localConfig: LocalConfig = { databaseId }; + const localPath = path.join(sourcePath, PROJECT_FILES.localConfig); + const existingLocal = fsSync.existsSync(localPath) + ? await this.readJSON(localPath) + : null; + await this.writeJSON(localPath, { ...existingLocal, ...localConfig }); + + // ---- 8. Add to the global index ---- + const now = new Date().toISOString(); + index.projects.push({ + id, + name: sourceMeta.name, + description: sourceMeta.description, + engine: engine ?? sourceMeta.engine, + databaseId, + sourcePath, + createdAt: sourceMeta.createdAt ?? now, + updatedAt: now, + }); + await this.saveIndex(index); + + // ---- 9. Return effective metadata (with local databaseId) ---- + return { + ...sourceMeta, + engine: engine ?? sourceMeta.engine, + databaseId, + sourcePath, + }; + } } // Singleton instance -export const projectStoreInstance = new ProjectStore(); \ No newline at end of file +export const projectStoreInstance = new ProjectStore(); diff --git a/bridge/src/services/queryExecutor.ts b/bridge/src/services/queryExecutor.ts index 425d58aa..9fdf8e8f 100644 --- a/bridge/src/services/queryExecutor.ts +++ b/bridge/src/services/queryExecutor.ts @@ -12,7 +12,7 @@ const PARALLEL_LIMIT = 5; async function parallelMap( items: T[], fn: (item: T) => Promise, - limit: number = PARALLEL_LIMIT + limit: number = PARALLEL_LIMIT, ): Promise { const results = new Array(items.length); let nextIndex = 0; @@ -61,7 +61,7 @@ export class QueryExecutor { conn: unknown, dbType: DBType, rpc: Rpc, - onCancel: (cancelFn: () => Promise) => void + onCancel: (cancelFn: () => Promise) => void, ) { const { sessionId, sql, batchSize = 200 } = params; const connector = getConnector(dbType); diff --git a/bridge/src/services/sshTunnelService.ts b/bridge/src/services/sshTunnelService.ts index 6a8fb5ec..7a8947aa 100644 --- a/bridge/src/services/sshTunnelService.ts +++ b/bridge/src/services/sshTunnelService.ts @@ -16,7 +16,7 @@ export class SSHTunnelService { async createSSHTunnel( ssh: SSHConfig, remoteHost: string, - remotePort: number + remotePort: number, ): Promise { return new Promise((resolve, reject) => { const sshClient = new Client(); @@ -54,7 +54,7 @@ export class SSHTunnelService { return; } socket.pipe(stream).pipe(socket); - } + }, ); }); }) diff --git a/bridge/src/sessionManager.ts b/bridge/src/sessionManager.ts index 33cec3b5..e38f587e 100644 --- a/bridge/src/sessionManager.ts +++ b/bridge/src/sessionManager.ts @@ -29,9 +29,15 @@ export class SessionManager { return s; } - get(id: string) { return this.sessions.get(id); } - remove(id: string) { return this.sessions.delete(id); } - list() { return Array.from(this.sessions.values()); } + get(id: string) { + return this.sessions.get(id); + } + remove(id: string) { + return this.sessions.delete(id); + } + list() { + return Array.from(this.sessions.values()); + } registerCancel(id: string, fn: () => Promise | void) { const s = this.sessions.get(id); @@ -69,4 +75,4 @@ export class SessionManager { } this.sessions.clear(); } -} \ No newline at end of file +} diff --git a/bridge/src/types/README.md b/bridge/src/types/README.md index 5722e126..427bf18b 100644 --- a/bridge/src/types/README.md +++ b/bridge/src/types/README.md @@ -3,6 +3,7 @@ This folder contains TypeScript types shared across bridge handlers, services, connectors and query result mapping. Layout + - `index.ts` - central export plus `DBType`, `Rpc`, `DatabaseConfig` and `QueryParams`. - `common.ts` - shared database metadata shapes such as tables, columns, keys, indexes, constraints, stats, migrations and SSH config. - `postgres.ts` - PostgreSQL config and PostgreSQL-specific metadata/DDL types. @@ -12,17 +13,20 @@ Layout - `ai.ts` - AI provider, prompt, result, history and error types. How it fits + - Connectors use these types for database-specific configs and normalized result shapes. - Services use these types to avoid duplicating payload contracts. - Handlers should return data that matches these types where possible, then frontend bridge services mirror the same shape. How to add or change types + 1. Prefer extending `common.ts` when a shape applies across database engines. 2. Use database-specific files only for engine-specific fields or operations. 3. Re-export new public types from `index.ts`. 4. Update connector and frontend types together when changing RPC response shapes. Notes + - Keep these files type-only. Runtime helpers belong in `src/utils` or `src/services`. - Avoid widening everything to `any`; use explicit optional fields when a database can omit metadata. - Be careful with credential-bearing types. Public response shapes should not include plaintext passwords. diff --git a/bridge/src/types/ai.ts b/bridge/src/types/ai.ts index 1cdd778a..3af4cccd 100644 --- a/bridge/src/types/ai.ts +++ b/bridge/src/types/ai.ts @@ -1,12 +1,6 @@ // ── Shared types for the AI integration layer (moved from src/ai/ai.types.ts) -export type AIProviderName = - | "anthropic" - | "openai" - | "gemini" - | "groq" - | "mistral" - | "ollama"; +export type AIProviderName = "anthropic" | "openai" | "gemini" | "groq" | "mistral" | "ollama"; /** * User-facing AI settings — stored client-side and passed on every RPC call. diff --git a/bridge/src/types/cache.ts b/bridge/src/types/cache.ts index 9cf6e4f4..edd4a54e 100644 --- a/bridge/src/types/cache.ts +++ b/bridge/src/types/cache.ts @@ -12,7 +12,7 @@ export const SCHEMA_CACHE_TTL = 300000; // 5 minutes for schemas (rarely change) * Generic cache entry with TTL support */ export type CacheEntry = { - data: T; - timestamp: number; - ttl: number; + data: T; + timestamp: number; + ttl: number; }; diff --git a/bridge/src/types/common.ts b/bridge/src/types/common.ts index 599a8341..8e32663d 100644 --- a/bridge/src/types/common.ts +++ b/bridge/src/types/common.ts @@ -7,126 +7,126 @@ * Basic table information */ export type TableInfo = { - schema: string; - name: string; - type: string; + schema: string; + name: string; + type: string; }; /** * Database statistics */ export type DBStats = { - total_tables: number; - total_db_size_mb: number; - total_rows: number; + total_tables: number; + total_db_size_mb: number; + total_rows: number; }; /** * Schema information */ export type SchemaInfo = { - name: string; + name: string; }; /** * Primary key column information */ export type PrimaryKeyInfo = { - column_name: string; + column_name: string; }; /** * Column detail information */ export type ColumnDetail = { - name: string; - type: string; - not_nullable: boolean; - default_value: string | null; - is_primary_key: boolean; - is_foreign_key: boolean; - ordinal_position?: number; - max_length?: number | null; - is_unique?: boolean; - is_serial?: boolean; - check_constraint?: string; - comment?: string | null; + name: string; + type: string; + not_nullable: boolean; + default_value: string | null; + is_primary_key: boolean; + is_foreign_key: boolean; + ordinal_position?: number; + max_length?: number | null; + is_unique?: boolean; + is_serial?: boolean; + check_constraint?: string; + comment?: string | null; }; /** * Foreign key relationship information */ export type ForeignKeyInfo = { - constraint_name: string; - source_schema: string; - source_table: string; - source_column: string; - target_schema: string; - target_table: string; - target_column: string; - update_rule: string; - delete_rule: string; - ordinal_position?: number; + constraint_name: string; + source_schema: string; + source_table: string; + source_column: string; + target_schema: string; + target_table: string; + target_column: string; + update_rule: string; + delete_rule: string; + ordinal_position?: number; }; /** * Index information */ export type IndexInfo = { - table_name: string; - index_name: string; - column_name: string; - is_unique: boolean; - is_primary: boolean; - index_type: string; - predicate?: string | null; - ordinal_position?: number; - seq_in_index?: number; // MySQL-specific + table_name: string; + index_name: string; + column_name: string; + is_unique: boolean; + is_primary: boolean; + index_type: string; + predicate?: string | null; + ordinal_position?: number; + seq_in_index?: number; // MySQL-specific }; /** * Unique constraint information */ export type UniqueConstraintInfo = { - constraint_name: string; - table_schema: string; - table_name: string; - column_name: string; - ordinal_position: number; + constraint_name: string; + table_schema: string; + table_name: string; + column_name: string; + ordinal_position: number; }; /** * Check constraint information */ export type CheckConstraintInfo = { - constraint_name: string; - table_schema: string; - table_name: string; - definition?: string; - check_clause?: string; // MySQL-specific + constraint_name: string; + table_schema: string; + table_name: string; + definition?: string; + check_clause?: string; // MySQL-specific }; /** * Applied migration record */ export type AppliedMigration = { - version: string; - name: string; - applied_at: Date; - checksum: string; + version: string; + name: string; + applied_at: Date; + checksum: string; }; /** * Alter table operation types */ export type AlterTableOperation = - | { type: "ADD_COLUMN"; columnName: string; columnDef: string } - | { type: "DROP_COLUMN"; columnName: string } - | { type: "RENAME_COLUMN"; oldName: string; newName: string } - | { type: "ALTER_COLUMN"; columnName: string; newDef: string } - | { type: "ADD_CONSTRAINT"; constraintDef: string } - | { type: "DROP_CONSTRAINT"; constraintName: string } - | { type: "RENAME_TABLE"; newName: string }; + | { type: "ADD_COLUMN"; columnName: string; columnDef: string } + | { type: "DROP_COLUMN"; columnName: string } + | { type: "RENAME_COLUMN"; oldName: string; newName: string } + | { type: "ALTER_COLUMN"; columnName: string; newDef: string } + | { type: "ADD_CONSTRAINT"; constraintDef: string } + | { type: "DROP_CONSTRAINT"; constraintName: string } + | { type: "RENAME_TABLE"; newName: string }; /** * Drop mode for table/schema operations @@ -137,11 +137,11 @@ export type DropMode = "CASCADE" | "RESTRICT" | undefined; * SSH Tunnel Configuration */ export type SSHConfig = { - host: string; - port: number; - username: string; - authMethod: "password" | "privateKey"; - password?: string; - privateKey?: string; // file path OR raw PEM string - passphrase?: string; + host: string; + port: number; + username: string; + authMethod: "password" | "privateKey"; + password?: string; + privateKey?: string; // file path OR raw PEM string + passphrase?: string; }; diff --git a/bridge/src/types/index.ts b/bridge/src/types/index.ts index dcfa1e9e..0aa8b07c 100644 --- a/bridge/src/types/index.ts +++ b/bridge/src/types/index.ts @@ -1,48 +1,48 @@ /** * Bridge Types - Main Entry Point - * + * * This module re-exports all types for convenient importing. - * + * * Usage: * import { DBType, MySQLConfig, PGConfig, CacheEntry } from '../types'; */ -import type { SSHConfig } from './common'; +import type { SSHConfig } from "./common"; -export * from './cache'; -export * from './common'; -export * from './mysql'; -export * from './postgres'; -export * from './sqlite'; -export * from './ai'; -export { SSHConfig } from './common'; +export * from "./cache"; +export * from "./common"; +export * from "./mysql"; +export * from "./postgres"; +export * from "./sqlite"; +export * from "./ai"; +export { SSHConfig } from "./common"; export enum DBType { - POSTGRES = "postgres", - MYSQL = "mysql", - MARIADB = "mariadb", - SQLITE = "sqlite", + POSTGRES = "postgres", + MYSQL = "mysql", + MARIADB = "mariadb", + SQLITE = "sqlite", } export type Rpc = { - sendResponse: (id: number | string, payload: any) => void; - sendError: (id: number | string, err: { code?: string; message: string; details?: any }) => void; - sendNotification?: (method: string, params?: any) => void; + sendResponse: (id: number | string, payload: any) => void; + sendError: (id: number | string, err: { code?: string; message: string; details?: any }) => void; + sendNotification?: (method: string, params?: any) => void; }; export interface DatabaseConfig { - host: string; - port: number; - user: string; - password?: string; - ssl?: boolean; - database: string; - ssh?: SSHConfig; + host: string; + port: number; + user: string; + password?: string; + ssl?: boolean; + database: string; + ssh?: SSHConfig; } export interface QueryParams { - sessionId: string; - dbId: string; - sql: string; - batchSize?: number; + sessionId: string; + dbId: string; + sql: string; + batchSize?: number; } diff --git a/bridge/src/types/mysql.ts b/bridge/src/types/mysql.ts index f80d8b6f..82896199 100644 --- a/bridge/src/types/mysql.ts +++ b/bridge/src/types/mysql.ts @@ -2,71 +2,81 @@ * MySQL-specific Types */ -import type { ColumnDetail, ForeignKeyInfo, IndexInfo, UniqueConstraintInfo, CheckConstraintInfo, PrimaryKeyInfo } from "./common"; +import type { + ColumnDetail, + ForeignKeyInfo, + IndexInfo, + UniqueConstraintInfo, + CheckConstraintInfo, + PrimaryKeyInfo, +} from "./common"; /** * MySQL connection configuration */ export type MySQLConfig = { - host: string; - port?: number; - user?: string; - password?: string; - database?: string; + host: string; + port?: number; + user?: string; + password?: string; + database?: string; }; /** * MySQL enum column information */ export type EnumColumnInfo = { - table_name: string; - column_name: string; - column_type?: string; - enum_values?: string[]; + table_name: string; + column_name: string; + column_type?: string; + enum_values?: string[]; }; /** * MySQL auto-increment column information */ export type AutoIncrementInfo = { - table_name: string; - column_name: string; - auto_increment_value: number | null; + table_name: string; + column_name: string; + auto_increment_value: number | null; }; /** * MySQL schema metadata batch result */ export type SchemaMetadataBatch = { - tables: Map; - enumColumns: EnumColumnInfo[]; - autoIncrements: AutoIncrementInfo[]; + tables: Map< + string, + { + columns: ColumnDetail[]; + primaryKeys: PrimaryKeyInfo[]; + foreignKeys: ForeignKeyInfo[]; + indexes: IndexInfo[]; + uniqueConstraints: UniqueConstraintInfo[]; + checkConstraints: CheckConstraintInfo[]; + } + >; + enumColumns: EnumColumnInfo[]; + autoIncrements: AutoIncrementInfo[]; }; /** * MySQL-specific alter table operations */ export type MySQLAlterTableOperation = - | { type: "ADD_COLUMN"; column: ColumnDetail } - | { type: "DROP_COLUMN"; column_name: string } - | { type: "RENAME_COLUMN"; from: string; to: string } - | { type: "SET_NOT_NULL"; column_name: string; new_type: string } - | { type: "DROP_NOT_NULL"; column_name: string; new_type: string } - | { type: "SET_DEFAULT"; column_name: string; default_value: string } - | { type: "DROP_DEFAULT"; column_name: string } - | { type: "ALTER_TYPE"; column_name: string; new_type: string }; + | { type: "ADD_COLUMN"; column: ColumnDetail } + | { type: "DROP_COLUMN"; column_name: string } + | { type: "RENAME_COLUMN"; from: string; to: string } + | { type: "SET_NOT_NULL"; column_name: string; new_type: string } + | { type: "DROP_NOT_NULL"; column_name: string; new_type: string } + | { type: "SET_DEFAULT"; column_name: string; default_value: string } + | { type: "DROP_DEFAULT"; column_name: string } + | { type: "ALTER_TYPE"; column_name: string; new_type: string }; /** * MySQL-specific drop mode */ export type MySQLDropMode = - | "RESTRICT" // fail if dependencies exist - | "DETACH_FKS" // drop dependent foreign keys first - | "CASCADE"; // explicit nuclear option + | "RESTRICT" // fail if dependencies exist + | "DETACH_FKS" // drop dependent foreign keys first + | "CASCADE"; // explicit nuclear option diff --git a/bridge/src/types/postgres.ts b/bridge/src/types/postgres.ts index 08094447..88fd1a75 100644 --- a/bridge/src/types/postgres.ts +++ b/bridge/src/types/postgres.ts @@ -2,73 +2,83 @@ * PostgreSQL-specific Types */ -import type { ColumnDetail, ForeignKeyInfo, IndexInfo, UniqueConstraintInfo, CheckConstraintInfo, PrimaryKeyInfo } from "./common"; +import type { + ColumnDetail, + ForeignKeyInfo, + IndexInfo, + UniqueConstraintInfo, + CheckConstraintInfo, + PrimaryKeyInfo, +} from "./common"; /** * PostgreSQL connection configuration */ export type PGConfig = { - host: string; - port?: number; - user?: string; - password?: string; - database?: string; - ssl?: boolean; - sslmode?: string; + host: string; + port?: number; + user?: string; + password?: string; + database?: string; + ssl?: boolean; + sslmode?: string; }; /** * PostgreSQL enum type information */ export type EnumInfo = { - schema_name: string; - enum_name: string; - enum_value: string; + schema_name: string; + enum_name: string; + enum_value: string; }; /** * PostgreSQL sequence information */ export type SequenceInfo = { - sequence_name: string; - sequence_schema: string; - table_name: string | null; - column_name: string | null; + sequence_name: string; + sequence_schema: string; + table_name: string | null; + column_name: string | null; }; /** * PostgreSQL schema metadata batch result */ export type PGSchemaMetadataBatch = { - tables: Map; - enums: EnumInfo[]; - sequences: SequenceInfo[]; + tables: Map< + string, + { + columns: ColumnDetail[]; + primaryKeys: PrimaryKeyInfo[]; + foreignKeys: ForeignKeyInfo[]; + indexes: IndexInfo[]; + uniqueConstraints: UniqueConstraintInfo[]; + checkConstraints: CheckConstraintInfo[]; + } + >; + enums: EnumInfo[]; + sequences: SequenceInfo[]; }; /** * PostgreSQL-specific alter table operations */ export type PGAlterTableOperation = - | { type: "ADD_COLUMN"; column: ColumnDetail } - | { type: "DROP_COLUMN"; column_name: string } - | { type: "RENAME_COLUMN"; from: string; to: string } - | { type: "SET_NOT_NULL"; column_name: string } - | { type: "DROP_NOT_NULL"; column_name: string } - | { type: "SET_DEFAULT"; column_name: string; default_value: string } - | { type: "DROP_DEFAULT"; column_name: string } - | { type: "ALTER_TYPE"; column_name: string; new_type: string }; + | { type: "ADD_COLUMN"; column: ColumnDetail } + | { type: "DROP_COLUMN"; column_name: string } + | { type: "RENAME_COLUMN"; from: string; to: string } + | { type: "SET_NOT_NULL"; column_name: string } + | { type: "DROP_NOT_NULL"; column_name: string } + | { type: "SET_DEFAULT"; column_name: string; default_value: string } + | { type: "DROP_DEFAULT"; column_name: string } + | { type: "ALTER_TYPE"; column_name: string; new_type: string }; /** * PostgreSQL-specific drop mode */ export type PGDropMode = - | "RESTRICT" // fail if dependencies exist - | "DETACH_FKS" // drop dependent foreign keys first - | "CASCADE"; // explicit nuclear option \ No newline at end of file + | "RESTRICT" // fail if dependencies exist + | "DETACH_FKS" // drop dependent foreign keys first + | "CASCADE"; // explicit nuclear option diff --git a/bridge/src/types/sqlite.ts b/bridge/src/types/sqlite.ts index 5b71d6c1..b86214cf 100644 --- a/bridge/src/types/sqlite.ts +++ b/bridge/src/types/sqlite.ts @@ -2,45 +2,53 @@ * SQLite-specific Types */ -import type { ColumnDetail, ForeignKeyInfo, IndexInfo, UniqueConstraintInfo, CheckConstraintInfo, PrimaryKeyInfo } from "./common"; +import type { + ColumnDetail, + ForeignKeyInfo, + IndexInfo, + UniqueConstraintInfo, + CheckConstraintInfo, + PrimaryKeyInfo, +} from "./common"; /** * SQLite connection configuration (file-based, no host/port/user) */ export type SQLiteConfig = { - path: string; - readonly?: boolean; + path: string; + readonly?: boolean; }; /** * SQLite schema metadata batch result */ export type SQLiteSchemaMetadataBatch = { - tables: Map; + tables: Map< + string, + { + columns: ColumnDetail[]; + primaryKeys: PrimaryKeyInfo[]; + foreignKeys: ForeignKeyInfo[]; + indexes: IndexInfo[]; + uniqueConstraints: UniqueConstraintInfo[]; + checkConstraints: CheckConstraintInfo[]; + } + >; }; /** -* SQLite has limited ALTER TABLE support: + * SQLite has limited ALTER TABLE support: * - ADD COLUMN * - DROP COLUMN (requires SQLite 3.35.0+) * - RENAME COLUMN * - RENAME TABLE */ export type SQLiteAlterTableOperation = - | { type: "ADD_COLUMN"; column: ColumnDetail } - | { type: "DROP_COLUMN"; column_name: string } - | { type: "RENAME_COLUMN"; from: string; to: string }; + | { type: "ADD_COLUMN"; column: ColumnDetail } + | { type: "DROP_COLUMN"; column_name: string } + | { type: "RENAME_COLUMN"; from: string; to: string }; /** * SQLite-specific drop mode */ -export type SQLiteDropMode = - | "RESTRICT" - | "CASCADE"; +export type SQLiteDropMode = "RESTRICT" | "CASCADE"; diff --git a/bridge/src/utils/README.md b/bridge/src/utils/README.md index d5a23927..caa40781 100644 --- a/bridge/src/utils/README.md +++ b/bridge/src/utils/README.md @@ -3,6 +3,7 @@ This folder contains small, reusable bridge helpers for paths, database type detection, migration file handling and configuration. Layout + - `config.ts` - RelWave data directories and file paths. Honors `RELWAVE_HOME` when set. - `dbTypeDetector.ts` - maps saved database records to `DBType`. - `sqlitePath.ts` - SQLite path normalization and resolution helpers. @@ -11,17 +12,20 @@ Layout - `baselineMigration.ts` - local baseline migration loading and writing helpers. How it fits + - Services and connectors use these helpers for filesystem paths, database type decisions and migration workflows. - `config.ts` is the source of truth for bridge persistence locations, including databases, projects, migrations and connection folders. - Migration utilities are used by migration handlers and connectors to generate, read and reconcile local migration files. How to add a utility + 1. Add utilities here only when they are reusable and do not own business state. 2. Keep functions deterministic where possible and pass dependencies in as parameters. 3. Use `config.ts` path helpers for filesystem locations instead of hardcoding OS-specific paths. 4. Add tests for parsing, path resolution or SQL generation behavior that can regress quietly. Notes + - Utilities should not send JSON-RPC responses or import frontend code. - Keep database-specific SQL in `src/queries`; use utility helpers for generation/parsing logic that is shared by workflows. - Avoid storing secrets in files managed by utility paths. Credentials should go through `keyringService`. diff --git a/bridge/src/utils/baselineMigration.ts b/bridge/src/utils/baselineMigration.ts index 291363e2..55171026 100644 --- a/bridge/src/utils/baselineMigration.ts +++ b/bridge/src/utils/baselineMigration.ts @@ -4,18 +4,18 @@ import path from "path"; import { SchemaFile } from "../services/projectStore"; function quoteIdent(name: string, dbType: string): string { - if (dbType === "mysql" || dbType === "mariadb") { - return `\`${name.replace(/`/g, "``")}\``; - } else { - return `"${name.replace(/"/g, '""')}"`; - } + if (dbType === "mysql" || dbType === "mariadb") { + return `\`${name.replace(/`/g, "``")}\``; + } else { + return `"${name.replace(/"/g, '""')}"`; + } } export function generateBaselineSQL(snapshot: SchemaFile, version: string, name: string) { - const dbType = snapshot.dialect || "unknown"; - - if (dbType === "unknown") { - return `-- ${version}_${name}.sql + const dbType = snapshot.dialect || "unknown"; + + if (dbType === "unknown") { + return `-- ${version}_${name}.sql -- +up -- Baseline migration @@ -25,95 +25,110 @@ export function generateBaselineSQL(snapshot: SchemaFile, version: string, name: -- +down -- Rollback not supported for baseline `; + } + + let upSQL = ""; + + for (const schema of snapshot.schemas) { + // Enums (Postgres) + if (schema.enums && dbType === "postgresql") { + for (const e of schema.enums) { + const vals = e.values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", "); + upSQL += `CREATE TYPE ${quoteIdent(schema.name, dbType)}.${quoteIdent(e.name, dbType)} AS ENUM (${vals});\n`; + } + if (schema.enums.length > 0) upSQL += "\n"; } - let upSQL = ""; - - for (const schema of snapshot.schemas) { - // Enums (Postgres) - if (schema.enums && dbType === "postgresql") { - for (const e of schema.enums) { - const vals = e.values.map(v => `'${v.replace(/'/g, "''")}'`).join(", "); - upSQL += `CREATE TYPE ${quoteIdent(schema.name, dbType)}.${quoteIdent(e.name, dbType)} AS ENUM (${vals});\n`; + // Tables + for (const table of schema.tables) { + // Skip internal migration tracking tables + if ( + ["schema_migrations", "__relwave_migrations", "relwave_migrations"].includes(table.name) + ) { + continue; + } + + const tableRef = + dbType === "sqlite" + ? quoteIdent(table.name, dbType) + : `${quoteIdent(schema.name, dbType)}.${quoteIdent(table.name, dbType)}`; + + // Check for sequences first (Postgres) + if (dbType === "postgresql") { + for (const col of table.columns) { + if (col.defaultValue && col.defaultValue.includes("nextval(")) { + // Extract 'windows_store_apps_id_seq' from nextval('windows_store_apps_id_seq'::regclass) + const seqMatch = + col.defaultValue.match(/nextval\('([^']+)'/i) || + col.defaultValue.match(/nextval\("([^"]+)"/i); + if (seqMatch && seqMatch[1]) { + const seqName = seqMatch[1]; + const isSchemaQualified = seqName.includes("."); + const seqRef = isSchemaQualified + ? seqName + : `${quoteIdent(schema.name, dbType)}.${quoteIdent(seqName, dbType)}`; + upSQL += `CREATE SEQUENCE IF NOT EXISTS ${seqRef};\n`; } - if (schema.enums.length > 0) upSQL += "\n"; + } } - - // Tables - for (const table of schema.tables) { - // Skip internal migration tracking tables - if (["schema_migrations", "__relwave_migrations", "relwave_migrations"].includes(table.name)) { - continue; - } - - const tableRef = dbType === "sqlite" ? quoteIdent(table.name, dbType) : `${quoteIdent(schema.name, dbType)}.${quoteIdent(table.name, dbType)}`; - - // Check for sequences first (Postgres) - if (dbType === "postgresql") { - for (const col of table.columns) { - if (col.defaultValue && col.defaultValue.includes("nextval(")) { - // Extract 'windows_store_apps_id_seq' from nextval('windows_store_apps_id_seq'::regclass) - const seqMatch = col.defaultValue.match(/nextval\('([^']+)'/i) || col.defaultValue.match(/nextval\("([^"]+)"/i); - if (seqMatch && seqMatch[1]) { - const seqName = seqMatch[1]; - const isSchemaQualified = seqName.includes("."); - const seqRef = isSchemaQualified ? seqName : `${quoteIdent(schema.name, dbType)}.${quoteIdent(seqName, dbType)}`; - upSQL += `CREATE SEQUENCE IF NOT EXISTS ${seqRef};\n`; - } - } - } - } - - const columnDefs = table.columns.map(col => { - let def = ` ${quoteIdent(col.name, dbType)} ${col.type}`; - if (!col.nullable) def += " NOT NULL"; - if (col.defaultValue) def += ` DEFAULT ${col.defaultValue}`; - if (col.isPrimaryKey) def += " PRIMARY KEY"; - if (col.isUnique && !col.isPrimaryKey) def += " UNIQUE"; - if (col.checkConstraint) def += ` ${col.checkConstraint}`; - return def; - }); - - // check constraints - if (table.checks && table.checks.length > 0) { - for (const chk of table.checks) { - columnDefs.push(` CONSTRAINT ${quoteIdent(chk.name, dbType)} CHECK (${chk.expression})`); - } - } - - const fkDefs = (table.foreignKeys || []).map(fk => { - const onDelete = fk.onDelete || "NO ACTION"; - const onUpdate = fk.onUpdate || "NO ACTION"; - const targetRef = dbType === "sqlite" ? quoteIdent(fk.referencedTable, dbType) : `${quoteIdent(fk.referencedSchema || schema.name, dbType)}.${quoteIdent(fk.referencedTable, dbType)}`; - const srcCols = fk.columns.map(c => quoteIdent(c, dbType)).join(", "); - const tgtCols = fk.referencedColumns.map(c => quoteIdent(c, dbType)).join(", "); - return ` CONSTRAINT ${quoteIdent(fk.name, dbType)} FOREIGN KEY (${srcCols}) REFERENCES ${targetRef}(${tgtCols}) ON DELETE ${onDelete} ON UPDATE ${onUpdate}`; - }); - - const allDefs = [...columnDefs, ...fkDefs].join(",\n"); - - upSQL += `CREATE TABLE ${tableRef} (\n${allDefs}\n);\n\n`; - - // Indexes - const indexesToCreate = (table.indexes || []); - for (const idx of indexesToCreate) { - const idxCols = idx.columns.map(c => quoteIdent(c, dbType)).join(", "); - const uniqueStr = idx.unique ? "UNIQUE " : ""; - upSQL += `CREATE ${uniqueStr}INDEX ${quoteIdent(idx.name, dbType)} ON ${tableRef} (${idxCols});\n`; - } - if (indexesToCreate.length > 0) upSQL += "\n"; - } - - // Views - if (schema.views) { - for (const v of schema.views) { - const viewRef = dbType === "sqlite" ? quoteIdent(v.name, dbType) : `${quoteIdent(schema.name, dbType)}.${quoteIdent(v.name, dbType)}`; - upSQL += `CREATE VIEW ${viewRef} AS ${v.definition};\n\n`; - } + } + + const columnDefs = table.columns.map((col) => { + let def = ` ${quoteIdent(col.name, dbType)} ${col.type}`; + if (!col.nullable) def += " NOT NULL"; + if (col.defaultValue) def += ` DEFAULT ${col.defaultValue}`; + if (col.isPrimaryKey) def += " PRIMARY KEY"; + if (col.isUnique && !col.isPrimaryKey) def += " UNIQUE"; + if (col.checkConstraint) def += ` ${col.checkConstraint}`; + return def; + }); + + // check constraints + if (table.checks && table.checks.length > 0) { + for (const chk of table.checks) { + columnDefs.push(` CONSTRAINT ${quoteIdent(chk.name, dbType)} CHECK (${chk.expression})`); } + } + + const fkDefs = (table.foreignKeys || []).map((fk) => { + const onDelete = fk.onDelete || "NO ACTION"; + const onUpdate = fk.onUpdate || "NO ACTION"; + const targetRef = + dbType === "sqlite" + ? quoteIdent(fk.referencedTable, dbType) + : `${quoteIdent(fk.referencedSchema || schema.name, dbType)}.${quoteIdent(fk.referencedTable, dbType)}`; + const srcCols = fk.columns.map((c) => quoteIdent(c, dbType)).join(", "); + const tgtCols = fk.referencedColumns.map((c) => quoteIdent(c, dbType)).join(", "); + return ` CONSTRAINT ${quoteIdent(fk.name, dbType)} FOREIGN KEY (${srcCols}) REFERENCES ${targetRef}(${tgtCols}) ON DELETE ${onDelete} ON UPDATE ${onUpdate}`; + }); + + const allDefs = [...columnDefs, ...fkDefs].join(",\n"); + + upSQL += `CREATE TABLE ${tableRef} (\n${allDefs}\n);\n\n`; + + // Indexes + const indexesToCreate = table.indexes || []; + for (const idx of indexesToCreate) { + const idxCols = idx.columns.map((c) => quoteIdent(c, dbType)).join(", "); + const uniqueStr = idx.unique ? "UNIQUE " : ""; + upSQL += `CREATE ${uniqueStr}INDEX ${quoteIdent(idx.name, dbType)} ON ${tableRef} (${idxCols});\n`; + } + if (indexesToCreate.length > 0) upSQL += "\n"; } - return `-- ${version}_${name}.sql + // Views + if (schema.views) { + for (const v of schema.views) { + const viewRef = + dbType === "sqlite" + ? quoteIdent(v.name, dbType) + : `${quoteIdent(schema.name, dbType)}.${quoteIdent(v.name, dbType)}`; + upSQL += `CREATE VIEW ${viewRef} AS ${v.definition};\n\n`; + } + } + } + + return `-- ${version}_${name}.sql -- +up -- Baseline migration generated from current schema snapshot @@ -124,36 +139,33 @@ ${upSQL.trim()} `; } - export function writeBaselineMigration( - migrationsDir: string, - version: string, - name: string, - snapshot: SchemaFile + migrationsDir: string, + version: string, + name: string, + snapshot: SchemaFile, ) { - if (!fs.existsSync(migrationsDir)) { - fs.mkdirSync(migrationsDir, { recursive: true }); - } + if (!fs.existsSync(migrationsDir)) { + fs.mkdirSync(migrationsDir, { recursive: true }); + } - const filename = `${version}_${name}.sql`; - const filepath = path.join(migrationsDir, filename); + const filename = `${version}_${name}.sql`; + const filepath = path.join(migrationsDir, filename); - const sql = generateBaselineSQL(snapshot, version, name); - fs.writeFileSync(filepath, sql, "utf8"); + const sql = generateBaselineSQL(snapshot, version, name); + fs.writeFileSync(filepath, sql, "utf8"); - return filepath; + return filepath; } export async function loadLocalMigrations(migrationsDir: string) { - const files = await fs.promises.readdir(migrationsDir); - const migrations = files - .filter((file) => file.endsWith(".sql")) - .map((file) => { - const version = file.split("_")[0]; - const name = file.split("_")[1]; - return { version, name }; - }); - return migrations; + const files = await fs.promises.readdir(migrationsDir); + const migrations = files + .filter((file) => file.endsWith(".sql")) + .map((file) => { + const version = file.split("_")[0]; + const name = file.split("_")[1]; + return { version, name }; + }); + return migrations; } - - diff --git a/bridge/src/utils/config.ts b/bridge/src/utils/config.ts index 998f5ed9..c73791f9 100644 --- a/bridge/src/utils/config.ts +++ b/bridge/src/utils/config.ts @@ -4,18 +4,12 @@ import fsSync from "fs"; export const CONFIG_FOLDER = process.env.RELWAVE_HOME || - path.join( - os.homedir(), - process.platform === "win32" - ? "AppData\\Roaming\\relwave" - : ".relwave" - ); + path.join(os.homedir(), process.platform === "win32" ? "AppData\\Roaming\\relwave" : ".relwave"); export const CONFIG_FILE = path.join(CONFIG_FOLDER, "databases.json"); export const CREDENTIALS_FILE = path.join(CONFIG_FOLDER, ".credentials"); export const AI_SETTINGS_FILE = path.join(CONFIG_FOLDER, "ai-settings.json"); - export const PROJECTS_FOLDER = path.join(CONFIG_FOLDER, "projects"); export const PROJECTS_INDEX_FILE = path.join(PROJECTS_FOLDER, "index.json"); @@ -31,4 +25,4 @@ export function ensureDir(dir: string) { if (!fsSync.existsSync(dir)) { fsSync.mkdirSync(dir, { recursive: true }); } -} \ No newline at end of file +} diff --git a/bridge/src/utils/dbTypeDetector.ts b/bridge/src/utils/dbTypeDetector.ts index 2f10174c..43c047f1 100644 --- a/bridge/src/utils/dbTypeDetector.ts +++ b/bridge/src/utils/dbTypeDetector.ts @@ -11,6 +11,6 @@ export class DBTypeDetector { } if (normalized.includes("sqlite")) return DBType.SQLITE; } - return DBType.POSTGRES; // default + return DBType.POSTGRES; // default } } diff --git a/bridge/src/utils/lruCache.ts b/bridge/src/utils/lruCache.ts index 31bad123..8b377a68 100644 --- a/bridge/src/utils/lruCache.ts +++ b/bridge/src/utils/lruCache.ts @@ -11,7 +11,7 @@ export class LRUCache { get(key: K): CacheEntry | undefined { const entry = this.map.get(key); if (!entry) return undefined; - + // Check TTL on read to lazily evict if (Date.now() - entry.timestamp > entry.ttl) { this.map.delete(key); diff --git a/bridge/src/utils/migrationFileReader.ts b/bridge/src/utils/migrationFileReader.ts index 88627fc1..7e9b629c 100644 --- a/bridge/src/utils/migrationFileReader.ts +++ b/bridge/src/utils/migrationFileReader.ts @@ -3,64 +3,59 @@ import path from "path"; import crypto from "crypto"; export interface ParsedMigration { - version: string; - name: string; - upSQL: string; - downSQL: string; - checksum: string; + version: string; + name: string; + upSQL: string; + downSQL: string; + checksum: string; } /** * Read and parse a migration file */ export function readMigrationFile(filepath: string): ParsedMigration { - const content = fs.readFileSync(filepath, "utf8"); - const filename = path.basename(filepath); - - // Accept both 14-digit (YYYYMMDDHHmmss) and 13-digit (Date.now() ms) version formats - const match = filename.match(/^(\d{13,14})_(.+)\.sql$/); - if (!match) { - throw new Error(`Invalid migration filename format: ${filename}`); - } - - const [, version, name] = match; - - // Parse up and down SQL - const upMatch = content.match(/--\s*\+up\s*\n([\s\S]*?)(?=\n--\s*\+down|$)/i); - const downMatch = content.match(/--\s*\+down\s*\n([\s\S]*?)$/i); - - if (!upMatch || !downMatch) { - throw new Error(`Migration file missing +up or +down sections: ${filename}`); - } - - const upSQL = upMatch[1].trim(); - const downSQL = downMatch[1].trim(); - - // Calculate checksum - const checksum = crypto - .createHash("sha256") - .update(content) - .digest("hex"); - - return { - version, - name, - upSQL, - downSQL, - checksum, - }; + const content = fs.readFileSync(filepath, "utf8"); + const filename = path.basename(filepath); + + // Accept both 14-digit (YYYYMMDDHHmmss) and 13-digit (Date.now() ms) version formats + const match = filename.match(/^(\d{13,14})_(.+)\.sql$/); + if (!match) { + throw new Error(`Invalid migration filename format: ${filename}`); + } + + const [, version, name] = match; + + // Parse up and down SQL + const upMatch = content.match(/--\s*\+up\s*\n([\s\S]*?)(?=\n--\s*\+down|$)/i); + const downMatch = content.match(/--\s*\+down\s*\n([\s\S]*?)$/i); + + if (!upMatch || !downMatch) { + throw new Error(`Migration file missing +up or +down sections: ${filename}`); + } + + const upSQL = upMatch[1].trim(); + const downSQL = downMatch[1].trim(); + + // Calculate checksum + const checksum = crypto.createHash("sha256").update(content).digest("hex"); + + return { + version, + name, + upSQL, + downSQL, + checksum, + }; } /** * List all migration files in a directory */ export function listMigrationFiles(migrationsDir: string): string[] { - if (!fs.existsSync(migrationsDir)) { - return []; - } + if (!fs.existsSync(migrationsDir)) { + return []; + } - const files = fs.readdirSync(migrationsDir); - return files - .filter((file) => file.endsWith(".sql")) - .sort(); // Sort by filename (which includes timestamp) + const files = fs.readdirSync(migrationsDir); + return files.filter((file) => file.endsWith(".sql")).sort(); // Sort by filename (which includes timestamp) } diff --git a/bridge/src/utils/migrationGenerator.ts b/bridge/src/utils/migrationGenerator.ts index aa246364..a266f1c7 100644 --- a/bridge/src/utils/migrationGenerator.ts +++ b/bridge/src/utils/migrationGenerator.ts @@ -2,11 +2,11 @@ import fs from "fs"; import path from "path"; export interface MigrationFile { - version: string; - name: string; - filename: string; - upSQL: string; - downSQL: string; + version: string; + name: string; + filename: string; + upSQL: string; + downSQL: string; } /** @@ -14,280 +14,279 @@ export interface MigrationFile { * Format: YYYYMMDDHHmmss */ export function generateMigrationVersion(): string { - const now = new Date(); - const year = now.getFullYear(); - const month = String(now.getMonth() + 1).padStart(2, "0"); - const day = String(now.getDate()).padStart(2, "0"); - const hours = String(now.getHours()).padStart(2, "0"); - const minutes = String(now.getMinutes()).padStart(2, "0"); - const seconds = String(now.getSeconds()).padStart(2, "0"); - - return `${year}${month}${day}${hours}${minutes}${seconds}`; + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, "0"); + const day = String(now.getDate()).padStart(2, "0"); + const hours = String(now.getHours()).padStart(2, "0"); + const minutes = String(now.getMinutes()).padStart(2, "0"); + const seconds = String(now.getSeconds()).padStart(2, "0"); + + return `${year}${month}${day}${hours}${minutes}${seconds}`; } /** * Generate CREATE TABLE migration */ export function generateCreateTableMigration(params: { - schemaName: string; - tableName: string; - columns: any[]; - foreignKeys?: any[]; - dbType: "mysql" | "postgres" | "mariadb" | "sqlite"; + schemaName: string; + tableName: string; + columns: any[]; + foreignKeys?: any[]; + dbType: "mysql" | "postgres" | "mariadb" | "sqlite"; }): MigrationFile { - const { schemaName, tableName, columns, foreignKeys = [], dbType } = params; - const version = generateMigrationVersion(); - const name = `create_${tableName}_table`; - const filename = `${version}_${name}.sql`; - - // Build column definitions - const columnDefs = columns.map((col) => { - let def = ` ${quoteIdent(col.name, dbType)} ${col.type}`; - if (col.not_nullable) def += " NOT NULL"; - if (col.default_value) def += ` DEFAULT ${col.default_value}`; - if (col.is_primary_key) def += " PRIMARY KEY"; - return def; - }).join(",\n"); - - // Build foreign key constraints - const fkDefs = foreignKeys.map((fk) => { - const onDelete = fk.on_delete || "NO ACTION"; - const onUpdate = fk.on_update || "NO ACTION"; - return ` CONSTRAINT ${quoteIdent(fk.constraint_name, dbType)} FOREIGN KEY (${quoteIdent(fk.source_column, dbType)}) REFERENCES ${quoteIdent(fk.target_schema, dbType)}.${quoteIdent(fk.target_table, dbType)}(${quoteIdent(fk.target_column, dbType)}) ON DELETE ${onDelete} ON UPDATE ${onUpdate}`; - }); - - const allDefs = [...[columnDefs], ...fkDefs].filter(Boolean).join(",\n"); - - // For MySQL/MariaDB, use database.table format (schemas are databases) - // For Postgres, use schema.table format - const tableRef = `${quoteIdent(schemaName, dbType)}.${quoteIdent(tableName, dbType)}`; - - // Generate UP SQL - const upSQL = `CREATE TABLE ${tableRef} ( + const { schemaName, tableName, columns, foreignKeys = [], dbType } = params; + const version = generateMigrationVersion(); + const name = `create_${tableName}_table`; + const filename = `${version}_${name}.sql`; + + // Build column definitions + const columnDefs = columns + .map((col) => { + let def = ` ${quoteIdent(col.name, dbType)} ${col.type}`; + if (col.not_nullable) def += " NOT NULL"; + if (col.default_value) def += ` DEFAULT ${col.default_value}`; + if (col.is_primary_key) def += " PRIMARY KEY"; + return def; + }) + .join(",\n"); + + // Build foreign key constraints + const fkDefs = foreignKeys.map((fk) => { + const onDelete = fk.on_delete || "NO ACTION"; + const onUpdate = fk.on_update || "NO ACTION"; + return ` CONSTRAINT ${quoteIdent(fk.constraint_name, dbType)} FOREIGN KEY (${quoteIdent(fk.source_column, dbType)}) REFERENCES ${quoteIdent(fk.target_schema, dbType)}.${quoteIdent(fk.target_table, dbType)}(${quoteIdent(fk.target_column, dbType)}) ON DELETE ${onDelete} ON UPDATE ${onUpdate}`; + }); + + const allDefs = [...[columnDefs], ...fkDefs].filter(Boolean).join(",\n"); + + // For MySQL/MariaDB, use database.table format (schemas are databases) + // For Postgres, use schema.table format + const tableRef = `${quoteIdent(schemaName, dbType)}.${quoteIdent(tableName, dbType)}`; + + // Generate UP SQL + const upSQL = `CREATE TABLE ${tableRef} ( ${allDefs} );`; - // Generate DOWN SQL - const downSQL = `DROP TABLE ${tableRef};`; + // Generate DOWN SQL + const downSQL = `DROP TABLE ${tableRef};`; - return { - version, - name, - filename, - upSQL, - downSQL, - }; + return { + version, + name, + filename, + upSQL, + downSQL, + }; } /** * Generate ALTER TABLE migration */ export function generateAlterTableMigration(params: { - schemaName: string; - tableName: string; - operations: any[]; - dbType: "mysql" | "postgres" | "mariadb" | "sqlite"; + schemaName: string; + tableName: string; + operations: any[]; + dbType: "mysql" | "postgres" | "mariadb" | "sqlite"; }): MigrationFile { - const { schemaName, tableName, operations, dbType } = params; - const version = generateMigrationVersion(); - const name = `alter_${tableName}_table`; - const filename = `${version}_${name}.sql`; - - // For all database types, use schema/database prefix - const fullTableName = `${quoteIdent(schemaName, dbType)}.${quoteIdent(tableName, dbType)}`; - - // Build UP SQL - const upStatements: string[] = []; - const downStatements: string[] = []; - - for (const op of operations) { - switch (op.type) { - case "ADD_COLUMN": - upStatements.push( - `ALTER TABLE ${fullTableName} ADD COLUMN ${quoteIdent(op.column.name, dbType)} ${op.column.type}${op.column.not_nullable ? " NOT NULL" : ""}${op.column.default_value ? ` DEFAULT ${op.column.default_value}` : ""};` - ); - downStatements.push( - `ALTER TABLE ${fullTableName} DROP COLUMN ${quoteIdent(op.column.name, dbType)};` - ); - break; - - case "DROP_COLUMN": - // Note: Can't fully reverse without knowing column definition - upStatements.push( - `ALTER TABLE ${fullTableName} DROP COLUMN ${quoteIdent(op.column_name, dbType)};` - ); - downStatements.push( - `-- WARNING: Cannot automatically reverse DROP COLUMN. Manual intervention required.` - ); - break; - - case "RENAME_COLUMN": - if (dbType === "postgres") { - upStatements.push( - `ALTER TABLE ${fullTableName} RENAME COLUMN ${quoteIdent(op.from, dbType)} TO ${quoteIdent(op.to, dbType)};` - ); - downStatements.push( - `ALTER TABLE ${fullTableName} RENAME COLUMN ${quoteIdent(op.to, dbType)} TO ${quoteIdent(op.from, dbType)};` - ); - } else { - upStatements.push( - `ALTER TABLE ${fullTableName} RENAME COLUMN ${quoteIdent(op.from, dbType)} TO ${quoteIdent(op.to, dbType)};` - ); - downStatements.push( - `ALTER TABLE ${fullTableName} RENAME COLUMN ${quoteIdent(op.to, dbType)} TO ${quoteIdent(op.from, dbType)};` - ); - } - break; - - case "ALTER_TYPE": - upStatements.push( - `ALTER TABLE ${fullTableName} ${dbType === "postgres" ? "ALTER COLUMN" : "MODIFY"} ${quoteIdent(op.column_name, dbType)} ${dbType === "postgres" ? "TYPE " : ""}${op.new_type};` - ); - downStatements.push( - `-- WARNING: Cannot automatically reverse ALTER TYPE. Manual intervention required.` - ); - break; - - case "SET_NOT_NULL": - if (dbType === "postgres") { - upStatements.push( - `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} SET NOT NULL;` - ); - downStatements.push( - `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP NOT NULL;` - ); - } else { - upStatements.push( - `ALTER TABLE ${fullTableName} MODIFY ${quoteIdent(op.column_name, dbType)} ${op.new_type} NOT NULL;` - ); - downStatements.push( - `ALTER TABLE ${fullTableName} MODIFY ${quoteIdent(op.column_name, dbType)} ${op.new_type};` - ); - } - break; - - case "DROP_NOT_NULL": - if (dbType === "postgres") { - upStatements.push( - `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP NOT NULL;` - ); - downStatements.push( - `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} SET NOT NULL;` - ); - } else { - upStatements.push( - `ALTER TABLE ${fullTableName} MODIFY ${quoteIdent(op.column_name, dbType)} ${op.new_type};` - ); - downStatements.push( - `ALTER TABLE ${fullTableName} MODIFY ${quoteIdent(op.column_name, dbType)} ${op.new_type} NOT NULL;` - ); - } - break; - - case "SET_DEFAULT": - if (dbType === "postgres") { - upStatements.push( - `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} SET DEFAULT ${op.default_value};` - ); - downStatements.push( - `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP DEFAULT;` - ); - } else { - upStatements.push( - `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} SET DEFAULT ${op.default_value};` - ); - downStatements.push( - `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP DEFAULT;` - ); - } - break; - - case "DROP_DEFAULT": - if (dbType === "postgres") { - upStatements.push( - `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP DEFAULT;` - ); - downStatements.push( - `-- WARNING: Cannot automatically reverse DROP DEFAULT. Manual intervention required.` - ); - } else { - upStatements.push( - `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP DEFAULT;` - ); - downStatements.push( - `-- WARNING: Cannot automatically reverse DROP DEFAULT. Manual intervention required.` - ); - } - break; + const { schemaName, tableName, operations, dbType } = params; + const version = generateMigrationVersion(); + const name = `alter_${tableName}_table`; + const filename = `${version}_${name}.sql`; + + // For all database types, use schema/database prefix + const fullTableName = `${quoteIdent(schemaName, dbType)}.${quoteIdent(tableName, dbType)}`; + + // Build UP SQL + const upStatements: string[] = []; + const downStatements: string[] = []; + + for (const op of operations) { + switch (op.type) { + case "ADD_COLUMN": + upStatements.push( + `ALTER TABLE ${fullTableName} ADD COLUMN ${quoteIdent(op.column.name, dbType)} ${op.column.type}${op.column.not_nullable ? " NOT NULL" : ""}${op.column.default_value ? ` DEFAULT ${op.column.default_value}` : ""};`, + ); + downStatements.push( + `ALTER TABLE ${fullTableName} DROP COLUMN ${quoteIdent(op.column.name, dbType)};`, + ); + break; + + case "DROP_COLUMN": + // Note: Can't fully reverse without knowing column definition + upStatements.push( + `ALTER TABLE ${fullTableName} DROP COLUMN ${quoteIdent(op.column_name, dbType)};`, + ); + downStatements.push( + `-- WARNING: Cannot automatically reverse DROP COLUMN. Manual intervention required.`, + ); + break; + + case "RENAME_COLUMN": + if (dbType === "postgres") { + upStatements.push( + `ALTER TABLE ${fullTableName} RENAME COLUMN ${quoteIdent(op.from, dbType)} TO ${quoteIdent(op.to, dbType)};`, + ); + downStatements.push( + `ALTER TABLE ${fullTableName} RENAME COLUMN ${quoteIdent(op.to, dbType)} TO ${quoteIdent(op.from, dbType)};`, + ); + } else { + upStatements.push( + `ALTER TABLE ${fullTableName} RENAME COLUMN ${quoteIdent(op.from, dbType)} TO ${quoteIdent(op.to, dbType)};`, + ); + downStatements.push( + `ALTER TABLE ${fullTableName} RENAME COLUMN ${quoteIdent(op.to, dbType)} TO ${quoteIdent(op.from, dbType)};`, + ); } + break; + + case "ALTER_TYPE": + upStatements.push( + `ALTER TABLE ${fullTableName} ${dbType === "postgres" ? "ALTER COLUMN" : "MODIFY"} ${quoteIdent(op.column_name, dbType)} ${dbType === "postgres" ? "TYPE " : ""}${op.new_type};`, + ); + downStatements.push( + `-- WARNING: Cannot automatically reverse ALTER TYPE. Manual intervention required.`, + ); + break; + + case "SET_NOT_NULL": + if (dbType === "postgres") { + upStatements.push( + `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} SET NOT NULL;`, + ); + downStatements.push( + `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP NOT NULL;`, + ); + } else { + upStatements.push( + `ALTER TABLE ${fullTableName} MODIFY ${quoteIdent(op.column_name, dbType)} ${op.new_type} NOT NULL;`, + ); + downStatements.push( + `ALTER TABLE ${fullTableName} MODIFY ${quoteIdent(op.column_name, dbType)} ${op.new_type};`, + ); + } + break; + + case "DROP_NOT_NULL": + if (dbType === "postgres") { + upStatements.push( + `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP NOT NULL;`, + ); + downStatements.push( + `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} SET NOT NULL;`, + ); + } else { + upStatements.push( + `ALTER TABLE ${fullTableName} MODIFY ${quoteIdent(op.column_name, dbType)} ${op.new_type};`, + ); + downStatements.push( + `ALTER TABLE ${fullTableName} MODIFY ${quoteIdent(op.column_name, dbType)} ${op.new_type} NOT NULL;`, + ); + } + break; + + case "SET_DEFAULT": + if (dbType === "postgres") { + upStatements.push( + `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} SET DEFAULT ${op.default_value};`, + ); + downStatements.push( + `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP DEFAULT;`, + ); + } else { + upStatements.push( + `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} SET DEFAULT ${op.default_value};`, + ); + downStatements.push( + `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP DEFAULT;`, + ); + } + break; + + case "DROP_DEFAULT": + if (dbType === "postgres") { + upStatements.push( + `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP DEFAULT;`, + ); + downStatements.push( + `-- WARNING: Cannot automatically reverse DROP DEFAULT. Manual intervention required.`, + ); + } else { + upStatements.push( + `ALTER TABLE ${fullTableName} ALTER COLUMN ${quoteIdent(op.column_name, dbType)} DROP DEFAULT;`, + ); + downStatements.push( + `-- WARNING: Cannot automatically reverse DROP DEFAULT. Manual intervention required.`, + ); + } + break; } - - const upSQL = upStatements.join("\n"); - const downSQL = downStatements.reverse().join("\n"); - - return { - version, - name, - filename, - upSQL, - downSQL, - }; + } + + const upSQL = upStatements.join("\n"); + const downSQL = downStatements.reverse().join("\n"); + + return { + version, + name, + filename, + upSQL, + downSQL, + }; } /** * Generate DROP TABLE migration */ export function generateDropTableMigration(params: { - schemaName: string; - tableName: string; - mode: "RESTRICT" | "DETACH_FKS" | "CASCADE"; - dbType: "mysql" | "postgres" | "mariadb" | "sqlite"; + schemaName: string; + tableName: string; + mode: "RESTRICT" | "DETACH_FKS" | "CASCADE"; + dbType: "mysql" | "postgres" | "mariadb" | "sqlite"; }): MigrationFile { - const { schemaName, tableName, mode, dbType } = params; - const version = generateMigrationVersion(); - const name = `drop_${tableName}_table`; - const filename = `${version}_${name}.sql`; - - // For all database types, use schema/database prefix - const fullTableName = `${quoteIdent(schemaName, dbType)}.${quoteIdent(tableName, dbType)}`; - - let upSQL = ""; - if (mode === "CASCADE") { - upSQL = `DROP TABLE ${fullTableName} CASCADE;`; - } else if (mode === "DETACH_FKS") { - upSQL = `-- First drop foreign key constraints, then drop table + const { schemaName, tableName, mode, dbType } = params; + const version = generateMigrationVersion(); + const name = `drop_${tableName}_table`; + const filename = `${version}_${name}.sql`; + + // For all database types, use schema/database prefix + const fullTableName = `${quoteIdent(schemaName, dbType)}.${quoteIdent(tableName, dbType)}`; + + let upSQL = ""; + if (mode === "CASCADE") { + upSQL = `DROP TABLE ${fullTableName} CASCADE;`; + } else if (mode === "DETACH_FKS") { + upSQL = `-- First drop foreign key constraints, then drop table -- WARNING: FK constraint names need to be specified manually DROP TABLE ${fullTableName};`; - } else { - upSQL = `DROP TABLE ${fullTableName};`; - } + } else { + upSQL = `DROP TABLE ${fullTableName};`; + } - const downSQL = `-- WARNING: Cannot automatically reverse DROP TABLE. + const downSQL = `-- WARNING: Cannot automatically reverse DROP TABLE. -- You must manually recreate the table with all its data, constraints, and indexes.`; - return { - version, - name, - filename, - upSQL, - downSQL, - }; + return { + version, + name, + filename, + upSQL, + downSQL, + }; } /** * Write migration file to disk */ -export function writeMigrationFile( - migrationsDir: string, - migration: MigrationFile -): string { - if (!fs.existsSync(migrationsDir)) { - fs.mkdirSync(migrationsDir, { recursive: true }); - } +export function writeMigrationFile(migrationsDir: string, migration: MigrationFile): string { + if (!fs.existsSync(migrationsDir)) { + fs.mkdirSync(migrationsDir, { recursive: true }); + } - const filepath = path.join(migrationsDir, migration.filename); + const filepath = path.join(migrationsDir, migration.filename); - const content = `-- ${migration.filename} + const content = `-- ${migration.filename} -- +up ${migration.upSQL} @@ -296,25 +295,25 @@ ${migration.upSQL} ${migration.downSQL} `; - fs.writeFileSync(filepath, content, "utf8"); + fs.writeFileSync(filepath, content, "utf8"); - return filepath; + return filepath; } /** * Helper: Quote identifier based on database type */ function quoteIdent(name: string, dbType: "mysql" | "postgres" | "mariadb" | "sqlite"): string { - if (dbType === "mysql" || dbType === "mariadb") { - return `\`${name.replace(/`/g, "``")}\``; - } else { - return `"${name.replace(/"/g, '""')}"`; - } + if (dbType === "mysql" || dbType === "mariadb") { + return `\`${name.replace(/`/g, "``")}\``; + } else { + return `"${name.replace(/"/g, '""')}"`; + } } /** * Helper: Typo fix for quoteIdent */ function quoteQuote(name: string, dbType: "mysql" | "postgres" | "mariadb" | "sqlite"): string { - return quoteIdent(name, dbType); + return quoteIdent(name, dbType); } diff --git a/scripts/package-bridge.mjs b/scripts/package-bridge.mjs index b450b4c3..acd22678 100644 --- a/scripts/package-bridge.mjs +++ b/scripts/package-bridge.mjs @@ -1,15 +1,12 @@ -import { execSync } from 'child_process'; +import { execSync } from "child_process"; const platform = process.platform; -const script = platform === 'win32' - ? 'build:pkg:win' - : platform === 'linux' - ? 'build:pkg:linux' - : null; +const script = + platform === "win32" ? "build:pkg:win" : platform === "linux" ? "build:pkg:linux" : null; if (!script) { console.error(`Unsupported platform for bridge packaging: ${platform}`); process.exit(1); } -execSync(`npm --prefix bridge run ${script}`, { stdio: 'inherit' }); \ No newline at end of file +execSync(`npm --prefix bridge run ${script}`, { stdio: "inherit" }); diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index a4c4ae62..bfed9eff 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -2,9 +2,7 @@ "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", "description": "Capability for the main window", - "windows": [ - "main" - ], + "windows": ["main"], "permissions": [ "core:default", "opener:default", @@ -22,4 +20,4 @@ "process:allow-exit", "aptabase:allow-track-event" ] -} \ No newline at end of file +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index ca0df74f..41d6c0f2 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -27,11 +27,7 @@ }, "bundle": { "active": true, - "targets": [ - "nsis", - "deb", - "appimage" - ], + "targets": ["nsis", "deb", "appimage"], "publisher": "Relwave", "copyright": "Copyright © 2026 Relwave", "category": "DeveloperTool", @@ -44,12 +40,8 @@ "icons/icon.icns", "icons/icon.ico" ], - "externalBin": [ - "resources/bridge" - ], - "resources": [ - "resources/better_sqlite3.node" - ], + "externalBin": ["resources/bridge"], + "resources": ["resources/better_sqlite3.node"], "createUpdaterArtifacts": true, "windows": { "nsis": { @@ -60,12 +52,10 @@ "plugins": { "updater": { "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEZCODA3MzJBRUNGNDE3NUIKUldSYkYvVHNLbk9BKzlKTVVlU2F2NGJET0VFcGlvZXhWVEhpUmhXR0J0cVFtY25zTlNIRDFNa0MK", - "endpoints": [ - "https://github.com/Relwave/relwave-app/releases/latest/download/latest.json" - ], + "endpoints": ["https://github.com/Relwave/relwave-app/releases/latest/download/latest.json"], "windows": { "installMode": "passive" } } } -} \ No newline at end of file +} diff --git a/src/App.css b/src/App.css index 8e5d8131..c794dc43 100644 --- a/src/App.css +++ b/src/App.css @@ -13,11 +13,8 @@ /* Font Family Configuration */ @theme inline { - --font-sans: - "Geist", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", - sans-serif; - --font-mono: - "Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, monospace; + --font-sans: "Geist", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + --font-mono: "Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, monospace; } @theme inline { @@ -93,8 +90,7 @@ --sidebar-ring: var(--ring); /* New Design System Tokens */ - --card-shadow: - 0 1px 2px rgba(15, 23, 42, 0.06), 0 12px 32px rgba(15, 23, 42, 0.05); + --card-shadow: 0 1px 2px rgba(15, 23, 42, 0.06), 0 12px 32px rgba(15, 23, 42, 0.05); --card-shadow-hover: 0 12px 36px rgba(15, 23, 42, 0.1); --glass-bg: rgba(255, 255, 255, 0.78); --glass-blur: 12px; @@ -150,10 +146,8 @@ body, --sidebar-accent-foreground: oklch(0.94 0.006 255); --sidebar-border: oklch(1 0 0 / 9%); --sidebar-ring: var(--ring); - --card-shadow: - 0 1px 0 rgba(255, 255, 255, 0.04) inset, 0 18px 52px rgba(0, 0, 0, 0.34); - --card-shadow-hover: - 0 1px 0 rgba(255, 255, 255, 0.06) inset, 0 22px 64px rgba(0, 0, 0, 0.42); + --card-shadow: 0 1px 0 rgba(255, 255, 255, 0.04) inset, 0 18px 52px rgba(0, 0, 0, 0.34); + --card-shadow-hover: 0 1px 0 rgba(255, 255, 255, 0.06) inset, 0 22px 64px rgba(0, 0, 0, 0.42); --glass-bg: rgba(23, 29, 39, 0.76); --surface: oklch(0.16 0.014 250); --surface-elevated: oklch(0.19 0.016 250); @@ -243,10 +237,8 @@ body, --sidebar-accent-foreground: #00f5ff; --sidebar-border: rgba(0, 245, 255, 0.08); --sidebar-ring: #00f5ff; - --card-shadow: - 0 0 0 1px rgba(0, 245, 255, 0.06), 0 8px 32px rgba(0, 0, 0, 0.6); - --card-shadow-hover: - 0 0 0 1px rgba(0, 245, 255, 0.14), 0 12px 44px rgba(0, 0, 0, 0.7); + --card-shadow: 0 0 0 1px rgba(0, 245, 255, 0.06), 0 8px 32px rgba(0, 0, 0, 0.6); + --card-shadow-hover: 0 0 0 1px rgba(0, 245, 255, 0.14), 0 12px 44px rgba(0, 0, 0, 0.7); --glass-bg: rgba(7, 11, 20, 0.85); --surface: #0a1220; --surface-elevated: #0d1526; @@ -294,10 +286,8 @@ body, --sidebar-accent-foreground: #ffffff; --sidebar-border: #3e3e42; --sidebar-ring: #569cd6; - --card-shadow: - 0 1px 0 rgba(255, 255, 255, 0.04) inset, 0 8px 24px rgba(0, 0, 0, 0.4); - --card-shadow-hover: - 0 1px 0 rgba(255, 255, 255, 0.06) inset, 0 12px 32px rgba(0, 0, 0, 0.5); + --card-shadow: 0 1px 0 rgba(255, 255, 255, 0.04) inset, 0 8px 24px rgba(0, 0, 0, 0.4); + --card-shadow-hover: 0 1px 0 rgba(255, 255, 255, 0.06) inset, 0 12px 32px rgba(0, 0, 0, 0.5); --glass-bg: rgba(37, 37, 38, 0.92); --surface: #252526; --surface-elevated: #2d2d30; @@ -334,8 +324,7 @@ body, --sidebar-border: oklch(0.91 0.05 11.4); --sidebar-ring: oklch(0.92 0.04 12.39); --card-shadow: - 0px 0px 3px 0px oklch(0.3 0.0891 19.6 / 0.08), - 0px 2px 4px -1px oklch(0.3 0.0891 19.6 / 0.08); + 0px 0px 3px 0px oklch(0.3 0.0891 19.6 / 0.08), 0px 2px 4px -1px oklch(0.3 0.0891 19.6 / 0.08); --glass-bg: rgba(253, 248, 247, 0.82); --surface: oklch(0.97 0.02 12.78); --surface-elevated: oklch(0.98 0.01 17.28); @@ -370,8 +359,7 @@ body, --sidebar-accent-foreground: oklch(0.99 0 359.99); --sidebar-border: oklch(0.39 0.12 20.37); --sidebar-ring: oklch(0.5 0.16 20.89); - --card-shadow: - 0 1px 3px 0px oklch(0 0 0 / 0.1), 0 2px 4px -1px oklch(0 0 0 / 0.1); + --card-shadow: 0 1px 3px 0px oklch(0 0 0 / 0.1), 0 2px 4px -1px oklch(0 0 0 / 0.1); --glass-bg: rgba(33, 14, 12, 0.82); --surface: oklch(0.21 0.05 19.26); --surface-elevated: oklch(0.26 0.07 19); @@ -407,8 +395,7 @@ body, --sidebar-accent-foreground: oklch(0.26 0.02 358.42); --sidebar-border: oklch(0.91 0 0.43); --sidebar-ring: oklch(0.71 0 0.37); - --card-shadow: - 0 1px 3px 0px oklch(0 0 0 / 0.08), 0 2px 4px -1px oklch(0 0 0 / 0.08); + --card-shadow: 0 1px 3px 0px oklch(0 0 0 / 0.08), 0 2px 4px -1px oklch(0 0 0 / 0.08); --glass-bg: rgba(244, 237, 216, 0.8); --surface: oklch(0.91 0.05 82.69); --surface-elevated: oklch(0.92 0.04 83.86); @@ -443,8 +430,7 @@ body, --sidebar-accent-foreground: oklch(0.86 0.05 84.5); --sidebar-border: oklch(0.33 0.02 60.7); --sidebar-ring: oklch(0.64 0.05 115.39); - --card-shadow: - 0 1px 3px 0px oklch(0 0 0 / 0.2), 0 2px 4px -1px oklch(0 0 0 / 0.2); + --card-shadow: 0 1px 3px 0px oklch(0 0 0 / 0.2), 0 2px 4px -1px oklch(0 0 0 / 0.2); --glass-bg: rgba(33, 25, 14, 0.82); --surface: oklch(0.25 0.01 56.14); --surface-elevated: oklch(0.27 0.01 39.35); @@ -467,11 +453,7 @@ body, color-mix(in oklch, var(--primary) 14%, transparent) 0, transparent 32rem ), - linear-gradient( - 180deg, - color-mix(in oklch, var(--background) 96%, white), - var(--background) - ); + linear-gradient(180deg, color-mix(in oklch, var(--background) 96%, white), var(--background)); } /* Apply monospace font to technical elements */ @@ -498,8 +480,6 @@ body { user-select: none; } - - @layer utilities { /* Webkit browsers (Chrome, Safari, Edge) - Applied globally */ ::-webkit-scrollbar { @@ -577,10 +557,7 @@ body { .hairline-grid { background-image: - linear-gradient( - color-mix(in oklch, var(--border) 38%, transparent) 1px, - transparent 1px - ), + linear-gradient(color-mix(in oklch, var(--border) 38%, transparent) 1px, transparent 1px), linear-gradient( 90deg, color-mix(in oklch, var(--border) 38%, transparent) 1px, @@ -641,8 +618,7 @@ body { .theme-transitioning [data-slot="dialog-content"] *, .theme-transitioning [data-slot="dialog-content"] *::before, .theme-transitioning [data-slot="dialog-content"] *::after { - transition-property: - color, background-color, border-color, box-shadow, opacity !important; + transition-property: color, background-color, border-color, box-shadow, opacity !important; transition-duration: 260ms !important; transition-timing-function: cubic-bezier(0.22, 1, 0.36, 1) !important; } diff --git a/src/components/dev/DeveloperContextMenu.tsx b/src/components/dev/DeveloperContextMenu.tsx index 32a7d365..591d22df 100644 --- a/src/components/dev/DeveloperContextMenu.tsx +++ b/src/components/dev/DeveloperContextMenu.tsx @@ -1,10 +1,10 @@ import { - ContextMenu, - ContextMenuContent, - ContextMenuItem, - ContextMenuSeparator, - ContextMenuTrigger, - ContextMenuShortcut, + ContextMenu, + ContextMenuContent, + ContextMenuItem, + ContextMenuSeparator, + ContextMenuTrigger, + ContextMenuShortcut, } from "@/components/ui/context-menu"; import { ArrowLeft, ArrowRight, RefreshCw, Bug } from "lucide-react"; import { useDevMode } from "@/features/settings/hooks/useDevMode"; @@ -12,50 +12,50 @@ import { useDevModeKeyboard } from "@/features/settings/hooks/useDevModeKeyboard import { useWebviewActions } from "@/features/settings/hooks/useWebviewActions"; interface DeveloperContextMenuProps { - children: React.ReactNode; + children: React.ReactNode; } export const DeveloperContextMenu = ({ children }: DeveloperContextMenuProps) => { - const devMode = useDevMode(); - useDevModeKeyboard(devMode); - const { reload, goBack, goForward, openDevtools } = useWebviewActions(); - - if (!devMode) { - return ( -
e.preventDefault()}> - {children} -
- ); - } + const devMode = useDevMode(); + useDevModeKeyboard(devMode); + const { reload, goBack, goForward, openDevtools } = useWebviewActions(); + if (!devMode) { return ( - - -
{children}
-
- - - - Back - Alt+← - - - - Forward - Alt+→ - - - - Reload - Ctrl+R - - - - - Inspect Element - F12 - - -
+
e.preventDefault()}> + {children} +
); -}; \ No newline at end of file + } + + return ( + + +
{children}
+
+ + + + Back + Alt+← + + + + Forward + Alt+→ + + + + Reload + Ctrl+R + + + + + Inspect Element + F12 + + +
+ ); +}; diff --git a/src/components/dev/RemoteConfigDialog.tsx b/src/components/dev/RemoteConfigDialog.tsx index c504a104..5de1be81 100644 --- a/src/components/dev/RemoteConfigDialog.tsx +++ b/src/components/dev/RemoteConfigDialog.tsx @@ -1,266 +1,243 @@ import { useState } from "react"; -import { - Globe, - Plus, - Trash2, - Pencil, - Check, - X, - Copy, -} from "lucide-react"; +import { Globe, Plus, Trash2, Pencil, Check, X, Copy } from "lucide-react"; import { Button } from "@/components/ui/button"; import { - Dialog, - DialogContent, - DialogHeader, - DialogTitle, - DialogFooter, + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Spinner } from "@/components/ui/spinner"; import { - useGitRemotes, - useGitRemoteAdd, - useGitRemoteRemove, - useGitRemoteSetUrl, + useGitRemotes, + useGitRemoteAdd, + useGitRemoteRemove, + useGitRemoteSetUrl, } from "@/features/git/hooks/useGitAdvanced"; import { toast } from "sonner"; import type { GitRemoteInfo } from "@/features/git/types"; interface RemoteConfigDialogProps { - open: boolean; - onOpenChange: (open: boolean) => void; - projectDir: string | null | undefined; + open: boolean; + onOpenChange: (open: boolean) => void; + projectDir: string | null | undefined; } export default function RemoteConfigDialog({ - open, - onOpenChange, - projectDir, + open, + onOpenChange, + projectDir, }: RemoteConfigDialogProps) { - const { data: remotes, isLoading } = useGitRemotes(open ? projectDir : undefined); - const addMutation = useGitRemoteAdd(projectDir); - const removeMutation = useGitRemoteRemove(projectDir); - const setUrlMutation = useGitRemoteSetUrl(projectDir); - - const [addMode, setAddMode] = useState(false); - const [newName, setNewName] = useState("origin"); - const [newUrl, setNewUrl] = useState(""); + const { data: remotes, isLoading } = useGitRemotes(open ? projectDir : undefined); + const addMutation = useGitRemoteAdd(projectDir); + const removeMutation = useGitRemoteRemove(projectDir); + const setUrlMutation = useGitRemoteSetUrl(projectDir); - // Editing state - const [editingRemote, setEditingRemote] = useState(null); - const [editUrl, setEditUrl] = useState(""); + const [addMode, setAddMode] = useState(false); + const [newName, setNewName] = useState("origin"); + const [newUrl, setNewUrl] = useState(""); - const handleAdd = async () => { - if (!newName.trim() || !newUrl.trim()) return; - try { - await addMutation.mutateAsync({ name: newName.trim(), url: newUrl.trim() }); - toast.success(`Remote '${newName.trim()}' added`); - setNewName("origin"); - setNewUrl(""); - setAddMode(false); - } catch (e: any) { - toast.error("Failed to add remote: " + e.message); - } - }; + // Editing state + const [editingRemote, setEditingRemote] = useState(null); + const [editUrl, setEditUrl] = useState(""); - const handleRemove = async (name: string) => { - try { - await removeMutation.mutateAsync(name); - toast.success(`Remote '${name}' removed`); - } catch (e: any) { - toast.error("Failed to remove remote: " + e.message); - } - }; + const handleAdd = async () => { + if (!newName.trim() || !newUrl.trim()) return; + try { + await addMutation.mutateAsync({ name: newName.trim(), url: newUrl.trim() }); + toast.success(`Remote '${newName.trim()}' added`); + setNewName("origin"); + setNewUrl(""); + setAddMode(false); + } catch (e: any) { + toast.error("Failed to add remote: " + e.message); + } + }; - const handleUpdateUrl = async (name: string) => { - if (!editUrl.trim()) return; - try { - await setUrlMutation.mutateAsync({ name, url: editUrl.trim() }); - toast.success(`Remote '${name}' URL updated`); - setEditingRemote(null); - setEditUrl(""); - } catch (e: any) { - toast.error("Failed to update URL: " + e.message); - } - }; + const handleRemove = async (name: string) => { + try { + await removeMutation.mutateAsync(name); + toast.success(`Remote '${name}' removed`); + } catch (e: any) { + toast.error("Failed to remove remote: " + e.message); + } + }; - return ( - - - - - - Remote Repositories - - + const handleUpdateUrl = async (name: string) => { + if (!editUrl.trim()) return; + try { + await setUrlMutation.mutateAsync({ name, url: editUrl.trim() }); + toast.success(`Remote '${name}' URL updated`); + setEditingRemote(null); + setEditUrl(""); + } catch (e: any) { + toast.error("Failed to update URL: " + e.message); + } + }; -
- {isLoading && ( -
- -
- )} + return ( + + + + + + Remote Repositories + + - {!isLoading && (!remotes || remotes.length === 0) && !addMode && ( -
- -

No remotes configured.

-

- Add a remote to push and pull changes. -

-
- )} +
+ {isLoading && ( +
+ +
+ )} - {remotes?.map((r: GitRemoteInfo) => ( -
-
- - {r.name} - -
- - - -
-
+ {!isLoading && (!remotes || remotes.length === 0) && !addMode && ( +
+ +

No remotes configured.

+

Add a remote to push and pull changes.

+
+ )} - {editingRemote === r.name ? ( -
- setEditUrl(e.target.value)} - placeholder="https://github.com/user/repo.git" - className="h-7 text-xs font-mono" - onKeyDown={(e) => { - if (e.key === "Enter") handleUpdateUrl(r.name); - if (e.key === "Escape") setEditingRemote(null); - }} - autoFocus - /> - - -
- ) : ( -

- {r.pushUrl || r.fetchUrl} -

- )} -
- ))} + {remotes?.map((r: GitRemoteInfo) => ( +
+
+ {r.name} +
+ + + +
+
- {/* Add new remote form */} - {addMode && ( -
- setNewName(e.target.value)} - placeholder="Remote name (e.g. origin)" - className="h-7 text-xs font-mono" - autoFocus - /> - setNewUrl(e.target.value)} - placeholder="https://github.com/user/repo.git" - className="h-7 text-xs font-mono" - onKeyDown={(e) => { - if (e.key === "Enter") handleAdd(); - if (e.key === "Escape") setAddMode(false); - }} - /> -
- - -
-
- )} + {editingRemote === r.name ? ( +
+ setEditUrl(e.target.value)} + placeholder="https://github.com/user/repo.git" + className="h-7 text-xs font-mono" + onKeyDown={(e) => { + if (e.key === "Enter") handleUpdateUrl(r.name); + if (e.key === "Escape") setEditingRemote(null); + }} + autoFocus + /> + +
+ ) : ( +

+ {r.pushUrl || r.fetchUrl} +

+ )} +
+ ))} + + {/* Add new remote form */} + {addMode && ( +
+ setNewName(e.target.value)} + placeholder="Remote name (e.g. origin)" + className="h-7 text-xs font-mono" + autoFocus + /> + setNewUrl(e.target.value)} + placeholder="https://github.com/user/repo.git" + className="h-7 text-xs font-mono" + onKeyDown={(e) => { + if (e.key === "Enter") handleAdd(); + if (e.key === "Escape") setAddMode(false); + }} + /> +
+ + +
+
+ )} +
- - {!addMode && ( - - )} - - -
-
- ); + + {!addMode && ( + + )} + + + +
+ ); } diff --git a/src/components/feedback/BridgeFailed.tsx b/src/components/feedback/BridgeFailed.tsx index af6843e6..f1ebb0f2 100644 --- a/src/components/feedback/BridgeFailed.tsx +++ b/src/components/feedback/BridgeFailed.tsx @@ -1,23 +1,23 @@ -import { Button } from '@/components/ui/button' -import { AlertCircle } from 'lucide-react' +import { Button } from "@/components/ui/button"; +import { AlertCircle } from "lucide-react"; const BridgeFailed = () => { - return ( -
-
-
- -
-

Connection Failed

-

- Unable to connect to the database bridge. -

- -
+ return ( +
+
+
+
- ) -} +

Connection Failed

+

+ Unable to connect to the database bridge. +

+ +
+
+ ); +}; -export default BridgeFailed \ No newline at end of file +export default BridgeFailed; diff --git a/src/components/feedback/BridgeLoader.tsx b/src/components/feedback/BridgeLoader.tsx index e19f071b..400cdf8f 100644 --- a/src/components/feedback/BridgeLoader.tsx +++ b/src/components/feedback/BridgeLoader.tsx @@ -1,13 +1,13 @@ -import { Spinner } from "@/components/ui/spinner" +import { Spinner } from "@/components/ui/spinner"; const BridgeLoader = () => { - return ( -
-
- -
-
- ) -} + return ( +
+
+ +
+
+ ); +}; -export default BridgeLoader \ No newline at end of file +export default BridgeLoader; diff --git a/src/components/layout/BridgeStatus.tsx b/src/components/layout/BridgeStatus.tsx index c30bcae6..13788bee 100644 --- a/src/components/layout/BridgeStatus.tsx +++ b/src/components/layout/BridgeStatus.tsx @@ -1,8 +1,12 @@ -import { useEffect, useState } from 'react'; -import { onConnectionStateChange, isBridgeHealthy, restartBridge } from '@/services/bridge/bridgeClient'; -import { WifiOff, RefreshCcw } from 'lucide-react'; -import { Button } from '@/components/ui/button'; -import { cn } from '@/lib/utils'; +import { useEffect, useState } from "react"; +import { + onConnectionStateChange, + isBridgeHealthy, + restartBridge, +} from "@/services/bridge/bridgeClient"; +import { WifiOff, RefreshCcw } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; const BridgeStatus = () => { const [healthy, setHealthy] = useState(isBridgeHealthy()); @@ -11,7 +15,7 @@ const BridgeStatus = () => { useEffect(() => { // Sync initial state setHealthy(isBridgeHealthy()); - + // Subscribe to changes return onConnectionStateChange((h) => setHealthy(h)); }, []); @@ -32,7 +36,9 @@ const BridgeStatus = () => {
- Bridge Disconnected + + Bridge Disconnected +
); diff --git a/src/components/layout/CommandPalette.tsx b/src/components/layout/CommandPalette.tsx index 99f97ab9..50453a05 100644 --- a/src/components/layout/CommandPalette.tsx +++ b/src/components/layout/CommandPalette.tsx @@ -89,7 +89,7 @@ function ItemBadge({ type }: { type: ItemType }) { // font-mono resolves to IBM Plex Mono via your global CSS / Tailwind config "ml-auto shrink-0 rounded border px-1.5 py-[2px]", "font-mono text-[9.5px] font-medium tracking-[0.12em]", - TYPE_COLORS[type] + TYPE_COLORS[type], )} > {TYPE_LABELS[type]} @@ -106,16 +106,14 @@ function KbdHint({ keys }: { keys: string[] }) {
{keys.map((k, i) => ( - {i > 0 && ( - + - )} + {i > 0 && +} {k} @@ -139,9 +137,7 @@ function EmptyState({ query }: { query: string }) { No results

{/* IBM Plex Mono for the echoed query — makes the search term look "literal" */} -

- “{query}” -

+

“{query}”

); @@ -167,9 +163,7 @@ function HighlightMatch({ text, query }: { text: string; query: string }) { return ( <> {text.slice(0, idx)} - - {text.slice(idx, idx + query.length)} - + {text.slice(idx, idx + query.length)} {text.slice(idx + query.length)} ); @@ -204,7 +198,9 @@ export function CommandPalette() { try { const saved = localStorage.getItem(RECENT_ITEMS_KEY); if (saved) setRecentItems(JSON.parse(saved)); - } catch { /* ignore */ } + } catch { + /* ignore */ + } }, []); const addToRecent = React.useCallback((item: Omit) => { @@ -243,13 +239,16 @@ export function CommandPalette() { command(); if (item) addToRecent(item); }, - [addToRecent] + [addToRecent], ); - const pages = React.useMemo(() => [ - { icon: Home, label: "Dashboard", path: "/" }, - { icon: Settings, label: "Settings", path: "/settings" }, - ], []); + const pages = React.useMemo( + () => [ + { icon: Home, label: "Dashboard", path: "/" }, + { icon: Settings, label: "Settings", path: "/settings" }, + ], + [], + ); const isSearching = search.trim().length > 0; const showRecent = !isSearching && recentItems.length > 0; @@ -282,7 +281,7 @@ export function CommandPalette() { "flex h-12 w-full bg-transparent py-3 outline-none", // IBM Plex Sans 400, slightly larger than item text for prominence "font-sans text-[14px] font-normal tracking-[-0.01em]", - "placeholder:text-muted-foreground/40 text-foreground" + "placeholder:text-muted-foreground/40 text-foreground", )} value={search} onValueChange={setSearch} @@ -290,10 +289,12 @@ export function CommandPalette() { {/* Active DB context pill */} {contextLabel && !isSearching && ( -
+
{contextLabel}
@@ -336,8 +337,11 @@ export function CommandPalette() { key={`recent-${item.id}`} valuePrefix="recent-" icon={ - item.type === "connection" ? Database : - item.type === "project" ? FolderOpen : Home + item.type === "connection" + ? Database + : item.type === "project" + ? FolderOpen + : Home } label={item.label} type={item.type} @@ -361,7 +365,10 @@ export function CommandPalette() { query={search} onSelect={() => runCommand(() => navigate(page.path), { - id: page.path, type: "page", label: page.label, path: page.path, + id: page.path, + type: "page", + label: page.label, + path: page.path, }) } /> @@ -381,7 +388,10 @@ export function CommandPalette() { meta={`${db.type} · ${db.host}`} onSelect={() => runCommand(() => navigate(`/${db.id}`), { - id: db.id, type: "connection", label: db.name, path: `/${db.id}`, + id: db.id, + type: "connection", + label: db.name, + path: `/${db.id}`, }) } /> @@ -391,7 +401,9 @@ export function CommandPalette() { {/* Tables */} {tables.length > 0 && ( - }> + } + > {tables.map((table) => ( runCommand(() => navigate(`/${project.databaseId}`), { - id: project.id, type: "project", label: project.name, path: `/${project.databaseId}`, + id: project.id, + type: "project", + label: project.name, + path: `/${project.databaseId}`, }) } /> @@ -447,7 +462,7 @@ export function CommandPalette() { meta={contextLabel ?? dbId} onSelect={() => runCommand(() => - navigate(`/${dbId}`, { state: { activePanel: "sql-workspace" } }) + navigate(`/${dbId}`, { state: { activePanel: "sql-workspace" } }), ) } /> @@ -458,9 +473,7 @@ export function CommandPalette() { label={`Switch to ${theme === "light" ? "Dark" : "Light"} Mode`} type="action" query={search} - onSelect={() => - runCommand(() => setTheme(theme === "light" ? "dark" : "light")) - } + onSelect={() => runCommand(() => setTheme(theme === "light" ? "dark" : "light"))} /> {THEME_VARIANTS.map((variant) => ( @@ -534,7 +547,7 @@ function GroupHeading({ "flex items-center gap-1.5", mono ? "font-mono text-[10px] font-medium tracking-[0.06em] text-muted-foreground/50" - : "font-sans text-[10px] font-semibold tracking-[0.1em] text-muted-foreground/50 uppercase" + : "font-sans text-[10px] font-semibold tracking-[0.1em] text-muted-foreground/50 uppercase", )} > {icon} @@ -562,7 +575,16 @@ interface CommandItemProps { valuePrefix?: string; } -function CommandItem({ icon: Icon, label, type, query, meta, suffix, onSelect, valuePrefix = "" }: CommandItemProps) { +function CommandItem({ + icon: Icon, + label, + type, + query, + meta, + suffix, + onSelect, + valuePrefix = "", +}: CommandItemProps) { return ( {/* Tinted icon tile */} -
+
{/* Label — IBM Plex Sans 450 (between regular and medium) */} - + diff --git a/src/components/layout/SlideOutPanel.tsx b/src/components/layout/SlideOutPanel.tsx index 3ae547d7..8dd53a2c 100644 --- a/src/components/layout/SlideOutPanel.tsx +++ b/src/components/layout/SlideOutPanel.tsx @@ -1,63 +1,54 @@ -import { X } from 'lucide-react'; -import { Button } from '@/components/ui/button'; -import { ScrollArea } from '@/components/ui/scroll-area'; +import { X } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { ScrollArea } from "@/components/ui/scroll-area"; interface SlideOutPanelProps { - isOpen: boolean; - onClose: () => void; - title: string; - children: React.ReactNode; - width?: string; - disableScroll?: boolean; + isOpen: boolean; + onClose: () => void; + title: string; + children: React.ReactNode; + width?: string; + disableScroll?: boolean; } export default function SlideOutPanel({ - isOpen, - onClose, - title, - children, - width = '400px', - disableScroll = false, + isOpen, + onClose, + title, + children, + width = "400px", + disableScroll = false, }: SlideOutPanelProps) { - if (!isOpen) return null; + if (!isOpen) return null; - return ( - <> - {/* Backdrop */} -
+ return ( + <> + {/* Backdrop */} +
- {/* Panel */} -
- {/* Header */} -
-

{title}

- -
+ {/* Panel */} +
+ {/* Header */} +
+

{title}

+ +
- {/* Content */} - {disableScroll ? ( -
- {children} -
- ) : ( - - {children} - - )} -
- - ); + {/* Content */} + {disableScroll ? ( +
{children}
+ ) : ( + {children} + )} +
+ + ); } diff --git a/src/components/layout/TitleBar.tsx b/src/components/layout/TitleBar.tsx index 3fe1d2d1..a371c44e 100644 --- a/src/components/layout/TitleBar.tsx +++ b/src/components/layout/TitleBar.tsx @@ -1,85 +1,93 @@ -import { Maximize2, Minus, Square, X } from 'lucide-react'; -import { getCurrentWindow } from '@tauri-apps/api/window'; -import BridgeStatus from './BridgeStatus'; +import { Maximize2, Minus, Square, X } from "lucide-react"; +import { getCurrentWindow } from "@tauri-apps/api/window"; +import BridgeStatus from "./BridgeStatus"; const TitleBar = () => { + const handleMinimize = async () => { + try { + const appWindow = getCurrentWindow(); + await appWindow.minimize(); + } catch (error) { + console.error("Failed to minimize:", error); + } + }; - const handleMinimize = async () => { - try { - const appWindow = getCurrentWindow(); - await appWindow.minimize(); - } catch (error) { - console.error('Failed to minimize:', error); - } - }; + const handleMaximize = async () => { + try { + const appWindow = getCurrentWindow(); + await appWindow.toggleMaximize(); + } catch (error) { + console.error("Failed to toggle maximize:", error); + } + }; - const handleMaximize = async () => { - try { - const appWindow = getCurrentWindow(); - await appWindow.toggleMaximize(); - } catch (error) { - console.error('Failed to toggle maximize:', error); - } - }; + const handleClose = async () => { + try { + const appWindow = getCurrentWindow(); + await appWindow.close(); + } catch (error) { + console.error("Failed to close:", error); + } + }; - const handleClose = async () => { - try { - const appWindow = getCurrentWindow(); - await appWindow.close(); - } catch (error) { - console.error('Failed to close:', error); - } - }; + return ( +
+ {/* App Title - Left */} +
+
+ RelWave +
- return ( -
- {/* App Title - Left */} -
-
- RelWave -
+ {/* Bridge Status - Center */} +
+ +
- {/* Bridge Status - Center */} -
- -
+ {/* Window Controls - Right */} +
+
+ {/* Close - Red */} + - {/* Window Controls - Right */} -
-
- {/* Close - Red */} - + {/* Minimize - Yellow */} + - {/* Minimize - Yellow */} - - - {/* Maximize - Green */} - -
-
+ {/* Maximize - Green */} +
- ); +
+
+ ); }; export default TitleBar; diff --git a/src/components/layout/VerticalIconBar.tsx b/src/components/layout/VerticalIconBar.tsx index d959777c..212de1c2 100644 --- a/src/components/layout/VerticalIconBar.tsx +++ b/src/components/layout/VerticalIconBar.tsx @@ -1,125 +1,150 @@ -import { Activity, Home, Database, Search, GitBranch, GitCommitHorizontal, Settings, Layers, Terminal, History, Sparkles } from 'lucide-react'; -import { Link, useLocation } from 'react-router-dom'; -import { Button } from '@/components/ui/button'; import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from '@/components/ui/tooltip'; + Activity, + Home, + Database, + Search, + GitBranch, + GitCommitHorizontal, + Settings, + Layers, + Terminal, + History, + Sparkles, +} from "lucide-react"; +import { Link, useLocation } from "react-router-dom"; +import { Button } from "@/components/ui/button"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; -export type PanelType = 'data' | 'sql-workspace' | 'query-builder' | 'schema-explorer' | 'er-diagram' | 'monitoring' | 'git-status' | 'migrations' | 'ai-workspace'; +export type PanelType = + | "data" + | "sql-workspace" + | "query-builder" + | "schema-explorer" + | "er-diagram" + | "monitoring" + | "git-status" + | "migrations" + | "ai-workspace"; interface VerticalIconBarProps { - dbId?: string; - databaseType?: string; - activePanel?: PanelType; - onPanelChange?: (panel: PanelType) => void; + dbId?: string; + databaseType?: string; + activePanel?: PanelType; + onPanelChange?: (panel: PanelType) => void; } -const globalNavigationItems = [ - { icon: Home, label: 'Dashboard', path: '/' }, -]; +const globalNavigationItems = [{ icon: Home, label: "Dashboard", path: "/" }]; function supportsMonitoring(databaseType?: string) { - const type = databaseType?.toLowerCase(); - return type === "postgres" || type === "postgresql" || type === "mysql" || type === "mariadb"; + const type = databaseType?.toLowerCase(); + return type === "postgres" || type === "postgresql" || type === "mysql" || type === "mariadb"; } -export default function VerticalIconBar({ dbId, databaseType, activePanel, onPanelChange }: VerticalIconBarProps) { - const location = useLocation(); +export default function VerticalIconBar({ + dbId, + databaseType, + activePanel, + onPanelChange, +}: VerticalIconBarProps) { + const location = useLocation(); - const isGlobalActive = (path: string) => { - if (path === '/') { - return location.pathname === '/'; - } - return location.pathname.includes(path); - }; + const isGlobalActive = (path: string) => { + if (path === "/") { + return location.pathname === "/"; + } + return location.pathname.includes(path); + }; - // Database-specific panel items (only shown when dbId is provided) - const databasePanelItems: Array<{ icon: any; label: string; panel: PanelType }> = dbId ? [ - { icon: Layers, label: 'Data View', panel: 'data' }, - { icon: Terminal, label: 'SQL Workspace', panel: 'sql-workspace' }, - { icon: Sparkles, label: 'AI Workspace', panel: 'ai-workspace' }, - { icon: Search, label: 'Query Builder', panel: 'query-builder' }, - { icon: GitBranch, label: 'Schema Explorer', panel: 'schema-explorer' }, - { icon: Database, label: 'ER Diagram', panel: 'er-diagram' }, - ...(supportsMonitoring(databaseType) ? [{ icon: Activity, label: 'Monitoring', panel: 'monitoring' as PanelType }] : []), - { icon: History, label: 'Migrations', panel: 'migrations' }, - { icon: GitCommitHorizontal, label: 'Git Status', panel: 'git-status' }, - ] : []; + // Database-specific panel items (only shown when dbId is provided) + const databasePanelItems: Array<{ icon: any; label: string; panel: PanelType }> = dbId + ? [ + { icon: Layers, label: "Data View", panel: "data" }, + { icon: Terminal, label: "SQL Workspace", panel: "sql-workspace" }, + { icon: Sparkles, label: "AI Workspace", panel: "ai-workspace" }, + { icon: Search, label: "Query Builder", panel: "query-builder" }, + { icon: GitBranch, label: "Schema Explorer", panel: "schema-explorer" }, + { icon: Database, label: "ER Diagram", panel: "er-diagram" }, + ...(supportsMonitoring(databaseType) + ? [{ icon: Activity, label: "Monitoring", panel: "monitoring" as PanelType }] + : []), + { icon: History, label: "Migrations", panel: "migrations" }, + { icon: GitCommitHorizontal, label: "Git Status", panel: "git-status" }, + ] + : []; - return ( -
+ + )} + + ); } diff --git a/src/components/providers/ThemeProvider.tsx b/src/components/providers/ThemeProvider.tsx index 3a3686b8..b1534bb1 100644 --- a/src/components/providers/ThemeProvider.tsx +++ b/src/components/providers/ThemeProvider.tsx @@ -1,108 +1,101 @@ -import { createContext, useContext, useEffect, useState } from "react" -import { flushSync } from "react-dom" +import { createContext, useContext, useEffect, useState } from "react"; +import { flushSync } from "react-dom"; -export type Theme = "dark" | "light" | "system" +export type Theme = "dark" | "light" | "system"; type ThemeProviderProps = { - children: React.ReactNode - defaultTheme?: Theme - storageKey?: string -} + children: React.ReactNode; + defaultTheme?: Theme; + storageKey?: string; +}; type ThemeProviderState = { - theme: Theme - setTheme: (theme: Theme) => void -} + theme: Theme; + setTheme: (theme: Theme) => void; +}; const initialState: ThemeProviderState = { - theme: "system", - setTheme: () => null, -} + theme: "system", + setTheme: () => null, +}; -const ThemeProviderContext = createContext(initialState) +const ThemeProviderContext = createContext(initialState); function getSystemTheme(): Exclude { - return window.matchMedia("(prefers-color-scheme: dark)").matches - ? "dark" - : "light" + return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; } function applyTheme(theme: Theme) { - const root = window.document.documentElement - const resolvedTheme = theme === "system" ? getSystemTheme() : theme - root.classList.remove("light", "dark") - root.classList.add(resolvedTheme) + const root = window.document.documentElement; + const resolvedTheme = theme === "system" ? getSystemTheme() : theme; + root.classList.remove("light", "dark"); + root.classList.add(resolvedTheme); } export function ThemeProvider({ - children, - defaultTheme = "system", - storageKey = "relwave:theme", + children, + defaultTheme = "system", + storageKey = "relwave:theme", }: ThemeProviderProps) { - const [theme, setTheme] = useState(() => { - const stored = (localStorage.getItem(storageKey) as Theme) || defaultTheme - applyTheme(stored) - return stored - }) - - useEffect(() => { - applyTheme(theme) - }, [theme]) - - useEffect(() => { - if (theme !== "system") return - - const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)") - const handleSystemThemeChange = () => applyTheme("system") - - mediaQuery.addEventListener("change", handleSystemThemeChange) - return () => mediaQuery.removeEventListener("change", handleSystemThemeChange) - }, [theme]) - - const value = { - theme, - setTheme: (newTheme: Theme) => { - const root = window.document.documentElement - - if (!document.startViewTransition) { - localStorage.setItem(storageKey, newTheme) - applyTheme(newTheme) - setTheme(newTheme) - return - } - - root.classList.add("theme-transitioning") - - const transition = document.startViewTransition(() => { - localStorage.setItem(storageKey, newTheme) - flushSync(() => { - applyTheme(newTheme) - setTheme(newTheme) - }) - }) - - transition.ready.catch(() => { - root.classList.remove("theme-transitioning") - }) - - transition.finished.finally(() => { - root.classList.remove("theme-transitioning") - }) - }, - } - - return ( - - {children} - - ) + const [theme, setTheme] = useState(() => { + const stored = (localStorage.getItem(storageKey) as Theme) || defaultTheme; + applyTheme(stored); + return stored; + }); + + useEffect(() => { + applyTheme(theme); + }, [theme]); + + useEffect(() => { + if (theme !== "system") return; + + const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"); + const handleSystemThemeChange = () => applyTheme("system"); + + mediaQuery.addEventListener("change", handleSystemThemeChange); + return () => mediaQuery.removeEventListener("change", handleSystemThemeChange); + }, [theme]); + + const value = { + theme, + setTheme: (newTheme: Theme) => { + const root = window.document.documentElement; + + if (!document.startViewTransition) { + localStorage.setItem(storageKey, newTheme); + applyTheme(newTheme); + setTheme(newTheme); + return; + } + + root.classList.add("theme-transitioning"); + + const transition = document.startViewTransition(() => { + localStorage.setItem(storageKey, newTheme); + flushSync(() => { + applyTheme(newTheme); + setTheme(newTheme); + }); + }); + + transition.ready.catch(() => { + root.classList.remove("theme-transitioning"); + }); + + transition.finished.finally(() => { + root.classList.remove("theme-transitioning"); + }); + }, + }; + + return {children}; } export const useTheme = () => { - const context = useContext(ThemeProviderContext) + const context = useContext(ThemeProviderContext); - if (context === undefined) - throw new Error("useTheme must be used within a ThemeProvider") + if (context === undefined) throw new Error("useTheme must be used within a ThemeProvider"); - return context -} \ No newline at end of file + return context; +}; diff --git a/src/components/shared/CommandPalette.tsx b/src/components/shared/CommandPalette.tsx index f0ea5cb5..c223f031 100644 --- a/src/components/shared/CommandPalette.tsx +++ b/src/components/shared/CommandPalette.tsx @@ -1,127 +1,123 @@ -import { useEffect, useState, useCallback } from 'react'; -import { Command, Search, Database as DatabaseIcon, Table, GitBranch } from 'lucide-react'; -import { useNavigate } from 'react-router-dom'; -import { - Dialog, - DialogContent, -} from '@/components/ui/dialog'; -import { Input } from '@/components/ui/input'; -import { ScrollArea } from '@/components/ui/scroll-area'; +import { useEffect, useState, useCallback } from "react"; +import { Command, Search, Database as DatabaseIcon, Table, GitBranch } from "lucide-react"; +import { useNavigate } from "react-router-dom"; +import { Dialog, DialogContent } from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { ScrollArea } from "@/components/ui/scroll-area"; interface CommandPaletteProps { - isOpen: boolean; - onClose: () => void; + isOpen: boolean; + onClose: () => void; } interface CommandItem { - id: string; - label: string; - icon: React.ReactNode; - action: () => void; - category: string; + id: string; + label: string; + icon: React.ReactNode; + action: () => void; + category: string; } export default function CommandPalette({ isOpen, onClose }: CommandPaletteProps) { - const [search, setSearch] = useState(''); - const navigate = useNavigate(); + const [search, setSearch] = useState(""); + const navigate = useNavigate(); - const commands: CommandItem[] = [ - { - id: 'home', - label: 'Go to Dashboard', - icon: , - action: () => navigate('/'), - category: 'Navigation', - }, - { - id: 'settings', - label: 'Go to Settings', - icon: , - action: () => navigate('/settings'), - category: 'Navigation', - }, - ]; + const commands: CommandItem[] = [ + { + id: "home", + label: "Go to Dashboard", + icon: , + action: () => navigate("/"), + category: "Navigation", + }, + { + id: "settings", + label: "Go to Settings", + icon: , + action: () => navigate("/settings"), + category: "Navigation", + }, + ]; - const filteredCommands = commands.filter((cmd) => - cmd.label.toLowerCase().includes(search.toLowerCase()) - ); + const filteredCommands = commands.filter((cmd) => + cmd.label.toLowerCase().includes(search.toLowerCase()), + ); - const handleSelect = (command: CommandItem) => { - command.action(); + const handleSelect = (command: CommandItem) => { + command.action(); + onClose(); + setSearch(""); + }; + + useEffect(() => { + const handleKeyDown = (e: KeyboardEvent) => { + if ((e.metaKey || e.ctrlKey) && e.key === "k") { + e.preventDefault(); onClose(); - setSearch(''); + } }; - useEffect(() => { - const handleKeyDown = (e: KeyboardEvent) => { - if ((e.metaKey || e.ctrlKey) && e.key === 'k') { - e.preventDefault(); - onClose(); - } - }; - - if (isOpen) { - document.addEventListener('keydown', handleKeyDown); - } - - return () => { - document.removeEventListener('keydown', handleKeyDown); - }; - }, [isOpen, onClose]); + if (isOpen) { + document.addEventListener("keydown", handleKeyDown); + } - return ( - - -
- - setSearch(e.target.value)} - className="border-0 focus-visible:ring-0 focus-visible:ring-offset-0 text-base h-14" - autoFocus - /> + return () => { + document.removeEventListener("keydown", handleKeyDown); + }; + }, [isOpen, onClose]); -
+ return ( + + +
+ + setSearch(e.target.value)} + className="border-0 focus-visible:ring-0 focus-visible:ring-offset-0 text-base h-14" + autoFocus + /> +
- -
- {filteredCommands.length === 0 ? ( -
- No results found -
- ) : ( -
- {filteredCommands.map((command) => ( - - ))} -
- )} + +
+ {filteredCommands.length === 0 ? ( +
+ No results found +
+ ) : ( +
+ {filteredCommands.map((command) => ( +
- ); + + ))} +
+ )} +
+ + +
+ Type to search +
+ + ↑↓ + + to navigate +
+
+ + + ); } diff --git a/src/components/shared/ConfirmDialog.tsx b/src/components/shared/ConfirmDialog.tsx index 34243989..fb18886d 100644 --- a/src/components/shared/ConfirmDialog.tsx +++ b/src/components/shared/ConfirmDialog.tsx @@ -1,58 +1,56 @@ import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, } from "@/components/ui/alert-dialog"; interface ConfirmDialogProps { - open: boolean; - onOpenChange: (open: boolean) => void; - title: string; - description: string; - confirmLabel?: string; - cancelLabel?: string; - variant?: "default" | "destructive"; - onConfirm: () => void; + open: boolean; + onOpenChange: (open: boolean) => void; + title: string; + description: string; + confirmLabel?: string; + cancelLabel?: string; + variant?: "default" | "destructive"; + onConfirm: () => void; } export default function ConfirmDialog({ - open, - onOpenChange, - title, - description, - confirmLabel = "Confirm", - cancelLabel = "Cancel", - variant = "default", - onConfirm, + open, + onOpenChange, + title, + description, + confirmLabel = "Confirm", + cancelLabel = "Cancel", + variant = "default", + onConfirm, }: ConfirmDialogProps) { - return ( - - - - {title} - {description} - - - - {cancelLabel} - - - {confirmLabel} - - - - - ); + return ( + + + + {title} + {description} + + + {cancelLabel} + + {confirmLabel} + + + + + ); } diff --git a/src/components/shared/DataTable.tsx b/src/components/shared/DataTable.tsx index 9daab308..fec24a20 100644 --- a/src/components/shared/DataTable.tsx +++ b/src/components/shared/DataTable.tsx @@ -82,7 +82,7 @@ export const DataTable = ({ {row[column] !== null && row[column] !== undefined ? ( formatCellValue(row[column], column) @@ -98,7 +98,7 @@ export const DataTable = ({ - - -

{label}

-
- - ); + > + {icon} + + + +

{label}

+
+ + ); } diff --git a/src/components/shared/InputDialog.tsx b/src/components/shared/InputDialog.tsx index f1d4d746..2bf80cb0 100644 --- a/src/components/shared/InputDialog.tsx +++ b/src/components/shared/InputDialog.tsx @@ -63,11 +63,7 @@ export function InputDialog({ className="bg-background/50 border-sidebar-border" /> - -

Shortcuts ?

+

+ Shortcuts ? +

); diff --git a/src/components/shared/UpdateNotification.tsx b/src/components/shared/UpdateNotification.tsx index 83bfbf64..86ef72fa 100644 --- a/src/components/shared/UpdateNotification.tsx +++ b/src/components/shared/UpdateNotification.tsx @@ -61,14 +61,8 @@ export function UpdateNotification() { // Standalone update checker button for settings export function UpdateCheckerButton() { - const { - status, - updateInfo, - downloadProgress, - checkForUpdates, - downloadAndInstall, - relaunchApp, - } = useUpdater(); + const { status, updateInfo, downloadProgress, checkForUpdates, downloadAndInstall, relaunchApp } = + useUpdater(); const getButtonContent = () => { switch (status) { diff --git a/src/components/shared/WhatsNewDialog.tsx b/src/components/shared/WhatsNewDialog.tsx index c7ee4517..0a66752b 100644 --- a/src/components/shared/WhatsNewDialog.tsx +++ b/src/components/shared/WhatsNewDialog.tsx @@ -41,7 +41,7 @@ async function fetchReleaseNotes(version: string): Promise { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", }, - } + }, ); if (!res.ok) return undefined; const data = await res.json(); @@ -87,7 +87,9 @@ export function WhatsNewDialog() { }; void load(); - return () => { mounted = false; }; + return () => { + mounted = false; + }; }, []); // Dev-only: Cmd+Shift+W resets and reloads @@ -171,13 +173,9 @@ export function WhatsNewDialog() { ), h3: ({ children }) => ( -

- {children} -

- ), - ul: ({ children }) => ( -
    {children}
+

{children}

), + ul: ({ children }) =>
    {children}
, ol: ({ children }) => (
    {children}
), @@ -188,19 +186,13 @@ export function WhatsNewDialog() { ), p: ({ children }) => ( -

- {children} -

+

{children}

), strong: ({ children }) => ( {children} ), - em: ({ children }) => ( - {children} - ), - hr: () => ( -
- ), + em: ({ children }) => {children}, + hr: () =>
, code: ({ children, className }) => { const isBlock = !!className; return isBlock ? ( @@ -237,14 +229,12 @@ export function WhatsNewDialog() { {/* Footer */} -

- Thanks for keeping RelWave up to date. -

+

Thanks for keeping RelWave up to date.

- - + + ); -} \ No newline at end of file +} diff --git a/src/components/ui/SQLPreviewSheet.tsx b/src/components/ui/SQLPreviewSheet.tsx index 91eb8353..f7dffd8f 100644 --- a/src/components/ui/SQLPreviewSheet.tsx +++ b/src/components/ui/SQLPreviewSheet.tsx @@ -33,7 +33,7 @@ export default function SQLPreviewSheet({
diff --git a/src/components/ui/alert-dialog.tsx b/src/components/ui/alert-dialog.tsx index 91e12553..fe36c98b 100644 --- a/src/components/ui/alert-dialog.tsx +++ b/src/components/ui/alert-dialog.tsx @@ -1,31 +1,23 @@ -"use client" +"use client"; -import * as React from "react" -import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog" +import * as React from "react"; +import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"; -import { cn } from "@/lib/utils" -import { buttonVariants } from "@/components/ui/button" +import { cn } from "@/lib/utils"; +import { buttonVariants } from "@/components/ui/button"; -function AlertDialog({ - ...props -}: React.ComponentProps) { - return +function AlertDialog({ ...props }: React.ComponentProps) { + return ; } function AlertDialogTrigger({ ...props }: React.ComponentProps) { - return ( - - ) + return ; } -function AlertDialogPortal({ - ...props -}: React.ComponentProps) { - return ( - - ) +function AlertDialogPortal({ ...props }: React.ComponentProps) { + return ; } function AlertDialogOverlay({ @@ -37,11 +29,11 @@ function AlertDialogOverlay({ data-slot="alert-dialog-overlay" className={cn( "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/60 backdrop-blur-sm", - className + className, )} {...props} /> - ) + ); } function AlertDialogContent({ @@ -55,41 +47,32 @@ function AlertDialogContent({ data-slot="alert-dialog-content" className={cn( "bg-popover/95 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border border-border/70 p-6 shadow-2xl backdrop-blur-xl duration-200 sm:max-w-lg", - className + className, )} {...props} /> - ) + ); } -function AlertDialogHeader({ - className, - ...props -}: React.ComponentProps<"div">) { +function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">) { return (
- ) + ); } -function AlertDialogFooter({ - className, - ...props -}: React.ComponentProps<"div">) { +function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">) { return (
- ) + ); } function AlertDialogTitle({ @@ -102,7 +85,7 @@ function AlertDialogTitle({ className={cn("text-lg font-semibold", className)} {...props} /> - ) + ); } function AlertDialogDescription({ @@ -115,19 +98,14 @@ function AlertDialogDescription({ className={cn("text-muted-foreground text-sm", className)} {...props} /> - ) + ); } function AlertDialogAction({ className, ...props }: React.ComponentProps) { - return ( - - ) + return ; } function AlertDialogCancel({ @@ -139,7 +117,7 @@ function AlertDialogCancel({ className={cn(buttonVariants({ variant: "outline" }), className)} {...props} /> - ) + ); } export { @@ -154,4 +132,4 @@ export { AlertDialogDescription, AlertDialogAction, AlertDialogCancel, -} +}; diff --git a/src/components/ui/alert.tsx b/src/components/ui/alert.tsx index 371f9ce3..80b8dc69 100644 --- a/src/components/ui/alert.tsx +++ b/src/components/ui/alert.tsx @@ -15,7 +15,7 @@ const alertVariants = cva( defaultVariants: { variant: "default", }, - } + }, ); function Alert({ @@ -47,7 +47,10 @@ function AlertDescription({ className, ...props }: React.ComponentProps<"div">) return (
); diff --git a/src/components/ui/badge.tsx b/src/components/ui/badge.tsx index fd3a406b..0092b288 100644 --- a/src/components/ui/badge.tsx +++ b/src/components/ui/badge.tsx @@ -1,46 +1,39 @@ -import * as React from "react" -import { Slot } from "@radix-ui/react-slot" -import { cva, type VariantProps } from "class-variance-authority" +import * as React from "react"; +import { Slot } from "@radix-ui/react-slot"; +import { cva, type VariantProps } from "class-variance-authority"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; const badgeVariants = cva( "inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden", { variants: { variant: { - default: - "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90", + default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90", secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90", destructive: "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", - outline: - "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground", + outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground", }, }, defaultVariants: { variant: "default", }, - } -) + }, +); function Badge({ className, variant, asChild = false, ...props -}: React.ComponentProps<"span"> & - VariantProps & { asChild?: boolean }) { - const Comp = asChild ? Slot : "span" +}: React.ComponentProps<"span"> & VariantProps & { asChild?: boolean }) { + const Comp = asChild ? Slot : "span"; return ( - - ) + + ); } -export { Badge, badgeVariants } +export { Badge, badgeVariants }; diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx index c97c3e39..08461c40 100644 --- a/src/components/ui/button.tsx +++ b/src/components/ui/button.tsx @@ -1,8 +1,8 @@ -import * as React from "react" -import { Slot } from "@radix-ui/react-slot" -import { cva, type VariantProps } from "class-variance-authority" +import * as React from "react"; +import { Slot } from "@radix-ui/react-slot"; +import { cva, type VariantProps } from "class-variance-authority"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium tracking-[0.005em] transition-all duration-150 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/45 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", @@ -14,10 +14,8 @@ const buttonVariants = cva( "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", outline: "border border-border/70 bg-background/70 shadow-xs hover:border-primary/35 hover:bg-accent/70 hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/55", - secondary: - "bg-secondary text-secondary-foreground hover:bg-secondary/80", - ghost: - "hover:bg-accent/80 hover:text-accent-foreground dark:hover:bg-accent/55", + secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: "hover:bg-accent/80 hover:text-accent-foreground dark:hover:bg-accent/55", link: "text-primary underline-offset-4 hover:underline", }, size: { @@ -33,8 +31,8 @@ const buttonVariants = cva( variant: "default", size: "default", }, - } -) + }, +); function Button({ className, @@ -44,9 +42,9 @@ function Button({ ...props }: React.ComponentProps<"button"> & VariantProps & { - asChild?: boolean + asChild?: boolean; }) { - const Comp = asChild ? Slot : "button" + const Comp = asChild ? Slot : "button"; return ( - ) + ); } -export { Button, buttonVariants } +export { Button, buttonVariants }; diff --git a/src/components/ui/card.tsx b/src/components/ui/card.tsx index 5b97a2e1..9b7e2add 100644 --- a/src/components/ui/card.tsx +++ b/src/components/ui/card.tsx @@ -1,6 +1,6 @@ -import * as React from "react" +import * as React from "react"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Card({ className, ...props }: React.ComponentProps<"div">) { return ( @@ -8,11 +8,11 @@ function Card({ className, ...props }: React.ComponentProps<"div">) { data-slot="card" className={cn( "bg-card/95 text-card-foreground flex flex-col gap-6 rounded-lg border border-border/60 py-6 shadow-sm backdrop-blur-sm transition-[border-color,box-shadow,transform]", - className + className, )} {...props} /> - ) + ); } function CardHeader({ className, ...props }: React.ComponentProps<"div">) { @@ -21,11 +21,11 @@ function CardHeader({ className, ...props }: React.ComponentProps<"div">) { data-slot="card-header" className={cn( "@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6", - className + className, )} {...props} /> - ) + ); } function CardTitle({ className, ...props }: React.ComponentProps<"div">) { @@ -35,7 +35,7 @@ function CardTitle({ className, ...props }: React.ComponentProps<"div">) { className={cn("leading-none font-semibold", className)} {...props} /> - ) + ); } function CardDescription({ className, ...props }: React.ComponentProps<"div">) { @@ -45,30 +45,21 @@ function CardDescription({ className, ...props }: React.ComponentProps<"div">) { className={cn("text-muted-foreground text-sm", className)} {...props} /> - ) + ); } function CardAction({ className, ...props }: React.ComponentProps<"div">) { return (
- ) + ); } function CardContent({ className, ...props }: React.ComponentProps<"div">) { - return ( -
- ) + return
; } function CardFooter({ className, ...props }: React.ComponentProps<"div">) { @@ -78,15 +69,7 @@ function CardFooter({ className, ...props }: React.ComponentProps<"div">) { className={cn("flex items-center px-6 [.border-t]:pt-6", className)} {...props} /> - ) + ); } -export { - Card, - CardHeader, - CardFooter, - CardTitle, - CardAction, - CardDescription, - CardContent, -} +export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent }; diff --git a/src/components/ui/chart.tsx b/src/components/ui/chart.tsx index 48d27244..b68b325b 100644 --- a/src/components/ui/chart.tsx +++ b/src/components/ui/chart.tsx @@ -1,35 +1,35 @@ -import * as React from "react" -import * as RechartsPrimitive from "recharts" +import * as React from "react"; +import * as RechartsPrimitive from "recharts"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; // Format: { THEME_NAME: CSS_SELECTOR } -const THEMES = { light: "", dark: ".dark" } as const +const THEMES = { light: "", dark: ".dark" } as const; export type ChartConfig = { [k in string]: { - label?: React.ReactNode - icon?: React.ComponentType + label?: React.ReactNode; + icon?: React.ComponentType; } & ( | { color?: string; theme?: never } | { color?: never; theme: Record } - ) -} + ); +}; type ChartContextProps = { - config: ChartConfig -} + config: ChartConfig; +}; -const ChartContext = React.createContext(null) +const ChartContext = React.createContext(null); function useChart() { - const context = React.useContext(ChartContext) + const context = React.useContext(ChartContext); if (!context) { - throw new Error("useChart must be used within a ") + throw new Error("useChart must be used within a "); } - return context + return context; } function ChartContainer({ @@ -39,13 +39,11 @@ function ChartContainer({ config, ...props }: React.ComponentProps<"div"> & { - config: ChartConfig - children: React.ComponentProps< - typeof RechartsPrimitive.ResponsiveContainer - >["children"] + config: ChartConfig; + children: React.ComponentProps["children"]; }) { - const uniqueId = React.useId() - const chartId = `chart-${id || uniqueId.replace(/:/g, "")}` + const uniqueId = React.useId(); + const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`; return ( @@ -54,26 +52,22 @@ function ChartContainer({ data-chart={chartId} className={cn( "[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden", - className + className, )} {...props} > - - {children} - + {children}
- ) + ); } const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => { - const colorConfig = Object.entries(config).filter( - ([, config]) => config.theme || config.color - ) + const colorConfig = Object.entries(config).filter(([, config]) => config.theme || config.color); if (!colorConfig.length) { - return null + return null; } return ( @@ -85,22 +79,20 @@ const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => { ${prefix} [data-chart=${id}] { ${colorConfig .map(([key, itemConfig]) => { - const color = - itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || - itemConfig.color - return color ? ` --color-${key}: ${color};` : null + const color = itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || itemConfig.color; + return color ? ` --color-${key}: ${color};` : null; }) .join("\n")} } -` +`, ) .join("\n"), }} /> - ) -} + ); +}; -const ChartTooltip = RechartsPrimitive.Tooltip +const ChartTooltip = RechartsPrimitive.Tooltip; function ChartTooltipContent({ active, @@ -118,61 +110,51 @@ function ChartTooltipContent({ labelKey, }: React.ComponentProps & React.ComponentProps<"div"> & { - hideLabel?: boolean - hideIndicator?: boolean - indicator?: "line" | "dot" | "dashed" - nameKey?: string - labelKey?: string + hideLabel?: boolean; + hideIndicator?: boolean; + indicator?: "line" | "dot" | "dashed"; + nameKey?: string; + labelKey?: string; }) { - const { config } = useChart() + const { config } = useChart(); const tooltipLabel = React.useMemo(() => { if (hideLabel || !payload?.length) { - return null + return null; } - const [item] = payload - const key = `${labelKey || item?.dataKey || item?.name || "value"}` - const itemConfig = getPayloadConfigFromPayload(config, item, key) + const [item] = payload; + const key = `${labelKey || item?.dataKey || item?.name || "value"}`; + const itemConfig = getPayloadConfigFromPayload(config, item, key); const value = !labelKey && typeof label === "string" ? config[label as keyof typeof config]?.label || label - : itemConfig?.label + : itemConfig?.label; if (labelFormatter) { return ( -
- {labelFormatter(value, payload)} -
- ) +
{labelFormatter(value, payload)}
+ ); } if (!value) { - return null + return null; } - return
{value}
- }, [ - label, - labelFormatter, - payload, - hideLabel, - labelClassName, - config, - labelKey, - ]) + return
{value}
; + }, [label, labelFormatter, payload, hideLabel, labelClassName, config, labelKey]); if (!active || !payload?.length) { - return null + return null; } - const nestLabel = payload.length === 1 && indicator !== "dot" + const nestLabel = payload.length === 1 && indicator !== "dot"; return (
{!nestLabel ? tooltipLabel : null} @@ -180,16 +162,16 @@ function ChartTooltipContent({ {payload .filter((item) => item.type !== "none") .map((item, index) => { - const key = `${nameKey || item.name || item.dataKey || "value"}` - const itemConfig = getPayloadConfigFromPayload(config, item, key) - const indicatorColor = color || item.payload.fill || item.color + const key = `${nameKey || item.name || item.dataKey || "value"}`; + const itemConfig = getPayloadConfigFromPayload(config, item, key); + const indicatorColor = color || item.payload.fill || item.color; return (
svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5", - indicator === "dot" && "items-center" + indicator === "dot" && "items-center", )} > {formatter && item?.value !== undefined && item.name ? ( @@ -209,7 +191,7 @@ function ChartTooltipContent({ "w-0 border-[1.5px] border-dashed bg-transparent": indicator === "dashed", "my-0.5": nestLabel && indicator === "dashed", - } + }, )} style={ { @@ -223,7 +205,7 @@ function ChartTooltipContent({
@@ -241,14 +223,14 @@ function ChartTooltipContent({ )}
- ) + ); })}
- ) + ); } -const ChartLegend = RechartsPrimitive.Legend +const ChartLegend = RechartsPrimitive.Legend; function ChartLegendContent({ className, @@ -258,13 +240,13 @@ function ChartLegendContent({ nameKey, }: React.ComponentProps<"div"> & Pick & { - hideIcon?: boolean - nameKey?: string + hideIcon?: boolean; + nameKey?: string; }) { - const { config } = useChart() + const { config } = useChart(); if (!payload?.length) { - return null + return null; } return ( @@ -272,20 +254,20 @@ function ChartLegendContent({ className={cn( "flex items-center justify-center gap-4", verticalAlign === "top" ? "pb-3" : "pt-3", - className + className, )} > {payload .filter((item) => item.type !== "none") .map((item) => { - const key = `${nameKey || item.dataKey || "value"}` - const itemConfig = getPayloadConfigFromPayload(config, item, key) + const key = `${nameKey || item.dataKey || "value"}`; + const itemConfig = getPayloadConfigFromPayload(config, item, key); return (
svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3" + "[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3", )} > {itemConfig?.icon && !hideIcon ? ( @@ -300,49 +282,36 @@ function ChartLegendContent({ )} {itemConfig?.label}
- ) + ); })}
- ) + ); } // Helper to extract item config from a payload. -function getPayloadConfigFromPayload( - config: ChartConfig, - payload: unknown, - key: string -) { +function getPayloadConfigFromPayload(config: ChartConfig, payload: unknown, key: string) { if (typeof payload !== "object" || payload === null) { - return undefined + return undefined; } const payloadPayload = - "payload" in payload && - typeof payload.payload === "object" && - payload.payload !== null + "payload" in payload && typeof payload.payload === "object" && payload.payload !== null ? payload.payload - : undefined + : undefined; - let configLabelKey: string = key + let configLabelKey: string = key; - if ( - key in payload && - typeof payload[key as keyof typeof payload] === "string" - ) { - configLabelKey = payload[key as keyof typeof payload] as string + if (key in payload && typeof payload[key as keyof typeof payload] === "string") { + configLabelKey = payload[key as keyof typeof payload] as string; } else if ( payloadPayload && key in payloadPayload && typeof payloadPayload[key as keyof typeof payloadPayload] === "string" ) { - configLabelKey = payloadPayload[ - key as keyof typeof payloadPayload - ] as string + configLabelKey = payloadPayload[key as keyof typeof payloadPayload] as string; } - return configLabelKey in config - ? config[configLabelKey] - : config[key as keyof typeof config] + return configLabelKey in config ? config[configLabelKey] : config[key as keyof typeof config]; } export { @@ -352,4 +321,4 @@ export { ChartLegend, ChartLegendContent, ChartStyle, -} +}; diff --git a/src/components/ui/checkbox.tsx b/src/components/ui/checkbox.tsx index 0e2a6cd9..2ffaa6b8 100644 --- a/src/components/ui/checkbox.tsx +++ b/src/components/ui/checkbox.tsx @@ -1,19 +1,16 @@ -import * as React from "react" -import * as CheckboxPrimitive from "@radix-ui/react-checkbox" -import { CheckIcon } from "lucide-react" +import * as React from "react"; +import * as CheckboxPrimitive from "@radix-ui/react-checkbox"; +import { CheckIcon } from "lucide-react"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; -function Checkbox({ - className, - ...props -}: React.ComponentProps) { +function Checkbox({ className, ...props }: React.ComponentProps) { return ( @@ -24,7 +21,7 @@ function Checkbox({ - ) + ); } -export { Checkbox } +export { Checkbox }; diff --git a/src/components/ui/collapsible.tsx b/src/components/ui/collapsible.tsx index 77f86bed..ecddbb59 100644 --- a/src/components/ui/collapsible.tsx +++ b/src/components/ui/collapsible.tsx @@ -1,31 +1,19 @@ -import * as CollapsiblePrimitive from "@radix-ui/react-collapsible" +import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"; -function Collapsible({ - ...props -}: React.ComponentProps) { - return +function Collapsible({ ...props }: React.ComponentProps) { + return ; } function CollapsibleTrigger({ ...props }: React.ComponentProps) { - return ( - - ) + return ; } function CollapsibleContent({ ...props }: React.ComponentProps) { - return ( - - ) + return ; } -export { Collapsible, CollapsibleTrigger, CollapsibleContent } +export { Collapsible, CollapsibleTrigger, CollapsibleContent }; diff --git a/src/components/ui/context-menu.tsx b/src/components/ui/context-menu.tsx index 624c588a..72bf4a4d 100644 --- a/src/components/ui/context-menu.tsx +++ b/src/components/ui/context-menu.tsx @@ -1,54 +1,35 @@ -import * as React from "react" -import * as ContextMenuPrimitive from "@radix-ui/react-context-menu" -import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react" +import * as React from "react"; +import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"; +import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; -function ContextMenu({ - ...props -}: React.ComponentProps) { - return +function ContextMenu({ ...props }: React.ComponentProps) { + return ; } function ContextMenuTrigger({ ...props }: React.ComponentProps) { - return ( - - ) + return ; } -function ContextMenuGroup({ - ...props -}: React.ComponentProps) { - return ( - - ) +function ContextMenuGroup({ ...props }: React.ComponentProps) { + return ; } -function ContextMenuPortal({ - ...props -}: React.ComponentProps) { - return ( - - ) +function ContextMenuPortal({ ...props }: React.ComponentProps) { + return ; } -function ContextMenuSub({ - ...props -}: React.ComponentProps) { - return +function ContextMenuSub({ ...props }: React.ComponentProps) { + return ; } function ContextMenuRadioGroup({ ...props }: React.ComponentProps) { - return ( - - ) + return ; } function ContextMenuSubTrigger({ @@ -57,7 +38,7 @@ function ContextMenuSubTrigger({ children, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( {children} - ) + ); } function ContextMenuSubContent({ @@ -84,11 +65,11 @@ function ContextMenuSubContent({ data-slot="context-menu-sub-content" className={cn( "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg", - className + className, )} {...props} /> - ) + ); } function ContextMenuContent({ @@ -101,12 +82,12 @@ function ContextMenuContent({ data-slot="context-menu-content" className={cn( "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md", - className + className, )} {...props} /> - ) + ); } function ContextMenuItem({ @@ -115,8 +96,8 @@ function ContextMenuItem({ variant = "default", ...props }: React.ComponentProps & { - inset?: boolean - variant?: "default" | "destructive" + inset?: boolean; + variant?: "default" | "destructive"; }) { return ( - ) + ); } function ContextMenuCheckboxItem({ @@ -143,7 +124,7 @@ function ContextMenuCheckboxItem({ data-slot="context-menu-checkbox-item" className={cn( "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", - className + className, )} checked={checked} {...props} @@ -155,7 +136,7 @@ function ContextMenuCheckboxItem({ {children} - ) + ); } function ContextMenuRadioItem({ @@ -168,7 +149,7 @@ function ContextMenuRadioItem({ data-slot="context-menu-radio-item" className={cn( "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", - className + className, )} {...props} > @@ -179,7 +160,7 @@ function ContextMenuRadioItem({ {children} - ) + ); } function ContextMenuLabel({ @@ -187,19 +168,16 @@ function ContextMenuLabel({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - ) + ); } function ContextMenuSeparator({ @@ -212,23 +190,17 @@ function ContextMenuSeparator({ className={cn("bg-border -mx-1 my-1 h-px", className)} {...props} /> - ) + ); } -function ContextMenuShortcut({ - className, - ...props -}: React.ComponentProps<"span">) { +function ContextMenuShortcut({ className, ...props }: React.ComponentProps<"span">) { return ( - ) + ); } export { @@ -247,4 +219,4 @@ export { ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuRadioGroup, -} +}; diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx index 0d75f8c8..66caa675 100644 --- a/src/components/ui/dialog.tsx +++ b/src/components/ui/dialog.tsx @@ -1,31 +1,23 @@ -import * as React from "react" -import * as DialogPrimitive from "@radix-ui/react-dialog" -import { XIcon } from "lucide-react" +import * as React from "react"; +import * as DialogPrimitive from "@radix-ui/react-dialog"; +import { XIcon } from "lucide-react"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; -function Dialog({ - ...props -}: React.ComponentProps) { - return +function Dialog({ ...props }: React.ComponentProps) { + return ; } -function DialogTrigger({ - ...props -}: React.ComponentProps) { - return +function DialogTrigger({ ...props }: React.ComponentProps) { + return ; } -function DialogPortal({ - ...props -}: React.ComponentProps) { - return +function DialogPortal({ ...props }: React.ComponentProps) { + return ; } -function DialogClose({ - ...props -}: React.ComponentProps) { - return +function DialogClose({ ...props }: React.ComponentProps) { + return ; } function DialogOverlay({ @@ -37,11 +29,11 @@ function DialogOverlay({ data-slot="dialog-overlay" className={cn( "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/60 backdrop-blur-sm", - className + className, )} {...props} /> - ) + ); } function DialogContent({ @@ -50,7 +42,7 @@ function DialogContent({ showCloseButton = true, ...props }: React.ComponentProps & { - showCloseButton?: boolean + showCloseButton?: boolean; }) { return ( @@ -59,7 +51,7 @@ function DialogContent({ data-slot="dialog-content" className={cn( "bg-popover/95 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border border-border/70 p-6 shadow-2xl backdrop-blur-xl duration-200 sm:max-w-lg", - className + className, )} {...props} > @@ -75,7 +67,7 @@ function DialogContent({ )} - ) + ); } function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { @@ -85,33 +77,27 @@ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { className={cn("flex flex-col gap-2 text-center sm:text-left", className)} {...props} /> - ) + ); } function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { return (
- ) + ); } -function DialogTitle({ - className, - ...props -}: React.ComponentProps) { +function DialogTitle({ className, ...props }: React.ComponentProps) { return ( - ) + ); } function DialogDescription({ @@ -124,7 +110,7 @@ function DialogDescription({ className={cn("text-muted-foreground text-sm", className)} {...props} /> - ) + ); } export { @@ -138,4 +124,4 @@ export { DialogPortal, DialogTitle, DialogTrigger, -} +}; diff --git a/src/components/ui/dropdown-menu.tsx b/src/components/ui/dropdown-menu.tsx index eaed9baf..0cb726d2 100644 --- a/src/components/ui/dropdown-menu.tsx +++ b/src/components/ui/dropdown-menu.tsx @@ -1,32 +1,23 @@ -import * as React from "react" -import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" -import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react" +import * as React from "react"; +import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"; +import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; -function DropdownMenu({ - ...props -}: React.ComponentProps) { - return +function DropdownMenu({ ...props }: React.ComponentProps) { + return ; } function DropdownMenuPortal({ ...props }: React.ComponentProps) { - return ( - - ) + return ; } function DropdownMenuTrigger({ ...props }: React.ComponentProps) { - return ( - - ) + return ; } function DropdownMenuContent({ @@ -41,20 +32,16 @@ function DropdownMenuContent({ sideOffset={sideOffset} className={cn( "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md", - className + className, )} {...props} /> - ) + ); } -function DropdownMenuGroup({ - ...props -}: React.ComponentProps) { - return ( - - ) +function DropdownMenuGroup({ ...props }: React.ComponentProps) { + return ; } function DropdownMenuItem({ @@ -63,8 +50,8 @@ function DropdownMenuItem({ variant = "default", ...props }: React.ComponentProps & { - inset?: boolean - variant?: "default" | "destructive" + inset?: boolean; + variant?: "default" | "destructive"; }) { return ( - ) + ); } function DropdownMenuCheckboxItem({ @@ -91,7 +78,7 @@ function DropdownMenuCheckboxItem({ data-slot="dropdown-menu-checkbox-item" className={cn( "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", - className + className, )} checked={checked} {...props} @@ -103,18 +90,13 @@ function DropdownMenuCheckboxItem({ {children} - ) + ); } function DropdownMenuRadioGroup({ ...props }: React.ComponentProps) { - return ( - - ) + return ; } function DropdownMenuRadioItem({ @@ -127,7 +109,7 @@ function DropdownMenuRadioItem({ data-slot="dropdown-menu-radio-item" className={cn( "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", - className + className, )} {...props} > @@ -138,7 +120,7 @@ function DropdownMenuRadioItem({ {children} - ) + ); } function DropdownMenuLabel({ @@ -146,19 +128,16 @@ function DropdownMenuLabel({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - ) + ); } function DropdownMenuSeparator({ @@ -171,29 +150,21 @@ function DropdownMenuSeparator({ className={cn("bg-border -mx-1 my-1 h-px", className)} {...props} /> - ) + ); } -function DropdownMenuShortcut({ - className, - ...props -}: React.ComponentProps<"span">) { +function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<"span">) { return ( - ) + ); } -function DropdownMenuSub({ - ...props -}: React.ComponentProps) { - return +function DropdownMenuSub({ ...props }: React.ComponentProps) { + return ; } function DropdownMenuSubTrigger({ @@ -202,7 +173,7 @@ function DropdownMenuSubTrigger({ children, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( {children} - ) + ); } function DropdownMenuSubContent({ @@ -229,11 +200,11 @@ function DropdownMenuSubContent({ data-slot="dropdown-menu-sub-content" className={cn( "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg", - className + className, )} {...props} /> - ) + ); } export { @@ -252,4 +223,4 @@ export { DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent, -} +}; diff --git a/src/components/ui/empty.tsx b/src/components/ui/empty.tsx index ce4b0095..e3510b60 100644 --- a/src/components/ui/empty.tsx +++ b/src/components/ui/empty.tsx @@ -1,6 +1,6 @@ -import { cva, type VariantProps } from "class-variance-authority" +import { cva, type VariantProps } from "class-variance-authority"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Empty({ className, ...props }: React.ComponentProps<"div">) { return ( @@ -8,24 +8,21 @@ function Empty({ className, ...props }: React.ComponentProps<"div">) { data-slot="empty" className={cn( "flex min-w-0 flex-1 flex-col items-center justify-center gap-6 rounded-lg border-dashed p-6 text-center text-balance md:p-12", - className + className, )} {...props} /> - ) + ); } function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) { return (
- ) + ); } const emptyMediaVariants = cva( @@ -40,8 +37,8 @@ const emptyMediaVariants = cva( defaultVariants: { variant: "default", }, - } -) + }, +); function EmptyMedia({ className, @@ -55,7 +52,7 @@ function EmptyMedia({ className={cn(emptyMediaVariants({ variant, className }))} {...props} /> - ) + ); } function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) { @@ -65,7 +62,7 @@ function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) { className={cn("text-lg font-medium tracking-tight", className)} {...props} /> - ) + ); } function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) { @@ -74,11 +71,11 @@ function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) { data-slot="empty-description" className={cn( "text-sm/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary", - className + className, )} {...props} /> - ) + ); } function EmptyContent({ className, ...props }: React.ComponentProps<"div">) { @@ -87,18 +84,11 @@ function EmptyContent({ className, ...props }: React.ComponentProps<"div">) { data-slot="empty-content" className={cn( "flex w-full max-w-sm min-w-0 flex-col items-center gap-4 text-sm text-balance", - className + className, )} {...props} /> - ) + ); } -export { - Empty, - EmptyHeader, - EmptyTitle, - EmptyDescription, - EmptyContent, - EmptyMedia, -} +export { Empty, EmptyHeader, EmptyTitle, EmptyDescription, EmptyContent, EmptyMedia }; diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsx index 27a1b52e..ca678d0b 100644 --- a/src/components/ui/input.tsx +++ b/src/components/ui/input.tsx @@ -1,8 +1,14 @@ -import * as React from "react" +import * as React from "react"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; -function Input({ className, type, autoComplete = "off", spellCheck = false, ...props }: React.ComponentProps<"input">) { +function Input({ + className, + type, + autoComplete = "off", + spellCheck = false, + ...props +}: React.ComponentProps<"input">) { return ( - ) + ); } -export { Input } +export { Input }; diff --git a/src/components/ui/label.tsx b/src/components/ui/label.tsx index ef7133a7..21120b24 100644 --- a/src/components/ui/label.tsx +++ b/src/components/ui/label.tsx @@ -1,22 +1,19 @@ -import * as React from "react" -import * as LabelPrimitive from "@radix-ui/react-label" +import * as React from "react"; +import * as LabelPrimitive from "@radix-ui/react-label"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; -function Label({ - className, - ...props -}: React.ComponentProps) { +function Label({ className, ...props }: React.ComponentProps) { return ( - ) + ); } -export { Label } +export { Label }; diff --git a/src/components/ui/pagination.tsx b/src/components/ui/pagination.tsx index 1dcfb0cc..8940389d 100644 --- a/src/components/ui/pagination.tsx +++ b/src/components/ui/pagination.tsx @@ -1,12 +1,8 @@ -import * as React from "react" -import { - ChevronLeftIcon, - ChevronRightIcon, - MoreHorizontalIcon, -} from "lucide-react" +import * as React from "react"; +import { ChevronLeftIcon, ChevronRightIcon, MoreHorizontalIcon } from "lucide-react"; -import { cn } from "@/lib/utils" -import { buttonVariants, type Button } from "@/components/ui/button" +import { cn } from "@/lib/utils"; +import { buttonVariants, type Button } from "@/components/ui/button"; function Pagination({ className, ...props }: React.ComponentProps<"nav">) { return ( @@ -17,37 +13,29 @@ function Pagination({ className, ...props }: React.ComponentProps<"nav">) { className={cn("mx-auto flex w-full justify-center", className)} {...props} /> - ) + ); } -function PaginationContent({ - className, - ...props -}: React.ComponentProps<"ul">) { +function PaginationContent({ className, ...props }: React.ComponentProps<"ul">) { return (