diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 00000000..f23f9919 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,25 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/typescript-node +{ + "name": "Node.js & TypeScript", + // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile + "image": "mcr.microsoft.com/devcontainers/typescript-node:5-24-trixie", + + // Features to add to the dev container. More info: https://containers.dev/features. + "features": { + "ghcr.io/devcontainers-extra/features/bun:1": {} + + }, + "postCreateCommand": "sudo apt-get update && sudo apt-get install -y lcov && bun install" + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Use 'postCreateCommand' to run commands after the container is created. + // "postCreateCommand": "yarn install", + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..f33a02cd --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for more information: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates +# https://containers.dev/guide/dependabot + +version: 2 +updates: + - package-ecosystem: "devcontainers" + directory: "/" + schedule: + interval: weekly diff --git a/bun.lock b/bun.lock index 1e3a6425..47da2b1f 100644 --- a/bun.lock +++ b/bun.lock @@ -1442,8 +1442,6 @@ "@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], - "@bcoe/v8-coverage": ["@bcoe/v8-coverage@1.0.2", "", {}, "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA=="], - "@bufbuild/protobuf": ["@bufbuild/protobuf@2.12.0", "", {}, "sha512-B/XlCaFIP8LOwzo+bz5uFzATYokcwCKQcghqnlfwSmM5eX/qTkvDBnDPs+gXtX/RyjxJ4DRikECcPJbyALA8FA=="], "@bufbuild/protoplugin": ["@bufbuild/protoplugin@2.12.0", "", { "dependencies": { "@bufbuild/protobuf": "2.12.0", "@typescript/vfs": "^1.6.2", "typescript": "5.4.5" } }, "sha512-ORlDITp8AFUXzIhLRoMCG+ud+D3MPKWb5HQXBoskMMnjeyEjE1H1qLonVNPyOr8lkx3xSfYUo8a0dvOZJVAzow=="], @@ -3002,8 +3000,6 @@ "@vitejs/plugin-react": ["@vitejs/plugin-react@4.7.0", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-beta.27", "@types/babel__core": "^7.20.5", "react-refresh": "^0.17.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA=="], - "@vitest/coverage-v8": ["@vitest/coverage-v8@4.1.8", "", { "dependencies": { "@bcoe/v8-coverage": "^1.0.2", "@vitest/utils": "4.1.8", "ast-v8-to-istanbul": "^1.0.0", "istanbul-lib-coverage": "^3.2.2", "istanbul-lib-report": "^3.0.1", "istanbul-reports": "^3.2.0", "magicast": "^0.5.2", "obug": "^2.1.1", "std-env": "^4.0.0-rc.1", "tinyrainbow": "^3.1.0" }, "peerDependencies": { "@vitest/browser": "4.1.8", "vitest": "4.1.8" }, "optionalPeers": ["@vitest/browser"] }, "sha512-lt3kovsyHwYe00wq4D1ti0Z974fWj4NLp6siqiyEufUpyFwK9Yhi7rBhac9JL5aA0zoMrJqc4vYPZRUnI7l7nw=="], - "@vitest/expect": ["@vitest/expect@3.2.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/spy": "3.2.4", "@vitest/utils": "3.2.4", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig=="], "@vitest/mocker": ["@vitest/mocker@4.1.7", "", { "dependencies": { "@vitest/spy": "4.1.7", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-vY7nuamKgfvpA1Koa3oYIw/k7D6kZnpGyNMZW8loow2bsBYla1TFdqTaXncWdRn4pgwNs+90RhnXhJScDwQeJA=="], @@ -3124,8 +3120,6 @@ "ast-types": ["ast-types@0.16.1", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg=="], - "ast-v8-to-istanbul": ["ast-v8-to-istanbul@1.0.3", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.31", "estree-walker": "^3.0.3", "js-tokens": "^10.0.0" } }, "sha512-jCMQ6ZylLPudp0CDfBmQBZUsrh1/8psbmu9ibeVWKuHWD0YrH9YABwlKu5kVEFoT0GCQQW9Z/SxfuEbbkGQCRg=="], - "astral-regex": ["astral-regex@2.0.0", "", {}, "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ=="], "astring": ["astring@1.9.0", "", { "bin": { "astring": "bin/astring" } }, "sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg=="], @@ -3610,8 +3604,6 @@ "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], - "encoding": ["encoding@0.1.13", "", { "dependencies": { "iconv-lite": "^0.6.2" } }, "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A=="], - "end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="], "engine.io-client": ["engine.io-client@6.6.5", "", { "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.4.1", "engine.io-parser": "~5.2.1", "ws": "~8.20.1", "xmlhttprequest-ssl": "~2.1.1" } }, "sha512-QCwxUDULPlXv8F6tqMMKx5dNkTe6OaBYRMPYeXKBlyOoKvAmE0ac6pW7fFhSscJ/5SI7666/U/B+MElbsrJlIg=="], @@ -4132,12 +4124,6 @@ "isomorphic-ws": ["isomorphic-ws@5.0.0", "", { "peerDependencies": { "ws": "*" } }, "sha512-muId7Zzn9ywDsyXgTIafTry2sV3nySZeUDe6YedVd1Hvuuep5AsIlqK+XefWpYTyJG5e503F2xIuT2lcU6rCSw=="], - "istanbul-lib-coverage": ["istanbul-lib-coverage@3.2.2", "", {}, "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg=="], - - "istanbul-lib-report": ["istanbul-lib-report@3.0.1", "", { "dependencies": { "istanbul-lib-coverage": "^3.0.0", "make-dir": "^4.0.0", "supports-color": "^7.1.0" } }, "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw=="], - - "istanbul-reports": ["istanbul-reports@3.2.0", "", { "dependencies": { "html-escaper": "^2.0.0", "istanbul-lib-report": "^3.0.0" } }, "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA=="], - "iterate-iterator": ["iterate-iterator@1.0.2", "", {}, "sha512-t91HubM4ZDQ70M9wqp+pcNpu8OyJ9UAtXntT/Bcsvp5tZMnz9vRa+IunKXeI8AnfZMTv0jNuVEmGeLSMjVvfPw=="], "iterate-value": ["iterate-value@1.0.2", "", { "dependencies": { "es-get-iterator": "^1.0.2", "iterate-iterator": "^1.0.1" } }, "sha512-A6fMAio4D2ot2r/TYzr4yUWrmwNdsN5xL7+HUiyACE4DXm+q8HtPcnFTp+NnW3k4N05tZ7FVYFFb2CR13NxyHQ=="], @@ -4306,8 +4292,6 @@ "magicast": ["magicast@0.3.5", "", { "dependencies": { "@babel/parser": "^7.25.4", "@babel/types": "^7.25.4", "source-map-js": "^1.2.0" } }, "sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ=="], - "make-dir": ["make-dir@4.0.0", "", { "dependencies": { "semver": "^7.5.3" } }, "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw=="], - "make-fetch-happen": ["make-fetch-happen@15.0.6", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/agent": "^4.0.0", "@npmcli/redact": "^4.0.0", "cacache": "^20.0.1", "http-cache-semantics": "^4.1.1", "minipass": "^7.0.2", "minipass-fetch": "^5.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^1.0.0", "proc-log": "^6.0.0", "ssri": "^13.0.0" } }, "sha512-Je0fLJ0F5atA7F+eIlLzk+Wkcl57JDf4kf+EW8xiP5E31xOQxkIxTbgf1Oi1Lw9tRI9UEMRdI5Vz2xTzoNU1Jw=="], "markdown-extensions": ["markdown-extensions@2.0.0", "", {}, "sha512-o5vL7aDWatOTX8LzaS1WMoaoxIiLRQJuIKKe2wAw6IeULDHaqbiqiggmx+pKvZDb1Sj+pE46Sn1T7lCqfFtg1Q=="], @@ -6122,10 +6106,6 @@ "@solidjs/start/vite": ["vite@7.1.10", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-CmuvUBzVJ/e3HGxhg6cYk88NGgTnBoOo7ogtfJJ0fefUWAxN/WDSUa50o+oVBxuIhO8FoEZW0j2eW7sfjs5EtA=="], - "@standard-community/standard-json/effect": ["effect@4.0.0-beta.74", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.8.0", "find-my-way-ts": "^0.1.6", "ini": "^7.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^2.0.1", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^14.0.0", "yaml": "^2.9.0" } }, "sha512-Yx+Kh12U+i2FmjwEfKs+ePFmpMd43RPD1oGqc/VraSS9bYzvF0Ff3PojwEFEVEewp8xc92Uxu28gTspU4qyvHA=="], - - "@standard-community/standard-openapi/effect": ["effect@4.0.0-beta.74", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.8.0", "find-my-way-ts": "^0.1.6", "ini": "^7.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^2.0.1", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^14.0.0", "yaml": "^2.9.0" } }, "sha512-Yx+Kh12U+i2FmjwEfKs+ePFmpMd43RPD1oGqc/VraSS9bYzvF0Ff3PojwEFEVEewp8xc92Uxu28gTspU4qyvHA=="], - "@storybook/csf-plugin/unplugin": ["unplugin@2.3.11", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "acorn": "^8.15.0", "picomatch": "^4.0.3", "webpack-virtual-modules": "^0.6.2" } }, "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww=="], "@tailwindcss/oxide/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], @@ -6154,10 +6134,6 @@ "@types/plist/xmlbuilder": ["xmlbuilder@15.1.1", "", {}, "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg=="], - "@vitest/coverage-v8/@vitest/utils": ["@vitest/utils@4.1.8", "", { "dependencies": { "@vitest/pretty-format": "4.1.8", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg=="], - - "@vitest/coverage-v8/magicast": ["magicast@0.5.3", "", { "dependencies": { "@babel/parser": "^7.29.3", "@babel/types": "^7.29.0", "source-map-js": "^1.2.1" } }, "sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw=="], - "@vitest/expect/@vitest/utils": ["@vitest/utils@3.2.4", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="], "@vitest/expect/tinyrainbow": ["tinyrainbow@2.0.0", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="], @@ -6208,8 +6184,6 @@ "archiver-utils/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="], - "ast-v8-to-istanbul/js-tokens": ["js-tokens@10.0.0", "", {}, "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q=="], - "astro/@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.6.1", "", {}, "sha512-l5Pqf6uZu31aG+3Lv8nl/3s4DbUzdlxTWDof4pEpto6GUJNhhCbelVi9dEyurOVyqaelwmS9oSyOWOENSfgo9A=="], "astro/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], @@ -6300,8 +6274,6 @@ "electron-winstaller/fs-extra": ["fs-extra@7.0.1", "", { "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw=="], - "encoding/iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="], - "engine.io-client/ws": ["ws@8.20.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w=="], "esast-util-from-js/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], @@ -6352,8 +6324,6 @@ "iconv-corefoundation/node-addon-api": ["node-addon-api@1.7.2", "", {}, "sha512-ibPK3iA+vaY1eEjESkQkM0BbCqFOaZMiXRTtdB0u7b4djtY6JnsjvPdUHVMg6xQt3B8fpTTWHI9A+ADjM9frzg=="], - "istanbul-reports/html-escaper": ["html-escaper@2.0.2", "", {}, "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg=="], - "js-beautify/glob": ["glob@10.5.0", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg=="], "js-beautify/nopt": ["nopt@7.2.1", "", { "dependencies": { "abbrev": "^2.0.0" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w=="], @@ -6960,18 +6930,12 @@ "@solidjs/start/shiki/@shikijs/types": ["@shikijs/types@1.29.2", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.1", "@types/hast": "^3.0.4" } }, "sha512-VJjK0eIijTZf0QSTODEXCqinjBn0joAHQ+aPSBzrv4O2d/QSbsMw+ZeSRx03kV34Hy7NzUvV/7NqfYGRLrASmw=="], - "@standard-community/standard-json/effect/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - - "@standard-community/standard-openapi/effect/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - "@storybook/csf-plugin/unplugin/acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="], "@storybook/csf-plugin/unplugin/webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="], "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util": ["@tybys/wasm-util@0.10.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg=="], - "@vitest/coverage-v8/@vitest/utils/@vitest/pretty-format": ["@vitest/pretty-format@4.1.8", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA=="], - "@vitest/expect/@vitest/utils/@vitest/pretty-format": ["@vitest/pretty-format@3.2.4", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA=="], "accepts/mime-types/mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], diff --git a/cmd_line b/cmd_line new file mode 100644 index 00000000..c3881a28 --- /dev/null +++ b/cmd_line @@ -0,0 +1 @@ +genhtml install diff --git a/packages/http-recorder/dist/effect.d.ts b/packages/http-recorder/dist/effect.d.ts new file mode 100644 index 00000000..8c719127 --- /dev/null +++ b/packages/http-recorder/dist/effect.d.ts @@ -0,0 +1,10 @@ +import * as Layer from "effect/Layer"; +import type * as HttpClient from "effect/unstable/http/HttpClient"; +import type { RecorderOptions } from "./types.js"; +/** + * Provides a fetch-backed `HttpClient` with cassette recording and replay. + * + * Locally, a missing cassette is recorded from the real service. Existing + * cassettes are replayed, and `CI=true` makes a missing cassette fail. + */ +export declare const http: (name: string, options?: RecorderOptions) => Layer.Layer; diff --git a/packages/http-recorder/dist/index.d.ts b/packages/http-recorder/dist/index.d.ts new file mode 100644 index 00000000..8ce46988 --- /dev/null +++ b/packages/http-recorder/dist/index.d.ts @@ -0,0 +1,17 @@ +/** HTTP and WebSocket cassette recording. */ +export declare const HttpRecorder: { + readonly http: (name: string, options?: import("./types.js").RecorderOptions) => import("effect/Layer").Layer; + readonly socket: (name: string, options?: import("./types.js").RecorderOptions) => import("effect/Layer").Layer; +}; +export declare namespace HttpRecorder { + /** Additional JSON metadata stored with a cassette. */ + type CassetteMetadata = import("./types.js").CassetteMetadata; + /** Recorder configuration. */ + type RecorderOptions = import("./types.js").RecorderOptions; + /** Additive redaction and header-preservation policy. */ + type RedactOptions = import("./types.js").RedactOptions; + /** Returns whether an incoming HTTP request matches a recorded request. */ + type RequestMatcher = import("./types.js").RequestMatcher; + /** The normalized HTTP request representation used for matching. */ + type RequestSnapshot = import("./types.js").RequestSnapshot; +} diff --git a/packages/http-recorder/dist/index.js b/packages/http-recorder/dist/index.js new file mode 100644 index 00000000..0d93da0a --- /dev/null +++ b/packages/http-recorder/dist/index.js @@ -0,0 +1,701 @@ +// src/effect.ts +import { NodeFileSystem as NodeFileSystem2 } from "@effect/platform-node"; +import * as Layer3 from "effect/Layer"; +import { FetchHttpClient as FetchHttpClient2 } from "effect/unstable/http"; + +// src/cassette.ts +import { Context, Effect, FileSystem, Layer, Schema as Schema3, Semaphore } from "effect"; +import * as path from "node:path"; + +// src/redaction.ts +import { Schema } from "effect"; +var REDACTED = "[REDACTED]"; +var DEFAULT_REDACT_HEADERS = [ + "authorization", + "cookie", + "proxy-authorization", + "set-cookie", + "x-api-key", + "x-amz-security-token", + "x-goog-api-key" +]; +var DEFAULT_REDACT_QUERY = [ + "access_token", + "api-key", + "api_key", + "apikey", + "code", + "key", + "signature", + "sig", + "token", + "x-amz-credential", + "x-amz-security-token", + "x-amz-signature" +]; +var SECRET_PATTERNS = [ + { label: "bearer token", pattern: /\bBearer\s+[A-Za-z0-9._~+/=-]{16,}\b/i }, + { label: "API key", pattern: /\bsk-[A-Za-z0-9][A-Za-z0-9_-]{20,}\b/ }, + { label: "Anthropic API key", pattern: /\bsk-ant-[A-Za-z0-9_-]{20,}\b/ }, + { label: "Google API key", pattern: /\bAIza[0-9A-Za-z_-]{20,}\b/ }, + { label: "AWS access key", pattern: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/ }, + { label: "GitHub token", pattern: /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/ }, + { label: "private key", pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ } +]; +var ENV_SECRET_NAMES = /(?:API|AUTH|BEARER|CREDENTIAL|KEY|PASSWORD|SECRET|TOKEN)/i; +var SAFE_ENV_VALUES = new Set(["fixture", "test", "test-key"]); +var envSecrets = () => Object.entries(process.env).flatMap(([name, value]) => { + if (!value) + return []; + if (!ENV_SECRET_NAMES.test(name)) + return []; + if (value.length < 12) + return []; + if (SAFE_ENV_VALUES.has(value.toLowerCase())) + return []; + return [{ name, value }]; +}); +var pathFor = (base, key) => base ? `${base}.${key}` : key; +var stringEntries = (value, base = "") => { + if (typeof value === "string") + return [{ path: base, value }]; + if (Array.isArray(value)) + return value.flatMap((item, index) => stringEntries(item, `${base}[${index}]`)); + if (value && typeof value === "object") { + return Object.entries(value).flatMap(([key, child]) => stringEntries(child, pathFor(base, key))); + } + return []; +}; +var redactionSet = (values, defaults) => new Set([...defaults, ...values ?? []].map((value) => value.toLowerCase())); +var redactUrl = (raw, query = DEFAULT_REDACT_QUERY, urlRedactor) => { + if (!URL.canParse(raw)) + return urlRedactor?.(raw) ?? raw; + const url = new URL(raw); + if (url.username) + url.username = REDACTED; + if (url.password) + url.password = REDACTED; + const redacted = redactionSet(query, DEFAULT_REDACT_QUERY); + for (const key of url.searchParams.keys()) { + if (redacted.has(key.toLowerCase())) + url.searchParams.set(key, REDACTED); + } + return urlRedactor?.(url.toString()) ?? url.toString(); +}; +var redactHeaders = (headers, allow, redact = DEFAULT_REDACT_HEADERS) => { + const allowed = new Set(allow.map((name) => name.toLowerCase())); + const redacted = redactionSet(redact, DEFAULT_REDACT_HEADERS); + return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]).filter(([name]) => allowed.has(name)).map(([name, value]) => [name, redacted.has(name) ? REDACTED : value]).toSorted(([a], [b]) => a.localeCompare(b))); +}; +var SecretFindingSchema = Schema.Struct({ + path: Schema.String, + reason: Schema.String +}); +var secretFindings = (value) => { + const environment = envSecrets(); + return stringEntries(value).flatMap((entry) => [ + ...SECRET_PATTERNS.filter((item) => item.pattern.test(entry.value)).map((item) => ({ + path: entry.path, + reason: item.label + })), + ...environment.filter((item) => entry.value.includes(item.value)).map((item) => ({ path: entry.path, reason: `environment secret ${item.name}` })) + ]); +}; + +// src/schema.ts +import { Schema as Schema2 } from "effect"; +var RequestSnapshotSchema = Schema2.Struct({ + method: Schema2.String, + url: Schema2.String, + headers: Schema2.Record(Schema2.String, Schema2.String), + body: Schema2.String +}); +var ResponseSnapshotSchema = Schema2.Struct({ + status: Schema2.Number, + headers: Schema2.Record(Schema2.String, Schema2.String), + body: Schema2.String, + bodyEncoding: Schema2.optional(Schema2.Literals(["text", "base64"])) +}); +var CassetteMetadataSchema = Schema2.Record(Schema2.String, Schema2.Unknown); +var HttpInteractionSchema = Schema2.Struct({ + transport: Schema2.tag("http"), + request: RequestSnapshotSchema, + response: ResponseSnapshotSchema +}); +var WebSocketEventSchema = Schema2.Union([ + Schema2.Struct({ + direction: Schema2.Literals(["client", "server"]), + kind: Schema2.tag("text"), + body: Schema2.String + }), + Schema2.Struct({ + direction: Schema2.Literals(["client", "server"]), + kind: Schema2.tag("binary"), + body: Schema2.String, + bodyEncoding: Schema2.Literal("base64") + }) +]); +var WebSocketInteractionSchema = Schema2.Struct({ + transport: Schema2.tag("websocket"), + open: Schema2.Struct({ + url: Schema2.String, + headers: Schema2.Record(Schema2.String, Schema2.String) + }), + events: Schema2.Array(WebSocketEventSchema) +}); +var InteractionSchema = Schema2.Union([HttpInteractionSchema, WebSocketInteractionSchema]).pipe(Schema2.toTaggedUnion("transport")); +var isHttpInteraction = InteractionSchema.guards.http; +var isWebSocketInteraction = InteractionSchema.guards.websocket; +var httpInteractions = (interactions) => interactions.filter(isHttpInteraction); +var webSocketInteractions = (interactions) => interactions.filter(isWebSocketInteraction); +var CassetteSchema = Schema2.Struct({ + version: Schema2.Literal(1), + metadata: Schema2.optional(CassetteMetadataSchema), + interactions: Schema2.Array(InteractionSchema) +}); +var decodeCassette = Schema2.decodeUnknownSync(CassetteSchema); +var encodeCassette = Schema2.encodeSync(CassetteSchema); + +// src/cassette.ts +var DEFAULT_RECORDINGS_DIR = path.resolve(process.cwd(), "test", "fixtures", "recordings"); + +class CassetteNotFoundError extends Schema3.TaggedErrorClass()("CassetteNotFoundError", { + cassetteName: Schema3.String +}) { + get message() { + return `Cassette "${this.cassetteName}" not found`; + } +} + +class UnsafeCassetteError extends Schema3.TaggedErrorClass()("UnsafeCassetteError", { + cassetteName: Schema3.String, + findings: Schema3.Array(SecretFindingSchema) +}) { + get message() { + return `Refusing to write cassette "${this.cassetteName}" because it contains possible secrets: ${this.findings.map((finding) => `${finding.path} (${finding.reason})`).join(", ")}`; + } +} + +class Service extends Context.Service()("@opencode-ai/http-recorder/Cassette") { +} +var cassettePath = (directory, name) => { + if (!name || path.isAbsolute(name) || path.win32.isAbsolute(name) || name.split(/[\\/]/).includes("..")) + throw new Error(`Invalid cassette name "${name}"`); + const root = path.resolve(directory); + const target = path.resolve(root, `${name}.json`); + const relative2 = path.relative(root, target); + if (!relative2 || relative2.startsWith("..") || path.isAbsolute(relative2)) + throw new Error(`Invalid cassette name "${name}"`); + return target; +}; +var buildCassette = (name, interactions, metadata) => ({ + version: 1, + metadata: { name, recordedAt: new Date().toISOString(), ...metadata }, + interactions +}); +var formatCassette = (cassette) => `${JSON.stringify(encodeCassette(cassette), null, 2)} +`; +var parseCassette = Schema3.decodeUnknownSync(Schema3.fromJsonString(CassetteSchema)); +var failIfUnsafe = (name, findings) => findings.length === 0 ? Effect.void : Effect.fail(new UnsafeCassetteError({ cassetteName: name, findings })); +var fileSystem = (options = {}) => Layer.effect(Service, Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = options.directory ?? DEFAULT_RECORDINGS_DIR; + const recorded = new Map; + const appendLock = yield* Semaphore.make(1); + const pathFor2 = (name) => cassettePath(directory, name); + const walk = (current) => Effect.gen(function* () { + const entries = yield* fs.readDirectory(current).pipe(Effect.catch(() => Effect.succeed([]))); + const nested = yield* Effect.forEach(entries, (entry) => { + const full = path.join(current, entry); + return fs.stat(full).pipe(Effect.flatMap((stat) => stat.type === "Directory" ? walk(full) : Effect.succeed([full])), Effect.catch(() => Effect.succeed([]))); + }); + return nested.flat(); + }); + return Service.of({ + read: (name) => fs.readFileString(pathFor2(name)).pipe(Effect.map((raw) => parseCassette(raw).interactions), Effect.catch(() => Effect.fail(new CassetteNotFoundError({ cassetteName: name })))), + append: (name, interaction, metadata) => appendLock.withPermit(Effect.gen(function* () { + const entry = recorded.get(name) ?? { interactions: [], findings: [] }; + const interactions = [...entry.interactions, interaction]; + const interactionFindings = [...entry.findings, ...secretFindings(interaction)]; + const cassette = buildCassette(name, interactions, metadata); + const findings = [...interactionFindings, ...secretFindings(cassette.metadata ?? {})]; + yield* failIfUnsafe(name, findings); + const target = pathFor2(name); + yield* fs.makeDirectory(path.dirname(target), { recursive: true }).pipe(Effect.orDie); + const temporary = `${target}.${crypto.randomUUID()}.tmp`; + yield* fs.writeFileString(temporary, formatCassette(cassette)).pipe(Effect.flatMap(() => fs.rename(temporary, target)), Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.catch(() => Effect.void))), Effect.orDie); + recorded.set(name, { interactions, findings: interactionFindings }); + })), + exists: (name) => fs.access(pathFor2(name)).pipe(Effect.as(true), Effect.catch(() => Effect.succeed(false))), + list: () => walk(directory).pipe(Effect.map((files) => files.filter((file) => file.endsWith(".json")).map((file) => path.relative(directory, file).replace(/\\/g, "/").replace(/\.json$/, "")).toSorted((a, b) => a.localeCompare(b)))) + }); +})); + +// src/internal-effect.ts +import { NodeFileSystem } from "@effect/platform-node"; +import { Deferred, Effect as Effect3, Layer as Layer2, Option as Option3, Ref } from "effect"; +import { + FetchHttpClient, + Headers, + HttpBody, + HttpClient, + HttpClientError, + HttpClientRequest, + HttpClientResponse, + UrlParams +} from "effect/unstable/http"; + +// src/matching.ts +import { Option, Schema as Schema4 } from "effect"; +var JsonValue = Schema4.fromJsonString(Schema4.Unknown); +var decodeJson = Schema4.decodeUnknownOption(JsonValue); +var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value); +var canonicalizeJson = (value) => { + if (Array.isArray(value)) + return value.map(canonicalizeJson); + if (isRecord(value)) { + return Object.fromEntries(Object.keys(value).toSorted().map((key) => [key, canonicalizeJson(value[key])])); + } + return value; +}; +var canonicalSnapshot = (snapshot) => JSON.stringify({ + method: snapshot.method, + url: snapshot.url, + headers: canonicalizeJson(snapshot.headers), + body: Option.match(decodeJson(snapshot.body), { + onNone: () => snapshot.body, + onSome: canonicalizeJson + }) +}); +var defaultMatcher = (incoming, recorded) => canonicalSnapshot(incoming) === canonicalSnapshot(recorded); +var safeText = (value) => { + if (value === undefined) + return "undefined"; + if (secretFindings(value).length > 0) + return JSON.stringify(REDACTED); + const text = JSON.stringify(value); + if (!text) + return typeof value; + return text.length > 300 ? `${text.slice(0, 300)}...` : text; +}; +var jsonBody = (body) => Option.getOrUndefined(decodeJson(body)); +var valueDiffs = (expected, received, base = "$", limit = 8) => { + if (Object.is(expected, received)) + return []; + if (isRecord(expected) && isRecord(received)) { + return [...new Set([...Object.keys(expected), ...Object.keys(received)])].toSorted().flatMap((key) => valueDiffs(expected[key], received[key], `${base}.${key}`, limit)).slice(0, limit); + } + if (Array.isArray(expected) && Array.isArray(received)) { + return Array.from({ length: Math.max(expected.length, received.length) }, (_, index) => index).flatMap((index) => valueDiffs(expected[index], received[index], `${base}[${index}]`, limit)).slice(0, limit); + } + return [`${base} expected ${safeText(expected)}, received ${safeText(received)}`]; +}; +var headerDiffs = (expected, received) => [...new Set([...Object.keys(expected), ...Object.keys(received)])].toSorted().flatMap((key) => { + if (expected[key] === received[key]) + return []; + if (expected[key] === undefined) + return [` ${key} unexpected ${safeText(received[key])}`]; + if (received[key] === undefined) + return [` ${key} missing expected ${safeText(expected[key])}`]; + return [` ${key} expected ${safeText(expected[key])}, received ${safeText(received[key])}`]; +}); +var requestDiff = (expected, received) => { + const lines = []; + if (expected.method !== received.method) { + lines.push("method:", ` expected ${expected.method}, received ${received.method}`); + } + if (expected.url !== received.url) { + lines.push("url:", ` expected ${expected.url}`, ` received ${received.url}`); + } + const headers = headerDiffs(expected.headers, received.headers); + if (headers.length > 0) + lines.push("headers:", ...headers.slice(0, 8)); + const expectedBody = jsonBody(expected.body); + const receivedBody = jsonBody(received.body); + const body = expectedBody !== undefined && receivedBody !== undefined ? valueDiffs(expectedBody, receivedBody).map((line) => ` ${line}`) : expected.body === received.body ? [] : [` expected ${safeText(expected.body)}, received ${safeText(received.body)}`]; + if (body.length > 0) + lines.push("body:", ...body); + return lines; +}; +var selectSequential = (interactions, incoming, match, index) => { + const interaction = interactions[index]; + if (!interaction) + return { interaction, detail: `interaction ${index + 1} of ${interactions.length} not recorded` }; + if (!match(incoming, interaction.request)) + return { interaction: undefined, detail: requestDiff(interaction.request, incoming).join(` +`) }; + return { interaction, detail: "" }; +}; + +// src/recorder.ts +import { Effect as Effect2, SynchronizedRef } from "effect"; +var isCI = () => { + const value = process.env.CI; + return value !== undefined && value !== "" && value !== "false" && value !== "0"; +}; +var resolveAutoMode = (cassette, name) => Effect2.gen(function* () { + if (isCI()) + return "replay"; + return (yield* cassette.exists(name)) ? "replay" : "record"; +}); +var makeReplayState = (cassette, name, project) => Effect2.gen(function* () { + const load = yield* Effect2.cached(cassette.read(name).pipe(Effect2.map(project))); + const position = yield* SynchronizedRef.make(0); + yield* Effect2.addFinalizer(() => Effect2.gen(function* () { + const used = yield* SynchronizedRef.get(position); + if (used === 0) + return yield* Effect2.void; + const interactions = yield* load.pipe(Effect2.orDie); + if (used < interactions.length) + return yield* Effect2.die(new Error(`Unused recorded interactions in ${name}: used ${used} of ${interactions.length}`)); + return yield* Effect2.void; + })); + return { + claim: (validate) => Effect2.flatMap(load, (interactions) => SynchronizedRef.modifyEffect(position, (index) => Effect2.gen(function* () { + const interaction = interactions[index]; + yield* validate(interaction, index, interactions); + if (interaction === undefined) + return yield* Effect2.die("Replay validation accepted a missing interaction"); + return [{ interaction, index }, index + 1]; + }))) + }; +}); + +// src/redactor.ts +import { Option as Option2 } from "effect"; +var DEFAULT_REQUEST_HEADERS = ["content-type", "accept", "openai-beta"]; +var DEFAULT_RESPONSE_HEADERS = ["content-type"]; +var identity = (value) => value; +var compose = (...redactors) => { + const requests = redactors.map((r) => r.request).filter((fn) => fn !== undefined); + const responses = redactors.map((r) => r.response).filter((fn) => fn !== undefined); + return { + request: requests.length === 0 ? identity : (snapshot) => requests.reduce((acc, fn) => fn(acc), snapshot), + response: responses.length === 0 ? identity : (snapshot) => responses.reduce((acc, fn) => fn(acc), snapshot) + }; +}; +var requestHeaders = (options = {}) => ({ + request: (snapshot) => ({ + ...snapshot, + headers: redactHeaders(snapshot.headers, options.allow ?? DEFAULT_REQUEST_HEADERS, options.redact) + }) +}); +var responseHeaders = (options = {}) => ({ + response: (snapshot) => ({ + ...snapshot, + headers: redactHeaders(snapshot.headers, options.allow ?? DEFAULT_RESPONSE_HEADERS, options.redact) + }) +}); +var url = (options = {}) => ({ + request: (snapshot) => ({ ...snapshot, url: redactUrl(snapshot.url, options.query, options.transform) }) +}); +var DEFAULT_REDACT_JSON_FIELDS = [ + "access_token", + "api_key", + "apikey", + "client_secret", + "password", + "refresh_token", + "secret", + "token" +]; +var normalizeField = (field) => field.replace(/[^a-z0-9]/gi, "").toLowerCase(); +var redactJsonFields = (value, fields) => { + if (Array.isArray(value)) + return value.map((item) => redactJsonFields(item, fields)); + if (!value || typeof value !== "object") + return value; + return Object.fromEntries(Object.entries(value).map(([key, child]) => [ + key, + fields.has(normalizeField(key)) ? REDACTED : redactJsonFields(child, fields) + ])); +}; +var redactBody = (value, fields, transform) => { + const redacted = Option2.match(decodeJson(value), { + onNone: () => value, + onSome: (parsed) => JSON.stringify(redactJsonFields(parsed, fields)) + }); + return transform?.(redacted) ?? redacted; +}; +var make = (options = {}) => { + const fields = new Set([...DEFAULT_REDACT_JSON_FIELDS, ...options.jsonFields ?? []].map(normalizeField)); + return compose(requestHeaders({ + allow: [...DEFAULT_REQUEST_HEADERS, ...options.allowRequestHeaders ?? [], ...options.headers ?? []], + redact: options.headers + }), responseHeaders({ + allow: [...DEFAULT_RESPONSE_HEADERS, ...options.allowResponseHeaders ?? [], ...options.headers ?? []], + redact: options.headers + }), url({ query: options.queryParameters, transform: options.url }), { + request: (snapshot) => ({ + ...snapshot, + body: redactBody(snapshot.body, fields, options.body) + }), + response: (snapshot) => ({ + ...snapshot, + body: redactBody(snapshot.body, fields, options.body) + }) + }); +}; + +// src/internal-effect.ts +var TEXT_CONTENT_TYPES = new Set([ + "application/graphql", + "application/javascript", + "application/json", + "application/sql", + "application/x-www-form-urlencoded", + "application/xml", + "application/yaml", + "image/svg+xml" +]); +var isTextContentType = (contentType) => { + const mediaType = contentType?.split(";", 1)[0]?.trim().toLowerCase(); + if (!mediaType) + return false; + return mediaType.startsWith("text/") || mediaType.endsWith("+json") || mediaType.endsWith("+xml") || TEXT_CONTENT_TYPES.has(mediaType); +}; +var captureResponseBody = (response, contentType) => response.arrayBuffer.pipe(Effect3.map((bytes) => isTextContentType(contentType) ? { body: new TextDecoder().decode(bytes) } : { body: Buffer.from(bytes).toString("base64"), bodyEncoding: "base64" })); +var decodeResponseBody = (snapshot) => snapshot.bodyEncoding === "base64" ? Buffer.from(snapshot.body, "base64") : snapshot.body; +var responseFromSnapshot = (request, snapshot) => HttpClientResponse.fromWeb(request, new Response(request.method === "HEAD" || snapshot.status === 204 || snapshot.status === 205 || snapshot.status === 304 ? null : decodeResponseBody(snapshot), snapshot)); +var redactedErrorRequest = (request) => HttpClientRequest.makeWith(request.method, redactUrl(request.url), UrlParams.empty, Option3.none(), Headers.empty, HttpBody.empty); +var transportError = (request, description) => new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ request: redactedErrorRequest(request), description }) +}); +var recordingLayer = (name, options = {}) => Layer2.effect(HttpClient.HttpClient, Effect3.gen(function* () { + const upstream = yield* HttpClient.HttpClient; + const cassetteService = yield* Service; + const redactor = options.redactor ?? make(); + const match = options.match ?? defaultMatcher; + const requested = options.mode ?? "auto"; + const mode = requested === "auto" ? yield* resolveAutoMode(cassetteService, name) : requested; + const snapshotRequest = (request) => Effect3.gen(function* () { + const web = yield* HttpClientRequest.toWeb(request).pipe(Effect3.orDie); + return redactor.request({ + method: web.method, + url: web.url, + headers: Object.fromEntries(web.headers.entries()), + body: yield* Effect3.promise(() => web.text()) + }); + }); + if (mode === "passthrough") + return upstream; + if (mode === "record") { + const initial = yield* Deferred.make(); + yield* Deferred.succeed(initial, undefined); + const tail = yield* Ref.make(initial); + return HttpClient.make((request) => Effect3.gen(function* () { + const completed = yield* Deferred.make(); + const previous = yield* Ref.modify(tail, (current) => [current, completed]); + return yield* Effect3.gen(function* () { + const incoming = yield* snapshotRequest(request); + const response = yield* upstream.execute(request); + const captured = yield* captureResponseBody(response, response.headers["content-type"]); + const responseSnapshot = { + status: response.status, + headers: response.headers, + ...captured + }; + const interaction = { + transport: "http", + request: incoming, + response: redactor.response(responseSnapshot) + }; + yield* Deferred.await(previous); + yield* cassetteService.append(name, interaction, options.metadata).pipe(Effect3.catchTag("UnsafeCassetteError", (error) => Effect3.fail(transportError(request, error.message)))); + return responseFromSnapshot(request, responseSnapshot); + }).pipe(Effect3.ensuring(Deferred.succeed(completed, undefined))); + })); + } + const replay = yield* makeReplayState(cassetteService, name, httpInteractions); + return HttpClient.make((request) => Effect3.gen(function* () { + const incoming = yield* snapshotRequest(request); + const claimed = yield* replay.claim((interaction, index, interactions) => { + const result = selectSequential(interactions, incoming, match, index); + if (result.interaction) + return Effect3.void; + return Effect3.fail(transportError(request, `Fixture "${name}" does not match the current request: ${result.detail}.`)); + }).pipe(Effect3.mapError((error) => error._tag === "CassetteNotFoundError" ? transportError(request, `Fixture "${name}" not found. Run locally to record it (CI=true forces replay).`) : error)); + return responseFromSnapshot(request, claimed.interaction.response); + })); +})); + +// src/effect.ts +var http = (name, options = {}) => recordingLayer(name, { + metadata: options.metadata, + redactor: make(options.redact), + match: options.match +}).pipe(Layer3.provide(fileSystem({ directory: options.directory })), Layer3.provide(FetchHttpClient2.layer), Layer3.provide(NodeFileSystem2.layer)); + +// src/socket.ts +import { NodeFileSystem as NodeFileSystem3 } from "@effect/platform-node"; +import { Deferred as Deferred2, Effect as Effect4, Exit, FiberSet, Layer as Layer4, Ref as Ref2, Semaphore as Semaphore2 } from "effect"; +import { Socket } from "effect/unstable/socket"; +var encodeEvent = (direction, message) => typeof message === "string" ? { direction, kind: "text", body: message } : { direction, kind: "binary", body: Buffer.from(message).toString("base64"), bodyEncoding: "base64" }; +var decodeEvent = (event) => event.kind === "text" ? event.body : new Uint8Array(Buffer.from(event.body, "base64")); +var redactEvent = (event, redactor) => { + if (event.kind === "binary") + return event; + const body = event.direction === "client" ? redactor.request({ method: "WEBSOCKET", url: "", headers: {}, body: event.body }).body : redactor.response({ status: 101, headers: {}, body: event.body }).body; + return { ...event, body }; +}; +var comparable = (event, asJson) => { + if (!asJson || event.kind === "binary") + return JSON.stringify(canonicalizeJson(event)); + const decoded = decodeJson(event.body); + return JSON.stringify(canonicalizeJson({ + ...event, + body: decoded._tag === "None" ? event.body : canonicalizeJson(decoded.value) + })); +}; +var assertEvent = (actual, expected, index, asJson) => Effect4.sync(() => { + if (expected && comparable(actual, asJson) === comparable(expected, asJson)) + return; + throw new Error(`WebSocket event ${index + 1}: expected ${safeText(expected)}, received ${safeText(actual)}`); +}); +var runHandler = (handler, value) => Effect4.suspend(() => { + const result = handler(value); + return Effect4.isEffect(result) ? Effect4.asVoid(result) : Effect4.void; +}); +var runReplay = (state, handler, decode, onOpen) => Effect4.scoped(Effect4.gen(function* () { + const handlers = yield* FiberSet.make(); + const run = yield* FiberSet.runtime(handlers)(); + if (onOpen) + yield* onOpen; + const drive = Effect4.gen(function* () { + while (true) { + const current = yield* Ref2.get(state.progress); + const event = state.interaction.events[current.position]; + if (!event) + return; + if (yield* Ref2.get(state.closed)) + return yield* Effect4.die(new Error(`WebSocket closed with unconsumed events: used ${current.position} of ${state.interaction.events.length}`)); + if (event.direction === "server") { + yield* Ref2.set(state.progress, { + position: current.position + 1, + changed: yield* Deferred2.make() + }); + run(runHandler(handler, decode(event))); + continue; + } + yield* Deferred2.await(current.changed); + } + }); + yield* drive.pipe(Effect4.raceFirst(FiberSet.join(handlers))); + yield* FiberSet.awaitEmpty(handlers).pipe(Effect4.raceFirst(FiberSet.join(handlers))); +})); +var openSnapshot = (request, redactor) => { + const snapshot = redactor.request({ method: "GET", url: request.url, headers: request.headers ?? {}, body: "" }); + return { url: snapshot.url, headers: snapshot.headers }; +}; +var makeRecordingSocket = (upstream, cassette, name, request, options, redactor) => Effect4.gen(function* () { + const active = yield* Ref2.make(undefined); + const writeLock = yield* Semaphore2.make(1); + return Socket.make({ + runRaw: (handler, runOptions) => Effect4.gen(function* () { + const state = { + events: [], + eventLock: yield* Semaphore2.make(1), + accepting: yield* Ref2.make(true), + opened: false, + valid: true + }; + const occupied = yield* Ref2.modify(active, (current) => [current !== undefined, current ?? state]); + if (occupied) + return yield* Effect4.die("Concurrent runs of a recorded WebSocket are not supported"); + yield* upstream.runRaw((message) => { + if (!Ref2.getUnsafe(state.accepting)) + throw new Error("WebSocket received a frame after closing"); + state.events.push(redactEvent(encodeEvent("server", message), redactor)); + return handler(message); + }, { + ...runOptions, + onOpen: Effect4.gen(function* () { + state.opened = true; + if (runOptions?.onOpen) + yield* runOptions.onOpen; + }) + }).pipe(Effect4.onExit((exit) => writeLock.withPermit(state.eventLock.withPermit(Effect4.gen(function* () { + yield* Ref2.set(state.accepting, false); + yield* Ref2.set(active, undefined); + if (!Exit.isSuccess(exit) || !state.opened || !state.valid) + return; + yield* cassette.append(name, { + transport: "websocket", + open: openSnapshot(request, redactor), + events: [...state.events] + }, options.metadata).pipe(Effect4.orDie); + }))))); + }), + writer: upstream.writer.pipe(Effect4.map((write) => (message) => writeLock.withPermit(Effect4.gen(function* () { + if (Socket.isCloseEvent(message)) + return yield* write(message); + const state = yield* Ref2.get(active); + if (!state || !(yield* Ref2.get(state.accepting))) + return yield* Effect4.die("WebSocket writer used without an active socket run"); + const event = redactEvent(encodeEvent("client", message), redactor); + yield* state.eventLock.withPermit(Effect4.sync(() => state.events.push(event))); + return yield* write(message).pipe(Effect4.onError(() => Effect4.sync(() => state.valid = false))); + })))) + }); +}); +var makeReplaySocket = (cassette, name, request, options, redactor) => Effect4.gen(function* () { + const replay = yield* makeReplayState(cassette, name, webSocketInteractions); + const active = yield* Ref2.make(undefined); + return Socket.make({ + runRaw: (handler, runOptions) => Effect4.gen(function* () { + const claimed = yield* replay.claim((interaction, index) => Effect4.sync(() => { + const incoming = openSnapshot(request, redactor); + if (interaction && JSON.stringify(canonicalizeJson(incoming)) === JSON.stringify(canonicalizeJson(interaction.open))) + return; + throw new Error(`WebSocket open ${index + 1}: expected ${safeText(interaction?.open)}, received ${safeText(incoming)}`); + })).pipe(Effect4.orDie); + const progress = yield* Ref2.make({ position: 0, changed: yield* Deferred2.make() }); + const writeLock = yield* Semaphore2.make(1); + const state = { + interaction: claimed.interaction, + progress, + writeLock, + closed: yield* Ref2.make(false) + }; + const occupied = yield* Ref2.modify(active, (current) => [current !== undefined, current ?? state]); + if (occupied) + return yield* Effect4.die("Concurrent runs of a replayed WebSocket are not supported"); + yield* runReplay(state, handler, decodeEvent, runOptions?.onOpen).pipe(Effect4.ensuring(Ref2.set(active, undefined))); + }), + writer: Effect4.succeed((message) => { + return Ref2.get(active).pipe(Effect4.flatMap((state) => state ? state.writeLock.withPermit(Effect4.gen(function* () { + const current = yield* Ref2.get(state.progress); + if (Socket.isCloseEvent(message)) { + yield* Ref2.set(state.closed, true); + yield* Deferred2.succeed(current.changed, undefined); + if (current.position === state.interaction.events.length) + return; + return yield* Effect4.die(new Error(`WebSocket closed with unconsumed events: used ${current.position} of ${state.interaction.events.length}`)); + } + const actual = redactEvent(encodeEvent("client", message), redactor); + yield* assertEvent(actual, state.interaction.events[current.position], current.position, options.compareClientMessagesAsJson === true); + yield* Ref2.set(state.progress, { + position: current.position + 1, + changed: yield* Deferred2.make() + }); + yield* Deferred2.succeed(current.changed, undefined); + })) : Effect4.die("WebSocket writer used without an active socket run"))); + }) + }); +}); +var recordingLayer2 = (name, request, options, forcedMode) => Layer4.effect(Socket.Socket, Effect4.gen(function* () { + const upstream = yield* Socket.Socket; + const cassette = yield* Service; + const redactor = make(options.redact); + if ((forcedMode ?? (yield* resolveAutoMode(cassette, name))) === "record") + return yield* makeRecordingSocket(upstream, cassette, name, request, options, redactor); + return yield* makeReplaySocket(cassette, name, request, options, redactor); +})); +var socket = (name, options = {}) => provideCassette(recordingLayer2(name, { url: "" }, { ...options, compareClientMessagesAsJson: true }), options); +var provideCassette = (layer, options) => layer.pipe(Layer4.provide(fileSystem({ directory: options.directory })), Layer4.provide(NodeFileSystem3.layer)); + +// src/index.ts +var HttpRecorder = { http, socket }; +export { + HttpRecorder +}; diff --git a/packages/http-recorder/dist/socket.d.ts b/packages/http-recorder/dist/socket.d.ts new file mode 100644 index 00000000..565a0865 --- /dev/null +++ b/packages/http-recorder/dist/socket.d.ts @@ -0,0 +1,11 @@ +import { Layer } from "effect"; +import { Socket } from "effect/unstable/socket"; +import type { RecorderOptions } from "./types.js"; +/** + * Wraps a provided `Socket.Socket` with cassette recording and replay. + * + * Supply the ordinary URL-bound Effect socket layer beneath this decorator. + * The cassette name identifies the connection; recorder configuration does not + * duplicate the transport URL. + */ +export declare const socket: (name: string, options?: RecorderOptions) => Layer.Layer; diff --git a/packages/http-recorder/dist/types.d.ts b/packages/http-recorder/dist/types.d.ts new file mode 100644 index 00000000..18df4da7 --- /dev/null +++ b/packages/http-recorder/dist/types.d.ts @@ -0,0 +1,43 @@ +/** Additional JSON metadata stored with a cassette. */ +export type CassetteMetadata = Record; +/** The normalized HTTP request representation used for matching. */ +export interface RequestSnapshot { + /** HTTP method. */ + readonly method: string; + /** Fully qualified URL after redaction. */ + readonly url: string; + /** Allowed and redacted request headers. */ + readonly headers: Record; + /** Request body after redaction. */ + readonly body: string; +} +/** Returns whether an incoming HTTP request matches a recorded request. */ +export type RequestMatcher = (incoming: RequestSnapshot, recorded: RequestSnapshot) => boolean; +/** Additive redaction and header-preservation policy. */ +export interface RedactOptions { + /** Additional sensitive headers to retain as `[REDACTED]`. */ + readonly headers?: ReadonlyArray; + /** Additional non-sensitive request headers to preserve for matching. */ + readonly allowRequestHeaders?: ReadonlyArray; + /** Additional non-sensitive response headers to preserve for replay. */ + readonly allowResponseHeaders?: ReadonlyArray; + /** Additional sensitive URL query parameter names. */ + readonly queryParameters?: ReadonlyArray; + /** Additional JSON field names to redact recursively. */ + readonly jsonFields?: ReadonlyArray; + /** Stabilizes a URL after built-in redaction. */ + readonly url?: (url: string) => string; + /** Stabilizes a request, response, or text-frame body after built-in redaction. */ + readonly body?: (body: string) => string; +} +/** Options shared by HTTP recorder layers. */ +export interface RecorderOptions { + /** Cassette directory. Defaults to `/test/fixtures/recordings`. */ + readonly directory?: string; + /** Additional metadata stored in the cassette. */ + readonly metadata?: CassetteMetadata; + /** Additive redaction and header-preservation policy. */ + readonly redact?: RedactOptions; + /** Custom HTTP request equivalence. */ + readonly match?: RequestMatcher; +} diff --git a/packages/tui/src/ui/dialog-export-options.tsx b/packages/tui/src/ui/dialog-export-options.tsx index f80f21a5..5805d112 100644 --- a/packages/tui/src/ui/dialog-export-options.tsx +++ b/packages/tui/src/ui/dialog-export-options.tsx @@ -5,7 +5,7 @@ import { createStore } from "solid-js/store" import { onMount, Show } from "solid-js" import { useTuiConfig } from "../config" import { useBindings } from "../keymap" - +//check export type DialogExportOptionsProps = { defaultFilename: string defaultThinking: boolean diff --git a/packages/tui/src/ui/dialog-scotty.tsx b/packages/tui/src/ui/dialog-scotty.tsx new file mode 100644 index 00000000..e69de29b diff --git a/packages/ui/src/theme/context.test.ts b/packages/ui/src/theme/context.test.ts new file mode 100644 index 00000000..d89455d3 --- /dev/null +++ b/packages/ui/src/theme/context.test.ts @@ -0,0 +1,270 @@ +// import { describe, expect, mock, test } from "bun:test" +// import { createStore } from "solid-js" +// import type { ColorScheme } from "./context" + +import { describe, it, expect, mock, beforeEach } from 'bun:test' + +// --- Types & Constants from context.tsx --- +type ColorScheme = 'light' | 'dark' | 'system' +type SystemMode = 'light' | 'dark' + +interface DesktopTheme { + id: string + name?: string + dark: Record + light: Record +} + +const STORAGE_KEYS = { + THEME_ID: 'opencode-theme-id', + COLOR_SCHEME: 'opencode-color-scheme', + THEME_CSS_LIGHT: 'opencode-theme-css-light', + THEME_CSS_DARK: 'opencode-theme-css-dark', +} as const + +interface Store { + themeId: string + colorScheme: ColorScheme + mode: SystemMode + themes: Record +} + +const clear = mock(() => {}) +const knownThemes = mock(() => new Set(['cyberpunk', 'nord', 'dracula'])) +const getSystemMode = mock((): SystemMode => 'dark') +const load = mock(async (themeId: string): Promise => { + if (themeId === 'corrupted') return undefined + return { + id: themeId, + name: themeId.toUpperCase(), + dark: {}, + light: {}, + } +}) +const cacheThemeVariants = mock((_theme: DesktopTheme, _themeId: string) => {}) + +let store: Store = { + themeId: 'oc-2', + colorScheme: 'system', + mode: 'dark', + themes: { + 'oc-2': { id: 'oc-2', name: 'OC-2', dark: {}, light: {} }, + custom_cached: { id: 'custom_cached', dark: {}, light: {} }, + }, +} + +const setStore = mock((key: keyof Store, value: unknown) => { + store = { ...store, [key]: value } +}) + +const waitFor = async (assertion: () => void, timeout = 1000) => { + const startTime = Date.now() + while (true) { + try { + assertion() + return + } catch (err) { + if (Date.now() - startTime > timeout) throw err + await new Promise((resolve) => setTimeout(resolve, 10)) + } + } +} + +function normalize(id: string | null | undefined): string | null | undefined { + return id === 'oc-1' ? 'oc-2' : id +} + +const handleThemeChange = (rawValue: string) => { + const next = normalize(rawValue) + if (!next) return + + if (next === 'oc-2') { + setStore('themeId', next) + clear() + return + } + + const isKnown = knownThemes().has(next) || Boolean(store.themes[next]) + if (!isKnown) return + + setStore('themeId', next) + + void load(next).then((theme) => { + if (theme && store.themeId === next) { + cacheThemeVariants(theme, next) + } + }) +} + +const handleColorSchemeChange = (rawValue: string) => { + const colorScheme = rawValue as ColorScheme + const mode = colorScheme === 'system' ? getSystemMode() : (colorScheme as 'light' | 'dark') + + setStore('colorScheme', colorScheme) + setStore('mode', mode) +} + +const onStorage = (e: Partial) => { + if (!e.newValue) return + + switch (e.key) { + case STORAGE_KEYS.THEME_ID: + handleThemeChange(e.newValue) + break + case STORAGE_KEYS.COLOR_SCHEME: + handleColorSchemeChange(e.newValue) + break + } +} + +describe('onStorage Event Handler Suite (SolidJS context logic)', () => { + beforeEach(() => { + clear.mockClear() + knownThemes.mockClear() + getSystemMode.mockClear() + load.mockClear() + cacheThemeVariants.mockClear() + setStore.mockClear() + + getSystemMode.mockImplementation((): SystemMode => 'dark') + load.mockImplementation(async (themeId: string): Promise => { + if (themeId === 'corrupted') return undefined + return { id: themeId, dark: {}, light: {} } + }) + + store = { + themeId: 'oc-2', + colorScheme: 'system', + mode: 'dark', + themes: { + 'oc-2': { id: 'oc-2', name: 'OC-2', dark: {}, light: {} }, + custom_cached: { id: 'custom_cached', dark: {}, light: {} }, + }, + } + }) + + describe('onStorage Router', () => { + it('should ignore storage events with null or empty newValue', () => { + onStorage({ key: STORAGE_KEYS.THEME_ID, newValue: null }) + onStorage({ key: STORAGE_KEYS.COLOR_SCHEME, newValue: '' }) + + expect(setStore).not.toHaveBeenCalled() + expect(clear).not.toHaveBeenCalled() + }) + + it('should ignore unrecognized storage keys', () => { + onStorage({ key: 'unrelated-key', newValue: 'nord' }) + + expect(setStore).not.toHaveBeenCalled() + expect(load).not.toHaveBeenCalled() + }) + + it('should route THEME_ID key to handleThemeChange', () => { + onStorage({ key: STORAGE_KEYS.THEME_ID, newValue: 'dracula' }) + + expect(setStore).toHaveBeenCalledWith('themeId', 'dracula') + expect(load).toHaveBeenCalledWith('dracula') + }) + + it('should route COLOR_SCHEME key to handleColorSchemeChange', () => { + onStorage({ key: STORAGE_KEYS.COLOR_SCHEME, newValue: 'light' }) + + expect(setStore).toHaveBeenCalledWith('colorScheme', 'light') + expect(setStore).toHaveBeenCalledWith('mode', 'light') + }) + }) + + describe('handleThemeChange Logic', () => { + it('should normalize legacy "oc-1" input to "oc-2"', () => { + onStorage({ key: STORAGE_KEYS.THEME_ID, newValue: 'oc-1' }) + + expect(setStore).toHaveBeenCalledWith('themeId', 'oc-2') + expect(clear).toHaveBeenCalledTimes(1) + expect(load).not.toHaveBeenCalled() + }) + + it('should handle default "oc-2" theme by invoking clear() and updating themeId', () => { + onStorage({ key: STORAGE_KEYS.THEME_ID, newValue: 'oc-2' }) + + expect(setStore).toHaveBeenCalledWith('themeId', 'oc-2') + expect(clear).toHaveBeenCalledTimes(1) + expect(load).not.toHaveBeenCalled() + }) + + it('should ignore unknown themes not present in knownThemes or store.themes', () => { + onStorage({ key: STORAGE_KEYS.THEME_ID, newValue: 'non-existent-theme' }) + + expect(setStore).not.toHaveBeenCalled() + expect(load).not.toHaveBeenCalled() + }) + + it('should load and cache valid theme from knownThemes', async () => { + onStorage({ key: STORAGE_KEYS.THEME_ID, newValue: 'nord' }) + + expect(setStore).toHaveBeenCalledWith('themeId', 'nord') + expect(load).toHaveBeenCalledWith('nord') + + await waitFor(() => { + expect(cacheThemeVariants).toHaveBeenCalledWith( + { id: 'nord', dark: {}, light: {} }, + 'nord' + ) + }) + }) + + it('should load theme if present in local store.themes', async () => { + onStorage({ key: STORAGE_KEYS.THEME_ID, newValue: 'custom_cached' }) + + expect(setStore).toHaveBeenCalledWith('themeId', 'custom_cached') + expect(load).toHaveBeenCalledWith('custom_cached') + }) + + it('should NOT cache variants if store.themeId changes before load resolves (race condition guard)', async () => { + let resolveLoad: (val: DesktopTheme | undefined) => void = () => {} + load.mockImplementationOnce( + () => new Promise((resolve) => { resolveLoad = resolve }) + ) + + onStorage({ key: STORAGE_KEYS.THEME_ID, newValue: 'nord' }) + expect(store.themeId).toBe('nord') + + // User rapidly switches theme while loading 'nord' + store.themeId = 'dracula' + + resolveLoad({ id: 'nord', dark: {}, light: {} }) + + await waitFor(() => { + expect(cacheThemeVariants).not.toHaveBeenCalled() + }) + }) + + }) + + describe('handleColorSchemeChange Logic', () => { + it('should set colorScheme and mode for explicit "light" mode', () => { + onStorage({ key: STORAGE_KEYS.COLOR_SCHEME, newValue: 'light' }) + + expect(setStore).toHaveBeenCalledWith('colorScheme', 'light') + expect(setStore).toHaveBeenCalledWith('mode', 'light') + expect(getSystemMode).not.toHaveBeenCalled() + }) + + it('should set colorScheme and mode for explicit "dark" mode', () => { + onStorage({ key: STORAGE_KEYS.COLOR_SCHEME, newValue: 'dark' }) + + expect(setStore).toHaveBeenCalledWith('colorScheme', 'dark') + expect(setStore).toHaveBeenCalledWith('mode', 'dark') + expect(getSystemMode).not.toHaveBeenCalled() + }) + + it('should query system mode when colorScheme is set to "system"', () => { + getSystemMode.mockImplementationOnce((): SystemMode => 'dark') + + onStorage({ key: STORAGE_KEYS.COLOR_SCHEME, newValue: 'system' }) + + expect(getSystemMode).toHaveBeenCalledTimes(1) + expect(setStore).toHaveBeenCalledWith('colorScheme', 'system') + expect(setStore).toHaveBeenCalledWith('mode', 'dark') + }) + }) +}) \ No newline at end of file diff --git a/packages/ui/src/theme/context.tsx b/packages/ui/src/theme/context.tsx index f225ee33..39ac0df7 100644 --- a/packages/ui/src/theme/context.tsx +++ b/packages/ui/src/theme/context.tsx @@ -231,27 +231,51 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({ const loadThemes = () => Promise.all(themeIDs().map(load)).then(() => store.themes) - const onStorage = (e: StorageEvent) => { - if (e.key === STORAGE_KEYS.THEME_ID && e.newValue) { - const next = normalize(e.newValue) - if (!next) return - if (next !== "oc-2" && !knownThemes().has(next) && !store.themes[next]) return + //changed section + const handleThemeChange = (rawValue: string) => { + const next = normalize(rawValue) + if (!next) return + + if (next === "oc-2") { setStore("themeId", next) - if (next === "oc-2") { - clear() - return - } - void load(next).then((theme) => { - if (!theme || store.themeId !== next) return - cacheThemeVariants(theme, next) - }) + clear() + return } - if (e.key === STORAGE_KEYS.COLOR_SCHEME && e.newValue) { - setStore("colorScheme", e.newValue as ColorScheme) - setStore("mode", e.newValue === "system" ? getSystemMode() : (e.newValue as "light" | "dark")) + + const isKnown = knownThemes().has(next) || Boolean(store.themes[next]) + if (!isKnown) return + + setStore("themeId", next) + + void load(next).then((theme) => { + if (theme && store.themeId === next) { + cacheThemeVariants(theme, next) + } + }) + } + + const handleColorSchemeChange = (rawValue: string) => { + const colorScheme = rawValue as ColorScheme + const mode = colorScheme === "system" ? getSystemMode() : (colorScheme as "light" | "dark") + + setStore("colorScheme", colorScheme) + setStore("mode", mode) + } + + const onStorage = (e: StorageEvent) => { + if (!e.newValue) return + switch (e.key) { + case STORAGE_KEYS.THEME_ID: + handleThemeChange(e.newValue) + break + case STORAGE_KEYS.COLOR_SCHEME: + handleColorSchemeChange(e.newValue) + break } } + //End of changed section + onMount(() => { makeEventListener(window, "storage", onStorage)