diff --git a/internal/component/cloudflare/worker-src/README.md b/internal/component/cloudflare/worker-src/README.md index a14449eea..7ce068c05 100644 --- a/internal/component/cloudflare/worker-src/README.md +++ b/internal/component/cloudflare/worker-src/README.md @@ -15,7 +15,7 @@ npm ci npm run build ``` -> Important: do not publish this worker (e.g. with `npx wrangler publish`), as it should not use the config in the `wrangler.toml` file! +> Important: do not deploy this worker (e.g. with `npx wrangler deploy`), as it should not use the config in the `wrangler.toml` file! ## Develop locally diff --git a/internal/component/cloudflare/worker-src/package-lock.json b/internal/component/cloudflare/worker-src/package-lock.json index 7d03490d3..5f7e16ee0 100644 --- a/internal/component/cloudflare/worker-src/package-lock.json +++ b/internal/component/cloudflare/worker-src/package-lock.json @@ -1,23 +1,23 @@ { "name": "dapr-cfworkers-client", - "version": "20230216", + "version": "20230517", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "dapr-cfworkers-client", - "version": "20230216", + "version": "20230517", "license": "Apache2", "dependencies": { - "itty-router": "3.0.11", - "jose": "4.12.0" + "itty-router": "3.0.12", + "jose": "4.14.4" }, "devDependencies": { - "@cloudflare/workers-types": "^4.20230215.0", - "esbuild": "^0.17.8", - "prettier": "^2.8.4", - "typescript": "^4.9.5", - "wrangler": "^2.10.0" + "@cloudflare/workers-types": "^4.20230511.0", + "esbuild": "^0.17.19", + "prettier": "^2.8.8", + "typescript": "^5.0.4", + "wrangler": "^3.0.0" } }, "node_modules/@cloudflare/kv-asset-handler": { @@ -29,10 +29,90 @@ "mime": "^3.0.0" } }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20230512.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20230512.0.tgz", + "integrity": "sha512-V80DswMTu0hiVue5BmjlC0cVufXLKk0KbkesbJ0IywHiuGk0f9uEOgwwL91ioOhPu+3Ss/ka5BNxwPXDxKkG3g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20230512.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20230512.0.tgz", + "integrity": "sha512-HojEqgtCW8FCRQq/ENPsBVv1YoxJVp2kDrC27D7xfwOa2+LCmxh55c2cckxZuGTNAsBIqk6lczq4yQx9xcfSdg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20230512.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20230512.0.tgz", + "integrity": "sha512-zhu61wFAyjbO+MtiQjcKDv+HUXYnW3GhGCKW8xKUsCktaXKr/l2Vp/t3VFzF+M8CuFMML5xmE/1gopHB9pIUcA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20230512.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20230512.0.tgz", + "integrity": "sha512-LvW/DFz35ISnkgagE6qra1CyFmak5sPJcOZ01fovtHIQdwtgUrU5Q+mTAoDZy+8yQnVIM8HCXJxe5gKxM9hnxQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20230512.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20230512.0.tgz", + "integrity": "sha512-OgRmn5FjroPSha/2JgcM8AQg5NpTig8TqDXgdM61Y/7DCCCEuOuMsZSqU1IrYkPU7gtOFvZSQZLgFA4XxbePbA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, "node_modules/@cloudflare/workers-types": { - "version": "4.20230215.0", - "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20230215.0.tgz", - "integrity": "sha512-s71gaGwtEIxjSu6l0cekbXm9AwjrmrFVcHPNx9tHidG2dnqamYf5Nms/KgMYZf7gnjdKOp/ZChYFeJJkNv3QfA==", + "version": "4.20230511.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20230511.0.tgz", + "integrity": "sha512-Br4i/8+t60HDJIo8o7O9Rrmp03bhdejRW9klb0bK9EfG5Ii7qz5G3PJO12gUz+Vu9m1v9tZ9KOh3Gg8oshXtug==", "dev": true }, "node_modules/@esbuild-plugins/node-globals-polyfill": { @@ -58,9 +138,9 @@ } }, "node_modules/@esbuild/android-arm": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.8.tgz", - "integrity": "sha512-0/rb91GYKhrtbeglJXOhAv9RuYimgI8h623TplY2X+vA4EXnk3Zj1fXZreJ0J3OJJu1bwmb0W7g+2cT/d8/l/w==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz", + "integrity": "sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==", "cpu": [ "arm" ], @@ -74,9 +154,9 @@ } }, "node_modules/@esbuild/android-arm64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.8.tgz", - "integrity": "sha512-oa/N5j6v1svZQs7EIRPqR8f+Bf8g6HBDjD/xHC02radE/NjKHK7oQmtmLxPs1iVwYyvE+Kolo6lbpfEQ9xnhxQ==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.19.tgz", + "integrity": "sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==", "cpu": [ "arm64" ], @@ -90,9 +170,9 @@ } }, "node_modules/@esbuild/android-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.8.tgz", - "integrity": "sha512-bTliMLqD7pTOoPg4zZkXqCDuzIUguEWLpeqkNfC41ODBHwoUgZ2w5JBeYimv4oP6TDVocoYmEhZrCLQTrH89bg==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.19.tgz", + "integrity": "sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==", "cpu": [ "x64" ], @@ -106,9 +186,9 @@ } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.8.tgz", - "integrity": "sha512-ghAbV3ia2zybEefXRRm7+lx8J/rnupZT0gp9CaGy/3iolEXkJ6LYRq4IpQVI9zR97ID80KJVoUlo3LSeA/sMAg==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.19.tgz", + "integrity": "sha512-80wEoCfF/hFKM6WE1FyBHc9SfUblloAWx6FJkFWTWiCoht9Mc0ARGEM47e67W9rI09YoUxJL68WHfDRYEAvOhg==", "cpu": [ "arm64" ], @@ -122,9 +202,9 @@ } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.8.tgz", - "integrity": "sha512-n5WOpyvZ9TIdv2V1K3/iIkkJeKmUpKaCTdun9buhGRWfH//osmUjlv4Z5mmWdPWind/VGcVxTHtLfLCOohsOXw==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz", + "integrity": "sha512-IJM4JJsLhRYr9xdtLytPLSH9k/oxR3boaUIYiHkAawtwNOXKE8KoU8tMvryogdcT8AU+Bflmh81Xn6Q0vTZbQw==", "cpu": [ "x64" ], @@ -138,9 +218,9 @@ } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.8.tgz", - "integrity": "sha512-a/SATTaOhPIPFWvHZDoZYgxaZRVHn0/LX1fHLGfZ6C13JqFUZ3K6SMD6/HCtwOQ8HnsNaEeokdiDSFLuizqv5A==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.19.tgz", + "integrity": "sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==", "cpu": [ "arm64" ], @@ -154,9 +234,9 @@ } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.8.tgz", - "integrity": "sha512-xpFJb08dfXr5+rZc4E+ooZmayBW6R3q59daCpKZ/cDU96/kvDM+vkYzNeTJCGd8rtO6fHWMq5Rcv/1cY6p6/0Q==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.19.tgz", + "integrity": "sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==", "cpu": [ "x64" ], @@ -170,9 +250,9 @@ } }, "node_modules/@esbuild/linux-arm": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.8.tgz", - "integrity": "sha512-6Ij8gfuGszcEwZpi5jQIJCVIACLS8Tz2chnEBfYjlmMzVsfqBP1iGmHQPp7JSnZg5xxK9tjCc+pJ2WtAmPRFVA==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.19.tgz", + "integrity": "sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==", "cpu": [ "arm" ], @@ -186,9 +266,9 @@ } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.8.tgz", - "integrity": "sha512-v3iwDQuDljLTxpsqQDl3fl/yihjPAyOguxuloON9kFHYwopeJEf1BkDXODzYyXEI19gisEsQlG1bM65YqKSIww==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz", + "integrity": "sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==", "cpu": [ "arm64" ], @@ -202,9 +282,9 @@ } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.8.tgz", - "integrity": "sha512-8svILYKhE5XetuFk/B6raFYIyIqydQi+GngEXJgdPdI7OMKUbSd7uzR02wSY4kb53xBrClLkhH4Xs8P61Q2BaA==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.19.tgz", + "integrity": "sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==", "cpu": [ "ia32" ], @@ -218,9 +298,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.8.tgz", - "integrity": "sha512-B6FyMeRJeV0NpyEOYlm5qtQfxbdlgmiGdD+QsipzKfFky0K5HW5Td6dyK3L3ypu1eY4kOmo7wW0o94SBqlqBSA==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.19.tgz", + "integrity": "sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==", "cpu": [ "loong64" ], @@ -234,9 +314,9 @@ } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.8.tgz", - "integrity": "sha512-CCb67RKahNobjm/eeEqeD/oJfJlrWyw29fgiyB6vcgyq97YAf3gCOuP6qMShYSPXgnlZe/i4a8WFHBw6N8bYAA==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.19.tgz", + "integrity": "sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==", "cpu": [ "mips64el" ], @@ -250,9 +330,9 @@ } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.8.tgz", - "integrity": "sha512-bytLJOi55y55+mGSdgwZ5qBm0K9WOCh0rx+vavVPx+gqLLhxtSFU0XbeYy/dsAAD6xECGEv4IQeFILaSS2auXw==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.19.tgz", + "integrity": "sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==", "cpu": [ "ppc64" ], @@ -266,9 +346,9 @@ } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.8.tgz", - "integrity": "sha512-2YpRyQJmKVBEHSBLa8kBAtbhucaclb6ex4wchfY0Tj3Kg39kpjeJ9vhRU7x4mUpq8ISLXRXH1L0dBYjAeqzZAw==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.19.tgz", + "integrity": "sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==", "cpu": [ "riscv64" ], @@ -282,9 +362,9 @@ } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.8.tgz", - "integrity": "sha512-QgbNY/V3IFXvNf11SS6exkpVcX0LJcob+0RWCgV9OiDAmVElnxciHIisoSix9uzYzScPmS6dJFbZULdSAEkQVw==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.19.tgz", + "integrity": "sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==", "cpu": [ "s390x" ], @@ -298,9 +378,9 @@ } }, "node_modules/@esbuild/linux-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.8.tgz", - "integrity": "sha512-mM/9S0SbAFDBc4OPoyP6SEOo5324LpUxdpeIUUSrSTOfhHU9hEfqRngmKgqILqwx/0DVJBzeNW7HmLEWp9vcOA==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz", + "integrity": "sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==", "cpu": [ "x64" ], @@ -314,9 +394,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.8.tgz", - "integrity": "sha512-eKUYcWaWTaYr9zbj8GertdVtlt1DTS1gNBWov+iQfWuWyuu59YN6gSEJvFzC5ESJ4kMcKR0uqWThKUn5o8We6Q==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.19.tgz", + "integrity": "sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==", "cpu": [ "x64" ], @@ -330,9 +410,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.8.tgz", - "integrity": "sha512-Vc9J4dXOboDyMXKD0eCeW0SIeEzr8K9oTHJU+Ci1mZc5njPfhKAqkRt3B/fUNU7dP+mRyralPu8QUkiaQn7iIg==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.19.tgz", + "integrity": "sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==", "cpu": [ "x64" ], @@ -346,9 +426,9 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.8.tgz", - "integrity": "sha512-0xvOTNuPXI7ft1LYUgiaXtpCEjp90RuBBYovdd2lqAFxje4sEucurg30M1WIm03+3jxByd3mfo+VUmPtRSVuOw==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.19.tgz", + "integrity": "sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==", "cpu": [ "x64" ], @@ -362,9 +442,9 @@ } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.8.tgz", - "integrity": "sha512-G0JQwUI5WdEFEnYNKzklxtBheCPkuDdu1YrtRrjuQv30WsYbkkoixKxLLv8qhJmNI+ATEWquZe/N0d0rpr55Mg==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz", + "integrity": "sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==", "cpu": [ "arm64" ], @@ -378,9 +458,9 @@ } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.8.tgz", - "integrity": "sha512-Fqy63515xl20OHGFykjJsMnoIWS+38fqfg88ClvPXyDbLtgXal2DTlhb1TfTX34qWi3u4I7Cq563QcHpqgLx8w==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.19.tgz", + "integrity": "sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==", "cpu": [ "ia32" ], @@ -394,9 +474,9 @@ } }, "node_modules/@esbuild/win32-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.8.tgz", - "integrity": "sha512-1iuezdyDNngPnz8rLRDO2C/ZZ/emJLb72OsZeqQ6gL6Avko/XCXZw+NuxBSNhBAP13Hie418V7VMt9et1FMvpg==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz", + "integrity": "sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==", "cpu": [ "x64" ], @@ -409,288 +489,27 @@ "node": ">=12" } }, - "node_modules/@iarna/toml": { - "version": "2.2.5", - "resolved": "https://registry.npmjs.org/@iarna/toml/-/toml-2.2.5.tgz", - "integrity": "sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==", - "dev": true - }, - "node_modules/@miniflare/cache": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/cache/-/cache-2.12.0.tgz", - "integrity": "sha512-rAeuCqjevXrNbMimN22Sa70PieiHvjeILHDOBObQ/0GqVNn/cFO6L/v9GYT8R4X5XhHoIuqo6cvZQrxERySDyQ==", + "node_modules/acorn": { + "version": "8.8.2", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", + "integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==", "dev": true, - "dependencies": { - "@miniflare/core": "2.12.0", - "@miniflare/shared": "2.12.0", - "http-cache-semantics": "^4.1.0", - "undici": "5.11.0" + "bin": { + "acorn": "bin/acorn" }, "engines": { - "node": ">=16.13" + "node": ">=0.4.0" } }, - "node_modules/@miniflare/cli-parser": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/cli-parser/-/cli-parser-2.12.0.tgz", - "integrity": "sha512-F+fUhJbAAqlKHfFHRyP/jsbNwP57uAU/IypLg+0i1mEhy1foq6XAVQrldsmHZPvKp/YUHWyMxKcWeDfMY3qnxg==", + "node_modules/acorn-walk": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", + "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", "dev": true, - "dependencies": { - "@miniflare/shared": "2.12.0", - "kleur": "^4.1.4" - }, "engines": { - "node": ">=16.13" + "node": ">=0.4.0" } }, - "node_modules/@miniflare/core": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/core/-/core-2.12.0.tgz", - "integrity": "sha512-TrlmF3lrXhPlkheNiYGFkVTEhZyN/ok7F42+csE7UDPZpm94n4VqbT/85ssAy5rOJRVlyscHMExrrPeB40L34A==", - "dev": true, - "dependencies": { - "@iarna/toml": "^2.2.5", - "@miniflare/queues": "2.12.0", - "@miniflare/shared": "2.12.0", - "@miniflare/watcher": "2.12.0", - "busboy": "^1.6.0", - "dotenv": "^10.0.0", - "kleur": "^4.1.4", - "set-cookie-parser": "^2.4.8", - "undici": "5.11.0", - "urlpattern-polyfill": "^4.0.3" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/d1": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/d1/-/d1-2.12.0.tgz", - "integrity": "sha512-KmaJoXnijuwldplWYnORy3/A2H6XKtrk51HUUe3hg6/JL46L3c7iRrKmruYUC5VtVwWMpvWzGT5uQfpdGQdiHw==", - "dev": true, - "dependencies": { - "@miniflare/core": "2.12.0", - "@miniflare/shared": "2.12.0" - }, - "engines": { - "node": ">=16.7" - } - }, - "node_modules/@miniflare/durable-objects": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/durable-objects/-/durable-objects-2.12.0.tgz", - "integrity": "sha512-tK0teVpYlT6R2rjvUlLoqf/7+3K3/XKzkJnG40Rtn6pNddtIyzGilmc8YHUpw3FFhOLaN+o5bDe01PRjOAQ9vA==", - "dev": true, - "dependencies": { - "@miniflare/core": "2.12.0", - "@miniflare/shared": "2.12.0", - "@miniflare/storage-memory": "2.12.0", - "undici": "5.11.0" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/html-rewriter": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/html-rewriter/-/html-rewriter-2.12.0.tgz", - "integrity": "sha512-aNZUh9uTr6nFg2Pn4sB5swRCBA/Oj66N8kDWZhjy56jpFq9w3XuZKc80GuPXKak9n4yLZB4d+cpEK4aVmn7cFg==", - "dev": true, - "dependencies": { - "@miniflare/core": "2.12.0", - "@miniflare/shared": "2.12.0", - "html-rewriter-wasm": "^0.4.1", - "undici": "5.11.0" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/http-server": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/http-server/-/http-server-2.12.0.tgz", - "integrity": "sha512-OWOssYXgKUYpbzhMD0l5Lq4j0GLNQLXLaraQrhmTK/x1Y4RVPcrlEgShoQ/Adlmc9rU3LEV8uQBXLAfYCQrH3Q==", - "dev": true, - "dependencies": { - "@miniflare/core": "2.12.0", - "@miniflare/shared": "2.12.0", - "@miniflare/web-sockets": "2.12.0", - "kleur": "^4.1.4", - "selfsigned": "^2.0.0", - "undici": "5.11.0", - "ws": "^8.2.2", - "youch": "^2.2.2" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/kv": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/kv/-/kv-2.12.0.tgz", - "integrity": "sha512-7EvlgeOeIDEFcFyimzuErkqhS1sB7MqRur7z07VmzdpEx3Ud15/XNGANSM0jd4Iv8pLPPJAq4ESnoJPS7R6m+Q==", - "dev": true, - "dependencies": { - "@miniflare/shared": "2.12.0" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/queues": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/queues/-/queues-2.12.0.tgz", - "integrity": "sha512-NSR2lSpK4xrrugj3vDaA9181sCydshff/1onAz7ypHOpWMrFebM8BWBeAT7Q1ktkn6633ropqHdOzwjByJj0EQ==", - "dev": true, - "dependencies": { - "@miniflare/shared": "2.12.0" - }, - "engines": { - "node": ">=16.7" - } - }, - "node_modules/@miniflare/r2": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/r2/-/r2-2.12.0.tgz", - "integrity": "sha512-FW9s61B3AOXbKfGNXnDKMVF7Tbx12f7+W/4HJdrqeuu1bgG9oBhCLELZ9UrIPNw3QF5a6Z39pKGu3HnxuH59Mg==", - "dev": true, - "dependencies": { - "@miniflare/shared": "2.12.0", - "undici": "5.11.0" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/runner-vm": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/runner-vm/-/runner-vm-2.12.0.tgz", - "integrity": "sha512-4o0VGR9ih3fp+np1L94W/nxGf2M0gTe/3drZjUmCHvgPsdBcUHqhquT3uEVX3x7HBhCKprU1X5VifMOVRo+Zwg==", - "dev": true, - "dependencies": { - "@miniflare/shared": "2.12.0" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/scheduler": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/scheduler/-/scheduler-2.12.0.tgz", - "integrity": "sha512-mFh+xxwbPHiUGP/8o2Qe63m/4ianMdb0MkPMksTP1gg/xRj0nybv7gj0V/iZ+RrjM0t1mYoA0keT3RjgpKlDEA==", - "dev": true, - "dependencies": { - "@miniflare/core": "2.12.0", - "@miniflare/shared": "2.12.0", - "cron-schedule": "^3.0.4" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/shared": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/shared/-/shared-2.12.0.tgz", - "integrity": "sha512-hxBZv0bhiSuUwEtIBmfnBvH3Zfv4OU0LVtKGc98icGQyI5pocBhMy9bXthZdEybQv7MikVp5HEFV2KRCudg2GA==", - "dev": true, - "dependencies": { - "@types/better-sqlite3": "^7.6.0", - "kleur": "^4.1.4", - "npx-import": "^1.1.4", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/sites": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/sites/-/sites-2.12.0.tgz", - "integrity": "sha512-ueUSfELJPzIWrv75HWpcMc989+LYZgwzglagW/pYC/oMc0fVYOXC6Ro/MUBrR3yUA9i8ySap4NOK3oO9dsSR9Q==", - "dev": true, - "dependencies": { - "@miniflare/kv": "2.12.0", - "@miniflare/shared": "2.12.0", - "@miniflare/storage-file": "2.12.0" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/storage-file": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/storage-file/-/storage-file-2.12.0.tgz", - "integrity": "sha512-KA1Uh02pE82McUr07b1oW4kv6dkE1xjBhjY0L0JzNT7tfm6yUvv1u3Xp0r84x5BC7p/0yqVq2zWE7PC+smbqyQ==", - "dev": true, - "dependencies": { - "@miniflare/shared": "2.12.0", - "@miniflare/storage-memory": "2.12.0" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/storage-memory": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/storage-memory/-/storage-memory-2.12.0.tgz", - "integrity": "sha512-riBoz0p8xKyPUbYy3HUc1mowAMinTxhkdBVorrdqAUucwK4HLGpVL9C1q8e10JZYpHkl/wde4puQId2ajWP+lg==", - "dev": true, - "dependencies": { - "@miniflare/shared": "2.12.0" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/watcher": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/watcher/-/watcher-2.12.0.tgz", - "integrity": "sha512-IH4bENdS2xM+KhlJ/1wAt0FGtOClQ+ortaycIA/FTxaS7v+hu3qha6DlV3/LKM1y3r1IcPK5+fEDrf+RPcEgJA==", - "dev": true, - "dependencies": { - "@miniflare/shared": "2.12.0" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@miniflare/web-sockets": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/@miniflare/web-sockets/-/web-sockets-2.12.0.tgz", - "integrity": "sha512-g8evGvmku5t6BdDDPvhhnpmTJU/iMJhwpMFRdX1j3gzY5aLjpS8E2ISE5hrXZyasygyYqrD0oMoAulI3R9PHog==", - "dev": true, - "dependencies": { - "@miniflare/core": "2.12.0", - "@miniflare/shared": "2.12.0", - "undici": "5.11.0", - "ws": "^8.2.2" - }, - "engines": { - "node": ">=16.13" - } - }, - "node_modules/@types/better-sqlite3": { - "version": "7.6.3", - "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.3.tgz", - "integrity": "sha512-YS64N9SNDT/NAvou3QNdzAu3E2om/W/0dhORimtPGLef+zSK5l1vDzfsWb4xgXOgfhtOI5ZDTRxnvRPb22AIVQ==", - "dev": true, - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/node": { - "version": "18.14.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.14.0.tgz", - "integrity": "sha512-5EWrvLmglK+imbCJY0+INViFWUHg1AHel1sq4ZVSfdcNqGy9Edv3UB9IIzzg+xPaUcAgZYcfVs2fBcwDeZzU0A==", - "dev": true - }, - "node_modules/@types/stack-trace": { - "version": "0.0.29", - "resolved": "https://registry.npmjs.org/@types/stack-trace/-/stack-trace-0.0.29.tgz", - "integrity": "sha512-TgfOX+mGY/NyNxJLIbDWrO9DjGoVSW9+aB8H2yy1fy32jsvxijhmyJI9fDFgvz3YP4lvJaq9DzdR/M1bOgVc9g==", - "dev": true - }, "node_modules/anymatch": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", @@ -704,6 +523,46 @@ "node": ">= 8" } }, + "node_modules/as-table": { + "version": "1.0.55", + "resolved": "https://registry.npmjs.org/as-table/-/as-table-1.0.55.tgz", + "integrity": "sha512-xvsWESUJn0JN421Xb9MQw6AsMHRCUknCe0Wjlxvjud80mU4E6hQf1A6NzQKcYNmYw62MfzEtXc+badstZP3JpQ==", + "dev": true, + "dependencies": { + "printable-characters": "^1.0.42" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/better-sqlite3": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-8.3.0.tgz", + "integrity": "sha512-JTmvBZL/JLTc+3Msbvq6gK6elbU9/wVMqiudplHrVJpr7sVMR9KJrNhZAbW+RhXKlpMcuEhYkdcHa3TXKNXQ1w==", + "dev": true, + "hasInstallScript": true, + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.0" + } + }, "node_modules/binary-extensions": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", @@ -713,6 +572,26 @@ "node": ">=8" } }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "dev": true, + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dev": true, + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, "node_modules/blake3-wasm": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", @@ -731,21 +610,36 @@ "node": ">=8" } }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, - "node_modules/builtins": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/builtins/-/builtins-5.0.1.tgz", - "integrity": "sha512-qwVpFEHNfhYJIzNRBvd2C1kyo6jz3ZSMPyyuR47OPdiKWlbYnZNyDWuyR175qDnAJLiCo5fBBqPb3RiXgWlkOQ==", - "dev": true, - "dependencies": { - "semver": "^7.0.0" - } - }, "node_modules/busboy": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", @@ -758,6 +652,16 @@ "node": ">=10.16.0" } }, + "node_modules/capnp-ts": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/capnp-ts/-/capnp-ts-0.7.0.tgz", + "integrity": "sha512-XKxXAC3HVPv7r674zP0VC3RTXz+/JKhfyw94ljvF80yynK6VkTnqE3jMuN8b3dUVmmc43TjyxjW4KTsmB3c86g==", + "dev": true, + "dependencies": { + "debug": "^4.3.1", + "tslib": "^2.2.0" + } + }, "node_modules/chokidar": { "version": "3.5.3", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", @@ -785,48 +689,90 @@ "fsevents": "~2.3.2" } }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "dev": true + }, "node_modules/cookie": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", - "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==", + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", "dev": true, "engines": { "node": ">= 0.6" } }, - "node_modules/cron-schedule": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/cron-schedule/-/cron-schedule-3.0.6.tgz", - "integrity": "sha512-izfGgKyzzIyLaeb1EtZ3KbglkS6AKp9cv7LxmiyoOu+fXfol1tQDC0Cof0enVZGNtudTHW+3lfuW9ZkLQss4Wg==", + "node_modules/data-uri-to-buffer": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-2.0.2.tgz", + "integrity": "sha512-ND9qDTLc6diwj+Xe5cdAgVTbLVdXbtxTJRXRhli8Mowuaan+0EJOtdqJ0QCHNSSPyoXGx9HX2/VMnKeC34AChA==", "dev": true }, - "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", "dev": true, "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" + "ms": "2.1.2" }, "engines": { - "node": ">= 8" + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "node_modules/dotenv": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-10.0.0.tgz", - "integrity": "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==", + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", "dev": true, + "dependencies": { + "mimic-response": "^3.1.0" + }, "engines": { "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "dev": true, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/detect-libc": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.1.tgz", + "integrity": "sha512-463v3ZeIrcWtdgIg6vI6XUncguvr2TnGl4SzDXinkt9mSLpBJKXT3mW6xT3VQdDN11+WVs29pgvivTc4Lp8v+w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "dev": true, + "dependencies": { + "once": "^1.4.0" } }, "node_modules/esbuild": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.17.8.tgz", - "integrity": "sha512-g24ybC3fWhZddZK6R3uD2iF/RIPnRpwJAqLov6ouX3hMbY4+tKolP0VMF3zuIYCaXun+yHwS5IPQ91N2BT191g==", + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.17.19.tgz", + "integrity": "sha512-XQ0jAPFkK/u3LcVRcvVHQcTIqD6E2H1fvZMA5dQPSOWb3suUbWbfbRf94pjc0bNzRYLfIrDRQXr7X+LHIm5oHw==", "dev": true, "hasInstallScript": true, "bin": { @@ -836,28 +782,28 @@ "node": ">=12" }, "optionalDependencies": { - "@esbuild/android-arm": "0.17.8", - "@esbuild/android-arm64": "0.17.8", - "@esbuild/android-x64": "0.17.8", - "@esbuild/darwin-arm64": "0.17.8", - "@esbuild/darwin-x64": "0.17.8", - "@esbuild/freebsd-arm64": "0.17.8", - "@esbuild/freebsd-x64": "0.17.8", - "@esbuild/linux-arm": "0.17.8", - "@esbuild/linux-arm64": "0.17.8", - "@esbuild/linux-ia32": "0.17.8", - "@esbuild/linux-loong64": "0.17.8", - "@esbuild/linux-mips64el": "0.17.8", - "@esbuild/linux-ppc64": "0.17.8", - "@esbuild/linux-riscv64": "0.17.8", - "@esbuild/linux-s390x": "0.17.8", - "@esbuild/linux-x64": "0.17.8", - "@esbuild/netbsd-x64": "0.17.8", - "@esbuild/openbsd-x64": "0.17.8", - "@esbuild/sunos-x64": "0.17.8", - "@esbuild/win32-arm64": "0.17.8", - "@esbuild/win32-ia32": "0.17.8", - "@esbuild/win32-x64": "0.17.8" + "@esbuild/android-arm": "0.17.19", + "@esbuild/android-arm64": "0.17.19", + "@esbuild/android-x64": "0.17.19", + "@esbuild/darwin-arm64": "0.17.19", + "@esbuild/darwin-x64": "0.17.19", + "@esbuild/freebsd-arm64": "0.17.19", + "@esbuild/freebsd-x64": "0.17.19", + "@esbuild/linux-arm": "0.17.19", + "@esbuild/linux-arm64": "0.17.19", + "@esbuild/linux-ia32": "0.17.19", + "@esbuild/linux-loong64": "0.17.19", + "@esbuild/linux-mips64el": "0.17.19", + "@esbuild/linux-ppc64": "0.17.19", + "@esbuild/linux-riscv64": "0.17.19", + "@esbuild/linux-s390x": "0.17.19", + "@esbuild/linux-x64": "0.17.19", + "@esbuild/netbsd-x64": "0.17.19", + "@esbuild/openbsd-x64": "0.17.19", + "@esbuild/sunos-x64": "0.17.19", + "@esbuild/win32-arm64": "0.17.19", + "@esbuild/win32-ia32": "0.17.19", + "@esbuild/win32-x64": "0.17.19" } }, "node_modules/escape-string-regexp": { @@ -878,29 +824,33 @@ "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", "dev": true }, - "node_modules/execa": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-6.1.0.tgz", - "integrity": "sha512-QVWlX2e50heYJcCPG0iWtf8r0xjEYfz/OYLGDYH+IyjWezzPNxz63qNFOu0l4YftGWuizFVZHHs8PrLU5p2IDA==", + "node_modules/exit-hook": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-2.2.1.tgz", + "integrity": "sha512-eNTPlAD67BmP31LDINZ3U7HSF8l57TxOY2PmBJ1shpCvpnxBF93mWCE8YHBnXs8qiUZJc9WDcWIeC3a2HIAMfw==", "dev": true, - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.1", - "human-signals": "^3.0.1", - "is-stream": "^3.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^5.1.0", - "onetime": "^6.0.0", - "signal-exit": "^3.0.7", - "strip-final-newline": "^3.0.0" - }, "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + "node": ">=6" }, "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" + "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "dev": true + }, "node_modules/fill-range": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", @@ -913,6 +863,12 @@ "node": ">=8" } }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "dev": true + }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", @@ -927,18 +883,31 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, - "node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "node_modules/get-source": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/get-source/-/get-source-2.0.12.tgz", + "integrity": "sha512-X5+4+iD+HoSeEED+uwrQ07BOQr0kEDFMVqqpBuI+RaZBpBpHCuXxo70bjar6f0b0u/DQJsJ7ssurpP0V60Az+w==", + "dev": true, + "dependencies": { + "data-uri-to-buffer": "^2.0.0", + "source-map": "^0.6.1" + } + }, + "node_modules/get-source/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true, "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=0.10.0" } }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "dev": true + }, "node_modules/glob-parent": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", @@ -951,10 +920,10 @@ "node": ">= 6" } }, - "node_modules/html-rewriter-wasm": { + "node_modules/glob-to-regexp": { "version": "0.4.1", - "resolved": "https://registry.npmjs.org/html-rewriter-wasm/-/html-rewriter-wasm-0.4.1.tgz", - "integrity": "sha512-lNovG8CMCCmcVB1Q7xggMSf7tqPCijZXaH4gL6iE8BFghdQCbaY5Met9i1x2Ex8m/cZHDUtXK9H6/znKamRP8Q==", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", "dev": true }, "node_modules/http-cache-semantics": { @@ -963,14 +932,37 @@ "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==", "dev": true }, - "node_modules/human-signals": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-3.0.1.tgz", - "integrity": "sha512-rQLskxnM/5OCldHo+wNXbpVgDn5A17CUoKX+7Sokwaknlq7CdSnphy0W39GU8dw59XiCXmFXDg4fRuckQRKewQ==", + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", "dev": true, - "engines": { - "node": ">=12.20.0" - } + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true }, "node_modules/is-binary-path": { "version": "2.1.0", @@ -1014,33 +1006,15 @@ "node": ">=0.12.0" } }, - "node_modules/is-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", - "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", - "dev": true, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true - }, "node_modules/itty-router": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/itty-router/-/itty-router-3.0.11.tgz", - "integrity": "sha512-vWsoHBi2CmU15YzyUeHjRfjdySL2jqZQKA9jP1LXkBcLJAo0KQNVlQMvhtzG0mzABhVYifeBF97UkrrpuTCWYQ==" + "version": "3.0.12", + "resolved": "https://registry.npmjs.org/itty-router/-/itty-router-3.0.12.tgz", + "integrity": "sha512-s98XTPhle6GGbaFf0kYrOD3Q8gyhnqvOqkwYijC3AmkceNKqWUp13YHg6dWmqmVv4pP7l7c94XI92I0EXVGO0w==" }, "node_modules/jose": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/jose/-/jose-4.12.0.tgz", - "integrity": "sha512-wW1u3cK81b+SFcHjGC8zw87yuyUweEFe0UJirrXEw1NasW00eF7sZjeG3SLBGz001ozxQ46Y9sofDvhBmWFtXQ==", + "version": "4.14.4", + "resolved": "https://registry.npmjs.org/jose/-/jose-4.14.4.tgz", + "integrity": "sha512-j8GhLiKmUAh+dsFXlX1aJCbt5KMibuKb+d7j1JaOJG6s2UjX1PQlW+OKB/sD4a/5ZYF4RcmYmLSndOoU3Lt/3g==", "funding": { "url": "https://github.com/sponsors/panva" } @@ -1075,12 +1049,6 @@ "sourcemap-codec": "^1.4.8" } }, - "node_modules/merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true - }, "node_modules/mime": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", @@ -1093,69 +1061,65 @@ "node": ">=10.0.0" } }, - "node_modules/mimic-fn": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", - "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", "dev": true, "engines": { - "node": ">=12" + "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/miniflare": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-2.12.0.tgz", - "integrity": "sha512-Af90T8nzDkZFNSYnOZB/ne7TjsIIPZ23BAmIks1itDUwDvuFooEbDnuvBgjyksg3WBm6o5QB4y2+Dx8/j8mptg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-3.0.0.tgz", + "integrity": "sha512-CW8yS00pQCbq2o4K8drePzJBkE0heL9cCY/O8DcYJOHd4M0RVutjrp+LqUP4hfzweZ+LqrLo8+Rzy4cORisQoQ==", "dev": true, "dependencies": { - "@miniflare/cache": "2.12.0", - "@miniflare/cli-parser": "2.12.0", - "@miniflare/core": "2.12.0", - "@miniflare/d1": "2.12.0", - "@miniflare/durable-objects": "2.12.0", - "@miniflare/html-rewriter": "2.12.0", - "@miniflare/http-server": "2.12.0", - "@miniflare/kv": "2.12.0", - "@miniflare/queues": "2.12.0", - "@miniflare/r2": "2.12.0", - "@miniflare/runner-vm": "2.12.0", - "@miniflare/scheduler": "2.12.0", - "@miniflare/shared": "2.12.0", - "@miniflare/sites": "2.12.0", - "@miniflare/storage-file": "2.12.0", - "@miniflare/storage-memory": "2.12.0", - "@miniflare/web-sockets": "2.12.0", - "kleur": "^4.1.4", - "semiver": "^1.1.0", - "source-map-support": "^0.5.20", - "undici": "5.11.0" - }, - "bin": { - "miniflare": "bootstrap.js" + "acorn": "^8.8.0", + "acorn-walk": "^8.2.0", + "better-sqlite3": "^8.1.0", + "capnp-ts": "^0.7.0", + "exit-hook": "^2.2.1", + "glob-to-regexp": "^0.4.1", + "http-cache-semantics": "^4.1.0", + "kleur": "^4.1.5", + "source-map-support": "0.5.21", + "stoppable": "^1.1.0", + "undici": "^5.13.0", + "workerd": "^1.20230512.0", + "ws": "^8.11.0", + "youch": "^3.2.2", + "zod": "^3.20.6" }, "engines": { "node": ">=16.13" - }, - "peerDependencies": { - "@miniflare/storage-redis": "2.12.0", - "cron-schedule": "^3.0.4", - "ioredis": "^4.27.9" - }, - "peerDependenciesMeta": { - "@miniflare/storage-redis": { - "optional": true - }, - "cron-schedule": { - "optional": true - }, - "ioredis": { - "optional": true - } } }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "dev": true + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, "node_modules/mustache": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", @@ -1166,10 +1130,16 @@ } }, "node_modules/nanoid": { - "version": "3.3.4", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz", - "integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==", + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz", + "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -1177,6 +1147,24 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/napi-build-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-1.0.2.tgz", + "integrity": "sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg==", + "dev": true + }, + "node_modules/node-abi": { + "version": "3.40.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.40.0.tgz", + "integrity": "sha512-zNy02qivjjRosswoYmPi8hIKJRr8MpQyeKT6qlcq/OnOgA3Rhoae+IYOqsM9V5+JnHWmxKnWOT2GxvtqdtOCXA==", + "dev": true, + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/node-forge": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.1.tgz", @@ -1195,73 +1183,13 @@ "node": ">=0.10.0" } }, - "node_modules/npm-run-path": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.1.0.tgz", - "integrity": "sha512-sJOdmRGrY2sjNTRMbSvluQqg+8X7ZK61yvzBEIDhz4f8z1TZFYABsqjjCBd/0PUNE9M6QDgHJXQkGUEm7Q+l9Q==", + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", "dev": true, "dependencies": { - "path-key": "^4.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/npm-run-path/node_modules/path-key": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", - "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", - "dev": true, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/npx-import": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/npx-import/-/npx-import-1.1.4.tgz", - "integrity": "sha512-3ShymTWOgqGyNlh5lMJAejLuIv3W1K3fbI5Ewc6YErZU3Sp0PqsNs8UIU1O8z5+KVl/Du5ag56Gza9vdorGEoA==", - "dev": true, - "dependencies": { - "execa": "^6.1.0", - "parse-package-name": "^1.0.0", - "semver": "^7.3.7", - "validate-npm-package-name": "^4.0.0" - } - }, - "node_modules/onetime": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", - "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", - "dev": true, - "dependencies": { - "mimic-fn": "^4.0.0" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/parse-package-name": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/parse-package-name/-/parse-package-name-1.0.0.tgz", - "integrity": "sha512-kBeTUtcj+SkyfaW4+KBe0HtsloBJ/mKTPoxpVdA57GZiPerREsUWJOhVj9anXweFiJkm5y8FG1sxFZkZ0SN6wg==", - "dev": true - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "engines": { - "node": ">=8" + "wrappy": "1" } }, "node_modules/path-to-regexp": { @@ -1282,10 +1210,36 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/prebuild-install": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.1.tgz", + "integrity": "sha512-jAXscXWMcCK8GgCoHOfIr0ODh5ai8mj63L2nWrjuAgXE6tDyYGnx4/8o/rCgU+B4JSyZBKbeZqzhtwtC3ovxjw==", + "dev": true, + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^1.0.1", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/prettier": { - "version": "2.8.4", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.4.tgz", - "integrity": "sha512-vIS4Rlc2FNh0BySk3Wkd6xmwxB0FpOndW5fisM5H8hsZSxU2VWVB5CWIkIjWvrHjIhxk2g3bfMKM87zNTrZddw==", + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", "dev": true, "bin": { "prettier": "bin-prettier.js" @@ -1297,6 +1251,51 @@ "url": "https://github.com/prettier/prettier?sponsor=1" } }, + "node_modules/printable-characters": { + "version": "1.0.42", + "resolved": "https://registry.npmjs.org/printable-characters/-/printable-characters-1.0.42.tgz", + "integrity": "sha512-dKp+C4iXWK4vVYZmYSd0KBH5F/h1HoZRsbJ82AVKRO3PEo8L4lBS/vLwhVtpwwuYcoIsVY+1JYKR268yn480uQ==", + "dev": true + }, + "node_modules/pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "dev": true, + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dev": true, + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", @@ -1339,6 +1338,26 @@ "estree-walker": "^0.6.1" } }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, "node_modules/selfsigned": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-2.1.1.tgz", @@ -1351,19 +1370,10 @@ "node": ">=10" } }, - "node_modules/semiver": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/semiver/-/semiver-1.1.0.tgz", - "integrity": "sha512-QNI2ChmuioGC1/xjyYwyZYADILWyW6AmS1UH6gDj/SFUUUS4MBAWs/7mxnkRPc/F4iHezDP+O8t0dO8WHiEOdg==", - "dev": true, - "engines": { - "node": ">=6" - } - }, "node_modules/semver": { - "version": "7.3.8", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", - "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", + "version": "7.5.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.1.tgz", + "integrity": "sha512-Wvss5ivl8TMRZXXESstBA4uR5iXgEN/VC5/sOcuXdVLzcdkz4HWetIoRfG5gb5X+ij/G9rw9YoGn3QoQ8OCSpw==", "dev": true, "dependencies": { "lru-cache": "^6.0.0" @@ -1375,39 +1385,51 @@ "node": ">=10" } }, - "node_modules/set-cookie-parser": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.5.1.tgz", - "integrity": "sha512-1jeBGaKNGdEq4FgIrORu/N570dwoPYio8lSoYLWmX7sQ//0JY08Xh9o5pBcgmHQ/MbsYp/aZnOe1s1lIsbLprQ==", - "dev": true - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" } }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true - }, "node_modules/source-map": { "version": "0.7.4", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.4.tgz", @@ -1443,13 +1465,24 @@ "deprecated": "Please use @jridgewell/sourcemap-codec instead", "dev": true }, - "node_modules/stack-trace": { - "version": "0.0.10", - "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", - "integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==", + "node_modules/stacktracey": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/stacktracey/-/stacktracey-2.1.8.tgz", + "integrity": "sha512-Kpij9riA+UNg7TnphqjH7/CzctQ/owJGNbFkfEeve4Z4uxT5+JapVLFXcsurIfN34gnTWZNJ/f7NMG0E8JDzTw==", + "dev": true, + "dependencies": { + "as-table": "^1.0.36", + "get-source": "^2.0.12" + } + }, + "node_modules/stoppable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stoppable/-/stoppable-1.1.0.tgz", + "integrity": "sha512-KXDYZ9dszj6bzvnEMRYvxgeTHU74QBFL54XKtP3nyMuJ81CFYtABZ3bAzL2EdFUaEwJOBOgENyFj3R7oTzDyyw==", "dev": true, "engines": { - "node": "*" + "node": ">=4", + "npm": ">=6" } }, "node_modules/streamsearch": { @@ -1461,16 +1494,50 @@ "node": ">=10.0.0" } }, - "node_modules/strip-final-newline": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", - "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", "dev": true, "engines": { - "node": ">=12" + "node": ">=0.10.0" + } + }, + "node_modules/tar-fs": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", + "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", + "dev": true, + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "dev": true, + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "engines": { + "node": ">=6" } }, "node_modules/to-regex-range": { @@ -1485,80 +1552,88 @@ "node": ">=8.0" } }, + "node_modules/tslib": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.1.tgz", + "integrity": "sha512-KaI6gPil5m9vF7DKaoXxx1ia9fxS4qG5YveErRRVknPDXXriu5M8h48YRjB6h5ZUOKuAKlSJYb0GaDe8I39fRw==", + "dev": true + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "dev": true, + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, "node_modules/typescript": { - "version": "4.9.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", - "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.0.4.tgz", + "integrity": "sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==", "dev": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }, "engines": { - "node": ">=4.2.0" + "node": ">=12.20" } }, "node_modules/undici": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-5.11.0.tgz", - "integrity": "sha512-oWjWJHzFet0Ow4YZBkyiJwiK5vWqEYoH7BINzJAJOLedZ++JpAlCbUktW2GQ2DS2FpKmxD/JMtWUUWl1BtghGw==", + "version": "5.22.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.22.1.tgz", + "integrity": "sha512-Ji2IJhFXZY0x/0tVBXeQwgPlLWw13GVzpsWPQ3rV50IFMMof2I55PZZxtm4P6iNq+L5znYN9nSTAq0ZyE6lSJw==", "dev": true, "dependencies": { "busboy": "^1.6.0" }, "engines": { - "node": ">=12.18" + "node": ">=14.0" } }, - "node_modules/urlpattern-polyfill": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/urlpattern-polyfill/-/urlpattern-polyfill-4.0.3.tgz", - "integrity": "sha512-DOE84vZT2fEcl9gqCUTcnAw5ZY5Id55ikUcziSUntuEFL3pRvavg5kwDmTEUJkeCHInTlV/HexFomgYnzO5kdQ==", + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "dev": true }, - "node_modules/validate-npm-package-name": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-4.0.0.tgz", - "integrity": "sha512-mzR0L8ZDktZjpX4OB46KT+56MAhl4EIazWP/+G/HPGuvfdaqg4YsCdtOm6U9+LOFyYDoh4dpnpxZRB9MQQns5Q==", + "node_modules/workerd": { + "version": "1.20230512.0", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20230512.0.tgz", + "integrity": "sha512-rueIsVxLTVlqWyaSVHlDKFZRLkDAMmUhxiKXE+guMR3fauwPPsuzs/VKWUqX2sqR2UKF+1JxrUtH9OvaIqoHhA==", "dev": true, - "dependencies": { - "builtins": "^5.0.0" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "dependencies": { - "isexe": "^2.0.0" - }, + "hasInstallScript": true, "bin": { - "node-which": "bin/node-which" + "workerd": "bin/workerd" }, "engines": { - "node": ">= 8" + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20230512.0", + "@cloudflare/workerd-darwin-arm64": "1.20230512.0", + "@cloudflare/workerd-linux-64": "1.20230512.0", + "@cloudflare/workerd-linux-arm64": "1.20230512.0", + "@cloudflare/workerd-windows-64": "1.20230512.0" } }, "node_modules/wrangler": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-2.10.0.tgz", - "integrity": "sha512-h/N7IN5R7P2xWMdUgLbgoWbfrTRVp2wXzT5HTXVg0DPufDY7X3Vf3xX2RW7pt+JTvbUdpOSD0dVyRR4Fxluzog==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-3.0.0.tgz", + "integrity": "sha512-azppXJjEQeaVg3wxFZJOGDGtpR8e9clHr2aHuanGHOk9vX3gvesCv97BF/n8qh1Y1d7vDKOBdfQW3UOYZNFGNw==", "dev": true, "dependencies": { "@cloudflare/kv-asset-handler": "^0.2.0", "@esbuild-plugins/node-globals-polyfill": "^0.1.1", "@esbuild-plugins/node-modules-polyfill": "^0.1.4", - "@miniflare/core": "2.12.0", - "@miniflare/d1": "2.12.0", - "@miniflare/durable-objects": "2.12.0", "blake3-wasm": "^2.1.5", "chokidar": "^3.5.3", "esbuild": "0.16.3", - "miniflare": "2.12.0", + "miniflare": "^3.0.0", "nanoid": "^3.3.3", "path-to-regexp": "^6.2.0", "selfsigned": "^2.0.1", @@ -1965,10 +2040,16 @@ "@esbuild/win32-x64": "0.16.3" } }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, "node_modules/ws": { - "version": "8.12.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.12.1.tgz", - "integrity": "sha512-1qo+M9Ba+xNhPB+YTWUlK6M17brTut5EXbcBaMRN5pH5dFrXz7lzz1ChFSUq3bOUl8yEvSenhHmYUNJxFzdJew==", + "version": "8.13.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", + "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", "dev": true, "engines": { "node": ">=10.0.0" @@ -1999,15 +2080,23 @@ "dev": true }, "node_modules/youch": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/youch/-/youch-2.2.2.tgz", - "integrity": "sha512-/FaCeG3GkuJwaMR34GHVg0l8jCbafZLHiFowSjqLlqhC6OMyf2tPJBu8UirF7/NI9X/R5ai4QfEKUCOxMAGxZQ==", + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/youch/-/youch-3.2.3.tgz", + "integrity": "sha512-ZBcWz/uzZaQVdCvfV4uk616Bbpf2ee+F/AvuKDR5EwX/Y4v06xWdtMluqTD7+KlZdM93lLm9gMZYo0sKBS0pgw==", "dev": true, "dependencies": { - "@types/stack-trace": "0.0.29", - "cookie": "^0.4.1", + "cookie": "^0.5.0", "mustache": "^4.2.0", - "stack-trace": "0.0.10" + "stacktracey": "^2.1.8" + } + }, + "node_modules/zod": { + "version": "3.21.4", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.21.4.tgz", + "integrity": "sha512-m46AKbrzKVzOzs/DZgVnG5H55N1sv1M8qZU3A8RIKbs3mrACDNeIOeilDymVb2HdmP8uwshOCF4uJ8uM9rCqJw==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" } } } diff --git a/internal/component/cloudflare/worker-src/package.json b/internal/component/cloudflare/worker-src/package.json index 098a431b6..5fd60ff76 100644 --- a/internal/component/cloudflare/worker-src/package.json +++ b/internal/component/cloudflare/worker-src/package.json @@ -2,24 +2,24 @@ "private": true, "name": "dapr-cfworkers-client", "description": "Client code for Dapr to interact with Cloudflare Workers", - "version": "20230216", + "version": "20230517", "main": "worker.ts", "scripts": { "build": "esbuild --bundle --minify --outfile=../workers/code/worker.js --format=esm --platform=browser --sourcemap worker.ts", - "start": "wrangler dev --local", + "start": "wrangler dev", "format": "prettier --write ." }, "author": "Dapr authors", "license": "Apache2", "devDependencies": { - "@cloudflare/workers-types": "^4.20230215.0", - "esbuild": "^0.17.8", - "prettier": "^2.8.4", - "typescript": "^4.9.5", - "wrangler": "^2.10.0" + "@cloudflare/workers-types": "^4.20230511.0", + "esbuild": "^0.17.19", + "prettier": "^2.8.8", + "typescript": "^5.0.4", + "wrangler": "^3.0.0" }, "dependencies": { - "itty-router": "3.0.11", - "jose": "4.12.0" + "itty-router": "3.0.12", + "jose": "4.14.4" } } diff --git a/internal/component/cloudflare/workers/code/worker.js b/internal/component/cloudflare/workers/code/worker.js index dae34c8ca..b55174002 100644 --- a/internal/component/cloudflare/workers/code/worker.js +++ b/internal/component/cloudflare/workers/code/worker.js @@ -1,2 +1,2 @@ -var se=({base:e="",routes:t=[]}={})=>({__proto__:new Proxy({},{get:(r,n,o)=>(a,...s)=>t.push([n.toUpperCase(),RegExp(`^${(e+a).replace(/(\/?)\*/g,"($1.*)?").replace(/(\/$)|((?<=\/)\/)/,"").replace(/(:(\w+)\+)/,"(?<$2>.*)").replace(/:(\w+)(\?)?(\.)?/g,"$2(?<$1>[^/]+)$2$3").replace(/\.(?=[\w(])/,"\\.").replace(/\)\.\?\(([^\[]+)\[\^/g,"?)\\.?($1(?<=\\.)[^\\.")}/*$`),s])&&o}),routes:t,async handle(r,...n){let o,a,s=new URL(r.url),c=r.query={};for(let[i,l]of s.searchParams)c[i]=c[i]===void 0?l:[c[i],l].flat();for(let[i,l,h]of t)if((i===r.method||i==="ALL")&&(a=s.pathname.match(l))){r.params=a.groups||{};for(let m of h)if((o=await m(r.proxy||r,...n))!==void 0)return o}}});var u=crypto,S=e=>e instanceof CryptoKey;var E=new TextEncoder,w=new TextDecoder,gt=2**32;function H(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;return e.forEach(o=>{r.set(o,n),n+=o.length}),r}var ce=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n{let t=e;t instanceof Uint8Array&&(t=w.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ce(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};var v=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},g=class extends v{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n}},I=class extends v{static get code(){return"ERR_JWT_EXPIRED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n}},T=class extends v{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},d=class extends v{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var p=class extends v{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},K=class extends v{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};var D=class extends v{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};var B=u.getRandomValues.bind(u);function x(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function _(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function O(e,t){return e.name===t}function Y(e){return parseInt(e.name.slice(4),10)}function Ke(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function xe(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function pe(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!O(e.algorithm,"HMAC"))throw _("HMAC");let n=parseInt(t.slice(2),10);if(Y(e.algorithm.hash)!==n)throw _(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!O(e.algorithm,"RSASSA-PKCS1-v1_5"))throw _("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Y(e.algorithm.hash)!==n)throw _(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!O(e.algorithm,"RSA-PSS"))throw _("RSA-PSS");let n=parseInt(t.slice(2),10);if(Y(e.algorithm.hash)!==n)throw _(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448"){if(x()){if(O(e.algorithm,"NODE-ED25519"))break;throw _("Ed25519, Ed448, or NODE-ED25519")}throw _("Ed25519 or Ed448")}break}case"ES256":case"ES384":case"ES512":{if(!O(e.algorithm,"ECDSA"))throw _("ECDSA");let n=Ke(t);if(e.algorithm.namedCurve!==n)throw _(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}xe(e,r)}function ue(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var A=(e,...t)=>ue("Key must be ",e,...t);function Q(e,t,...r){return ue(`Key for the ${e} algorithm must be `,t,...r)}var Z=e=>S(e),f=["CryptoKey"];var Je=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return!1;r.add(a)}}return!0},J=Je;function Re(e){return typeof e=="object"&&e!==null}function y(e){if(!Re(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var L=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var W=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((a,s)=>a===t[s])||W(e,t,n+1)},le=e=>{switch(!0){case W(e,[42,134,72,206,61,3,1,7]):return"P-256";case W(e,[43,129,4,0,34]):return"P-384";case W(e,[43,129,4,0,35]):return"P-521";case W(e,[43,101,110]):return"X25519";case W(e,[43,101,111]):return"X448";case W(e,[43,101,112]):return"Ed25519";case W(e,[43,101,113]):return"Ed448";default:throw new d("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Me=async(e,t,r,n,o)=>{var a,s;let c,i,l=new Uint8Array(atob(r.replace(e,"")).split("").map(m=>m.charCodeAt(0))),h=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":c={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},i=h?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":c={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},i=h?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":c={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},i=h?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":c={name:"ECDSA",namedCurve:"P-256"},i=h?["verify"]:["sign"];break;case"ES384":c={name:"ECDSA",namedCurve:"P-384"},i=h?["verify"]:["sign"];break;case"ES512":c={name:"ECDSA",namedCurve:"P-521"},i=h?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let m=le(l);c=m.startsWith("P-")?{name:"ECDH",namedCurve:m}:{name:m},i=h?[]:["deriveBits"];break}case"EdDSA":c={name:le(l)},i=h?["verify"]:["sign"];break;default:throw new d('Invalid or unsupported "alg" (Algorithm) value')}try{return await u.subtle.importKey(t,l,c,(a=o?.extractable)!==null&&a!==void 0?a:!1,i)}catch(m){if(c.name==="Ed25519"&&m?.name==="NotSupportedError"&&x())return c={name:"NODE-ED25519",namedCurve:"NODE-ED25519"},await u.subtle.importKey(t,l,c,(s=o?.extractable)!==null&&s!==void 0?s:!1,i);throw m}};var me=(e,t,r)=>Me(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);async function j(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return me(e,t,r)}var ke=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Z(t))throw new TypeError(Q(e,t,...f,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${f.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Ne=(e,t,r)=>{if(!Z(t))throw new TypeError(Q(e,t,...f));if(t.type==="secret")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},Be=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?ke(e,t):Ne(e,t,r)},M=Be;function Xe(e,t,r,n,o){if(o.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let s of n.crit){if(!a.has(s))throw new d(`Extension Header Parameter "${s}" is not recognized`);if(o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(a.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}var R=Xe;var qe=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},te=qe;var Ze=Symbol();function $(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return x()&&t.name==="NODE-ED25519"?{name:"NODE-ED25519",namedCurve:"NODE-ED25519"}:{name:t.name};default:throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function G(e,t,r){if(S(t))return pe(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(A(t,...f));return u.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(A(t,...f,"Uint8Array"))}var je=async(e,t,r,n)=>{let o=await G(e,t,"verify");L(e,o);let a=$(e,o.algorithm);try{return await u.subtle.verify(a,o,r,n)}catch{return!1}},Ee=je;async function V(e,t,r){var n;if(!y(e))throw new p("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new p('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new p("JWS Protected Header incorrect type");if(e.payload===void 0)throw new p("JWS Payload missing");if(typeof e.signature!="string")throw new p("JWS Signature missing or incorrect type");if(e.header!==void 0&&!y(e.header))throw new p("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{let ie=b(e.protected);o=JSON.parse(w.decode(ie))}catch{throw new p("JWS Protected Header is invalid")}if(!J(o,e.header))throw new p("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let a={...o,...e.header},s=R(p,new Map([["b64",!0]]),r?.crit,o,a),c=!0;if(s.has("b64")&&(c=o.b64,typeof c!="boolean"))throw new p('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=a;if(typeof i!="string"||!i)throw new p('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=r&&te("algorithms",r.algorithms);if(l&&!l.has(i))throw new T('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof e.payload!="string")throw new p("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new p("JWS Payload must be a string or an Uint8Array instance");let h=!1;typeof t=="function"&&(t=await t(o,e),h=!0),M(i,t,"verify");let m=H(E.encode((n=e.protected)!==null&&n!==void 0?n:""),E.encode("."),typeof e.payload=="string"?E.encode(e.payload):e.payload),q=b(e.signature);if(!await Ee(i,t,q,m))throw new D;let k;c?k=b(e.payload):typeof e.payload=="string"?k=E.encode(e.payload):k=e.payload;let N={payload:k};return e.protected!==void 0&&(N.protectedHeader=o),e.header!==void 0&&(N.unprotectedHeader=e.header),h?{...N,key:t}:N}async function re(e,t,r){if(e instanceof Uint8Array&&(e=w.decode(e)),typeof e!="string")throw new p("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:a,length:s}=e.split(".");if(s!==3)throw new p("Invalid Compact JWS");let c=await V({payload:o,protected:n,signature:a},t,r),i={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t=="function"?{...i,key:c.key}:i}var ne=e=>Math.floor(e.getTime()/1e3);var et=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,z=e=>{let t=et.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var ge=e=>e.toLowerCase().replace(/^application\//,""),tt=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,F=(e,t,r={})=>{let{typ:n}=r;if(n&&(typeof e.typ!="string"||ge(e.typ)!==ge(n)))throw new g('unexpected "typ" JWT header value',"typ","check_failed");let o;try{o=JSON.parse(w.decode(t))}catch{}if(!y(o))throw new K("JWT Claims Set must be a top-level JSON object");let{issuer:a}=r;if(a&&!(Array.isArray(a)?a:[a]).includes(o.iss))throw new g('unexpected "iss" claim value',"iss","check_failed");let{subject:s}=r;if(s&&o.sub!==s)throw new g('unexpected "sub" claim value',"sub","check_failed");let{audience:c}=r;if(c&&!tt(o.aud,typeof c=="string"?[c]:c))throw new g('unexpected "aud" claim value',"aud","check_failed");let i;switch(typeof r.clockTolerance){case"string":i=z(r.clockTolerance);break;case"number":i=r.clockTolerance;break;case"undefined":i=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:l}=r,h=ne(l||new Date);if((o.iat!==void 0||r.maxTokenAge)&&typeof o.iat!="number")throw new g('"iat" claim must be a number',"iat","invalid");if(o.nbf!==void 0){if(typeof o.nbf!="number")throw new g('"nbf" claim must be a number',"nbf","invalid");if(o.nbf>h+i)throw new g('"nbf" claim timestamp check failed',"nbf","check_failed")}if(o.exp!==void 0){if(typeof o.exp!="number")throw new g('"exp" claim must be a number',"exp","invalid");if(o.exp<=h-i)throw new I('"exp" claim timestamp check failed',"exp","check_failed")}if(r.maxTokenAge){let m=h-o.iat,q=typeof r.maxTokenAge=="number"?r.maxTokenAge:z(r.maxTokenAge);if(m-i>q)throw new I('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(m<0-i)throw new g('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return o};async function oe(e,t,r){var n;let o=await re(e,t,r);if(!((n=o.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&o.protectedHeader.b64===!1)throw new K("JWTs MUST NOT use unencoded payload");let s={payload:F(o.protectedHeader,o.payload,r),protectedHeader:o.protectedHeader};return typeof t=="function"?{...s,key:o.key}:s}var dt=/^(?:Bearer )?([A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+)/i;async function X(e,t){if(t.SKIP_AUTH==="true")return!0;let r=dt.exec(e.headers.get("authorization")||"");if(!r||!r[1])return!1;let n=await j(t.PUBLIC_KEY,"EdDSA");try{await oe(r[1],n,{issuer:"dapr.io/cloudflare",audience:t.TOKEN_AUDIENCE,algorithms:["EdDSA"],clockTolerance:300})}catch(o){return console.error("Failed to validate JWT: "+o),!1}return!0}var be="20230216";var ut=se().get("/.well-known/dapr/info",async(e,t)=>{if(!await X(e,t))return new Response("Unauthorized",{status:401});let n=[],o=[],a=[],s=Object.keys(t);for(let i=0;i{let{namespace:r,key:n,errorRes:o}=await ae(e,t);if(o)return o;let a=await r.get(n,"stream");return a?new Response(a,{status:200}):new Response("",{status:404})}).post("/kv/:namespace/:key",async(e,t)=>{let{namespace:r,key:n,errorRes:o}=await ae(e,t);if(o)return o;let a,s=new URL(e.url),c=parseInt(s.searchParams.get("ttl")||"",10);return c>0&&(a=c),await r.put(n,e.body,{expirationTtl:a}),new Response("",{status:201})}).delete("/kv/:namespace/:key",async(e,t)=>{let{namespace:r,key:n,errorRes:o}=await ae(e,t);return o||(await r.delete(n),new Response("",{status:204}))}).post("/queues/:queue",async(e,t)=>{let{queue:r,errorRes:n}=await ft(e,t);if(n)return n;let o=await e.text();return await r.send(o),new Response("",{status:201})}).all("*",()=>new Response("Not found",{status:404}));async function ae(e,t){if(!e?.text||!e.params?.namespace||!e.params?.key)return{errorRes:new Response("Bad request",{status:400})};let r=t[e.params.namespace];return typeof r!="object"||!["KVNamespace","KvNamespace"].includes(r?.constructor?.name)?{errorRes:new Response(`Worker is not bound to KV '${e.params.kv}'`,{status:412})}:await X(e,t)?{namespace:r,key:e.params.key}:{errorRes:new Response("Unauthorized",{status:401})}}async function ft(e,t){if(!e?.text||!e.params?.queue)return{errorRes:new Response("Bad request",{status:400})};let r=t[e.params.queue];return typeof r!="object"||!["WorkerQueue","Queue"].includes(r?.constructor?.name)?{errorRes:new Response(`Worker is not bound to queue '${e.params.queue}'`,{status:412})}:await X(e,t)?{queue:r}:{errorRes:new Response("Unauthorized",{status:401})}}var Uc={fetch:ut.handle};export{Uc as default}; +var se=({base:e="",routes:t=[]}={})=>({__proto__:new Proxy({},{get:(r,n,o)=>(i,...a)=>t.push([n.toUpperCase(),RegExp(`^${(e+i).replace(/(\/?)\*/g,"($1.*)?").replace(/(\/$)|((?<=\/)\/)/,"").replace(/(:(\w+)\+)/,"(?<$2>.*)").replace(/:(\w+)(\?)?(\.)?/g,"$2(?<$1>[^/]+)$2$3").replace(/\.(?=[\w(])/,"\\.").replace(/\)\.\?\(([^\[]+)\[\^/g,"?)\\.?($1(?<=\\.)[^\\.")}/*$`),a])&&o}),routes:t,async handle(r,...n){let o,i,a=new URL(r.url),c=r.query={};for(let[s,d]of a.searchParams)c[s]=c[s]===void 0?d:[c[s],d].flat();for(let[s,d,m]of t)if((s===r.method||s==="ALL")&&(i=a.pathname.match(d))){r.params=i.groups||{};for(let I of m)if((o=await I(r.proxy||r,...n))!==void 0)return o}}});var f=crypto,g=e=>e instanceof CryptoKey;var E=new TextEncoder,y=new TextDecoder,yt=2**32;function H(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;return e.forEach(o=>{r.set(o,n),n+=o.length}),r}var ce=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n{let t=e;t instanceof Uint8Array&&(t=y.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ce(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};var b=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},w=class extends b{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n}},U=class extends b{static get code(){return"ERR_JWT_EXPIRED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n}},D=class extends b{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},p=class extends b{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var u=class extends b{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},_=class extends b{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};var O=class extends b{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};var $=f.getRandomValues.bind(f);function v(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function B(e,t){return e.name===t}function Y(e){return parseInt(e.name.slice(4),10)}function Ke(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function xe(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function pe(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!B(e.algorithm,"HMAC"))throw v("HMAC");let n=parseInt(t.slice(2),10);if(Y(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!B(e.algorithm,"RSASSA-PKCS1-v1_5"))throw v("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Y(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!B(e.algorithm,"RSA-PSS"))throw v("RSA-PSS");let n=parseInt(t.slice(2),10);if(Y(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw v("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!B(e.algorithm,"ECDSA"))throw v("ECDSA");let n=Ke(t);if(e.algorithm.namedCurve!==n)throw v(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}xe(e,r)}function ue(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var S=(e,...t)=>ue("Key must be ",e,...t);function Q(e,t,...r){return ue(`Key for the ${e} algorithm must be `,t,...r)}var Z=e=>g(e),l=["CryptoKey"];var Je=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let i of o){if(r.has(i))return!1;r.add(i)}}return!0},J=Je;function Re(e){return typeof e=="object"&&e!==null}function h(e){if(!Re(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var L=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var P=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((i,a)=>i===t[a])||P(e,t,n+1)},le=e=>{switch(!0){case P(e,[42,134,72,206,61,3,1,7]):return"P-256";case P(e,[43,129,4,0,34]):return"P-384";case P(e,[43,129,4,0,35]):return"P-521";case P(e,[43,101,110]):return"X25519";case P(e,[43,101,111]):return"X448";case P(e,[43,101,112]):return"Ed25519";case P(e,[43,101,113]):return"Ed448";default:throw new p("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},De=async(e,t,r,n,o)=>{var i;let a,c,s=new Uint8Array(atob(r.replace(e,"")).split("").map(m=>m.charCodeAt(0))),d=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},c=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},c=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},c=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},c=d?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},c=d?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},c=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let m=le(s);a=m.startsWith("P-")?{name:"ECDH",namedCurve:m}:{name:m},c=d?[]:["deriveBits"];break}case"EdDSA":a={name:le(s)},c=d?["verify"]:["sign"];break;default:throw new p('Invalid or unsupported "alg" (Algorithm) value')}return f.subtle.importKey(t,s,a,(i=o?.extractable)!==null&&i!==void 0?i:!1,c)};var me=(e,t,r)=>De(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);async function j(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return me(e,t,r)}var Oe=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Z(t))throw new TypeError(Q(e,t,...l,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${l.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},Me=(e,t,r)=>{if(!Z(t))throw new TypeError(Q(e,t,...l));if(t.type==="secret")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},ke=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Oe(e,t):Me(e,t,r)},k=ke;function Fe(e,t,r,n,o){if(o.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let a of n.crit){if(!i.has(a))throw new p(`Extension Header Parameter "${a}" is not recognized`);if(o[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&n[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var R=Fe;var ze=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},te=ze;var Ye=Symbol();function G(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new p(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function V(e,t,r){if(g(t))return pe(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(S(t,...l));return f.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(S(t,...l,"Uint8Array"))}var Qe=async(e,t,r,n)=>{let o=await V(e,t,"verify");L(e,o);let i=G(e,o.algorithm);try{return await f.subtle.verify(i,o,r,n)}catch{return!1}},Ee=Qe;async function F(e,t,r){var n;if(!h(e))throw new u("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new u('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new u("JWS Protected Header incorrect type");if(e.payload===void 0)throw new u("JWS Payload missing");if(typeof e.signature!="string")throw new u("JWS Signature missing or incorrect type");if(e.header!==void 0&&!h(e.header))throw new u("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{let ie=A(e.protected);o=JSON.parse(y.decode(ie))}catch{throw new u("JWS Protected Header is invalid")}if(!J(o,e.header))throw new u("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...o,...e.header},a=R(u,new Map([["b64",!0]]),r?.crit,o,i),c=!0;if(a.has("b64")&&(c=o.b64,typeof c!="boolean"))throw new u('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=i;if(typeof s!="string"||!s)throw new u('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=r&&te("algorithms",r.algorithms);if(d&&!d.has(s))throw new D('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof e.payload!="string")throw new u("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new u("JWS Payload must be a string or an Uint8Array instance");let m=!1;typeof t=="function"&&(t=await t(o,e),m=!0),k(s,t,"verify");let I=H(E.encode((n=e.protected)!==null&&n!==void 0?n:""),E.encode("."),typeof e.payload=="string"?E.encode(e.payload):e.payload),T=A(e.signature);if(!await Ee(s,t,T,I))throw new O;let W;c?W=A(e.payload):typeof e.payload=="string"?W=E.encode(e.payload):W=e.payload;let N={payload:W};return e.protected!==void 0&&(N.protectedHeader=o),e.header!==void 0&&(N.unprotectedHeader=e.header),m?{...N,key:t}:N}async function re(e,t,r){if(e instanceof Uint8Array&&(e=y.decode(e)),typeof e!="string")throw new u("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:a}=e.split(".");if(a!==3)throw new u("Invalid Compact JWS");let c=await F({payload:o,protected:n,signature:i},t,r),s={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t=="function"?{...s,key:c.key}:s}var ne=e=>Math.floor(e.getTime()/1e3);var Ze=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,z=e=>{let t=Ze.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var ge=e=>e.toLowerCase().replace(/^application\//,""),je=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,X=(e,t,r={})=>{let{typ:n}=r;if(n&&(typeof e.typ!="string"||ge(e.typ)!==ge(n)))throw new w('unexpected "typ" JWT header value',"typ","check_failed");let o;try{o=JSON.parse(y.decode(t))}catch{}if(!h(o))throw new _("JWT Claims Set must be a top-level JSON object");let{requiredClaims:i=[],issuer:a,subject:c,audience:s,maxTokenAge:d}=r;d!==void 0&&i.push("iat"),s!==void 0&&i.push("aud"),c!==void 0&&i.push("sub"),a!==void 0&&i.push("iss");for(let x of new Set(i.reverse()))if(!(x in o))throw new w(`missing required "${x}" claim`,x,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(o.iss))throw new w('unexpected "iss" claim value',"iss","check_failed");if(c&&o.sub!==c)throw new w('unexpected "sub" claim value',"sub","check_failed");if(s&&!je(o.aud,typeof s=="string"?[s]:s))throw new w('unexpected "aud" claim value',"aud","check_failed");let m;switch(typeof r.clockTolerance){case"string":m=z(r.clockTolerance);break;case"number":m=r.clockTolerance;break;case"undefined":m=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:I}=r,T=ne(I||new Date);if((o.iat!==void 0||d)&&typeof o.iat!="number")throw new w('"iat" claim must be a number',"iat","invalid");if(o.nbf!==void 0){if(typeof o.nbf!="number")throw new w('"nbf" claim must be a number',"nbf","invalid");if(o.nbf>T+m)throw new w('"nbf" claim timestamp check failed',"nbf","check_failed")}if(o.exp!==void 0){if(typeof o.exp!="number")throw new w('"exp" claim must be a number',"exp","invalid");if(o.exp<=T-m)throw new U('"exp" claim timestamp check failed',"exp","check_failed")}if(d){let x=T-o.iat,W=typeof d=="number"?d:z(d);if(x-m>W)throw new U('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(x<0-m)throw new w('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return o};async function oe(e,t,r){var n;let o=await re(e,t,r);if(!((n=o.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&o.protectedHeader.b64===!1)throw new _("JWTs MUST NOT use unencoded payload");let a={payload:X(o.protectedHeader,o.payload,r),protectedHeader:o.protectedHeader};return typeof t=="function"?{...a,key:o.key}:a}var st=/^(?:Bearer )?([A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+)/i;async function q(e,t){if(t.SKIP_AUTH==="true")return!0;let r=st.exec(e.headers.get("authorization")||"");if(!r||!r[1])return!1;let n=await j(t.PUBLIC_KEY,"EdDSA");try{await oe(r[1],n,{issuer:"dapr.io/cloudflare",audience:t.TOKEN_AUDIENCE,algorithms:["EdDSA"],clockTolerance:300})}catch(o){return console.error("Failed to validate JWT: "+o),!1}return!0}var be="20230517";var dt=se().get("/.well-known/dapr/info",async(e,t)=>{if(!await q(e,t))return new Response("Unauthorized",{status:401});let n=[],o=[],i=[],a=Object.keys(t);for(let s=0;s{let{namespace:r,key:n,errorRes:o}=await ae(e,t);if(o)return o;let i=await r.get(n,"stream");return i?new Response(i,{status:200}):new Response("",{status:404})}).post("/kv/:namespace/:key",async(e,t)=>{let{namespace:r,key:n,errorRes:o}=await ae(e,t);if(o)return o;let i,a=new URL(e.url),c=parseInt(a.searchParams.get("ttl")||"",10);return c>0&&(i=c),await r.put(n,e.body,{expirationTtl:i}),new Response("",{status:201})}).delete("/kv/:namespace/:key",async(e,t)=>{let{namespace:r,key:n,errorRes:o}=await ae(e,t);return o||(await r.delete(n),new Response("",{status:204}))}).post("/queues/:queue",async(e,t)=>{let{queue:r,errorRes:n}=await pt(e,t);if(n)return n;let o=await e.text();return await r.send(o),new Response("",{status:201})}).all("*",()=>new Response("Not found",{status:404}));async function ae(e,t){if(!e?.text||!e.params?.namespace||!e.params?.key)return{errorRes:new Response("Bad request",{status:400})};let r=t[e.params.namespace];return typeof r!="object"||!["KVNamespace","KvNamespace"].includes(r?.constructor?.name)?{errorRes:new Response(`Worker is not bound to KV '${e.params.kv}'`,{status:412})}:await q(e,t)?{namespace:r,key:e.params.key}:{errorRes:new Response("Unauthorized",{status:401})}}async function pt(e,t){if(!e?.text||!e.params?.queue)return{errorRes:new Response("Bad request",{status:400})};let r=t[e.params.queue];return typeof r!="object"||!["WorkerQueue","Queue"].includes(r?.constructor?.name)?{errorRes:new Response(`Worker is not bound to queue '${e.params.queue}'`,{status:412})}:await q(e,t)?{queue:r}:{errorRes:new Response("Unauthorized",{status:401})}}var Cc={fetch:dt.handle};export{Cc as default}; //# sourceMappingURL=worker.js.map diff --git a/internal/component/cloudflare/workers/code/worker.js.map b/internal/component/cloudflare/workers/code/worker.js.map index e1b276eb2..a066b5e7f 100644 --- a/internal/component/cloudflare/workers/code/worker.js.map +++ b/internal/component/cloudflare/workers/code/worker.js.map @@ -1,7 +1,7 @@ { "version": 3, - "sources": ["../../worker-src/node_modules/itty-router/dist/itty-router.mjs", "../../worker-src/node_modules/jose/dist/browser/runtime/webcrypto.js", "../../worker-src/node_modules/jose/dist/browser/lib/buffer_utils.js", "../../worker-src/node_modules/jose/dist/browser/runtime/base64url.js", "../../worker-src/node_modules/jose/dist/browser/util/errors.js", "../../worker-src/node_modules/jose/dist/browser/runtime/random.js", "../../worker-src/node_modules/jose/dist/browser/runtime/env.js", "../../worker-src/node_modules/jose/dist/browser/lib/crypto_key.js", "../../worker-src/node_modules/jose/dist/browser/lib/invalid_key_input.js", "../../worker-src/node_modules/jose/dist/browser/runtime/is_key_like.js", "../../worker-src/node_modules/jose/dist/browser/lib/is_disjoint.js", "../../worker-src/node_modules/jose/dist/browser/lib/is_object.js", "../../worker-src/node_modules/jose/dist/browser/runtime/check_key_length.js", "../../worker-src/node_modules/jose/dist/browser/runtime/asn1.js", "../../worker-src/node_modules/jose/dist/browser/key/import.js", "../../worker-src/node_modules/jose/dist/browser/lib/check_key_type.js", "../../worker-src/node_modules/jose/dist/browser/lib/validate_crit.js", "../../worker-src/node_modules/jose/dist/browser/lib/validate_algorithms.js", "../../worker-src/node_modules/jose/dist/browser/jwe/flattened/encrypt.js", "../../worker-src/node_modules/jose/dist/browser/runtime/subtle_dsa.js", "../../worker-src/node_modules/jose/dist/browser/runtime/get_sign_verify_key.js", "../../worker-src/node_modules/jose/dist/browser/runtime/verify.js", "../../worker-src/node_modules/jose/dist/browser/jws/flattened/verify.js", "../../worker-src/node_modules/jose/dist/browser/jws/compact/verify.js", "../../worker-src/node_modules/jose/dist/browser/lib/epoch.js", "../../worker-src/node_modules/jose/dist/browser/lib/secs.js", "../../worker-src/node_modules/jose/dist/browser/lib/jwt_claims_set.js", "../../worker-src/node_modules/jose/dist/browser/jwt/verify.js", "../../worker-src/lib/jwt-auth.ts", "../../worker-src/package.json", "../../worker-src/worker.ts"], - "sourcesContent": ["const e=({base:e=\"\",routes:r=[]}={})=>({__proto__:new Proxy({},{get:(a,o,t)=>(a,...p)=>r.push([o.toUpperCase(),RegExp(`^${(e+a).replace(/(\\/?)\\*/g,\"($1.*)?\").replace(/(\\/$)|((?<=\\/)\\/)/,\"\").replace(/(:(\\w+)\\+)/,\"(?<$2>.*)\").replace(/:(\\w+)(\\?)?(\\.)?/g,\"$2(?<$1>[^/]+)$2$3\").replace(/\\.(?=[\\w(])/,\"\\\\.\").replace(/\\)\\.\\?\\(([^\\[]+)\\[\\^/g,\"?)\\\\.?($1(?<=\\\\.)[^\\\\.\")}/*$`),p])&&t}),routes:r,async handle(e,...a){let o,t,p=new URL(e.url),l=e.query={};for(let[e,r]of p.searchParams)l[e]=void 0===l[e]?r:[l[e],r].flat();for(let[l,s,c]of r)if((l===e.method||\"ALL\"===l)&&(t=p.pathname.match(s))){e.params=t.groups||{};for(let r of c)if(void 0!==(o=await r(e.proxy||e,...a)))return o}}});export{e as Router};\n", "export default crypto;\nexport const isCryptoKey = (key) => key instanceof CryptoKey;\n", "import digest from '../runtime/digest.js';\nexport const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0);\n const buf = new Uint8Array(size);\n let i = 0;\n buffers.forEach((buffer) => {\n buf.set(buffer, i);\n i += buffer.length;\n });\n return buf;\n}\nexport function p2s(alg, p2sInput) {\n return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32) {\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n }\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n const high = Math.floor(value / MAX_INT32);\n const low = value % MAX_INT32;\n const buf = new Uint8Array(8);\n writeUInt32BE(buf, high, 0);\n writeUInt32BE(buf, low, 4);\n return buf;\n}\nexport function uint32be(value) {\n const buf = new Uint8Array(4);\n writeUInt32BE(buf, value);\n return buf;\n}\nexport function lengthAndInput(input) {\n return concat(uint32be(input.length), input);\n}\nexport async function concatKdf(secret, bits, value) {\n const iterations = Math.ceil((bits >> 3) / 32);\n const res = new Uint8Array(iterations * 32);\n for (let iter = 0; iter < iterations; iter++) {\n const buf = new Uint8Array(4 + secret.length + value.length);\n buf.set(uint32be(iter + 1));\n buf.set(secret, 4);\n buf.set(value, 4 + secret.length);\n res.set(await digest('sha256', buf), iter * 32);\n }\n return res.slice(0, bits >> 3);\n}\n", "import { encoder, decoder } from '../lib/buffer_utils.js';\nexport const encodeBase64 = (input) => {\n let unencoded = input;\n if (typeof unencoded === 'string') {\n unencoded = encoder.encode(unencoded);\n }\n const CHUNK_SIZE = 0x8000;\n const arr = [];\n for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join(''));\n};\nexport const encode = (input) => {\n return encodeBase64(input).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n};\nexport const decodeBase64 = (encoded) => {\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n};\nexport const decode = (input) => {\n let encoded = input;\n if (encoded instanceof Uint8Array) {\n encoded = decoder.decode(encoded);\n }\n encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\\s/g, '');\n try {\n return decodeBase64(encoded);\n }\n catch (_a) {\n throw new TypeError('The input to be decoded is not correctly encoded.');\n }\n};\n", "export class JOSEError extends Error {\n static get code() {\n return 'ERR_JOSE_GENERIC';\n }\n constructor(message) {\n var _a;\n super(message);\n this.code = 'ERR_JOSE_GENERIC';\n this.name = this.constructor.name;\n (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor);\n }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n static get code() {\n return 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n }\n constructor(message, claim = 'unspecified', reason = 'unspecified') {\n super(message);\n this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n this.claim = claim;\n this.reason = reason;\n }\n}\nexport class JWTExpired extends JOSEError {\n static get code() {\n return 'ERR_JWT_EXPIRED';\n }\n constructor(message, claim = 'unspecified', reason = 'unspecified') {\n super(message);\n this.code = 'ERR_JWT_EXPIRED';\n this.claim = claim;\n this.reason = reason;\n }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n }\n static get code() {\n return 'ERR_JOSE_ALG_NOT_ALLOWED';\n }\n}\nexport class JOSENotSupported extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JOSE_NOT_SUPPORTED';\n }\n static get code() {\n return 'ERR_JOSE_NOT_SUPPORTED';\n }\n}\nexport class JWEDecryptionFailed extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWE_DECRYPTION_FAILED';\n this.message = 'decryption operation failed';\n }\n static get code() {\n return 'ERR_JWE_DECRYPTION_FAILED';\n }\n}\nexport class JWEInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWE_INVALID';\n }\n static get code() {\n return 'ERR_JWE_INVALID';\n }\n}\nexport class JWSInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWS_INVALID';\n }\n static get code() {\n return 'ERR_JWS_INVALID';\n }\n}\nexport class JWTInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWT_INVALID';\n }\n static get code() {\n return 'ERR_JWT_INVALID';\n }\n}\nexport class JWKInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWK_INVALID';\n }\n static get code() {\n return 'ERR_JWK_INVALID';\n }\n}\nexport class JWKSInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWKS_INVALID';\n }\n static get code() {\n return 'ERR_JWKS_INVALID';\n }\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWKS_NO_MATCHING_KEY';\n this.message = 'no applicable key found in the JSON Web Key Set';\n }\n static get code() {\n return 'ERR_JWKS_NO_MATCHING_KEY';\n }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n this.message = 'multiple matching keys found in the JSON Web Key Set';\n }\n static get code() {\n return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n }\n}\nSymbol.asyncIterator;\nexport class JWKSTimeout extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWKS_TIMEOUT';\n this.message = 'request timed out';\n }\n static get code() {\n return 'ERR_JWKS_TIMEOUT';\n }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n this.message = 'signature verification failed';\n }\n static get code() {\n return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n }\n}\n", "import crypto from './webcrypto.js';\nexport default crypto.getRandomValues.bind(crypto);\n", "export function isCloudflareWorkers() {\n return (typeof WebSocketPair !== 'undefined' ||\n (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||\n (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));\n}\n", "import { isCloudflareWorkers } from '../runtime/env.js';\nfunction unusable(name, prop = 'algorithm.name') {\n return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\n}\nfunction isAlgorithm(algorithm, name) {\n return algorithm.name === name;\n}\nfunction getHashLength(hash) {\n return parseInt(hash.name.slice(4), 10);\n}\nfunction getNamedCurve(alg) {\n switch (alg) {\n case 'ES256':\n return 'P-256';\n case 'ES384':\n return 'P-384';\n case 'ES512':\n return 'P-521';\n default:\n throw new Error('unreachable');\n }\n}\nfunction checkUsage(key, usages) {\n if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {\n let msg = 'CryptoKey does not support this operation, its usages must include ';\n if (usages.length > 2) {\n const last = usages.pop();\n msg += `one of ${usages.join(', ')}, or ${last}.`;\n }\n else if (usages.length === 2) {\n msg += `one of ${usages[0]} or ${usages[1]}.`;\n }\n else {\n msg += `${usages[0]}.`;\n }\n throw new TypeError(msg);\n }\n}\nexport function checkSigCryptoKey(key, alg, ...usages) {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512': {\n if (!isAlgorithm(key.algorithm, 'HMAC'))\n throw unusable('HMAC');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'RS256':\n case 'RS384':\n case 'RS512': {\n if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))\n throw unusable('RSASSA-PKCS1-v1_5');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'PS256':\n case 'PS384':\n case 'PS512': {\n if (!isAlgorithm(key.algorithm, 'RSA-PSS'))\n throw unusable('RSA-PSS');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'EdDSA': {\n if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {\n if (isCloudflareWorkers()) {\n if (isAlgorithm(key.algorithm, 'NODE-ED25519'))\n break;\n throw unusable('Ed25519, Ed448, or NODE-ED25519');\n }\n throw unusable('Ed25519 or Ed448');\n }\n break;\n }\n case 'ES256':\n case 'ES384':\n case 'ES512': {\n if (!isAlgorithm(key.algorithm, 'ECDSA'))\n throw unusable('ECDSA');\n const expected = getNamedCurve(alg);\n const actual = key.algorithm.namedCurve;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.namedCurve');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usages);\n}\nexport function checkEncCryptoKey(key, alg, ...usages) {\n switch (alg) {\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM': {\n if (!isAlgorithm(key.algorithm, 'AES-GCM'))\n throw unusable('AES-GCM');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n if (!isAlgorithm(key.algorithm, 'AES-KW'))\n throw unusable('AES-KW');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'ECDH': {\n switch (key.algorithm.name) {\n case 'ECDH':\n case 'X25519':\n case 'X448':\n break;\n default:\n throw unusable('ECDH, X25519, or X448');\n }\n break;\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW':\n if (!isAlgorithm(key.algorithm, 'PBKDF2'))\n throw unusable('PBKDF2');\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))\n throw unusable('RSA-OAEP');\n const expected = parseInt(alg.slice(9), 10) || 1;\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usages);\n}\n", "function message(msg, actual, ...types) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(', ')}, or ${last}.`;\n }\n else if (types.length === 2) {\n msg += `one of type ${types[0]} or ${types[1]}.`;\n }\n else {\n msg += `of type ${types[0]}.`;\n }\n if (actual == null) {\n msg += ` Received ${actual}`;\n }\n else if (typeof actual === 'function' && actual.name) {\n msg += ` Received function ${actual.name}`;\n }\n else if (typeof actual === 'object' && actual != null) {\n if (actual.constructor && actual.constructor.name) {\n msg += ` Received an instance of ${actual.constructor.name}`;\n }\n }\n return msg;\n}\nexport default (actual, ...types) => {\n return message('Key must be ', actual, ...types);\n};\nexport function withAlg(alg, actual, ...types) {\n return message(`Key for the ${alg} algorithm must be `, actual, ...types);\n}\n", "import { isCryptoKey } from './webcrypto.js';\nexport default (key) => {\n return isCryptoKey(key);\n};\nexport const types = ['CryptoKey'];\n", "const isDisjoint = (...headers) => {\n const sources = headers.filter(Boolean);\n if (sources.length === 0 || sources.length === 1) {\n return true;\n }\n let acc;\n for (const header of sources) {\n const parameters = Object.keys(header);\n if (!acc || acc.size === 0) {\n acc = new Set(parameters);\n continue;\n }\n for (const parameter of parameters) {\n if (acc.has(parameter)) {\n return false;\n }\n acc.add(parameter);\n }\n }\n return true;\n};\nexport default isDisjoint;\n", "function isObjectLike(value) {\n return typeof value === 'object' && value !== null;\n}\nexport default function isObject(input) {\n if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(input) === null) {\n return true;\n }\n let proto = input;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(input) === proto;\n}\n", "export default (alg, key) => {\n if (alg.startsWith('RS') || alg.startsWith('PS')) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n }\n }\n};\n", "import { isCloudflareWorkers } from './env.js';\nimport crypto, { isCryptoKey } from './webcrypto.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { encodeBase64 } from './base64url.js';\nimport formatPEM from '../lib/format_pem.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { types } from './is_key_like.js';\nconst genericExport = async (keyType, keyFormat, key) => {\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, ...types));\n }\n if (!key.extractable) {\n throw new TypeError('CryptoKey is not extractable');\n }\n if (key.type !== keyType) {\n throw new TypeError(`key is not a ${keyType} key`);\n }\n return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);\n};\nexport const toSPKI = (key) => {\n return genericExport('public', 'spki', key);\n};\nexport const toPKCS8 = (key) => {\n return genericExport('private', 'pkcs8', key);\n};\nconst findOid = (keyData, oid, from = 0) => {\n if (from === 0) {\n oid.unshift(oid.length);\n oid.unshift(0x06);\n }\n let i = keyData.indexOf(oid[0], from);\n if (i === -1)\n return false;\n const sub = keyData.subarray(i, i + oid.length);\n if (sub.length !== oid.length)\n return false;\n return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1);\n};\nconst getNamedCurve = (keyData) => {\n switch (true) {\n case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]):\n return 'P-256';\n case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]):\n return 'P-384';\n case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]):\n return 'P-521';\n case findOid(keyData, [0x2b, 0x65, 0x6e]):\n return 'X25519';\n case findOid(keyData, [0x2b, 0x65, 0x6f]):\n return 'X448';\n case findOid(keyData, [0x2b, 0x65, 0x70]):\n return 'Ed25519';\n case findOid(keyData, [0x2b, 0x65, 0x71]):\n return 'Ed448';\n default:\n throw new JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type');\n }\n};\nconst genericImport = async (replace, keyFormat, pem, alg, options) => {\n var _a, _b;\n let algorithm;\n let keyUsages;\n const keyData = new Uint8Array(atob(pem.replace(replace, ''))\n .split('')\n .map((c) => c.charCodeAt(0)));\n const isPublic = keyFormat === 'spki';\n switch (alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,\n };\n keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'];\n break;\n case 'ES256':\n algorithm = { name: 'ECDSA', namedCurve: 'P-256' };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'ES384':\n algorithm = { name: 'ECDSA', namedCurve: 'P-384' };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'ES512':\n algorithm = { name: 'ECDSA', namedCurve: 'P-521' };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n const namedCurve = getNamedCurve(keyData);\n algorithm = namedCurve.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: namedCurve };\n keyUsages = isPublic ? [] : ['deriveBits'];\n break;\n }\n case 'EdDSA':\n algorithm = { name: getNamedCurve(keyData) };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported \"alg\" (Algorithm) value');\n }\n try {\n return await crypto.subtle.importKey(keyFormat, keyData, algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages);\n }\n catch (err) {\n if (algorithm.name === 'Ed25519' &&\n (err === null || err === void 0 ? void 0 : err.name) === 'NotSupportedError' &&\n isCloudflareWorkers()) {\n algorithm = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' };\n return await crypto.subtle.importKey(keyFormat, keyData, algorithm, (_b = options === null || options === void 0 ? void 0 : options.extractable) !== null && _b !== void 0 ? _b : false, keyUsages);\n }\n throw err;\n }\n};\nexport const fromPKCS8 = (pem, alg, options) => {\n return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\\s)/g, 'pkcs8', pem, alg, options);\n};\nexport const fromSPKI = (pem, alg, options) => {\n return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\\s)/g, 'spki', pem, alg, options);\n};\n", "import { decode as decodeBase64URL, encodeBase64, decodeBase64 } from '../runtime/base64url.js';\nimport { fromSPKI as importPublic } from '../runtime/asn1.js';\nimport { fromPKCS8 as importPrivate } from '../runtime/asn1.js';\nimport asKeyObject from '../runtime/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport formatPEM from '../lib/format_pem.js';\nimport isObject from '../lib/is_object.js';\nfunction getElement(seq) {\n let result = [];\n let next = 0;\n while (next < seq.length) {\n let nextPart = parseElement(seq.subarray(next));\n result.push(nextPart);\n next += nextPart.byteLength;\n }\n return result;\n}\nfunction parseElement(bytes) {\n let position = 0;\n let tag = bytes[0] & 0x1f;\n position++;\n if (tag === 0x1f) {\n tag = 0;\n while (bytes[position] >= 0x80) {\n tag = tag * 128 + bytes[position] - 0x80;\n position++;\n }\n tag = tag * 128 + bytes[position] - 0x80;\n position++;\n }\n let length = 0;\n if (bytes[position] < 0x80) {\n length = bytes[position];\n position++;\n }\n else if (length === 0x80) {\n length = 0;\n while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) {\n if (length > bytes.byteLength) {\n throw new TypeError('invalid indefinite form length');\n }\n length++;\n }\n const byteLength = position + length + 2;\n return {\n byteLength,\n contents: bytes.subarray(position, position + length),\n raw: bytes.subarray(0, byteLength),\n };\n }\n else {\n let numberOfDigits = bytes[position] & 0x7f;\n position++;\n length = 0;\n for (let i = 0; i < numberOfDigits; i++) {\n length = length * 256 + bytes[position];\n position++;\n }\n }\n const byteLength = position + length;\n return {\n byteLength,\n contents: bytes.subarray(position, byteLength),\n raw: bytes.subarray(0, byteLength),\n };\n}\nfunction spkiFromX509(buf) {\n const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents);\n return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw);\n}\nfunction getSPKI(x509) {\n const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\\s)/g, '');\n const raw = decodeBase64(pem);\n return formatPEM(spkiFromX509(raw), 'PUBLIC KEY');\n}\nexport async function importSPKI(spki, alg, options) {\n if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n throw new TypeError('\"spki\" must be SPKI formatted string');\n }\n return importPublic(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n throw new TypeError('\"x509\" must be X.509 formatted string');\n }\n let spki;\n try {\n spki = getSPKI(x509);\n }\n catch (cause) {\n throw new TypeError('failed to parse the X.509 certificate', { cause });\n }\n return importPublic(spki, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n }\n return importPrivate(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg, octAsKeyObject) {\n var _a;\n if (!isObject(jwk)) {\n throw new TypeError('JWK must be an object');\n }\n alg || (alg = jwk.alg);\n if (typeof alg !== 'string' || !alg) {\n throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n }\n switch (jwk.kty) {\n case 'oct':\n if (typeof jwk.k !== 'string' || !jwk.k) {\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n }\n octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : (octAsKeyObject = jwk.ext !== true);\n if (octAsKeyObject) {\n return asKeyObject({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false });\n }\n return decodeBase64URL(jwk.k);\n case 'RSA':\n if (jwk.oth !== undefined) {\n throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n }\n case 'EC':\n case 'OKP':\n return asKeyObject({ ...jwk, alg });\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\n", "import { withAlg as invalidKeyInput } from './invalid_key_input.js';\nimport isKeyLike, { types } from '../runtime/is_key_like.js';\nconst symmetricTypeCheck = (alg, key) => {\n if (key instanceof Uint8Array)\n return;\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array'));\n }\n if (key.type !== 'secret') {\n throw new TypeError(`${types.join(' or ')} instances for symmetric algorithms must be of type \"secret\"`);\n }\n};\nconst asymmetricTypeCheck = (alg, key, usage) => {\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, ...types));\n }\n if (key.type === 'secret') {\n throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithms must not be of type \"secret\"`);\n }\n if (usage === 'sign' && key.type === 'public') {\n throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm signing must be of type \"private\"`);\n }\n if (usage === 'decrypt' && key.type === 'public') {\n throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm decryption must be of type \"private\"`);\n }\n if (key.algorithm && usage === 'verify' && key.type === 'private') {\n throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm verifying must be of type \"public\"`);\n }\n if (key.algorithm && usage === 'encrypt' && key.type === 'private') {\n throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm encryption must be of type \"public\"`);\n }\n};\nconst checkKeyType = (alg, key, usage) => {\n const symmetric = alg.startsWith('HS') ||\n alg === 'dir' ||\n alg.startsWith('PBES2') ||\n /^A\\d{3}(?:GCM)?KW$/.test(alg);\n if (symmetric) {\n symmetricTypeCheck(alg, key);\n }\n else {\n asymmetricTypeCheck(alg, key, usage);\n }\n};\nexport default checkKeyType;\n", "import { JOSENotSupported } from '../util/errors.js';\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== undefined && protectedHeader.crit === undefined) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n }\n if (!protectedHeader || protectedHeader.crit === undefined) {\n return new Set();\n }\n if (!Array.isArray(protectedHeader.crit) ||\n protectedHeader.crit.length === 0 ||\n protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n }\n let recognized;\n if (recognizedOption !== undefined) {\n recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);\n }\n else {\n recognized = recognizedDefault;\n }\n for (const parameter of protectedHeader.crit) {\n if (!recognized.has(parameter)) {\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n }\n if (joseHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n }\n else if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n }\n return new Set(protectedHeader.crit);\n}\nexport default validateCrit;\n", "const validateAlgorithms = (option, algorithms) => {\n if (algorithms !== undefined &&\n (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n }\n if (!algorithms) {\n return undefined;\n }\n return new Set(algorithms);\n};\nexport default validateAlgorithms;\n", "import { encode as base64url } from '../../runtime/base64url.js';\nimport encrypt from '../../runtime/encrypt.js';\nimport { deflate } from '../../runtime/zlib.js';\nimport generateIv from '../../lib/iv.js';\nimport encryptKeyManagement from '../../lib/encrypt_key_management.js';\nimport { JOSENotSupported, JWEInvalid } from '../../util/errors.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport { encoder, decoder, concat } from '../../lib/buffer_utils.js';\nimport validateCrit from '../../lib/validate_crit.js';\nexport const unprotected = Symbol();\nexport class FlattenedEncrypt {\n constructor(plaintext) {\n if (!(plaintext instanceof Uint8Array)) {\n throw new TypeError('plaintext must be an instance of Uint8Array');\n }\n this._plaintext = plaintext;\n }\n setKeyManagementParameters(parameters) {\n if (this._keyManagementParameters) {\n throw new TypeError('setKeyManagementParameters can only be called once');\n }\n this._keyManagementParameters = parameters;\n return this;\n }\n setProtectedHeader(protectedHeader) {\n if (this._protectedHeader) {\n throw new TypeError('setProtectedHeader can only be called once');\n }\n this._protectedHeader = protectedHeader;\n return this;\n }\n setSharedUnprotectedHeader(sharedUnprotectedHeader) {\n if (this._sharedUnprotectedHeader) {\n throw new TypeError('setSharedUnprotectedHeader can only be called once');\n }\n this._sharedUnprotectedHeader = sharedUnprotectedHeader;\n return this;\n }\n setUnprotectedHeader(unprotectedHeader) {\n if (this._unprotectedHeader) {\n throw new TypeError('setUnprotectedHeader can only be called once');\n }\n this._unprotectedHeader = unprotectedHeader;\n return this;\n }\n setAdditionalAuthenticatedData(aad) {\n this._aad = aad;\n return this;\n }\n setContentEncryptionKey(cek) {\n if (this._cek) {\n throw new TypeError('setContentEncryptionKey can only be called once');\n }\n this._cek = cek;\n return this;\n }\n setInitializationVector(iv) {\n if (this._iv) {\n throw new TypeError('setInitializationVector can only be called once');\n }\n this._iv = iv;\n return this;\n }\n async encrypt(key, options) {\n if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {\n throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');\n }\n if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) {\n throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...this._protectedHeader,\n ...this._unprotectedHeader,\n ...this._sharedUnprotectedHeader,\n };\n validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);\n if (joseHeader.zip !== undefined) {\n if (!this._protectedHeader || !this._protectedHeader.zip) {\n throw new JWEInvalid('JWE \"zip\" (Compression Algorithm) Header MUST be integrity protected');\n }\n if (joseHeader.zip !== 'DEF') {\n throw new JOSENotSupported('Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value');\n }\n }\n const { alg, enc } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWEInvalid('JWE \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n if (typeof enc !== 'string' || !enc) {\n throw new JWEInvalid('JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid');\n }\n let encryptedKey;\n if (alg === 'dir') {\n if (this._cek) {\n throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption');\n }\n }\n else if (alg === 'ECDH-ES') {\n if (this._cek) {\n throw new TypeError('setContentEncryptionKey cannot be called when using Direct Key Agreement');\n }\n }\n let cek;\n {\n let parameters;\n ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, key, this._cek, this._keyManagementParameters));\n if (parameters) {\n if (options && unprotected in options) {\n if (!this._unprotectedHeader) {\n this.setUnprotectedHeader(parameters);\n }\n else {\n this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters };\n }\n }\n else {\n if (!this._protectedHeader) {\n this.setProtectedHeader(parameters);\n }\n else {\n this._protectedHeader = { ...this._protectedHeader, ...parameters };\n }\n }\n }\n }\n this._iv || (this._iv = generateIv(enc));\n let additionalData;\n let protectedHeader;\n let aadMember;\n if (this._protectedHeader) {\n protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));\n }\n else {\n protectedHeader = encoder.encode('');\n }\n if (this._aad) {\n aadMember = base64url(this._aad);\n additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember));\n }\n else {\n additionalData = protectedHeader;\n }\n let ciphertext;\n let tag;\n if (joseHeader.zip === 'DEF') {\n const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || deflate)(this._plaintext);\n ({ ciphertext, tag } = await encrypt(enc, deflated, cek, this._iv, additionalData));\n }\n else {\n ;\n ({ ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData));\n }\n const jwe = {\n ciphertext: base64url(ciphertext),\n iv: base64url(this._iv),\n tag: base64url(tag),\n };\n if (encryptedKey) {\n jwe.encrypted_key = base64url(encryptedKey);\n }\n if (aadMember) {\n jwe.aad = aadMember;\n }\n if (this._protectedHeader) {\n jwe.protected = decoder.decode(protectedHeader);\n }\n if (this._sharedUnprotectedHeader) {\n jwe.unprotected = this._sharedUnprotectedHeader;\n }\n if (this._unprotectedHeader) {\n jwe.header = this._unprotectedHeader;\n }\n return jwe;\n }\n}\n", "import { isCloudflareWorkers } from './env.js';\nimport { JOSENotSupported } from '../util/errors.js';\nexport default function subtleDsa(alg, algorithm) {\n const hash = `SHA-${alg.slice(-3)}`;\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { hash, name: 'HMAC' };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { hash, name: 'RSA-PSS', saltLength: alg.slice(-3) >> 3 };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { hash, name: 'RSASSA-PKCS1-v1_5' };\n case 'ES256':\n case 'ES384':\n case 'ES512':\n return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };\n case 'EdDSA':\n if (isCloudflareWorkers() && algorithm.name === 'NODE-ED25519') {\n return { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' };\n }\n return { name: algorithm.name };\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n}\n", "import crypto, { isCryptoKey } from './webcrypto.js';\nimport { checkSigCryptoKey } from '../lib/crypto_key.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nexport default function getCryptoKey(alg, key, usage) {\n if (isCryptoKey(key)) {\n checkSigCryptoKey(key, alg, usage);\n return key;\n }\n if (key instanceof Uint8Array) {\n if (!alg.startsWith('HS')) {\n throw new TypeError(invalidKeyInput(key, ...types));\n }\n return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);\n }\n throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));\n}\n", "import subtleAlgorithm from './subtle_dsa.js';\nimport crypto from './webcrypto.js';\nimport checkKeyLength from './check_key_length.js';\nimport getVerifyKey from './get_sign_verify_key.js';\nconst verify = async (alg, key, signature, data) => {\n const cryptoKey = await getVerifyKey(alg, key, 'verify');\n checkKeyLength(alg, cryptoKey);\n const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);\n try {\n return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);\n }\n catch (_a) {\n return false;\n }\n};\nexport default verify;\n", "import { decode as base64url } from '../../runtime/base64url.js';\nimport verify from '../../runtime/verify.js';\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';\nimport { concat, encoder, decoder } from '../../lib/buffer_utils.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport isObject from '../../lib/is_object.js';\nimport checkKeyType from '../../lib/check_key_type.js';\nimport validateCrit from '../../lib/validate_crit.js';\nimport validateAlgorithms from '../../lib/validate_algorithms.js';\nexport async function flattenedVerify(jws, key, options) {\n var _a;\n if (!isObject(jws)) {\n throw new JWSInvalid('Flattened JWS must be an object');\n }\n if (jws.protected === undefined && jws.header === undefined) {\n throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n }\n if (jws.protected !== undefined && typeof jws.protected !== 'string') {\n throw new JWSInvalid('JWS Protected Header incorrect type');\n }\n if (jws.payload === undefined) {\n throw new JWSInvalid('JWS Payload missing');\n }\n if (typeof jws.signature !== 'string') {\n throw new JWSInvalid('JWS Signature missing or incorrect type');\n }\n if (jws.header !== undefined && !isObject(jws.header)) {\n throw new JWSInvalid('JWS Unprotected Header incorrect type');\n }\n let parsedProt = {};\n if (jws.protected) {\n try {\n const protectedHeader = base64url(jws.protected);\n parsedProt = JSON.parse(decoder.decode(protectedHeader));\n }\n catch (_b) {\n throw new JWSInvalid('JWS Protected Header is invalid');\n }\n }\n if (!isDisjoint(parsedProt, jws.header)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...parsedProt,\n ...jws.header,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = parsedProt.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n const algorithms = options && validateAlgorithms('algorithms', options.algorithms);\n if (algorithms && !algorithms.has(alg)) {\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter not allowed');\n }\n if (b64) {\n if (typeof jws.payload !== 'string') {\n throw new JWSInvalid('JWS Payload must be a string');\n }\n }\n else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {\n throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');\n }\n let resolvedKey = false;\n if (typeof key === 'function') {\n key = await key(parsedProt, jws);\n resolvedKey = true;\n }\n checkKeyType(alg, key, 'verify');\n const data = concat(encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload);\n const signature = base64url(jws.signature);\n const verified = await verify(alg, key, signature, data);\n if (!verified) {\n throw new JWSSignatureVerificationFailed();\n }\n let payload;\n if (b64) {\n payload = base64url(jws.payload);\n }\n else if (typeof jws.payload === 'string') {\n payload = encoder.encode(jws.payload);\n }\n else {\n payload = jws.payload;\n }\n const result = { payload };\n if (jws.protected !== undefined) {\n result.protectedHeader = parsedProt;\n }\n if (jws.header !== undefined) {\n result.unprotectedHeader = jws.header;\n }\n if (resolvedKey) {\n return { ...result, key };\n }\n return result;\n}\n", "import { flattenedVerify } from '../flattened/verify.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactVerify(jws, key, options) {\n if (jws instanceof Uint8Array) {\n jws = decoder.decode(jws);\n }\n if (typeof jws !== 'string') {\n throw new JWSInvalid('Compact JWS must be a string or Uint8Array');\n }\n const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');\n if (length !== 3) {\n throw new JWSInvalid('Invalid Compact JWS');\n }\n const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);\n const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n", "export default (date) => Math.floor(date.getTime() / 1000);\n", "const minute = 60;\nconst hour = minute * 60;\nconst day = hour * 24;\nconst week = day * 7;\nconst year = day * 365.25;\nconst REGEX = /^(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;\nexport default (str) => {\n const matched = REGEX.exec(str);\n if (!matched) {\n throw new TypeError('Invalid time period format');\n }\n const value = parseFloat(matched[1]);\n const unit = matched[2].toLowerCase();\n switch (unit) {\n case 'sec':\n case 'secs':\n case 'second':\n case 'seconds':\n case 's':\n return Math.round(value);\n case 'minute':\n case 'minutes':\n case 'min':\n case 'mins':\n case 'm':\n return Math.round(value * minute);\n case 'hour':\n case 'hours':\n case 'hr':\n case 'hrs':\n case 'h':\n return Math.round(value * hour);\n case 'day':\n case 'days':\n case 'd':\n return Math.round(value * day);\n case 'week':\n case 'weeks':\n case 'w':\n return Math.round(value * week);\n default:\n return Math.round(value * year);\n }\n};\n", "import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';\nimport { decoder } from './buffer_utils.js';\nimport epoch from './epoch.js';\nimport secs from './secs.js';\nimport isObject from './is_object.js';\nconst normalizeTyp = (value) => value.toLowerCase().replace(/^application\\//, '');\nconst checkAudiencePresence = (audPayload, audOption) => {\n if (typeof audPayload === 'string') {\n return audOption.includes(audPayload);\n }\n if (Array.isArray(audPayload)) {\n return audOption.some(Set.prototype.has.bind(new Set(audPayload)));\n }\n return false;\n};\nexport default (protectedHeader, encodedPayload, options = {}) => {\n const { typ } = options;\n if (typ &&\n (typeof protectedHeader.typ !== 'string' ||\n normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', 'typ', 'check_failed');\n }\n let payload;\n try {\n payload = JSON.parse(decoder.decode(encodedPayload));\n }\n catch (_a) {\n }\n if (!isObject(payload)) {\n throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');\n }\n const { issuer } = options;\n if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {\n throw new JWTClaimValidationFailed('unexpected \"iss\" claim value', 'iss', 'check_failed');\n }\n const { subject } = options;\n if (subject && payload.sub !== subject) {\n throw new JWTClaimValidationFailed('unexpected \"sub\" claim value', 'sub', 'check_failed');\n }\n const { audience } = options;\n if (audience &&\n !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {\n throw new JWTClaimValidationFailed('unexpected \"aud\" claim value', 'aud', 'check_failed');\n }\n let tolerance;\n switch (typeof options.clockTolerance) {\n case 'string':\n tolerance = secs(options.clockTolerance);\n break;\n case 'number':\n tolerance = options.clockTolerance;\n break;\n case 'undefined':\n tolerance = 0;\n break;\n default:\n throw new TypeError('Invalid clockTolerance option type');\n }\n const { currentDate } = options;\n const now = epoch(currentDate || new Date());\n if ((payload.iat !== undefined || options.maxTokenAge) && typeof payload.iat !== 'number') {\n throw new JWTClaimValidationFailed('\"iat\" claim must be a number', 'iat', 'invalid');\n }\n if (payload.nbf !== undefined) {\n if (typeof payload.nbf !== 'number') {\n throw new JWTClaimValidationFailed('\"nbf\" claim must be a number', 'nbf', 'invalid');\n }\n if (payload.nbf > now + tolerance) {\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', 'nbf', 'check_failed');\n }\n }\n if (payload.exp !== undefined) {\n if (typeof payload.exp !== 'number') {\n throw new JWTClaimValidationFailed('\"exp\" claim must be a number', 'exp', 'invalid');\n }\n if (payload.exp <= now - tolerance) {\n throw new JWTExpired('\"exp\" claim timestamp check failed', 'exp', 'check_failed');\n }\n }\n if (options.maxTokenAge) {\n const age = now - payload.iat;\n const max = typeof options.maxTokenAge === 'number' ? options.maxTokenAge : secs(options.maxTokenAge);\n if (age - tolerance > max) {\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', 'iat', 'check_failed');\n }\n if (age < 0 - tolerance) {\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed');\n }\n }\n return payload;\n};\n", "import { compactVerify } from '../jws/compact/verify.js';\nimport jwtPayload from '../lib/jwt_claims_set.js';\nimport { JWTInvalid } from '../util/errors.js';\nexport async function jwtVerify(jwt, key, options) {\n var _a;\n const verified = await compactVerify(jwt, key, options);\n if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes('b64')) && verified.protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n const payload = jwtPayload(verified.protectedHeader, verified.payload, options);\n const result = { payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n", "/*\nCopyright 2022 The Dapr Authors\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { importSPKI, jwtVerify } from 'jose'\nimport { IRequest } from 'itty-router'\n\nimport { Environment } from '$lib/environment'\n\nconst tokenHeaderMatch =\n /^(?:Bearer )?([A-Za-z0-9_\\-]+\\.[A-Za-z0-9_\\-]+\\.[A-Za-z0-9_\\-]+)/i\n\nexport async function AuthorizeRequest(\n req: IRequest,\n env: Environment\n): Promise {\n // If \"SKIP_AUTH\" is set, we can allow skipping authorization\n if (env.SKIP_AUTH === 'true') {\n return true\n }\n\n // Ensure we have an Authorization header with a bearer JWT token\n const match = tokenHeaderMatch.exec(req.headers.get('authorization') || '')\n if (!match || !match[1]) {\n return false\n }\n\n // Validate the JWT\n const pk = await importSPKI(env.PUBLIC_KEY, 'EdDSA')\n try {\n await jwtVerify(match[1], pk, {\n issuer: 'dapr.io/cloudflare',\n audience: env.TOKEN_AUDIENCE,\n algorithms: ['EdDSA'],\n // Allow 5 mins of clock skew\n clockTolerance: 300,\n })\n } catch (err) {\n console.error('Failed to validate JWT: ' + err)\n return false\n }\n\n return true\n}\n", "{\n \"private\": true,\n \"name\": \"dapr-cfworkers-client\",\n \"description\": \"Client code for Dapr to interact with Cloudflare Workers\",\n \"version\": \"20230216\",\n \"main\": \"worker.ts\",\n \"scripts\": {\n \"build\": \"esbuild --bundle --minify --outfile=../workers/code/worker.js --format=esm --platform=browser --sourcemap worker.ts\",\n \"start\": \"wrangler dev --local\",\n \"format\": \"prettier --write .\"\n },\n \"author\": \"Dapr authors\",\n \"license\": \"Apache2\",\n \"devDependencies\": {\n \"@cloudflare/workers-types\": \"^4.20230215.0\",\n \"esbuild\": \"^0.17.8\",\n \"prettier\": \"^2.8.4\",\n \"typescript\": \"^4.9.5\",\n \"wrangler\": \"^2.10.0\"\n },\n \"dependencies\": {\n \"itty-router\": \"3.0.11\",\n \"jose\": \"4.12.0\"\n }\n}\n", "/*\nCopyright 2022 The Dapr Authors\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Router, IRequest } from 'itty-router'\n\nimport { Environment } from '$lib/environment'\nimport { AuthorizeRequest } from '$lib/jwt-auth'\n\nimport { version } from './package.json'\n\nconst router = Router()\n // Handle the info endpoint\n .get(\n '/.well-known/dapr/info',\n async (req: IRequest, env: Environment): Promise => {\n const auth = await AuthorizeRequest(req, env)\n if (!auth) {\n return new Response('Unauthorized', { status: 401 })\n }\n\n // Filter all bindings by type\n const queues: string[] = []\n const kv: string[] = []\n const r2: string[] = []\n const all = Object.keys(env)\n for (let i = 0; i < all.length; i++) {\n if (!all[i]) {\n continue\n }\n const obj = env[all[i]]\n if (!obj || typeof obj != 'object' || !obj.constructor) {\n continue\n }\n switch (obj.constructor.name) {\n case 'KvNamespace':\n case 'KVNamespace':\n kv.push(all[i])\n break\n case 'WorkerQueue':\n case 'Queue':\n queues.push(all[i])\n break\n case 'R2Bucket':\n // Note that we currently don't support R2 yet\n r2.push(all[i])\n break\n }\n }\n\n const res = JSON.stringify({\n version,\n queues: queues && queues.length ? queues : undefined,\n kv: kv && kv.length ? kv : undefined,\n r2: r2 && r2.length ? r2 : undefined,\n })\n return new Response(res, {\n headers: {\n 'content-type': 'application/json',\n },\n })\n }\n )\n\n // Retrieve a value from KV\n .get(\n '/kv/:namespace/:key',\n async (req: IRequest, env: Environment): Promise => {\n const { namespace, key, errorRes } = await setupKVRequest(req, env)\n if (errorRes) {\n return errorRes\n }\n\n const val = await namespace!.get(key!, 'stream')\n if (!val) {\n return new Response('', { status: 404 })\n }\n\n return new Response(val, { status: 200 })\n }\n )\n\n // Store a value in KV\n .post(\n '/kv/:namespace/:key',\n async (req: IRequest, env: Environment): Promise => {\n const { namespace, key, errorRes } = await setupKVRequest(req, env)\n if (errorRes) {\n return errorRes\n }\n\n let expirationTtl: number | undefined = undefined\n const reqUrl = new URL(req.url)\n const ttlParam = parseInt(reqUrl.searchParams.get('ttl') || '', 10)\n if (ttlParam > 0) {\n expirationTtl = ttlParam\n }\n await namespace!.put(key!, req.body!, { expirationTtl })\n\n return new Response('', { status: 201 })\n }\n )\n\n // Delete a value from KV\n .delete(\n '/kv/:namespace/:key',\n async (req: IRequest, env: Environment): Promise => {\n const { namespace, key, errorRes } = await setupKVRequest(req, env)\n if (errorRes) {\n return errorRes\n }\n\n await namespace!.delete(key!)\n\n return new Response('', { status: 204 })\n }\n )\n\n // Publish a message in a queue\n .post(\n '/queues/:queue',\n async (req: IRequest, env: Environment): Promise => {\n const { queue, errorRes } = await setupQueueRequest(req, env)\n if (errorRes) {\n return errorRes\n }\n\n let message = await req.text()\n await queue!.send(message)\n return new Response('', { status: 201 })\n }\n )\n\n // Catch-all route to handle 404s\n .all('*', (): Response => {\n return new Response('Not found', { status: 404 })\n })\n\n// Performs the init setps for a KV request. Returns a Response object in case of error.\nasync function setupKVRequest(\n req: IRequest,\n env: Environment\n): Promise<{\n namespace?: KVNamespace\n key?: string\n errorRes?: Response\n}> {\n if (!req?.text || !req.params?.namespace || !req.params?.key) {\n return { errorRes: new Response('Bad request', { status: 400 }) }\n }\n const namespace = env[req.params.namespace] as KVNamespace\n if (\n typeof namespace != 'object' ||\n !['KVNamespace', 'KvNamespace'].includes(namespace?.constructor?.name)\n ) {\n return {\n errorRes: new Response(\n `Worker is not bound to KV '${req.params.kv}'`,\n { status: 412 }\n ),\n }\n }\n\n const auth = await AuthorizeRequest(req, env)\n if (!auth) {\n return { errorRes: new Response('Unauthorized', { status: 401 }) }\n }\n\n return { namespace, key: req.params.key }\n}\n\n// Performs the init setps for a Queue request. Returns a Response object in case of error.\nasync function setupQueueRequest(\n req: IRequest,\n env: Environment\n): Promise<{ queue?: Queue; errorRes?: Response }> {\n if (!req?.text || !req.params?.queue) {\n return { errorRes: new Response('Bad request', { status: 400 }) }\n }\n const queue = env[req.params.queue] as Queue\n if (\n typeof queue != 'object' ||\n !['WorkerQueue', 'Queue'].includes(queue?.constructor?.name)\n ) {\n return {\n errorRes: new Response(\n `Worker is not bound to queue '${req.params.queue}'`,\n { status: 412 }\n ),\n }\n }\n\n const auth = await AuthorizeRequest(req, env)\n if (!auth) {\n return { errorRes: new Response('Unauthorized', { status: 401 }) }\n }\n\n return { queue }\n}\n\nexport default {\n fetch: router.handle,\n}\n"], - "mappings": "AAAA,IAAMA,GAAE,CAAC,CAAC,KAAK,EAAE,GAAG,OAAOC,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,UAAU,IAAI,MAAM,CAAC,EAAE,CAAC,IAAI,CAACC,EAAEC,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,EAAI,OAAO,SAAS,EAC1C,OACI,OAAOU,GAAa,UACpB,CAAC,CAAC,cAAe,aAAa,EAAE,SAASA,GAAW,aAAa,IAAI,EAE9D,CACH,SAAU,IAAI,SACV,8BAA8BV,EAAI,OAAO,MACzC,CAAE,OAAQ,GAAI,CAClB,CACJ,EAGS,MAAME,EAAiBF,EAAKC,CAAG,EAKrC,CAAE,UAAAS,EAAW,IAAKV,EAAI,OAAO,GAAI,EAH7B,CAAE,SAAU,IAAI,SAAS,eAAgB,CAAE,OAAQ,GAAI,CAAC,CAAE,CAIzE,CAGA,eAAemB,GACXnB,EACAC,EACuD,CACvD,GAAI,CAACD,GAAK,MAAQ,CAACA,EAAI,QAAQ,MAC3B,MAAO,CAAE,SAAU,IAAI,SAAS,cAAe,CAAE,OAAQ,GAAI,CAAC,CAAE,EAEpE,IAAMkB,EAAQjB,EAAID,EAAI,OAAO,KAAK,EAClC,OACI,OAAOkB,GAAS,UAChB,CAAC,CAAC,cAAe,OAAO,EAAE,SAASA,GAAO,aAAa,IAAI,EAEpD,CACH,SAAU,IAAI,SACV,iCAAiClB,EAAI,OAAO,SAC5C,CAAE,OAAQ,GAAI,CAClB,CACJ,EAGS,MAAME,EAAiBF,EAAKC,CAAG,EAKrC,CAAE,MAAAiB,CAAM,EAHJ,CAAE,SAAU,IAAI,SAAS,eAAgB,CAAE,OAAQ,GAAI,CAAC,CAAE,CAIzE,CAEA,IAAOG,GAAQ,CACX,MAAOvB,GAAO,MAClB", - "names": ["e", "r", "a", "o", "t", "p", "l", "s", "c", "webcrypto_default", "isCryptoKey", "key", "encoder", "decoder", "MAX_INT32", "concat", "buffers", "size", "acc", "length", "buf", "i", "buffer", "decodeBase64", "encoded", "binary", "bytes", "i", "decode", "input", "decoder", "JOSEError", "message", "_a", "JWTClaimValidationFailed", "claim", "reason", "JWTExpired", "JOSEAlgNotAllowed", "JOSENotSupported", "JWSInvalid", "JOSEError", "JWTInvalid", "JWSSignatureVerificationFailed", "JOSEError", "random_default", "webcrypto_default", "isCloudflareWorkers", "unusable", "name", "prop", "isAlgorithm", "algorithm", "getHashLength", "hash", "getNamedCurve", "alg", "checkUsage", "key", "usages", "expected", "msg", "last", "checkSigCryptoKey", "isCloudflareWorkers", "message", "msg", "actual", "types", "last", "invalid_key_input_default", "withAlg", "alg", "is_key_like_default", "key", "isCryptoKey", "types", "isDisjoint", "headers", "sources", "acc", "header", "parameters", "parameter", "is_disjoint_default", "isObjectLike", "value", "isObject", "input", "proto", "check_key_length_default", "alg", "key", "modulusLength", "findOid", "keyData", "oid", "from", "i", "sub", "value", "index", "getNamedCurve", "JOSENotSupported", "genericImport", "replace", "keyFormat", "pem", "alg", "options", "_a", "_b", "algorithm", "keyUsages", "c", "isPublic", "namedCurve", "webcrypto_default", "err", "isCloudflareWorkers", "fromSPKI", "pem", "alg", "options", "genericImport", "importSPKI", "spki", "alg", "options", "fromSPKI", "symmetricTypeCheck", "alg", "key", "is_key_like_default", "withAlg", "types", "asymmetricTypeCheck", "usage", "checkKeyType", "check_key_type_default", "validateCrit", "Err", "recognizedDefault", "recognizedOption", "protectedHeader", "joseHeader", "input", "recognized", "parameter", "JOSENotSupported", "validate_crit_default", "validateAlgorithms", "option", "algorithms", "s", "validate_algorithms_default", "unprotected", "subtleDsa", "alg", "algorithm", "hash", "isCloudflareWorkers", "JOSENotSupported", "getCryptoKey", "alg", "key", "usage", "isCryptoKey", "checkSigCryptoKey", "invalid_key_input_default", "types", "webcrypto_default", "verify", "alg", "key", "signature", "data", "cryptoKey", "getCryptoKey", "check_key_length_default", "algorithm", "subtleDsa", "webcrypto_default", "verify_default", "flattenedVerify", "jws", "key", "options", "_a", "isObject", "JWSInvalid", "parsedProt", "protectedHeader", "decode", "decoder", "is_disjoint_default", "joseHeader", "extensions", "validate_crit_default", "b64", "alg", "algorithms", "validate_algorithms_default", "JOSEAlgNotAllowed", "resolvedKey", "check_key_type_default", "data", "concat", "encoder", "signature", "verify_default", "JWSSignatureVerificationFailed", "payload", "result", "compactVerify", "jws", "key", "options", "decoder", "JWSInvalid", "protectedHeader", "payload", "signature", "length", "verified", "flattenedVerify", "result", "epoch_default", "date", "REGEX", "secs_default", "str", "matched", "value", "normalizeTyp", "value", "checkAudiencePresence", "audPayload", "audOption", "jwt_claims_set_default", "protectedHeader", "encodedPayload", "options", "typ", "JWTClaimValidationFailed", "payload", "decoder", "isObject", "JWTInvalid", "issuer", "subject", "audience", "tolerance", "secs_default", "currentDate", "now", "epoch_default", "JWTExpired", "age", "max", "jwtVerify", "jwt", "key", "options", "_a", "verified", "compactVerify", "JWTInvalid", "result", "jwt_claims_set_default", "tokenHeaderMatch", "AuthorizeRequest", "req", "env", "match", "pk", "importSPKI", "jwtVerify", "err", "version", "router", "e", "req", "env", "AuthorizeRequest", "queues", "kv", "r2", "all", "obj", "res", "version", "namespace", "key", "errorRes", "setupKVRequest", "val", "expirationTtl", "reqUrl", "ttlParam", "queue", "setupQueueRequest", "message", "worker_default"] + "sources": ["../../worker-src/node_modules/itty-router/dist/itty-router.mjs", "../../worker-src/node_modules/jose/dist/browser/runtime/webcrypto.js", "../../worker-src/node_modules/jose/dist/browser/lib/buffer_utils.js", "../../worker-src/node_modules/jose/dist/browser/runtime/base64url.js", "../../worker-src/node_modules/jose/dist/browser/util/errors.js", "../../worker-src/node_modules/jose/dist/browser/runtime/random.js", "../../worker-src/node_modules/jose/dist/browser/lib/crypto_key.js", "../../worker-src/node_modules/jose/dist/browser/lib/invalid_key_input.js", "../../worker-src/node_modules/jose/dist/browser/runtime/is_key_like.js", "../../worker-src/node_modules/jose/dist/browser/lib/is_disjoint.js", "../../worker-src/node_modules/jose/dist/browser/lib/is_object.js", "../../worker-src/node_modules/jose/dist/browser/runtime/check_key_length.js", "../../worker-src/node_modules/jose/dist/browser/runtime/asn1.js", "../../worker-src/node_modules/jose/dist/browser/key/import.js", "../../worker-src/node_modules/jose/dist/browser/lib/check_key_type.js", "../../worker-src/node_modules/jose/dist/browser/lib/validate_crit.js", "../../worker-src/node_modules/jose/dist/browser/lib/validate_algorithms.js", "../../worker-src/node_modules/jose/dist/browser/jwe/flattened/encrypt.js", "../../worker-src/node_modules/jose/dist/browser/runtime/subtle_dsa.js", "../../worker-src/node_modules/jose/dist/browser/runtime/get_sign_verify_key.js", "../../worker-src/node_modules/jose/dist/browser/runtime/verify.js", "../../worker-src/node_modules/jose/dist/browser/jws/flattened/verify.js", "../../worker-src/node_modules/jose/dist/browser/jws/compact/verify.js", "../../worker-src/node_modules/jose/dist/browser/lib/epoch.js", "../../worker-src/node_modules/jose/dist/browser/lib/secs.js", "../../worker-src/node_modules/jose/dist/browser/lib/jwt_claims_set.js", "../../worker-src/node_modules/jose/dist/browser/jwt/verify.js", "../../worker-src/lib/jwt-auth.ts", "../../worker-src/package.json", "../../worker-src/worker.ts"], + "sourcesContent": ["const e=({base:e=\"\",routes:r=[]}={})=>({__proto__:new Proxy({},{get:(a,o,t)=>(a,...p)=>r.push([o.toUpperCase(),RegExp(`^${(e+a).replace(/(\\/?)\\*/g,\"($1.*)?\").replace(/(\\/$)|((?<=\\/)\\/)/,\"\").replace(/(:(\\w+)\\+)/,\"(?<$2>.*)\").replace(/:(\\w+)(\\?)?(\\.)?/g,\"$2(?<$1>[^/]+)$2$3\").replace(/\\.(?=[\\w(])/,\"\\\\.\").replace(/\\)\\.\\?\\(([^\\[]+)\\[\\^/g,\"?)\\\\.?($1(?<=\\\\.)[^\\\\.\")}/*$`),p])&&t}),routes:r,async handle(e,...a){let o,t,p=new URL(e.url),l=e.query={};for(let[e,r]of p.searchParams)l[e]=void 0===l[e]?r:[l[e],r].flat();for(let[l,s,c]of r)if((l===e.method||\"ALL\"===l)&&(t=p.pathname.match(s))){e.params=t.groups||{};for(let r of c)if(void 0!==(o=await r(e.proxy||e,...a)))return o}}});export{e as Router};\n", "export default crypto;\nexport const isCryptoKey = (key) => key instanceof CryptoKey;\n", "import digest from '../runtime/digest.js';\nexport const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0);\n const buf = new Uint8Array(size);\n let i = 0;\n buffers.forEach((buffer) => {\n buf.set(buffer, i);\n i += buffer.length;\n });\n return buf;\n}\nexport function p2s(alg, p2sInput) {\n return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32) {\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n }\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n const high = Math.floor(value / MAX_INT32);\n const low = value % MAX_INT32;\n const buf = new Uint8Array(8);\n writeUInt32BE(buf, high, 0);\n writeUInt32BE(buf, low, 4);\n return buf;\n}\nexport function uint32be(value) {\n const buf = new Uint8Array(4);\n writeUInt32BE(buf, value);\n return buf;\n}\nexport function lengthAndInput(input) {\n return concat(uint32be(input.length), input);\n}\nexport async function concatKdf(secret, bits, value) {\n const iterations = Math.ceil((bits >> 3) / 32);\n const res = new Uint8Array(iterations * 32);\n for (let iter = 0; iter < iterations; iter++) {\n const buf = new Uint8Array(4 + secret.length + value.length);\n buf.set(uint32be(iter + 1));\n buf.set(secret, 4);\n buf.set(value, 4 + secret.length);\n res.set(await digest('sha256', buf), iter * 32);\n }\n return res.slice(0, bits >> 3);\n}\n", "import { encoder, decoder } from '../lib/buffer_utils.js';\nexport const encodeBase64 = (input) => {\n let unencoded = input;\n if (typeof unencoded === 'string') {\n unencoded = encoder.encode(unencoded);\n }\n const CHUNK_SIZE = 0x8000;\n const arr = [];\n for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join(''));\n};\nexport const encode = (input) => {\n return encodeBase64(input).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n};\nexport const decodeBase64 = (encoded) => {\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n};\nexport const decode = (input) => {\n let encoded = input;\n if (encoded instanceof Uint8Array) {\n encoded = decoder.decode(encoded);\n }\n encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\\s/g, '');\n try {\n return decodeBase64(encoded);\n }\n catch (_a) {\n throw new TypeError('The input to be decoded is not correctly encoded.');\n }\n};\n", "export class JOSEError extends Error {\n static get code() {\n return 'ERR_JOSE_GENERIC';\n }\n constructor(message) {\n var _a;\n super(message);\n this.code = 'ERR_JOSE_GENERIC';\n this.name = this.constructor.name;\n (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor);\n }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n static get code() {\n return 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n }\n constructor(message, claim = 'unspecified', reason = 'unspecified') {\n super(message);\n this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n this.claim = claim;\n this.reason = reason;\n }\n}\nexport class JWTExpired extends JOSEError {\n static get code() {\n return 'ERR_JWT_EXPIRED';\n }\n constructor(message, claim = 'unspecified', reason = 'unspecified') {\n super(message);\n this.code = 'ERR_JWT_EXPIRED';\n this.claim = claim;\n this.reason = reason;\n }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n }\n static get code() {\n return 'ERR_JOSE_ALG_NOT_ALLOWED';\n }\n}\nexport class JOSENotSupported extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JOSE_NOT_SUPPORTED';\n }\n static get code() {\n return 'ERR_JOSE_NOT_SUPPORTED';\n }\n}\nexport class JWEDecryptionFailed extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWE_DECRYPTION_FAILED';\n this.message = 'decryption operation failed';\n }\n static get code() {\n return 'ERR_JWE_DECRYPTION_FAILED';\n }\n}\nexport class JWEInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWE_INVALID';\n }\n static get code() {\n return 'ERR_JWE_INVALID';\n }\n}\nexport class JWSInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWS_INVALID';\n }\n static get code() {\n return 'ERR_JWS_INVALID';\n }\n}\nexport class JWTInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWT_INVALID';\n }\n static get code() {\n return 'ERR_JWT_INVALID';\n }\n}\nexport class JWKInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWK_INVALID';\n }\n static get code() {\n return 'ERR_JWK_INVALID';\n }\n}\nexport class JWKSInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWKS_INVALID';\n }\n static get code() {\n return 'ERR_JWKS_INVALID';\n }\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWKS_NO_MATCHING_KEY';\n this.message = 'no applicable key found in the JSON Web Key Set';\n }\n static get code() {\n return 'ERR_JWKS_NO_MATCHING_KEY';\n }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n this.message = 'multiple matching keys found in the JSON Web Key Set';\n }\n static get code() {\n return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n }\n}\nSymbol.asyncIterator;\nexport class JWKSTimeout extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWKS_TIMEOUT';\n this.message = 'request timed out';\n }\n static get code() {\n return 'ERR_JWKS_TIMEOUT';\n }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n this.message = 'signature verification failed';\n }\n static get code() {\n return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n }\n}\n", "import crypto from './webcrypto.js';\nexport default crypto.getRandomValues.bind(crypto);\n", "function unusable(name, prop = 'algorithm.name') {\n return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\n}\nfunction isAlgorithm(algorithm, name) {\n return algorithm.name === name;\n}\nfunction getHashLength(hash) {\n return parseInt(hash.name.slice(4), 10);\n}\nfunction getNamedCurve(alg) {\n switch (alg) {\n case 'ES256':\n return 'P-256';\n case 'ES384':\n return 'P-384';\n case 'ES512':\n return 'P-521';\n default:\n throw new Error('unreachable');\n }\n}\nfunction checkUsage(key, usages) {\n if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {\n let msg = 'CryptoKey does not support this operation, its usages must include ';\n if (usages.length > 2) {\n const last = usages.pop();\n msg += `one of ${usages.join(', ')}, or ${last}.`;\n }\n else if (usages.length === 2) {\n msg += `one of ${usages[0]} or ${usages[1]}.`;\n }\n else {\n msg += `${usages[0]}.`;\n }\n throw new TypeError(msg);\n }\n}\nexport function checkSigCryptoKey(key, alg, ...usages) {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512': {\n if (!isAlgorithm(key.algorithm, 'HMAC'))\n throw unusable('HMAC');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'RS256':\n case 'RS384':\n case 'RS512': {\n if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))\n throw unusable('RSASSA-PKCS1-v1_5');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'PS256':\n case 'PS384':\n case 'PS512': {\n if (!isAlgorithm(key.algorithm, 'RSA-PSS'))\n throw unusable('RSA-PSS');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'EdDSA': {\n if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {\n throw unusable('Ed25519 or Ed448');\n }\n break;\n }\n case 'ES256':\n case 'ES384':\n case 'ES512': {\n if (!isAlgorithm(key.algorithm, 'ECDSA'))\n throw unusable('ECDSA');\n const expected = getNamedCurve(alg);\n const actual = key.algorithm.namedCurve;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.namedCurve');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usages);\n}\nexport function checkEncCryptoKey(key, alg, ...usages) {\n switch (alg) {\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM': {\n if (!isAlgorithm(key.algorithm, 'AES-GCM'))\n throw unusable('AES-GCM');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n if (!isAlgorithm(key.algorithm, 'AES-KW'))\n throw unusable('AES-KW');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'ECDH': {\n switch (key.algorithm.name) {\n case 'ECDH':\n case 'X25519':\n case 'X448':\n break;\n default:\n throw unusable('ECDH, X25519, or X448');\n }\n break;\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW':\n if (!isAlgorithm(key.algorithm, 'PBKDF2'))\n throw unusable('PBKDF2');\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))\n throw unusable('RSA-OAEP');\n const expected = parseInt(alg.slice(9), 10) || 1;\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usages);\n}\n", "function message(msg, actual, ...types) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(', ')}, or ${last}.`;\n }\n else if (types.length === 2) {\n msg += `one of type ${types[0]} or ${types[1]}.`;\n }\n else {\n msg += `of type ${types[0]}.`;\n }\n if (actual == null) {\n msg += ` Received ${actual}`;\n }\n else if (typeof actual === 'function' && actual.name) {\n msg += ` Received function ${actual.name}`;\n }\n else if (typeof actual === 'object' && actual != null) {\n if (actual.constructor && actual.constructor.name) {\n msg += ` Received an instance of ${actual.constructor.name}`;\n }\n }\n return msg;\n}\nexport default (actual, ...types) => {\n return message('Key must be ', actual, ...types);\n};\nexport function withAlg(alg, actual, ...types) {\n return message(`Key for the ${alg} algorithm must be `, actual, ...types);\n}\n", "import { isCryptoKey } from './webcrypto.js';\nexport default (key) => {\n return isCryptoKey(key);\n};\nexport const types = ['CryptoKey'];\n", "const isDisjoint = (...headers) => {\n const sources = headers.filter(Boolean);\n if (sources.length === 0 || sources.length === 1) {\n return true;\n }\n let acc;\n for (const header of sources) {\n const parameters = Object.keys(header);\n if (!acc || acc.size === 0) {\n acc = new Set(parameters);\n continue;\n }\n for (const parameter of parameters) {\n if (acc.has(parameter)) {\n return false;\n }\n acc.add(parameter);\n }\n }\n return true;\n};\nexport default isDisjoint;\n", "function isObjectLike(value) {\n return typeof value === 'object' && value !== null;\n}\nexport default function isObject(input) {\n if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(input) === null) {\n return true;\n }\n let proto = input;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(input) === proto;\n}\n", "export default (alg, key) => {\n if (alg.startsWith('RS') || alg.startsWith('PS')) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n }\n }\n};\n", "import crypto, { isCryptoKey } from './webcrypto.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { encodeBase64, decodeBase64 } from './base64url.js';\nimport formatPEM from '../lib/format_pem.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { types } from './is_key_like.js';\nconst genericExport = async (keyType, keyFormat, key) => {\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, ...types));\n }\n if (!key.extractable) {\n throw new TypeError('CryptoKey is not extractable');\n }\n if (key.type !== keyType) {\n throw new TypeError(`key is not a ${keyType} key`);\n }\n return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);\n};\nexport const toSPKI = (key) => {\n return genericExport('public', 'spki', key);\n};\nexport const toPKCS8 = (key) => {\n return genericExport('private', 'pkcs8', key);\n};\nconst findOid = (keyData, oid, from = 0) => {\n if (from === 0) {\n oid.unshift(oid.length);\n oid.unshift(0x06);\n }\n let i = keyData.indexOf(oid[0], from);\n if (i === -1)\n return false;\n const sub = keyData.subarray(i, i + oid.length);\n if (sub.length !== oid.length)\n return false;\n return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1);\n};\nconst getNamedCurve = (keyData) => {\n switch (true) {\n case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]):\n return 'P-256';\n case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]):\n return 'P-384';\n case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]):\n return 'P-521';\n case findOid(keyData, [0x2b, 0x65, 0x6e]):\n return 'X25519';\n case findOid(keyData, [0x2b, 0x65, 0x6f]):\n return 'X448';\n case findOid(keyData, [0x2b, 0x65, 0x70]):\n return 'Ed25519';\n case findOid(keyData, [0x2b, 0x65, 0x71]):\n return 'Ed448';\n default:\n throw new JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type');\n }\n};\nconst genericImport = async (replace, keyFormat, pem, alg, options) => {\n var _a;\n let algorithm;\n let keyUsages;\n const keyData = new Uint8Array(atob(pem.replace(replace, ''))\n .split('')\n .map((c) => c.charCodeAt(0)));\n const isPublic = keyFormat === 'spki';\n switch (alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,\n };\n keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'];\n break;\n case 'ES256':\n algorithm = { name: 'ECDSA', namedCurve: 'P-256' };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'ES384':\n algorithm = { name: 'ECDSA', namedCurve: 'P-384' };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'ES512':\n algorithm = { name: 'ECDSA', namedCurve: 'P-521' };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n const namedCurve = getNamedCurve(keyData);\n algorithm = namedCurve.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: namedCurve };\n keyUsages = isPublic ? [] : ['deriveBits'];\n break;\n }\n case 'EdDSA':\n algorithm = { name: getNamedCurve(keyData) };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported \"alg\" (Algorithm) value');\n }\n return crypto.subtle.importKey(keyFormat, keyData, algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages);\n};\nexport const fromPKCS8 = (pem, alg, options) => {\n return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\\s)/g, 'pkcs8', pem, alg, options);\n};\nexport const fromSPKI = (pem, alg, options) => {\n return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\\s)/g, 'spki', pem, alg, options);\n};\nfunction getElement(seq) {\n let result = [];\n let next = 0;\n while (next < seq.length) {\n let nextPart = parseElement(seq.subarray(next));\n result.push(nextPart);\n next += nextPart.byteLength;\n }\n return result;\n}\nfunction parseElement(bytes) {\n let position = 0;\n let tag = bytes[0] & 0x1f;\n position++;\n if (tag === 0x1f) {\n tag = 0;\n while (bytes[position] >= 0x80) {\n tag = tag * 128 + bytes[position] - 0x80;\n position++;\n }\n tag = tag * 128 + bytes[position] - 0x80;\n position++;\n }\n let length = 0;\n if (bytes[position] < 0x80) {\n length = bytes[position];\n position++;\n }\n else if (length === 0x80) {\n length = 0;\n while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) {\n if (length > bytes.byteLength) {\n throw new TypeError('invalid indefinite form length');\n }\n length++;\n }\n const byteLength = position + length + 2;\n return {\n byteLength,\n contents: bytes.subarray(position, position + length),\n raw: bytes.subarray(0, byteLength),\n };\n }\n else {\n let numberOfDigits = bytes[position] & 0x7f;\n position++;\n length = 0;\n for (let i = 0; i < numberOfDigits; i++) {\n length = length * 256 + bytes[position];\n position++;\n }\n }\n const byteLength = position + length;\n return {\n byteLength,\n contents: bytes.subarray(position, byteLength),\n raw: bytes.subarray(0, byteLength),\n };\n}\nfunction spkiFromX509(buf) {\n const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents);\n return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw);\n}\nfunction getSPKI(x509) {\n const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\\s)/g, '');\n const raw = decodeBase64(pem);\n return formatPEM(spkiFromX509(raw), 'PUBLIC KEY');\n}\nexport const fromX509 = (pem, alg, options) => {\n let spki;\n try {\n spki = getSPKI(pem);\n }\n catch (cause) {\n throw new TypeError('failed to parse the X.509 certificate', { cause });\n }\n return fromSPKI(spki, alg, options);\n};\n", "import { decode as decodeBase64URL } from '../runtime/base64url.js';\nimport { fromSPKI, fromPKCS8, fromX509 } from '../runtime/asn1.js';\nimport asKeyObject from '../runtime/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport isObject from '../lib/is_object.js';\nexport async function importSPKI(spki, alg, options) {\n if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n throw new TypeError('\"spki\" must be SPKI formatted string');\n }\n return fromSPKI(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n throw new TypeError('\"x509\" must be X.509 formatted string');\n }\n return fromX509(x509, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n }\n return fromPKCS8(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg, octAsKeyObject) {\n var _a;\n if (!isObject(jwk)) {\n throw new TypeError('JWK must be an object');\n }\n alg || (alg = jwk.alg);\n switch (jwk.kty) {\n case 'oct':\n if (typeof jwk.k !== 'string' || !jwk.k) {\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n }\n octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : (octAsKeyObject = jwk.ext !== true);\n if (octAsKeyObject) {\n return asKeyObject({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false });\n }\n return decodeBase64URL(jwk.k);\n case 'RSA':\n if (jwk.oth !== undefined) {\n throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n }\n case 'EC':\n case 'OKP':\n return asKeyObject({ ...jwk, alg });\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\n", "import { withAlg as invalidKeyInput } from './invalid_key_input.js';\nimport isKeyLike, { types } from '../runtime/is_key_like.js';\nconst symmetricTypeCheck = (alg, key) => {\n if (key instanceof Uint8Array)\n return;\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array'));\n }\n if (key.type !== 'secret') {\n throw new TypeError(`${types.join(' or ')} instances for symmetric algorithms must be of type \"secret\"`);\n }\n};\nconst asymmetricTypeCheck = (alg, key, usage) => {\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, ...types));\n }\n if (key.type === 'secret') {\n throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithms must not be of type \"secret\"`);\n }\n if (usage === 'sign' && key.type === 'public') {\n throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm signing must be of type \"private\"`);\n }\n if (usage === 'decrypt' && key.type === 'public') {\n throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm decryption must be of type \"private\"`);\n }\n if (key.algorithm && usage === 'verify' && key.type === 'private') {\n throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm verifying must be of type \"public\"`);\n }\n if (key.algorithm && usage === 'encrypt' && key.type === 'private') {\n throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm encryption must be of type \"public\"`);\n }\n};\nconst checkKeyType = (alg, key, usage) => {\n const symmetric = alg.startsWith('HS') ||\n alg === 'dir' ||\n alg.startsWith('PBES2') ||\n /^A\\d{3}(?:GCM)?KW$/.test(alg);\n if (symmetric) {\n symmetricTypeCheck(alg, key);\n }\n else {\n asymmetricTypeCheck(alg, key, usage);\n }\n};\nexport default checkKeyType;\n", "import { JOSENotSupported } from '../util/errors.js';\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== undefined && protectedHeader.crit === undefined) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n }\n if (!protectedHeader || protectedHeader.crit === undefined) {\n return new Set();\n }\n if (!Array.isArray(protectedHeader.crit) ||\n protectedHeader.crit.length === 0 ||\n protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n }\n let recognized;\n if (recognizedOption !== undefined) {\n recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);\n }\n else {\n recognized = recognizedDefault;\n }\n for (const parameter of protectedHeader.crit) {\n if (!recognized.has(parameter)) {\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n }\n if (joseHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n }\n else if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n }\n return new Set(protectedHeader.crit);\n}\nexport default validateCrit;\n", "const validateAlgorithms = (option, algorithms) => {\n if (algorithms !== undefined &&\n (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n }\n if (!algorithms) {\n return undefined;\n }\n return new Set(algorithms);\n};\nexport default validateAlgorithms;\n", "import { encode as base64url } from '../../runtime/base64url.js';\nimport encrypt from '../../runtime/encrypt.js';\nimport { deflate } from '../../runtime/zlib.js';\nimport generateIv from '../../lib/iv.js';\nimport encryptKeyManagement from '../../lib/encrypt_key_management.js';\nimport { JOSENotSupported, JWEInvalid } from '../../util/errors.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport { encoder, decoder, concat } from '../../lib/buffer_utils.js';\nimport validateCrit from '../../lib/validate_crit.js';\nexport const unprotected = Symbol();\nexport class FlattenedEncrypt {\n constructor(plaintext) {\n if (!(plaintext instanceof Uint8Array)) {\n throw new TypeError('plaintext must be an instance of Uint8Array');\n }\n this._plaintext = plaintext;\n }\n setKeyManagementParameters(parameters) {\n if (this._keyManagementParameters) {\n throw new TypeError('setKeyManagementParameters can only be called once');\n }\n this._keyManagementParameters = parameters;\n return this;\n }\n setProtectedHeader(protectedHeader) {\n if (this._protectedHeader) {\n throw new TypeError('setProtectedHeader can only be called once');\n }\n this._protectedHeader = protectedHeader;\n return this;\n }\n setSharedUnprotectedHeader(sharedUnprotectedHeader) {\n if (this._sharedUnprotectedHeader) {\n throw new TypeError('setSharedUnprotectedHeader can only be called once');\n }\n this._sharedUnprotectedHeader = sharedUnprotectedHeader;\n return this;\n }\n setUnprotectedHeader(unprotectedHeader) {\n if (this._unprotectedHeader) {\n throw new TypeError('setUnprotectedHeader can only be called once');\n }\n this._unprotectedHeader = unprotectedHeader;\n return this;\n }\n setAdditionalAuthenticatedData(aad) {\n this._aad = aad;\n return this;\n }\n setContentEncryptionKey(cek) {\n if (this._cek) {\n throw new TypeError('setContentEncryptionKey can only be called once');\n }\n this._cek = cek;\n return this;\n }\n setInitializationVector(iv) {\n if (this._iv) {\n throw new TypeError('setInitializationVector can only be called once');\n }\n this._iv = iv;\n return this;\n }\n async encrypt(key, options) {\n if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {\n throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');\n }\n if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) {\n throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...this._protectedHeader,\n ...this._unprotectedHeader,\n ...this._sharedUnprotectedHeader,\n };\n validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);\n if (joseHeader.zip !== undefined) {\n if (!this._protectedHeader || !this._protectedHeader.zip) {\n throw new JWEInvalid('JWE \"zip\" (Compression Algorithm) Header MUST be integrity protected');\n }\n if (joseHeader.zip !== 'DEF') {\n throw new JOSENotSupported('Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value');\n }\n }\n const { alg, enc } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWEInvalid('JWE \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n if (typeof enc !== 'string' || !enc) {\n throw new JWEInvalid('JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid');\n }\n let encryptedKey;\n if (alg === 'dir') {\n if (this._cek) {\n throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption');\n }\n }\n else if (alg === 'ECDH-ES') {\n if (this._cek) {\n throw new TypeError('setContentEncryptionKey cannot be called when using Direct Key Agreement');\n }\n }\n let cek;\n {\n let parameters;\n ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, key, this._cek, this._keyManagementParameters));\n if (parameters) {\n if (options && unprotected in options) {\n if (!this._unprotectedHeader) {\n this.setUnprotectedHeader(parameters);\n }\n else {\n this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters };\n }\n }\n else {\n if (!this._protectedHeader) {\n this.setProtectedHeader(parameters);\n }\n else {\n this._protectedHeader = { ...this._protectedHeader, ...parameters };\n }\n }\n }\n }\n this._iv || (this._iv = generateIv(enc));\n let additionalData;\n let protectedHeader;\n let aadMember;\n if (this._protectedHeader) {\n protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));\n }\n else {\n protectedHeader = encoder.encode('');\n }\n if (this._aad) {\n aadMember = base64url(this._aad);\n additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember));\n }\n else {\n additionalData = protectedHeader;\n }\n let ciphertext;\n let tag;\n if (joseHeader.zip === 'DEF') {\n const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || deflate)(this._plaintext);\n ({ ciphertext, tag } = await encrypt(enc, deflated, cek, this._iv, additionalData));\n }\n else {\n ;\n ({ ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData));\n }\n const jwe = {\n ciphertext: base64url(ciphertext),\n iv: base64url(this._iv),\n tag: base64url(tag),\n };\n if (encryptedKey) {\n jwe.encrypted_key = base64url(encryptedKey);\n }\n if (aadMember) {\n jwe.aad = aadMember;\n }\n if (this._protectedHeader) {\n jwe.protected = decoder.decode(protectedHeader);\n }\n if (this._sharedUnprotectedHeader) {\n jwe.unprotected = this._sharedUnprotectedHeader;\n }\n if (this._unprotectedHeader) {\n jwe.header = this._unprotectedHeader;\n }\n return jwe;\n }\n}\n", "import { JOSENotSupported } from '../util/errors.js';\nexport default function subtleDsa(alg, algorithm) {\n const hash = `SHA-${alg.slice(-3)}`;\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { hash, name: 'HMAC' };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { hash, name: 'RSA-PSS', saltLength: alg.slice(-3) >> 3 };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { hash, name: 'RSASSA-PKCS1-v1_5' };\n case 'ES256':\n case 'ES384':\n case 'ES512':\n return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };\n case 'EdDSA':\n return { name: algorithm.name };\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n}\n", "import crypto, { isCryptoKey } from './webcrypto.js';\nimport { checkSigCryptoKey } from '../lib/crypto_key.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nexport default function getCryptoKey(alg, key, usage) {\n if (isCryptoKey(key)) {\n checkSigCryptoKey(key, alg, usage);\n return key;\n }\n if (key instanceof Uint8Array) {\n if (!alg.startsWith('HS')) {\n throw new TypeError(invalidKeyInput(key, ...types));\n }\n return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);\n }\n throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));\n}\n", "import subtleAlgorithm from './subtle_dsa.js';\nimport crypto from './webcrypto.js';\nimport checkKeyLength from './check_key_length.js';\nimport getVerifyKey from './get_sign_verify_key.js';\nconst verify = async (alg, key, signature, data) => {\n const cryptoKey = await getVerifyKey(alg, key, 'verify');\n checkKeyLength(alg, cryptoKey);\n const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);\n try {\n return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);\n }\n catch (_a) {\n return false;\n }\n};\nexport default verify;\n", "import { decode as base64url } from '../../runtime/base64url.js';\nimport verify from '../../runtime/verify.js';\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';\nimport { concat, encoder, decoder } from '../../lib/buffer_utils.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport isObject from '../../lib/is_object.js';\nimport checkKeyType from '../../lib/check_key_type.js';\nimport validateCrit from '../../lib/validate_crit.js';\nimport validateAlgorithms from '../../lib/validate_algorithms.js';\nexport async function flattenedVerify(jws, key, options) {\n var _a;\n if (!isObject(jws)) {\n throw new JWSInvalid('Flattened JWS must be an object');\n }\n if (jws.protected === undefined && jws.header === undefined) {\n throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n }\n if (jws.protected !== undefined && typeof jws.protected !== 'string') {\n throw new JWSInvalid('JWS Protected Header incorrect type');\n }\n if (jws.payload === undefined) {\n throw new JWSInvalid('JWS Payload missing');\n }\n if (typeof jws.signature !== 'string') {\n throw new JWSInvalid('JWS Signature missing or incorrect type');\n }\n if (jws.header !== undefined && !isObject(jws.header)) {\n throw new JWSInvalid('JWS Unprotected Header incorrect type');\n }\n let parsedProt = {};\n if (jws.protected) {\n try {\n const protectedHeader = base64url(jws.protected);\n parsedProt = JSON.parse(decoder.decode(protectedHeader));\n }\n catch (_b) {\n throw new JWSInvalid('JWS Protected Header is invalid');\n }\n }\n if (!isDisjoint(parsedProt, jws.header)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...parsedProt,\n ...jws.header,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = parsedProt.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n const algorithms = options && validateAlgorithms('algorithms', options.algorithms);\n if (algorithms && !algorithms.has(alg)) {\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter not allowed');\n }\n if (b64) {\n if (typeof jws.payload !== 'string') {\n throw new JWSInvalid('JWS Payload must be a string');\n }\n }\n else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {\n throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');\n }\n let resolvedKey = false;\n if (typeof key === 'function') {\n key = await key(parsedProt, jws);\n resolvedKey = true;\n }\n checkKeyType(alg, key, 'verify');\n const data = concat(encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload);\n const signature = base64url(jws.signature);\n const verified = await verify(alg, key, signature, data);\n if (!verified) {\n throw new JWSSignatureVerificationFailed();\n }\n let payload;\n if (b64) {\n payload = base64url(jws.payload);\n }\n else if (typeof jws.payload === 'string') {\n payload = encoder.encode(jws.payload);\n }\n else {\n payload = jws.payload;\n }\n const result = { payload };\n if (jws.protected !== undefined) {\n result.protectedHeader = parsedProt;\n }\n if (jws.header !== undefined) {\n result.unprotectedHeader = jws.header;\n }\n if (resolvedKey) {\n return { ...result, key };\n }\n return result;\n}\n", "import { flattenedVerify } from '../flattened/verify.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactVerify(jws, key, options) {\n if (jws instanceof Uint8Array) {\n jws = decoder.decode(jws);\n }\n if (typeof jws !== 'string') {\n throw new JWSInvalid('Compact JWS must be a string or Uint8Array');\n }\n const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');\n if (length !== 3) {\n throw new JWSInvalid('Invalid Compact JWS');\n }\n const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);\n const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n", "export default (date) => Math.floor(date.getTime() / 1000);\n", "const minute = 60;\nconst hour = minute * 60;\nconst day = hour * 24;\nconst week = day * 7;\nconst year = day * 365.25;\nconst REGEX = /^(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;\nexport default (str) => {\n const matched = REGEX.exec(str);\n if (!matched) {\n throw new TypeError('Invalid time period format');\n }\n const value = parseFloat(matched[1]);\n const unit = matched[2].toLowerCase();\n switch (unit) {\n case 'sec':\n case 'secs':\n case 'second':\n case 'seconds':\n case 's':\n return Math.round(value);\n case 'minute':\n case 'minutes':\n case 'min':\n case 'mins':\n case 'm':\n return Math.round(value * minute);\n case 'hour':\n case 'hours':\n case 'hr':\n case 'hrs':\n case 'h':\n return Math.round(value * hour);\n case 'day':\n case 'days':\n case 'd':\n return Math.round(value * day);\n case 'week':\n case 'weeks':\n case 'w':\n return Math.round(value * week);\n default:\n return Math.round(value * year);\n }\n};\n", "import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';\nimport { decoder } from './buffer_utils.js';\nimport epoch from './epoch.js';\nimport secs from './secs.js';\nimport isObject from './is_object.js';\nconst normalizeTyp = (value) => value.toLowerCase().replace(/^application\\//, '');\nconst checkAudiencePresence = (audPayload, audOption) => {\n if (typeof audPayload === 'string') {\n return audOption.includes(audPayload);\n }\n if (Array.isArray(audPayload)) {\n return audOption.some(Set.prototype.has.bind(new Set(audPayload)));\n }\n return false;\n};\nexport default (protectedHeader, encodedPayload, options = {}) => {\n const { typ } = options;\n if (typ &&\n (typeof protectedHeader.typ !== 'string' ||\n normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', 'typ', 'check_failed');\n }\n let payload;\n try {\n payload = JSON.parse(decoder.decode(encodedPayload));\n }\n catch (_a) {\n }\n if (!isObject(payload)) {\n throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');\n }\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;\n if (maxTokenAge !== undefined)\n requiredClaims.push('iat');\n if (audience !== undefined)\n requiredClaims.push('aud');\n if (subject !== undefined)\n requiredClaims.push('sub');\n if (issuer !== undefined)\n requiredClaims.push('iss');\n for (const claim of new Set(requiredClaims.reverse())) {\n if (!(claim in payload)) {\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, claim, 'missing');\n }\n }\n if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {\n throw new JWTClaimValidationFailed('unexpected \"iss\" claim value', 'iss', 'check_failed');\n }\n if (subject && payload.sub !== subject) {\n throw new JWTClaimValidationFailed('unexpected \"sub\" claim value', 'sub', 'check_failed');\n }\n if (audience &&\n !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {\n throw new JWTClaimValidationFailed('unexpected \"aud\" claim value', 'aud', 'check_failed');\n }\n let tolerance;\n switch (typeof options.clockTolerance) {\n case 'string':\n tolerance = secs(options.clockTolerance);\n break;\n case 'number':\n tolerance = options.clockTolerance;\n break;\n case 'undefined':\n tolerance = 0;\n break;\n default:\n throw new TypeError('Invalid clockTolerance option type');\n }\n const { currentDate } = options;\n const now = epoch(currentDate || new Date());\n if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {\n throw new JWTClaimValidationFailed('\"iat\" claim must be a number', 'iat', 'invalid');\n }\n if (payload.nbf !== undefined) {\n if (typeof payload.nbf !== 'number') {\n throw new JWTClaimValidationFailed('\"nbf\" claim must be a number', 'nbf', 'invalid');\n }\n if (payload.nbf > now + tolerance) {\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', 'nbf', 'check_failed');\n }\n }\n if (payload.exp !== undefined) {\n if (typeof payload.exp !== 'number') {\n throw new JWTClaimValidationFailed('\"exp\" claim must be a number', 'exp', 'invalid');\n }\n if (payload.exp <= now - tolerance) {\n throw new JWTExpired('\"exp\" claim timestamp check failed', 'exp', 'check_failed');\n }\n }\n if (maxTokenAge) {\n const age = now - payload.iat;\n const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);\n if (age - tolerance > max) {\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', 'iat', 'check_failed');\n }\n if (age < 0 - tolerance) {\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed');\n }\n }\n return payload;\n};\n", "import { compactVerify } from '../jws/compact/verify.js';\nimport jwtPayload from '../lib/jwt_claims_set.js';\nimport { JWTInvalid } from '../util/errors.js';\nexport async function jwtVerify(jwt, key, options) {\n var _a;\n const verified = await compactVerify(jwt, key, options);\n if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes('b64')) && verified.protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n const payload = jwtPayload(verified.protectedHeader, verified.payload, options);\n const result = { payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n", "/*\nCopyright 2022 The Dapr Authors\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { importSPKI, jwtVerify } from 'jose'\nimport { IRequest } from 'itty-router'\n\nimport { Environment } from '$lib/environment'\n\nconst tokenHeaderMatch =\n /^(?:Bearer )?([A-Za-z0-9_\\-]+\\.[A-Za-z0-9_\\-]+\\.[A-Za-z0-9_\\-]+)/i\n\nexport async function AuthorizeRequest(\n req: IRequest,\n env: Environment\n): Promise {\n // If \"SKIP_AUTH\" is set, we can allow skipping authorization\n if (env.SKIP_AUTH === 'true') {\n return true\n }\n\n // Ensure we have an Authorization header with a bearer JWT token\n const match = tokenHeaderMatch.exec(req.headers.get('authorization') || '')\n if (!match || !match[1]) {\n return false\n }\n\n // Validate the JWT\n const pk = await importSPKI(env.PUBLIC_KEY, 'EdDSA')\n try {\n await jwtVerify(match[1], pk, {\n issuer: 'dapr.io/cloudflare',\n audience: env.TOKEN_AUDIENCE,\n algorithms: ['EdDSA'],\n // Allow 5 mins of clock skew\n clockTolerance: 300,\n })\n } catch (err) {\n console.error('Failed to validate JWT: ' + err)\n return false\n }\n\n return true\n}\n", "{\n \"private\": true,\n \"name\": \"dapr-cfworkers-client\",\n \"description\": \"Client code for Dapr to interact with Cloudflare Workers\",\n \"version\": \"20230517\",\n \"main\": \"worker.ts\",\n \"scripts\": {\n \"build\": \"esbuild --bundle --minify --outfile=../workers/code/worker.js --format=esm --platform=browser --sourcemap worker.ts\",\n \"start\": \"wrangler dev\",\n \"format\": \"prettier --write .\"\n },\n \"author\": \"Dapr authors\",\n \"license\": \"Apache2\",\n \"devDependencies\": {\n \"@cloudflare/workers-types\": \"^4.20230511.0\",\n \"esbuild\": \"^0.17.19\",\n \"prettier\": \"^2.8.8\",\n \"typescript\": \"^5.0.4\",\n \"wrangler\": \"^3.0.0\"\n },\n \"dependencies\": {\n \"itty-router\": \"3.0.12\",\n \"jose\": \"4.14.4\"\n }\n}\n", "/*\nCopyright 2022 The Dapr Authors\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Router, IRequest } from 'itty-router'\n\nimport { Environment } from '$lib/environment'\nimport { AuthorizeRequest } from '$lib/jwt-auth'\n\nimport { version } from './package.json'\n\nconst router = Router()\n // Handle the info endpoint\n .get(\n '/.well-known/dapr/info',\n async (req: IRequest, env: Environment): Promise => {\n const auth = await AuthorizeRequest(req, env)\n if (!auth) {\n return new Response('Unauthorized', { status: 401 })\n }\n\n // Filter all bindings by type\n const queues: string[] = []\n const kv: string[] = []\n const r2: string[] = []\n const all = Object.keys(env)\n for (let i = 0; i < all.length; i++) {\n if (!all[i]) {\n continue\n }\n const obj = env[all[i]]\n if (!obj || typeof obj != 'object' || !obj.constructor) {\n continue\n }\n switch (obj.constructor.name) {\n case 'KvNamespace':\n case 'KVNamespace':\n kv.push(all[i])\n break\n case 'WorkerQueue':\n case 'Queue':\n queues.push(all[i])\n break\n case 'R2Bucket':\n // Note that we currently don't support R2 yet\n r2.push(all[i])\n break\n }\n }\n\n const res = JSON.stringify({\n version,\n queues: queues && queues.length ? queues : undefined,\n kv: kv && kv.length ? kv : undefined,\n r2: r2 && r2.length ? r2 : undefined,\n })\n return new Response(res, {\n headers: {\n 'content-type': 'application/json',\n },\n })\n }\n )\n\n // Retrieve a value from KV\n .get(\n '/kv/:namespace/:key',\n async (req: IRequest, env: Environment): Promise => {\n const { namespace, key, errorRes } = await setupKVRequest(req, env)\n if (errorRes) {\n return errorRes\n }\n\n const val = await namespace!.get(key!, 'stream')\n if (!val) {\n return new Response('', { status: 404 })\n }\n\n return new Response(val, { status: 200 })\n }\n )\n\n // Store a value in KV\n .post(\n '/kv/:namespace/:key',\n async (req: IRequest, env: Environment): Promise => {\n const { namespace, key, errorRes } = await setupKVRequest(req, env)\n if (errorRes) {\n return errorRes\n }\n\n let expirationTtl: number | undefined = undefined\n const reqUrl = new URL(req.url)\n const ttlParam = parseInt(reqUrl.searchParams.get('ttl') || '', 10)\n if (ttlParam > 0) {\n expirationTtl = ttlParam\n }\n await namespace!.put(key!, req.body!, { expirationTtl })\n\n return new Response('', { status: 201 })\n }\n )\n\n // Delete a value from KV\n .delete(\n '/kv/:namespace/:key',\n async (req: IRequest, env: Environment): Promise => {\n const { namespace, key, errorRes } = await setupKVRequest(req, env)\n if (errorRes) {\n return errorRes\n }\n\n await namespace!.delete(key!)\n\n return new Response('', { status: 204 })\n }\n )\n\n // Publish a message in a queue\n .post(\n '/queues/:queue',\n async (req: IRequest, env: Environment): Promise => {\n const { queue, errorRes } = await setupQueueRequest(req, env)\n if (errorRes) {\n return errorRes\n }\n\n let message = await req.text()\n await queue!.send(message)\n return new Response('', { status: 201 })\n }\n )\n\n // Catch-all route to handle 404s\n .all('*', (): Response => {\n return new Response('Not found', { status: 404 })\n })\n\n// Performs the init setps for a KV request. Returns a Response object in case of error.\nasync function setupKVRequest(\n req: IRequest,\n env: Environment\n): Promise<{\n namespace?: KVNamespace\n key?: string\n errorRes?: Response\n}> {\n if (!req?.text || !req.params?.namespace || !req.params?.key) {\n return { errorRes: new Response('Bad request', { status: 400 }) }\n }\n const namespace = env[req.params.namespace] as KVNamespace\n if (\n typeof namespace != 'object' ||\n !['KVNamespace', 'KvNamespace'].includes(namespace?.constructor?.name)\n ) {\n return {\n errorRes: new Response(\n `Worker is not bound to KV '${req.params.kv}'`,\n { status: 412 }\n ),\n }\n }\n\n const auth = await AuthorizeRequest(req, env)\n if (!auth) {\n return { errorRes: new Response('Unauthorized', { status: 401 }) }\n }\n\n return { namespace, key: req.params.key }\n}\n\n// Performs the init setps for a Queue request. Returns a Response object in case of error.\nasync function setupQueueRequest(\n req: IRequest,\n env: Environment\n): Promise<{ queue?: Queue; errorRes?: Response }> {\n if (!req?.text || !req.params?.queue) {\n return { errorRes: new Response('Bad request', { status: 400 }) }\n }\n const queue = env[req.params.queue] as Queue\n if (\n typeof queue != 'object' ||\n !['WorkerQueue', 'Queue'].includes(queue?.constructor?.name)\n ) {\n return {\n errorRes: new Response(\n `Worker is not bound to queue '${req.params.queue}'`,\n { status: 412 }\n ),\n }\n }\n\n const auth = await AuthorizeRequest(req, env)\n if (!auth) {\n return { errorRes: new Response('Unauthorized', { status: 401 }) }\n }\n\n return { queue }\n}\n\nexport default {\n fetch: router.handle,\n}\n"], + "mappings": "AAAA,IAAMA,GAAE,CAAC,CAAC,KAAK,EAAE,GAAG,OAAOC,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,UAAU,IAAI,MAAM,CAAC,EAAE,CAAC,IAAI,CAACC,EAAEC,EAAEC,IAAI,CAACF,KAAKG,IAAIJ,EAAE,KAAK,CAACE,EAAE,YAAY,EAAE,OAAO,KAAK,EAAED,GAAG,QAAQ,WAAW,SAAS,EAAE,QAAQ,oBAAoB,EAAE,EAAE,QAAQ,aAAa,WAAW,EAAE,QAAQ,oBAAoB,oBAAoB,EAAE,QAAQ,cAAc,KAAK,EAAE,QAAQ,wBAAwB,wBAAwB,MAAM,EAAEG,CAAC,CAAC,GAAGD,CAAC,CAAC,EAAE,OAAOH,EAAE,MAAM,OAAOD,KAAKE,EAAE,CAAC,IAAI,EAAEE,EAAEC,EAAE,IAAI,IAAIL,EAAE,GAAG,EAAEM,EAAEN,EAAE,MAAM,CAAC,EAAE,OAAO,CAACA,EAAEC,CAAC,IAAII,EAAE,aAAaC,EAAEN,CAAC,EAAWM,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Q,GAAI,CAAC,CAAE,CAIzE,CAEA,IAAOG,GAAQ,CACX,MAAOxB,GAAO,MAClB", + "names": ["e", "r", "a", "o", "t", "p", "l", "s", "c", "webcrypto_default", "isCryptoKey", "key", "encoder", "decoder", "MAX_INT32", "concat", "buffers", "size", "acc", "length", "buf", "i", "buffer", "decodeBase64", "encoded", "binary", "bytes", "i", "decode", "input", "decoder", "JOSEError", "message", "_a", "JWTClaimValidationFailed", "claim", "reason", "JWTExpired", "JOSEAlgNotAllowed", "JOSENotSupported", "JWSInvalid", "JOSEError", "JWTInvalid", "JWSSignatureVerificationFailed", "JOSEError", "random_default", "webcrypto_default", "unusable", "name", "prop", "isAlgorithm", "algorithm", "getHashLength", "hash", "getNamedCurve", "alg", "checkUsage", "key", "usages", "expected", "msg", "last", "checkSigCryptoKey", "message", "msg", "actual", "types", "last", "invalid_key_input_default", "withAlg", "alg", "is_key_like_default", "key", "isCryptoKey", "types", "isDisjoint", "headers", "sources", "acc", "header", "parameters", "parameter", "is_disjoint_default", "isObjectLike", "value", "isObject", "input", "proto", "check_key_length_default", "alg", "key", "modulusLength", "findOid", "keyData", "oid", "from", "i", "sub", "value", "index", "getNamedCurve", "JOSENotSupported", "genericImport", "replace", "keyFormat", "pem", "alg", "options", "_a", "algorithm", "keyUsages", "c", "isPublic", "namedCurve", "webcrypto_default", "fromSPKI", "pem", "alg", "options", "genericImport", "importSPKI", "spki", "alg", "options", "fromSPKI", "symmetricTypeCheck", "alg", "key", "is_key_like_default", "withAlg", "types", "asymmetricTypeCheck", "usage", "checkKeyType", "check_key_type_default", "validateCrit", "Err", "recognizedDefault", "recognizedOption", "protectedHeader", "joseHeader", "input", "recognized", "parameter", "JOSENotSupported", "validate_crit_default", "validateAlgorithms", "option", "algorithms", "s", "validate_algorithms_default", "unprotected", "subtleDsa", "alg", "algorithm", "hash", "JOSENotSupported", "getCryptoKey", "alg", "key", "usage", "isCryptoKey", "checkSigCryptoKey", "invalid_key_input_default", "types", "webcrypto_default", "verify", "alg", "key", "signature", "data", "cryptoKey", "getCryptoKey", "check_key_length_default", "algorithm", "subtleDsa", "webcrypto_default", "verify_default", "flattenedVerify", "jws", "key", "options", "_a", "isObject", "JWSInvalid", "parsedProt", "protectedHeader", "decode", "decoder", "is_disjoint_default", "joseHeader", "extensions", "validate_crit_default", "b64", "alg", "algorithms", "validate_algorithms_default", "JOSEAlgNotAllowed", "resolvedKey", "check_key_type_default", "data", "concat", "encoder", "signature", "verify_default", "JWSSignatureVerificationFailed", "payload", "result", "compactVerify", "jws", "key", "options", "decoder", "JWSInvalid", "protectedHeader", "payload", "signature", "length", "verified", "flattenedVerify", "result", "epoch_default", "date", "REGEX", "secs_default", "str", "matched", "value", "normalizeTyp", "value", "checkAudiencePresence", "audPayload", "audOption", "jwt_claims_set_default", "protectedHeader", "encodedPayload", "options", "typ", "JWTClaimValidationFailed", "payload", "decoder", "isObject", "JWTInvalid", "requiredClaims", "issuer", "subject", "audience", "maxTokenAge", "claim", "tolerance", "secs_default", "currentDate", "now", "epoch_default", "JWTExpired", "age", "max", "jwtVerify", "jwt", "key", "options", "_a", "verified", "compactVerify", "JWTInvalid", "result", "jwt_claims_set_default", "tokenHeaderMatch", "AuthorizeRequest", "req", "env", "match", "pk", "importSPKI", "jwtVerify", "err", "version", "router", "e", "req", "env", "AuthorizeRequest", "queues", "kv", "r2", "all", "i", "obj", "res", "version", "namespace", "key", "errorRes", "setupKVRequest", "val", "expirationTtl", "reqUrl", "ttlParam", "queue", "setupQueueRequest", "message", "worker_default"] } diff --git a/internal/component/postgresql/postgresdbaccess.go b/internal/component/postgresql/postgresdbaccess.go index ae2dc27ec..626d41b4e 100644 --- a/internal/component/postgresql/postgresdbaccess.go +++ b/internal/component/postgresql/postgresdbaccess.go @@ -193,7 +193,7 @@ func (p *PostgresDBAccess) doSet(parentCtx context.Context, db dbquerier, req *s params []any ) - if req.ETag == nil || *req.ETag == "" { + if !req.HasETag() { params = []any{req.Key, value, isBinary} } else { var etag64 uint64 @@ -220,7 +220,7 @@ func (p *PostgresDBAccess) doSet(parentCtx context.Context, db dbquerier, req *s return err } if result.RowsAffected() != 1 { - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, nil) } return errors.New("no item was updated") @@ -291,13 +291,39 @@ func (p *PostgresDBAccess) BulkGet(parentCtx context.Context, req []state.GetReq // Scan all rows var n int res := make([]state.BulkGetResponse, len(req)) + foundKeys := make(map[string]struct{}, len(req)) for ; rows.Next(); n++ { + if n >= len(req) { + // Sanity check to prevent panics, which should never happen + return nil, fmt.Errorf("query returned more records than expected (expected %d)", len(req)) + } + r := state.BulkGetResponse{} r.Key, r.Data, r.ETag, err = readRow(rows) if err != nil { r.Error = err.Error() } res[n] = r + foundKeys[r.Key] = struct{}{} + } + + // Populate missing keys with empty values + // This is to ensure consistency with the other state stores that implement BulkGet as a loop over Get, and with the Get method + if len(foundKeys) < len(req) { + var ok bool + for _, r := range req { + _, ok = foundKeys[r.Key] + if !ok { + if n >= len(req) { + // Sanity check to prevent panics, which should never happen + return nil, fmt.Errorf("query returned more records than expected (expected %d)", len(req)) + } + res[n] = state.BulkGetResponse{ + Key: r.Key, + } + n++ + } + } } return res[:n], nil @@ -352,7 +378,7 @@ func (p *PostgresDBAccess) doDelete(parentCtx context.Context, db dbquerier, req ctx, cancel := context.WithTimeout(parentCtx, p.metadata.Timeout) defer cancel() var result pgconn.CommandTag - if req.ETag == nil || *req.ETag == "" { + if !req.HasETag() { result, err = db.Exec(ctx, "DELETE FROM "+p.metadata.TableName+" WHERE key = $1", req.Key) } else { // Convert req.ETag to uint32 for postgres XID compatibility diff --git a/state/aerospike/aerospike.go b/state/aerospike/aerospike.go index 04e246362..9568a7629 100644 --- a/state/aerospike/aerospike.go +++ b/state/aerospike/aerospike.go @@ -129,7 +129,7 @@ func (aspike *Aerospike) Set(ctx context.Context, req *state.SetRequest) error { writePolicy := &as.WritePolicy{} // not a new record - if req.ETag != nil { + if req.HasETag() { var gen uint32 gen, err = convertETag(*req.ETag) if err != nil { @@ -158,7 +158,7 @@ func (aspike *Aerospike) Set(ctx context.Context, req *state.SetRequest) error { } err = aspike.client.Put(writePolicy, asKey, as.BinMap(data)) if err != nil { - if req.ETag != nil { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, err) } @@ -210,7 +210,7 @@ func (aspike *Aerospike) Delete(ctx context.Context, req *state.DeleteRequest) e } writePolicy := &as.WritePolicy{} - if req.ETag != nil { + if req.HasETag() { var gen uint32 gen, err = convertETag(*req.ETag) if err != nil { @@ -235,7 +235,7 @@ func (aspike *Aerospike) Delete(ctx context.Context, req *state.DeleteRequest) e _, err = aspike.client.Delete(writePolicy, asKey) if err != nil { - if req.ETag != nil { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, err) } diff --git a/state/alicloud/tablestore/tablestore.go b/state/alicloud/tablestore/tablestore.go index fc2de00dd..1ea6cf3cf 100644 --- a/state/alicloud/tablestore/tablestore.go +++ b/state/alicloud/tablestore/tablestore.go @@ -170,7 +170,7 @@ func (s *AliCloudTableStore) updateRowChange(req *state.SetRequest) *tablestore. value, _ := marshal(req.Value) change.PutColumn(stateValue, value) - if req.ETag != nil { + if req.HasETag() { change.PutColumn(sateEtag, *req.ETag) } diff --git a/state/aws/dynamodb/dynamodb.go b/state/aws/dynamodb/dynamodb.go index d7bc6cb32..1fefd1f36 100644 --- a/state/aws/dynamodb/dynamodb.go +++ b/state/aws/dynamodb/dynamodb.go @@ -138,9 +138,10 @@ func (d *StateStore) Get(ctx context.Context, req *state.GetRequest) (*state.Get Data: []byte(output), } - var etag string - if etagVal, ok := result.Item["etag"]; ok { - if err = dynamodbattribute.Unmarshal(etagVal, &etag); err != nil { + if result.Item["etag"] != nil { + var etag string + err = dynamodbattribute.Unmarshal(result.Item["etag"], &etag) + if err != nil { return nil, err } resp.ETag = &etag @@ -161,9 +162,7 @@ func (d *StateStore) Set(ctx context.Context, req *state.SetRequest) error { TableName: &d.table, } - haveEtag := false - if req.ETag != nil && *req.ETag != "" { - haveEtag = true + if req.HasETag() { condExpr := "etag = :etag" input.ConditionExpression = &condExpr exprAttrValues := make(map[string]*dynamodb.AttributeValue) @@ -177,7 +176,7 @@ func (d *StateStore) Set(ctx context.Context, req *state.SetRequest) error { } _, err = d.client.PutItemWithContext(ctx, input) - if err != nil && haveEtag { + if err != nil && req.HasETag() { switch cErr := err.(type) { case *dynamodb.ConditionalCheckFailedException: err = state.NewETagError(state.ETagMismatch, cErr) @@ -198,7 +197,7 @@ func (d *StateStore) Delete(ctx context.Context, req *state.DeleteRequest) error TableName: aws.String(d.table), } - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { condExpr := "etag = :etag" input.ConditionExpression = &condExpr exprAttrValues := make(map[string]*dynamodb.AttributeValue) diff --git a/state/azure/blobstorage/blobstorage.go b/state/azure/blobstorage/blobstorage.go index a068dc365..65644c5c5 100644 --- a/state/azure/blobstorage/blobstorage.go +++ b/state/azure/blobstorage/blobstorage.go @@ -152,10 +152,10 @@ func (r *StateStore) readFile(ctx context.Context, req *state.GetRequest) (*stat func (r *StateStore) writeFile(ctx context.Context, req *state.SetRequest) error { modifiedAccessConditions := blob.ModifiedAccessConditions{} - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { modifiedAccessConditions.IfMatch = ptr.Of(azcore.ETag(*req.ETag)) } - if req.Options.Concurrency == state.FirstWrite && (req.ETag == nil || *req.ETag == "") { + if req.Options.Concurrency == state.FirstWrite && !req.HasETag() { modifiedAccessConditions.IfNoneMatch = ptr.Of(azcore.ETagAny) } @@ -179,7 +179,7 @@ func (r *StateStore) writeFile(ctx context.Context, req *state.SetRequest) error if err != nil { // Check if the error is due to ETag conflict - if req.ETag != nil && isETagConflictError(err) { + if req.HasETag() && isETagConflictError(err) { return state.NewETagError(state.ETagMismatch, err) } @@ -193,7 +193,7 @@ func (r *StateStore) deleteFile(ctx context.Context, req *state.DeleteRequest) e blockBlobClient := r.containerClient.NewBlockBlobClient(getFileName(req.Key)) modifiedAccessConditions := blob.ModifiedAccessConditions{} - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { modifiedAccessConditions.IfMatch = ptr.Of(azcore.ETag(*req.ETag)) } @@ -206,7 +206,7 @@ func (r *StateStore) deleteFile(ctx context.Context, req *state.DeleteRequest) e _, err := blockBlobClient.Delete(ctx, &deleteOptions) if err != nil { - if req.ETag != nil && isETagConflictError(err) { + if req.HasETag() && isETagConflictError(err) { return state.NewETagError(state.ETagMismatch, err) } else if isNotFoundError(err) { // deleting an item that doesn't exist without specifying an ETAG is a noop diff --git a/state/azure/cosmosdb/cosmosdb.go b/state/azure/cosmosdb/cosmosdb.go index 834fca37b..956040a30 100644 --- a/state/azure/cosmosdb/cosmosdb.go +++ b/state/azure/cosmosdb/cosmosdb.go @@ -385,7 +385,7 @@ func (c *StateStore) Set(ctx context.Context, req *state.SetRequest) error { partitionKey := populatePartitionMetadata(req.Key, req.Metadata) options := azcosmos.ItemOptions{} - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { etag := azcore.ETag(*req.ETag) options.IfMatchEtag = &etag } else if req.Options.Concurrency == state.FirstWrite { @@ -436,7 +436,7 @@ func (c *StateStore) Delete(ctx context.Context, req *state.DeleteRequest) error partitionKey := populatePartitionMetadata(req.Key, req.Metadata) options := azcosmos.ItemOptions{} - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { etag := azcore.ETag(*req.ETag) options.IfMatchEtag = &etag } else if req.Options.Concurrency == state.FirstWrite { @@ -494,7 +494,7 @@ func (c *StateStore) Multi(ctx context.Context, request *state.TransactionalStat } doc.PartitionKey = partitionKey - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { etag := azcore.ETag(*req.ETag) options.IfMatchETag = &etag } else if req.Options.Concurrency == state.FirstWrite { @@ -514,7 +514,7 @@ func (c *StateStore) Multi(ctx context.Context, request *state.TransactionalStat batch.UpsertItem(marsh, options) numOperations++ case state.DeleteRequest: - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { etag := azcore.ETag(*req.ETag) options.IfMatchETag = &etag } else if req.Options.Concurrency == state.FirstWrite { diff --git a/state/azure/tablestorage/tablestorage.go b/state/azure/tablestorage/tablestorage.go index 1b578edcb..8c89c6676 100644 --- a/state/azure/tablestorage/tablestorage.go +++ b/state/azure/tablestorage/tablestorage.go @@ -54,6 +54,7 @@ import ( mdutils "github.com/dapr/components-contrib/metadata" "github.com/dapr/components-contrib/state" "github.com/dapr/kit/logger" + "github.com/dapr/kit/ptr" ) const ( @@ -168,7 +169,7 @@ func (r *StateStore) Features() []state.Feature { func (r *StateStore) Delete(ctx context.Context, req *state.DeleteRequest) error { err := r.deleteRow(ctx, req) if err != nil { - if req.ETag != nil { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, err) } else if isNotFoundError(err) { // deleting an item that doesn't exist without specifying an ETAG is a noop @@ -262,18 +263,16 @@ func (r *StateStore) writeRow(ctx context.Context, req *state.SetRequest) error // Always Update using the etag when provided even if Concurrency != FirstWrite. // Today the presence of etag takes precedence over Concurrency. // In the future #2739 will impose a breaking change which must disallow the use of etag when not using FirstWrite. - if req.ETag != nil && *req.ETag != "" { - etag := azcore.ETag(*req.ETag) - - _, uerr := r.client.UpdateEntity(updateContext, marshalledEntity, &aztables.UpdateEntityOptions{ - IfMatch: &etag, + if req.HasETag() { + _, err = r.client.UpdateEntity(updateContext, marshalledEntity, &aztables.UpdateEntityOptions{ + IfMatch: ptr.Of(azcore.ETag(*req.ETag)), UpdateMode: aztables.UpdateModeReplace, }) - if uerr != nil { - if isNotFoundError(uerr) { - return state.NewETagError(state.ETagMismatch, uerr) + if err != nil { + if isPreconditionFailedError(err) { + return state.NewETagError(state.ETagMismatch, err) } - return uerr + return err } } else if req.Options.Concurrency == state.FirstWrite { // Otherwise, if FirstWrite was set, but no etag was provided for an Update operation @@ -283,12 +282,12 @@ func (r *StateStore) writeRow(ctx context.Context, req *state.SetRequest) error return state.NewETagError(state.ETagMismatch, errors.New("update with Concurrency.FirstWrite without ETag")) } else { // Finally, last write semantics without ETag should always perform a force update. - _, uerr := r.client.UpdateEntity(updateContext, marshalledEntity, &aztables.UpdateEntityOptions{ + _, err = r.client.UpdateEntity(updateContext, marshalledEntity, &aztables.UpdateEntityOptions{ IfMatch: nil, // this is the same as "*" matching all ETags UpdateMode: aztables.UpdateModeReplace, }) - if uerr != nil { - return uerr + if err != nil { + return err } } } else { @@ -308,6 +307,14 @@ func isNotFoundError(err error) bool { return false } +func isPreconditionFailedError(err error) bool { + var respErr *azcore.ResponseError + if errors.As(err, &respErr) { + return respErr.ErrorCode == string(aztables.UpdateConditionNotSatisfied) + } + return false +} + func isEntityAlreadyExistsError(err error) bool { var respErr *azcore.ResponseError if errors.As(err, &respErr) { @@ -329,10 +336,17 @@ func (r *StateStore) deleteRow(ctx context.Context, req *state.DeleteRequest) er deleteContext, cancel := context.WithTimeout(ctx, timeout) defer cancel() - if req.ETag != nil { - azcoreETag := azcore.ETag(*req.ETag) - _, err := r.client.DeleteEntity(deleteContext, pk, rk, &aztables.DeleteEntityOptions{IfMatch: &azcoreETag}) - return err + if req.HasETag() { + _, err := r.client.DeleteEntity(deleteContext, pk, rk, &aztables.DeleteEntityOptions{ + IfMatch: ptr.Of(azcore.ETag(*req.ETag)), + }) + if err != nil { + if isPreconditionFailedError(err) { + return state.NewETagError(state.ETagMismatch, err) + } + return err + } + return nil } all := azcore.ETagAny _, err := r.client.DeleteEntity(deleteContext, pk, rk, &aztables.DeleteEntityOptions{IfMatch: &all}) @@ -373,7 +387,7 @@ func (r *StateStore) marshal(req *state.SetRequest) ([]byte, error) { }, } - if req.ETag != nil { + if req.HasETag() { entity.ETag = *req.ETag } diff --git a/state/cockroachdb/cockroachdb.go b/state/cockroachdb/cockroachdb.go index cc30c8873..4cd6cfa09 100644 --- a/state/cockroachdb/cockroachdb.go +++ b/state/cockroachdb/cockroachdb.go @@ -28,12 +28,17 @@ func New(logger logger.Logger) state.Store { ETagColumn: "etag", MigrateFn: ensureTables, SetQueryFn: func(req *state.SetRequest, opts postgresql.SetQueryOptions) string { - // String concat is required for table name because sql.DB does not - // substitute parameters for table names. - // Other parameters use sql.DB parameter substitution. - if req.ETag == nil || *req.ETag == "" { + // Sprintf is required for table name because the driver does not substitute parameters for table names. + if !req.HasETag() { + // We do an upsert in both cases, even when concurrency is first-write, because the row may exist but be expired (and not yet garbage collected) + // The difference is that with concurrency as first-write, we'll update the row only if it's expired + var whereClause string + if req.Options.Concurrency == state.FirstWrite { + whereClause = " WHERE (t.expiredate IS NOT NULL AND t.expiredate < CURRENT_TIMESTAMP)" + } + return ` -INSERT INTO ` + opts.TableName + ` +INSERT INTO ` + opts.TableName + ` AS t (key, value, isbinary, etag, expiredate) VALUES ($1, $2, $3, 1, ` + opts.ExpireDateValue + `) @@ -42,7 +47,8 @@ ON CONFLICT (key) DO UPDATE SET isbinary = $3, updatedate = NOW(), etag = EXCLUDED.etag + 1, - expiredate = ` + opts.ExpireDateValue + `;` + expiredate = ` + opts.ExpireDateValue + + whereClause } // When an etag is provided do an update - no insert. diff --git a/state/couchbase/couchbase.go b/state/couchbase/couchbase.go index d101c221c..0ea4293dc 100644 --- a/state/couchbase/couchbase.go +++ b/state/couchbase/couchbase.go @@ -173,7 +173,7 @@ func (cbs *Couchbase) Set(ctx context.Context, req *state.SetRequest) error { //nolint:nestif // key already exists (use Replace) - if req.ETag != nil { + if req.HasETag() { // compare-and-swap (CAS) for managing concurrent modifications - https://docs.couchbase.com/go-sdk/current/concurrent-mutations-cluster.html cas, cerr := eTagToCas(*req.ETag) if cerr != nil { @@ -194,7 +194,7 @@ func (cbs *Couchbase) Set(ctx context.Context, req *state.SetRequest) error { } if err != nil { - if req.ETag != nil { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, err) } @@ -231,7 +231,7 @@ func (cbs *Couchbase) Delete(ctx context.Context, req *state.DeleteRequest) erro var cas gocb.Cas = 0 - if req.ETag != nil { + if req.HasETag() { cas, err = eTagToCas(*req.ETag) if err != nil { return err @@ -243,7 +243,7 @@ func (cbs *Couchbase) Delete(ctx context.Context, req *state.DeleteRequest) erro _, err = cbs.bucket.Remove(req.Key, cas) } if err != nil { - if req.ETag != nil { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, err) } diff --git a/state/etcd/etcd.go b/state/etcd/etcd.go index c083d60a4..5dc68f60f 100644 --- a/state/etcd/etcd.go +++ b/state/etcd/etcd.go @@ -344,7 +344,7 @@ func (e *Etcd) Multi(ctx context.Context, request *state.TransactionalStateReque return err } var cmp clientv3.Cmp - if req.ETag != nil { + if req.HasETag() { etag, _ := strconv.ParseInt(*req.ETag, 10, 64) cmp = clientv3.Compare(clientv3.ModRevision(keyWithPath), "=", etag) } @@ -354,14 +354,14 @@ func (e *Etcd) Multi(ctx context.Context, request *state.TransactionalStateReque return fmt.Errorf("couldn't grant lease %s: %w", keyWithPath, err) } put := clientv3.OpPut(keyWithPath, string(reqVal), clientv3.WithLease(resp.ID)) - if req.ETag != nil { + if req.HasETag() { ops = append(ops, clientv3.OpTxn([]clientv3.Cmp{cmp}, []clientv3.Op{put}, nil)) } else { ops = append(ops, clientv3.OpTxn(nil, []clientv3.Op{put}, nil)) } } else { put := clientv3.OpPut(keyWithPath, string(reqVal)) - if req.ETag != nil { + if req.HasETag() { ops = append(ops, clientv3.OpTxn([]clientv3.Cmp{cmp}, []clientv3.Op{put}, nil)) } else { ops = append(ops, clientv3.OpTxn(nil, []clientv3.Op{put}, nil)) @@ -379,7 +379,7 @@ func (e *Etcd) Multi(ctx context.Context, request *state.TransactionalStateReque } del := clientv3.OpDelete(keyWithPath) - if req.ETag != nil { + if req.HasETag() { etag, _ := strconv.ParseInt(*req.ETag, 10, 64) cmp := clientv3.Compare(clientv3.ModRevision(keyWithPath), "=", etag) ops = append(ops, clientv3.OpTxn([]clientv3.Cmp{cmp}, []clientv3.Op{del}, nil)) diff --git a/state/in-memory/in_memory.go b/state/in-memory/in_memory.go index 42c142e32..f3e5d28a3 100644 --- a/state/in-memory/in_memory.go +++ b/state/in-memory/in_memory.go @@ -169,7 +169,6 @@ func (store *inMemoryStore) BulkGet(ctx context.Context, req []state.GetRequest, store.lock.RLock() defer store.lock.RUnlock() - n := 0 for i, r := range req { item := store.items[r.Key] if item != nil && !item.isExpired() { @@ -178,11 +177,14 @@ func (store *inMemoryStore) BulkGet(ctx context.Context, req []state.GetRequest, Data: item.data, ETag: item.etag, } - n++ + } else { + res[i] = state.BulkGetResponse{ + Key: r.Key, + } } } - return res[:n], nil + return res, nil } func (store *inMemoryStore) getAndExpire(key string) *inMemStateStoreItem { diff --git a/state/mongodb/mongodb.go b/state/mongodb/mongodb.go index ef221db95..627c9819d 100644 --- a/state/mongodb/mongodb.go +++ b/state/mongodb/mongodb.go @@ -206,7 +206,7 @@ func (m *MongoDB) setInternal(ctx context.Context, req *state.SetRequest) error // create a document based on request key and value filter := bson.M{id: req.Key} - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { filter[etag] = *req.ETag } else if req.Options.Concurrency == state.FirstWrite { uuid, err := uuid.NewRandom() @@ -302,7 +302,7 @@ func (m *MongoDB) Get(ctx context.Context, req *state.GetRequest) (*state.GetRes func (m *MongoDB) BulkGet(ctx context.Context, req []state.GetRequest, _ state.BulkGetOpts) ([]state.BulkGetResponse, error) { // If nothing is being requested, short-circuit if len(req) == 0 { - return []state.BulkGetResponse{}, nil + return nil, nil } // Get all the keys @@ -326,12 +326,13 @@ func (m *MongoDB) BulkGet(ctx context.Context, req []state.GetRequest, _ state.B // No documents found, just return an empty list err = nil } - return []state.BulkGetResponse{}, err + return nil, err } defer cur.Close(ctx) // Read all results res := make([]state.BulkGetResponse, 0, len(keys)) + foundKeys := make(map[string]struct{}, len(keys)) for cur.Next(ctx) { var ( doc Item @@ -339,7 +340,7 @@ func (m *MongoDB) BulkGet(ctx context.Context, req []state.GetRequest, _ state.B ) err = cur.Decode(&doc) if err != nil { - return res, err + return nil, err } bgr := state.BulkGetResponse{ @@ -356,12 +357,27 @@ func (m *MongoDB) BulkGet(ctx context.Context, req []state.GetRequest, _ state.B bgr.Data = data } res = append(res, bgr) + foundKeys[bgr.Key] = struct{}{} } err = cur.Err() if err != nil { return res, err } + // Populate missing keys with empty values + // This is to ensure consistency with the other state stores that implement BulkGet as a loop over Get, and with the Get method + if len(foundKeys) < len(req) { + var ok bool + for _, r := range req { + _, ok = foundKeys[r.Key] + if !ok { + res = append(res, state.BulkGetResponse{ + Key: r.Key, + }) + } + } + } + return res, nil } @@ -427,7 +443,7 @@ func (m *MongoDB) Delete(ctx context.Context, req *state.DeleteRequest) error { func (m *MongoDB) deleteInternal(ctx context.Context, req *state.DeleteRequest) error { filter := bson.M{id: req.Key} - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { filter[etag] = *req.ETag } result, err := m.collection.DeleteOne(ctx, filter) @@ -436,7 +452,7 @@ func (m *MongoDB) deleteInternal(ctx context.Context, req *state.DeleteRequest) } if result.DeletedCount == 0 && req.ETag != nil && *req.ETag != "" { - return errors.New("key or etag not found") + return state.NewETagError(state.ETagMismatch, err) } return nil diff --git a/state/mysql/mysql.go b/state/mysql/mysql.go index c5393e55e..b78f2be83 100644 --- a/state/mysql/mysql.go +++ b/state/mysql/mysql.go @@ -495,7 +495,7 @@ func (m *MySQL) deleteValue(parentCtx context.Context, querier querier, req *sta execCtx, cancel := context.WithTimeout(parentCtx, m.timeout) defer cancel() - if req.ETag == nil || *req.ETag == "" { + if !req.HasETag() { result, err = querier.ExecContext(execCtx, `DELETE FROM `+m.tableName+` WHERE id = ?`, req.Key) @@ -721,13 +721,39 @@ func (m *MySQL) BulkGet(parentCtx context.Context, req []state.GetRequest, _ sta var n int res := make([]state.BulkGetResponse, len(req)) + foundKeys := make(map[string]struct{}, len(req)) for ; rows.Next(); n++ { + if n >= len(req) { + // Sanity check to prevent panics, which should never happen + return nil, fmt.Errorf("query returned more records than expected (expected %d)", len(req)) + } + r := state.BulkGetResponse{} r.Key, r.Data, r.ETag, err = readRow(rows) if err != nil { r.Error = err.Error() } res[n] = r + foundKeys[r.Key] = struct{}{} + } + + // Populate missing keys with empty values + // This is to ensure consistency with the other state stores that implement BulkGet as a loop over Get, and with the Get method + if len(foundKeys) < len(req) { + var ok bool + for _, r := range req { + _, ok = foundKeys[r.Key] + if !ok { + if n >= len(req) { + // Sanity check to prevent panics, which should never happen + return nil, fmt.Errorf("query returned more records than expected (expected %d)", len(req)) + } + res[n] = state.BulkGetResponse{ + Key: r.Key, + } + n++ + } + } } return res[:n], nil diff --git a/state/oracledatabase/oracledatabaseaccess.go b/state/oracledatabase/oracledatabaseaccess.go index 79db875f3..e79acbd0e 100644 --- a/state/oracledatabase/oracledatabaseaccess.go +++ b/state/oracledatabase/oracledatabaseaccess.go @@ -162,7 +162,7 @@ func (o *oracleDatabaseAccess) doSet(ctx context.Context, db querier, req *state etag := etagObj.String() var result sql.Result - if req.ETag == nil || *req.ETag == "" { + if !req.HasETag() { // Sprintf is required for table name because sql.DB does not substitute parameters for table names. // Other parameters use sql.DB parameter substitution. var stmt string @@ -201,7 +201,7 @@ func (o *oracleDatabaseAccess) doSet(ctx context.Context, db querier, req *state return err } if rows != 1 { - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, err) } return errors.New("no item was updated") @@ -262,7 +262,7 @@ func (o *oracleDatabaseAccess) doDelete(ctx context.Context, db querier, req *st } var result sql.Result - if req.ETag == nil || *req.ETag == "" { + if !req.HasETag() { result, err = db.ExecContext(ctx, "DELETE FROM "+o.metadata.TableName+" WHERE key = :key", req.Key) } else { result, err = db.ExecContext(ctx, "DELETE FROM "+o.metadata.TableName+" WHERE key = :key AND etag = :etag", req.Key, *req.ETag) diff --git a/state/postgresql/postgresql.go b/state/postgresql/postgresql.go index 92392607a..638999c01 100644 --- a/state/postgresql/postgresql.go +++ b/state/postgresql/postgresql.go @@ -25,10 +25,8 @@ func NewPostgreSQLStateStore(logger logger.Logger) state.Store { ETagColumn: "xmin", MigrateFn: performMigration, SetQueryFn: func(req *state.SetRequest, opts postgresql.SetQueryOptions) string { - // Sprintf is required for table name because sql.DB does not - // substitute parameters for table names. - // Other parameters use sql.DB parameter substitution. - if req.ETag == nil || *req.ETag == "" { + // Sprintf is required for table name because the driver does not substitute parameters for table names. + if !req.HasETag() { // We do an upsert in both cases, even when concurrency is first-write, because the row may exist but be expired (and not yet garbage collected) // The difference is that with concurrency as first-write, we'll update the row only if it's expired var whereClause string diff --git a/state/redis/redis.go b/state/redis/redis.go index 8f1e3602b..2435a26da 100644 --- a/state/redis/redis.go +++ b/state/redis/redis.go @@ -102,8 +102,7 @@ type StateStore struct { querySchemas querySchemas suppressActorStateStoreWarning atomic.Bool - features []state.Feature - logger logger.Logger + logger logger.Logger } // NewRedisStateStore returns a new redis state store. @@ -116,7 +115,6 @@ func NewRedisStateStore(log logger.Logger) state.Store { func newStateStore(log logger.Logger) *StateStore { return &StateStore{ json: jsoniter.ConfigFastest, - features: []state.Feature{state.FeatureETag, state.FeatureTransactional, state.FeatureQueryAPI}, logger: log, suppressActorStateStoreWarning: atomic.Bool{}, } @@ -162,7 +160,11 @@ func (r *StateStore) Init(ctx context.Context, metadata state.Metadata) error { // Features returns the features available in this state store. func (r *StateStore) Features() []state.Feature { - return r.features + if r.clientHasJSON { + return []state.Feature{state.FeatureETag, state.FeatureTransactional, state.FeatureQueryAPI} + } else { + return []state.Feature{state.FeatureETag, state.FeatureTransactional} + } } func (r *StateStore) getConnectedSlaves(ctx context.Context) (int, error) { @@ -201,9 +203,8 @@ func (r *StateStore) Delete(ctx context.Context, req *state.DeleteRequest) error return err } - if req.ETag == nil { - etag := "0" - req.ETag = &etag + if !req.HasETag() { + req.ETag = ptr.Of("0") } if req.Metadata[daprmetadata.ContentType] == contenttype.JSONContentType && r.clientHasJSON { @@ -352,7 +353,7 @@ func (r *StateStore) Set(ctx context.Context, req *state.SetRequest) error { } if err != nil { - if req.ETag != nil { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, err) } @@ -426,9 +427,8 @@ func (r *StateStore) Multi(ctx context.Context, request *state.TransactionalStat } case state.DeleteRequest: - if req.ETag == nil { - etag := "0" - req.ETag = &etag + if !req.HasETag() { + req.ETag = ptr.Of("0") } isReqJSON := isJSON || (len(req.Metadata) > 0 && req.Metadata[daprmetadata.ContentType] == contenttype.JSONContentType) diff --git a/state/requests.go b/state/requests.go index 4d6cd3ef7..b4a243a81 100644 --- a/state/requests.go +++ b/state/requests.go @@ -57,6 +57,11 @@ func (r DeleteRequest) GetMetadata() map[string]string { return r.Metadata } +// HasETag returns true if the request has a non-empty ETag. +func (r DeleteRequest) HasETag() bool { + return r.ETag != nil && *r.ETag != "" +} + // Operation returns the operation type for DeleteRequest, implementing TransactionalStateOperationRequest. func (r DeleteRequest) Operation() OperationType { return OperationDelete @@ -88,6 +93,11 @@ func (r SetRequest) GetMetadata() map[string]string { return r.Metadata } +// HasETag returns true if the request has a non-empty ETag. +func (r SetRequest) HasETag() bool { + return r.ETag != nil && *r.ETag != "" +} + // Operation returns the operation type for SetRequest, implementing TransactionalStateOperationRequest. func (r SetRequest) Operation() OperationType { return OperationUpsert diff --git a/state/sqlite/sqlite_dbaccess.go b/state/sqlite/sqlite_dbaccess.go index 20ff3a61b..51b9f7c54 100644 --- a/state/sqlite/sqlite_dbaccess.go +++ b/state/sqlite/sqlite_dbaccess.go @@ -299,13 +299,39 @@ func (a *sqliteDBAccess) BulkGet(parentCtx context.Context, req []state.GetReque var n int res := make([]state.BulkGetResponse, len(req)) + foundKeys := make(map[string]struct{}, len(req)) for ; rows.Next(); n++ { + if n >= len(req) { + // Sanity check to prevent panics, which should never happen + return nil, fmt.Errorf("query returned more records than expected (expected %d)", len(req)) + } + r := state.BulkGetResponse{} r.Key, r.Data, r.ETag, err = readRow(rows) if err != nil { r.Error = err.Error() } res[n] = r + foundKeys[r.Key] = struct{}{} + } + + // Populate missing keys with empty values + // This is to ensure consistency with the other state stores that implement BulkGet as a loop over Get, and with the Get method + if len(foundKeys) < len(req) { + var ok bool + for _, r := range req { + _, ok = foundKeys[r.Key] + if !ok { + if n >= len(req) { + // Sanity check to prevent panics, which should never happen + return nil, fmt.Errorf("query returned more records than expected (expected %d)", len(req)) + } + res[n] = state.BulkGetResponse{ + Key: r.Key, + } + n++ + } + } } return res[:n], nil @@ -393,7 +419,7 @@ func (a *sqliteDBAccess) doSet(parentCtx context.Context, db querier, req *state ) // Sprintf is required for table name because sql.DB does not substitute parameters for table names. // And the same is for DATETIME function's seconds parameter (which is from an integer anyways). - if req.ETag == nil || *req.ETag == "" { + if !req.HasETag() { // If the operation uses first-write concurrency, we need to handle the special case of a row that has expired but hasn't been garbage collected yet // In this case, the row should be considered as if it were deleted // With SQLite, the only way we can handle that is by performing a SELECT query first @@ -457,7 +483,7 @@ func (a *sqliteDBAccess) doSet(parentCtx context.Context, db querier, req *state return err } if rows == 0 { - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, nil) } return errors.New("no item was updated") @@ -530,7 +556,7 @@ func (a *sqliteDBAccess) doDelete(parentCtx context.Context, db querier, req *st ctx, cancel := context.WithTimeout(parentCtx, a.metadata.timeout) defer cancel() var result sql.Result - if req.ETag == nil || *req.ETag == "" { + if !req.HasETag() { // Concatenation is required for table name because sql.DB does not substitute parameters for table names. result, err = db.ExecContext(ctx, "DELETE FROM "+a.metadata.TableName+" WHERE key = ?", req.Key) diff --git a/state/sqlserver/sqlserver.go b/state/sqlserver/sqlserver.go index b066fc8c9..89030fe36 100644 --- a/state/sqlserver/sqlserver.go +++ b/state/sqlserver/sqlserver.go @@ -204,7 +204,7 @@ func (s *SQLServer) Delete(ctx context.Context, req *state.DeleteRequest) error func (s *SQLServer) executeDelete(ctx context.Context, db dbExecutor, req *state.DeleteRequest) error { var err error var res sql.Result - if req.ETag != nil { + if req.HasETag() { var b []byte b, err = hex.DecodeString(*req.ETag) if err != nil { @@ -292,7 +292,7 @@ func (s *SQLServer) executeSet(ctx context.Context, db dbExecutor, req *state.Se return err } etag := sql.Named(rowVersionColumnName, nil) - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { var b []byte b, err = hex.DecodeString(*req.ETag) if err != nil { @@ -327,7 +327,7 @@ func (s *SQLServer) executeSet(ctx context.Context, db dbExecutor, req *state.Se } if rows != 1 { - if req.ETag != nil && *req.ETag != "" { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, err) } return errors.New("no item was updated") diff --git a/state/zookeeper/zk.go b/state/zookeeper/zk.go index 5c6da42d5..b4c92e287 100644 --- a/state/zookeeper/zk.go +++ b/state/zookeeper/zk.go @@ -186,7 +186,7 @@ func (s *StateStore) Delete(ctx context.Context, req *state.DeleteRequest) error } if err != nil { - if req.ETag != nil { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, err) } @@ -209,7 +209,7 @@ func (s *StateStore) Set(ctx context.Context, req *state.SetRequest) error { } if err != nil { - if req.ETag != nil { + if req.HasETag() { return state.NewETagError(state.ETagMismatch, err) } @@ -232,7 +232,7 @@ func (s *StateStore) newDeleteRequest(req *state.DeleteRequest) (*zk.DeleteReque } else { var etag string - if req.ETag != nil { + if req.HasETag() { etag = *req.ETag } version = s.parseETag(etag) @@ -262,7 +262,7 @@ func (s *StateStore) newSetDataRequest(req *state.SetRequest) (*zk.SetDataReques } else { var etag string - if req.ETag != nil { + if req.HasETag() { etag = *req.ETag } version = s.parseETag(etag) diff --git a/tests/config/state/tests.yml b/tests/config/state/tests.yml index b1878330d..7d037e6cd 100644 --- a/tests/config/state/tests.yml +++ b/tests/config/state/tests.yml @@ -1,83 +1,106 @@ -# Supported operations: set, get, delete, bulkget, bulkset, bulkdelete, transaction, etag, first-write, query, ttl +# Supported operations: transaction, etag, first-write, query, ttl +# Supported config: +# - badEtag: string containing a value for the bad etag, for exaple if the component uses numeric etags (default: "bad-etag") componentType: state components: - component: redis.v6 allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete", "transaction", "etag", "first-write", "query", "ttl" ] + operations: [ "transaction", "etag", "first-write", "query", "ttl" ] + config: + # This component requires etags to be numeric + badEtag: "9999999" - component: redis.v7 allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete", "transaction", "etag", "first-write" ] + # "query" is not included because redisjson hasn't been updated to Redis v7 yet + operations: [ "transaction", "etag", "first-write", "ttl" ] + config: + # This component requires etags to be numeric + badEtag: "9999999" - component: mongodb allOperations: false - operations: [ "set", "get", "delete", "bulkget", "bulkset", "bulkdelete", "transaction", "etag", "first-write", "query", "ttl" ] + operations: [ "transaction", "etag", "first-write", "query", "ttl" ] - component: memcached allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete", "ttl" ] + operations: [ "ttl" ] - component: azure.cosmosdb allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete", "transaction", "etag", "first-write", "query", "ttl" ] + operations: [ "transaction", "etag", "first-write", "query", "ttl" ] - component: azure.blobstorage allOperations: false - operations: [ "set", "get", "delete", "etag", "bulkset", "bulkdelete", "first-write" ] + operations: [ "etag", "first-write" ] - component: azure.sql allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete", "transaction", "etag", "first-write" ] + operations: [ "transaction", "etag", "first-write", "ttl" ] + config: + # This component requires etags to be hex-encoded numbers + badEtag: "FFFF" - component: sqlserver allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete", "transaction", "etag", "first-write", "ttl" ] + operations: [ "transaction", "etag", "first-write", "ttl" ] + config: + # This component requires etags to be hex-encoded numbers + badEtag: "FFFF" - component: postgresql allOperations: false - operations: [ "set", "get", "delete", "bulkget", "bulkset", "bulkdelete", "transaction", "etag", "first-write", "query", "ttl" ] + operations: [ "transaction", "etag", "first-write", "query", "ttl" ] + config: + # This component requires etags to be numeric + badEtag: "1" - component: sqlite allOperations: false - operations: [ "set", "get", "delete", "bulkget", "bulkset", "bulkdelete", "transaction", "etag", "first-write", "ttl" ] + operations: [ "transaction", "etag", "first-write", "ttl" ] - component: mysql.mysql allOperations: false - operations: [ "set", "get", "delete", "bulkget", "bulkset", "bulkdelete", "transaction", "etag", "first-write", "ttl" ] + operations: [ "transaction", "etag", "first-write", "ttl" ] - component: mysql.mariadb allOperations: false - operations: [ "set", "get", "delete", "bulkget", "bulkset", "bulkdelete", "transaction", "etag", "first-write", "ttl" ] + operations: [ "transaction", "etag", "first-write", "ttl" ] - component: azure.tablestorage.storage allOperations: false - operations: ["set", "get", "delete", "etag", "bulkset", "bulkdelete", "first-write"] + operations: [ "etag", "first-write"] + config: + # This component requires etags to be in this format + badEtag: "W/\"datetime'2023-05-09T12%3A28%3A54.1442151Z'\"" - component: azure.tablestorage.cosmosdb allOperations: false - operations: ["set", "get", "delete", "etag", "bulkset", "bulkdelete", "first-write"] + operations: [ "etag", "first-write"] + config: + # This component requires etags to be in this format + badEtag: "W/\"datetime'2023-05-09T12%3A28%3A54.1442151Z'\"" - component: oracledatabase allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete", "transaction", "etag", "first-write", "ttl" ] + operations: [ "transaction", "etag", "first-write", "ttl" ] - component: cassandra allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete", "ttl" ] + operations: [ "ttl" ] - component: cloudflare.workerskv allOperations: false # Although this component supports TTLs, the minimum TTL is 60s, which makes it not suitable for our conformance tests - # TODO: perhaps create a special case `ttl60` operation for this component - # where the test would set a TTL of 60s for this particular operation. - # `ttl` and `ttl60` are mutually exclusive, and `allOperations` would - # exclude `ttl60` - operations: [ "set", "get", "delete", "bulkset", "bulkdelete"] + operations: [] - component: cockroachdb allOperations: false - operations: [ "set", "get", "delete", "bulkget", "bulkset", "bulkdelete", "transaction", "etag", "query", "ttl" ] + operations: [ "transaction", "etag", "first-write", "query", "ttl" ] + config: + # This component requires etags to be numeric + badEtag: "9999999" - component: rethinkdb allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete"] + operations: [] - component: in-memory allOperations: false - operations: [ "set", "get", "delete", "bulkget", "bulkset", "bulkdelete", "transaction", "etag", "first-write", "ttl" ] + operations: [ "transaction", "etag", "first-write", "ttl" ] - component: aws.dynamodb.docker allOperations: false - operations: [ "set", "get", "delete", "etag", "bulkset", "bulkdelete", "transaction", "first-write" ] + operations: [ "transaction", "etag", "first-write" ] - component: aws.dynamodb.terraform allOperations: false - operations: [ "set", "get", "delete", "etag", "bulkset", "bulkdelete", "transaction", "first-write" ] + operations: [ "transaction", "etag", "first-write" ] - component: etcd allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete", "transaction", "etag", "first-write", "ttl" ] + operations: [ "transaction", "etag", "first-write", "ttl" ] - component: gcp.firestore.docker allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete" ] + operations: [] - component: gcp.firestore.cloud allOperations: false - operations: [ "set", "get", "delete", "bulkset", "bulkdelete" ] \ No newline at end of file + operations: [] \ No newline at end of file diff --git a/tests/conformance/common.go b/tests/conformance/common.go index f1cf2cf41..8f2d73287 100644 --- a/tests/conformance/common.go +++ b/tests/conformance/common.go @@ -30,7 +30,6 @@ import ( "testing" "github.com/google/uuid" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" @@ -366,97 +365,66 @@ func (tc *TestConfiguration) Run(t *testing.T) { case "state": filepath := fmt.Sprintf("../config/state/%s", componentConfigPath) props, err := tc.loadComponentsAndProperties(t, filepath) - if err != nil { - t.Errorf("error running conformance test for %s: %s", comp.Component, err) - break - } + require.NoErrorf(t, err, "error running conformance test for component %s", comp.Component) store := loadStateStore(comp) - assert.NotNil(t, store) - storeConfig := conf_state.NewTestConfig(comp.Component, comp.AllOperations, comp.Operations, comp.Config) + require.NotNilf(t, store, "error running conformance test for component %s", comp.Component) + storeConfig, err := conf_state.NewTestConfig(comp.Component, comp.AllOperations, comp.Operations, comp.Config) + require.NoErrorf(t, err, "error running conformance test for component %s", comp.Component) conf_state.ConformanceTests(t, props, store, storeConfig) case "secretstores": filepath := fmt.Sprintf("../config/secretstores/%s", componentConfigPath) props, err := tc.loadComponentsAndProperties(t, filepath) - if err != nil { - t.Errorf("error running conformance test for %s: %s", comp.Component, err) - break - } + require.NoErrorf(t, err, "error running conformance test for component %s", comp.Component) store := loadSecretStore(comp) - assert.NotNil(t, store) + require.NotNilf(t, store, "error running conformance test for component %s", comp.Component) storeConfig := conf_secret.NewTestConfig(comp.Component, comp.AllOperations, comp.Operations) conf_secret.ConformanceTests(t, props, store, storeConfig) case "pubsub": filepath := fmt.Sprintf("../config/pubsub/%s", componentConfigPath) props, err := tc.loadComponentsAndProperties(t, filepath) - if err != nil { - t.Errorf("error running conformance test for %s: %s", comp.Component, err) - break - } + require.NoErrorf(t, err, "error running conformance test for component %s", comp.Component) pubsub := loadPubSub(comp) - assert.NotNil(t, pubsub) + require.NotNil(t, pubsub, "error running conformance test for component %s", comp.Component) pubsubConfig, err := conf_pubsub.NewTestConfig(comp.Component, comp.AllOperations, comp.Operations, comp.Config) - if err != nil { - t.Errorf("error running conformance test for %s: %s", comp.Component, err) - break - } + require.NoErrorf(t, err, "error running conformance test for component %s", comp.Component) conf_pubsub.ConformanceTests(t, props, pubsub, pubsubConfig) case "bindings": filepath := fmt.Sprintf("../config/bindings/%s", componentConfigPath) props, err := tc.loadComponentsAndProperties(t, filepath) - if err != nil { - t.Errorf("error running conformance test for %s: %s", comp.Component, err) - break - } + require.NoErrorf(t, err, "error running conformance test for component %s", comp.Component) inputBinding := loadInputBindings(comp) outputBinding := loadOutputBindings(comp) - atLeastOne(t, func(item interface{}) bool { - return item != nil - }, inputBinding, outputBinding) + require.True(t, inputBinding != nil || outputBinding != nil) bindingsConfig, err := conf_bindings.NewTestConfig(comp.Component, comp.AllOperations, comp.Operations, comp.Config) - if err != nil { - t.Errorf("error running conformance test for %s: %s", comp.Component, err) - break - } + require.NoErrorf(t, err, "error running conformance test for component %s", comp.Component) conf_bindings.ConformanceTests(t, props, inputBinding, outputBinding, bindingsConfig) case "workflows": filepath := fmt.Sprintf("../config/workflows/%s", componentConfigPath) props, err := tc.loadComponentsAndProperties(t, filepath) - if err != nil { - t.Errorf("error running conformance test for %s: %s", comp.Component, err) - break - } + require.NoErrorf(t, err, "error running conformance test for component %s", comp.Component) wf := loadWorkflow(comp) wfConfig := conf_workflows.NewTestConfig(comp.Component, comp.AllOperations, comp.Operations, comp.Config) conf_workflows.ConformanceTests(t, props, wf, wfConfig) case "crypto": filepath := fmt.Sprintf("../config/crypto/%s", componentConfigPath) props, err := tc.loadComponentsAndProperties(t, filepath) - if err != nil { - t.Errorf("error running conformance test for %s: %s", comp.Component, err) - break - } + require.NoErrorf(t, err, "error running conformance test for component %s", comp.Component) component := loadCryptoProvider(comp) - require.NotNil(t, component) + require.NotNil(t, component, "error running conformance test for component %s", comp.Component) cryptoConfig, err := conf_crypto.NewTestConfig(comp.Component, comp.AllOperations, comp.Operations, comp.Config) - if err != nil { - t.Errorf("error running conformance test for %s: %s", comp.Component, err) - break - } + require.NoErrorf(t, err, "error running conformance test for component %s", comp.Component) conf_crypto.ConformanceTests(t, props, component, cryptoConfig) case "configuration": filepath := fmt.Sprintf("../config/configuration/%s", componentConfigPath) props, err := tc.loadComponentsAndProperties(t, filepath) - if err != nil { - t.Errorf("error running conformance test for %s: %s", comp.Component, err) - break - } + require.NoErrorf(t, err, "error running conformance test for component %s", comp.Component) store, updater := loadConfigurationStore(comp) - require.NotNil(t, store) - require.NotNil(t, updater) + require.NotNil(t, store, "error running conformance test for component %s", comp.Component) + require.NotNil(t, updater, "error running conformance test for component %s", comp.Component) configurationConfig := conf_configuration.NewTestConfig(comp.Component, comp.AllOperations, comp.Operations, comp.Config) conf_configuration.ConformanceTests(t, props, store, updater, configurationConfig, comp.Component) default: - t.Errorf("unknown component type %s", tc.ComponentType) + t.Fatalf("unknown component type %s", tc.ComponentType) } }) } @@ -709,13 +677,3 @@ func loadWorkflow(tc TestComponent) workflows.Workflow { return wf } - -func atLeastOne(t *testing.T, predicate func(interface{}) bool, items ...interface{}) { - met := false - - for _, item := range items { - met = met || predicate(item) - } - - assert.True(t, met) -} diff --git a/tests/conformance/state/state.go b/tests/conformance/state/state.go index 0fd8e42df..2956159a8 100644 --- a/tests/conformance/state/state.go +++ b/tests/conformance/state/state.go @@ -26,11 +26,13 @@ import ( "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "golang.org/x/exp/slices" "github.com/dapr/components-contrib/contenttype" "github.com/dapr/components-contrib/metadata" "github.com/dapr/components-contrib/state" "github.com/dapr/components-contrib/tests/conformance/utils" + "github.com/dapr/kit/config" "github.com/dapr/kit/ptr" ) @@ -59,19 +61,27 @@ type queryScenario struct { type TestConfig struct { utils.CommonConfig + + BadEtag string `mapstructure:"badEtag"` } -func NewTestConfig(component string, allOperations bool, operations []string, conf map[string]interface{}) TestConfig { - tc := TestConfig{ +func NewTestConfig(component string, allOperations bool, operations []string, configMap map[string]interface{}) (TestConfig, error) { + testConfig := TestConfig{ CommonConfig: utils.CommonConfig{ ComponentType: "state", ComponentName: component, AllOperations: allOperations, Operations: utils.NewStringSet(operations...), }, + BadEtag: "bad-etag", } - return tc + err := config.Decode(configMap, &testConfig) + if err != nil { + return testConfig, err + } + + return testConfig, nil } // ConformanceTests runs conf tests for state store. @@ -237,7 +247,7 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St // Don't run more tests if init failed if t.Failed() { - t.Fatal("Init test failed, stopping further tests") + t.Fatal("Init failed, stopping further tests") } t.Run("ping", func(t *testing.T) { @@ -252,46 +262,46 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St } }) - if config.HasOperation("set") { - t.Run("set", func(t *testing.T) { - for _, scenario := range scenarios { - if !scenario.bulkOnly && !scenario.transactionOnly { - t.Logf("Setting value for %s", scenario.key) - req := &state.SetRequest{ - Key: scenario.key, - Value: scenario.value, - } - if len(scenario.contentType) != 0 { - req.Metadata = map[string]string{metadata.ContentType: scenario.contentType} - } - err := statestore.Set(context.Background(), req) - assert.NoError(t, err) + t.Run("set", func(t *testing.T) { + for _, scenario := range scenarios { + if !scenario.bulkOnly && !scenario.transactionOnly { + t.Logf("Setting value for %s", scenario.key) + req := &state.SetRequest{ + Key: scenario.key, + Value: scenario.value, } + if len(scenario.contentType) != 0 { + req.Metadata = map[string]string{metadata.ContentType: scenario.contentType} + } + err := statestore.Set(context.Background(), req) + assert.NoError(t, err) } - }) - } + } + }) - if config.HasOperation("get") { - t.Run("get", func(t *testing.T) { - for _, scenario := range scenarios { - if !scenario.bulkOnly && !scenario.transactionOnly { - t.Logf("Checking value presence for %s", scenario.key) - req := &state.GetRequest{ - Key: scenario.key, - } - if len(scenario.contentType) != 0 { - req.Metadata = map[string]string{metadata.ContentType: scenario.contentType} - } - res, err := statestore.Get(context.Background(), req) - require.NoError(t, err) - assertEquals(t, scenario.value, res) + t.Run("get", func(t *testing.T) { + for _, scenario := range scenarios { + if !scenario.bulkOnly && !scenario.transactionOnly { + t.Logf("Checking value presence for %s", scenario.key) + req := &state.GetRequest{ + Key: scenario.key, } + if len(scenario.contentType) != 0 { + req.Metadata = map[string]string{metadata.ContentType: scenario.contentType} + } + res, err := statestore.Get(context.Background(), req) + require.NoError(t, err) + assertEquals(t, scenario.value, res) } - }) - } + } + }) if config.HasOperation("query") { t.Run("query", func(t *testing.T) { + // Check if query feature is listed + features := statestore.Features() + require.True(t, state.FeatureQueryAPI.IsPresent(features)) + querier, ok := statestore.(state.Querier) assert.True(t, ok, "Querier interface is not implemented") for _, scenario := range queryScenarios { @@ -317,116 +327,135 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St } } }) - } - - if config.HasOperation("delete") { - t.Run("delete", func(t *testing.T) { - for _, scenario := range scenarios { - if !scenario.bulkOnly && scenario.toBeDeleted { - // this also deletes two keys that were not inserted in the set operation - t.Logf("Deleting %s", scenario.key) - req := &state.DeleteRequest{ - Key: scenario.key, - } - if len(scenario.contentType) != 0 { - req.Metadata = map[string]string{metadata.ContentType: scenario.contentType} - } - err := statestore.Delete(context.Background(), req) - assert.NoError(t, err, "no error expected while deleting %s", scenario.key) - - t.Logf("Checking value absence for %s", scenario.key) - res, err := statestore.Get(context.Background(), &state.GetRequest{ - Key: scenario.key, - }) - assert.NoError(t, err, "no error expected while checking for absence for %s", scenario.key) - assert.Nil(t, res.Data, "no data expected while checking for absence for %s", scenario.key) - } - } + } else { + t.Run("query API feature not present", func(t *testing.T) { + features := statestore.Features() + assert.False(t, state.FeatureQueryAPI.IsPresent(features)) }) } - if config.HasOperation("bulkset") { - t.Run("bulkset", func(t *testing.T) { - var bulk []state.SetRequest - for _, scenario := range scenarios { - if scenario.bulkOnly { - t.Logf("Adding set request to bulk for %s", scenario.key) - bulk = append(bulk, state.SetRequest{ - Key: scenario.key, - Value: scenario.value, - }) + t.Run("delete", func(t *testing.T) { + for _, scenario := range scenarios { + if !scenario.bulkOnly && scenario.toBeDeleted { + // this also deletes two keys that were not inserted in the set operation + t.Logf("Deleting %s", scenario.key) + req := &state.DeleteRequest{ + Key: scenario.key, } - } - err := statestore.BulkSet(context.Background(), bulk, state.BulkStoreOpts{}) - require.NoError(t, err) - - for _, scenario := range scenarios { - if scenario.bulkOnly { - t.Logf("Checking value presence for %s", scenario.key) - // Data should have been inserted at this point - res, err := statestore.Get(context.Background(), &state.GetRequest{ - Key: scenario.key, - }) - require.NoError(t, err) - assertEquals(t, scenario.value, res) + if len(scenario.contentType) != 0 { + req.Metadata = map[string]string{metadata.ContentType: scenario.contentType} } - } - }) - } + err := statestore.Delete(context.Background(), req) + assert.NoError(t, err, "no error expected while deleting %s", scenario.key) - if config.HasOperation("bulkget") { - t.Run("bulkget", func(t *testing.T) { - var req []state.GetRequest - expects := map[string]any{} - for _, scenario := range scenarios { - if scenario.bulkOnly { - t.Logf("Adding get request to bulk for %s", scenario.key) - req = append(req, state.GetRequest{ - Key: scenario.key, - }) - expects[scenario.key] = scenario.value - } - } - res, err := statestore.BulkGet(context.Background(), req, state.BulkGetOpts{}) - require.NoError(t, err) - require.Len(t, res, len(expects)) - - for _, r := range res { - t.Logf("Checking value equality %s", r.Key) - _, ok := expects[r.Key] - if assert.Empty(t, r.Error) && assert.True(t, ok) { - assertDataEquals(t, expects[r.Key], r.Data) - } - } - }) - } - - if config.HasOperation("bulkdelete") { - t.Run("bulkdelete", func(t *testing.T) { - var bulk []state.DeleteRequest - for _, scenario := range scenarios { - if scenario.bulkOnly && scenario.toBeDeleted { - t.Logf("Adding delete request to bulk for %s", scenario.key) - bulk = append(bulk, state.DeleteRequest{ - Key: scenario.key, - }) - } - } - err := statestore.BulkDelete(context.Background(), bulk, state.BulkStoreOpts{}) - assert.NoError(t, err) - - for _, req := range bulk { - t.Logf("Checking value absence for %s", req.Key) + t.Logf("Checking value absence for %s", scenario.key) res, err := statestore.Get(context.Background(), &state.GetRequest{ - Key: req.Key, + Key: scenario.key, }) - assert.NoError(t, err) - assert.Nil(t, res.Data) + assert.NoError(t, err, "no error expected while checking for absence for %s", scenario.key) + assert.Nil(t, res.Data, "no data expected while checking for absence for %s", scenario.key) } - }) - } + } + }) + + t.Run("bulkset", func(t *testing.T) { + var bulk []state.SetRequest + for _, scenario := range scenarios { + if scenario.bulkOnly { + t.Logf("Adding set request to bulk for %s", scenario.key) + bulk = append(bulk, state.SetRequest{ + Key: scenario.key, + Value: scenario.value, + }) + } + } + err := statestore.BulkSet(context.Background(), bulk, state.BulkStoreOpts{}) + require.NoError(t, err) + + for _, scenario := range scenarios { + if scenario.bulkOnly { + t.Logf("Checking value presence for %s", scenario.key) + // Data should have been inserted at this point + res, err := statestore.Get(context.Background(), &state.GetRequest{ + Key: scenario.key, + }) + require.NoError(t, err) + assertEquals(t, scenario.value, res) + } + } + }) + + t.Run("bulkget", func(t *testing.T) { + tests := []struct { + name string + req []state.GetRequest + expect map[string]any + }{ + {name: "scenario", req: []state.GetRequest{}, expect: map[string]any{}}, + {name: "include non-existent key", req: []state.GetRequest{{Key: "doesnotexist"}}, expect: map[string]any{"doesnotexist": nil}}, + } + + // Build test cases + first := true + for _, scenario := range scenarios { + if scenario.bulkOnly { + t.Logf("Adding get request to bulk for %s", scenario.key) + tests[0].req = append(tests[0].req, state.GetRequest{ + Key: scenario.key, + }) + tests[0].expect[scenario.key] = scenario.value + + if first { + tests[1].req = append(tests[1].req, state.GetRequest{ + Key: scenario.key, + }) + tests[1].expect[scenario.key] = scenario.value + first = false + } + } + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + res, err := statestore.BulkGet(context.Background(), tt.req, state.BulkGetOpts{}) + require.NoError(t, err) + require.Len(t, res, len(tt.expect)) + + for _, r := range res { + t.Logf("Checking value equality %s", r.Key) + val, ok := tt.expect[r.Key] + if assert.Empty(t, r.Error) && assert.True(t, ok) { + assertDataEquals(t, val, r.Data) + } + delete(tt.expect, r.Key) + } + }) + } + }) + + t.Run("bulkdelete", func(t *testing.T) { + var bulk []state.DeleteRequest + for _, scenario := range scenarios { + if scenario.bulkOnly && scenario.toBeDeleted { + t.Logf("Adding delete request to bulk for %s", scenario.key) + bulk = append(bulk, state.DeleteRequest{ + Key: scenario.key, + }) + } + } + err := statestore.BulkDelete(context.Background(), bulk, state.BulkStoreOpts{}) + assert.NoError(t, err) + + for _, req := range bulk { + t.Logf("Checking value absence for %s", req.Key) + res, err := statestore.Get(context.Background(), &state.GetRequest{ + Key: req.Key, + }) + assert.NoError(t, err) + assert.Nil(t, res.Data) + } + }) - //nolint:nestif if config.HasOperation("transaction") { t.Run("transaction", func(t *testing.T) { // Check if transactional feature is listed @@ -512,11 +541,11 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St t.Run("transaction-order", func(t *testing.T) { // Arrange - firstKey := "key1" + firstKey := key + "-key1" firstValue := "value1" - secondKey := "key2" + secondKey := key + "-key2" secondValue := "value2" - thirdKey := "key3" + thirdKey := key + "-key3" thirdValue := "value3" // for CosmosDB @@ -593,92 +622,254 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St } }) } else { - // Check if transactional feature is NOT listed - features := statestore.Features() - assert.False(t, state.FeatureTransactional.IsPresent(features)) + t.Run("transactional feature not present", func(t *testing.T) { + features := statestore.Features() + assert.False(t, state.FeatureTransactional.IsPresent(features)) + }) } // Supporting etags requires support for get, set, and delete so they are not checked individually if config.HasOperation("etag") { t.Run("etag", func(t *testing.T) { - testKey := "etagTest" - firstValue := []byte("testValue1") - secondValue := []byte("testValue2") - fakeEtag := "not-an-etag" + var ( + etagErr *state.ETagError + bulkStoreErr state.BulkStoreError + testKeys = [4]string{key + "-etag1", key + "-etag2", key + "-etag3", key + "-etag4"} + etags [4]string + ) + const ( + firstValue = "first-value" + secondValue = "second-value" + thirdValue = "third-value" + ) // Check if eTag feature is listed features := statestore.Features() require.True(t, state.FeatureETag.IsPresent(features)) - // Delete any potential object, it's important to start from a clean slate. - err := statestore.Delete(context.Background(), &state.DeleteRequest{ - Key: testKey, - }) + // Set some objects (no etag as they are new) + err := statestore.BulkSet(context.Background(), []state.SetRequest{ + {Key: testKeys[0], Value: firstValue}, + {Key: testKeys[1], Value: firstValue}, + {Key: testKeys[2], Value: firstValue}, + {Key: testKeys[3], Value: firstValue}, + }, state.BulkStoreOpts{}) require.NoError(t, err) - // Set an object. - err = statestore.Set(context.Background(), &state.SetRequest{ - Key: testKey, - Value: firstValue, - }) - require.NoError(t, err) - - // Validate the set. + // Validate the set, using both regular Get and BulkGet res, err := statestore.Get(context.Background(), &state.GetRequest{ - Key: testKey, + Key: testKeys[0], }) require.NoError(t, err) + require.NotNil(t, res.ETag) + require.NotEmpty(t, *res.ETag) assertEquals(t, firstValue, res) - etag := res.ETag + etags[0] = *res.ETag - // Try and update with wrong ETag, expect failure. + bulkRes, err := statestore.BulkGet(context.Background(), []state.GetRequest{ + {Key: testKeys[1]}, + {Key: testKeys[2]}, + {Key: testKeys[3]}, + }, state.BulkGetOpts{}) + require.NoError(t, err) + require.Len(t, bulkRes, 3) + for i := 0; i < 3; i++ { + require.NotNil(t, bulkRes[i].ETag) + require.NotEmpty(t, *bulkRes[i].ETag) + assertDataEquals(t, firstValue, bulkRes[i].Data) + switch bulkRes[i].Key { + case testKeys[1]: + etags[1] = *bulkRes[i].ETag + case testKeys[2]: + etags[2] = *bulkRes[i].ETag + case testKeys[3]: + etags[3] = *bulkRes[i].ETag + } + } + + // Try and update with wrong ETag, expect failure err = statestore.Set(context.Background(), &state.SetRequest{ - Key: testKey, + Key: testKeys[0], Value: secondValue, - ETag: &fakeEtag, + ETag: &config.BadEtag, }) require.Error(t, err) + require.ErrorAs(t, err, &etagErr) + assert.Equal(t, state.ETagMismatch, etagErr.Kind()) - // Try and update with corect ETag, expect success. + // Try and update with Set and corect ETag, expect success err = statestore.Set(context.Background(), &state.SetRequest{ - Key: testKey, + Key: testKeys[0], Value: secondValue, - ETag: etag, + ETag: &etags[0], }) require.NoError(t, err) - // Validate the set. + // Validate the Set res, err = statestore.Get(context.Background(), &state.GetRequest{ - Key: testKey, + Key: testKeys[0], }) require.NoError(t, err) assertEquals(t, secondValue, res) - require.NotEqual(t, etag, res.ETag) - etag = res.ETag + require.NotNil(t, res.ETag) + require.NotEqual(t, etags[0], *res.ETag) + etags[0] = *res.ETag - // Try and delete with wrong ETag, expect failure. - err = statestore.Delete(context.Background(), &state.DeleteRequest{ - Key: testKey, - ETag: &fakeEtag, - }) + // Try and update bulk with one ETag wrong, expect partial success + err = statestore.BulkSet(context.Background(), []state.SetRequest{ + {Key: testKeys[1], Value: secondValue, ETag: &config.BadEtag}, + {Key: testKeys[2], Value: secondValue, ETag: &etags[2]}, + }, state.BulkStoreOpts{}) require.Error(t, err) + unwrapErr, ok := err.(interface{ Unwrap() []error }) + require.True(t, ok, "Returned error is not a joined error") + errs := unwrapErr.Unwrap() + require.Len(t, errs, 1) + require.ErrorAs(t, errs[0], &bulkStoreErr) + assert.Equal(t, testKeys[1], bulkStoreErr.Key()) + etagErr = bulkStoreErr.ETagError() + require.NotNil(t, etagErr) + assert.Equal(t, state.ETagMismatch, etagErr.Kind()) - // Try and delete with correct ETag, expect success. - err = statestore.Delete(context.Background(), &state.DeleteRequest{ - Key: testKey, - ETag: etag, + // Validate: key 1 should be unchanged, and key 2 should be changed + res, err = statestore.Get(context.Background(), &state.GetRequest{ + Key: testKeys[1], }) require.NoError(t, err) + assertEquals(t, firstValue, res) + require.NotNil(t, res.ETag) + require.Equal(t, etags[1], *res.ETag) + + res, err = statestore.Get(context.Background(), &state.GetRequest{ + Key: testKeys[2], + }) + require.NoError(t, err) + assertEquals(t, secondValue, res) + require.NotNil(t, res.ETag) + require.NotEqual(t, etags[2], *res.ETag) + etags[2] = *res.ETag + + // Update bulk with valid etags + err = statestore.BulkSet(context.Background(), []state.SetRequest{ + {Key: testKeys[1], Value: thirdValue, ETag: &etags[1]}, + {Key: testKeys[2], Value: thirdValue, ETag: &etags[2]}, + }, state.BulkStoreOpts{}) + require.NoError(t, err) + + // Validate + bulkRes, err = statestore.BulkGet(context.Background(), []state.GetRequest{ + {Key: testKeys[1]}, + {Key: testKeys[2]}, + }, state.BulkGetOpts{}) + require.NoError(t, err) + require.Len(t, bulkRes, 2) + for i := 0; i < 2; i++ { + require.NotNil(t, bulkRes[i].ETag) + require.NotEmpty(t, *bulkRes[i].ETag) + assertDataEquals(t, thirdValue, bulkRes[i].Data) + switch bulkRes[i].Key { + case testKeys[1]: + etags[1] = *bulkRes[i].ETag + case testKeys[2]: + etags[2] = *bulkRes[i].ETag + } + } + + // Try and delete with wrong ETag, expect failure + err = statestore.Delete(context.Background(), &state.DeleteRequest{ + Key: testKeys[0], + ETag: &config.BadEtag, + }) + require.Error(t, err) + require.ErrorAs(t, err, &etagErr) + assert.NotEmpty(t, etagErr.Kind()) + + // Try and delete with correct ETag, expect success + err = statestore.Delete(context.Background(), &state.DeleteRequest{ + Key: testKeys[0], + ETag: &etags[0], + }) + require.NoError(t, err) + + // Validate missing + res, err = statestore.Get(context.Background(), &state.GetRequest{ + Key: testKeys[0], + }) + require.NoError(t, err) + require.Empty(t, res.Data) + require.Empty(t, res.ETag) + + // Try and delete bulk with two ETag's wrong, expect partial success + err = statestore.BulkDelete(context.Background(), []state.DeleteRequest{ + {Key: testKeys[1], ETag: &etags[1]}, + {Key: testKeys[2], ETag: &config.BadEtag}, + }, state.BulkStoreOpts{}) + require.Error(t, err) + unwrapErr, ok = err.(interface{ Unwrap() []error }) + require.True(t, ok, "Returned error is not a joined error") + errs = unwrapErr.Unwrap() + require.Len(t, errs, 1) + require.ErrorAs(t, errs[0], &bulkStoreErr) + assert.Equal(t, testKeys[2], bulkStoreErr.Key()) + etagErr = bulkStoreErr.ETagError() + require.NotNil(t, etagErr) + assert.Equal(t, state.ETagMismatch, etagErr.Kind()) + + // Validate key 1 missing + res, err = statestore.Get(context.Background(), &state.GetRequest{ + Key: testKeys[1], + }) + require.NoError(t, err) + require.Empty(t, res.Data) + require.Empty(t, res.ETag) + + // Validate key 2 unchanged + res, err = statestore.Get(context.Background(), &state.GetRequest{ + Key: testKeys[2], + }) + require.NoError(t, err) + assertEquals(t, thirdValue, res) + require.NotNil(t, res.ETag) + require.Equal(t, etags[2], *res.ETag) + + // Try and delete bulk with valid ETags + err = statestore.BulkDelete(context.Background(), []state.DeleteRequest{ + {Key: testKeys[2], ETag: &etags[2]}, + {Key: testKeys[3], ETag: &etags[3]}, + }, state.BulkStoreOpts{}) + require.NoError(t, err) + + // Validate keys missing + bulkRes, err = statestore.BulkGet(context.Background(), []state.GetRequest{ + {Key: testKeys[2]}, + {Key: testKeys[3]}, + }, state.BulkGetOpts{}) + require.NoError(t, err) + require.Len(t, bulkRes, 2) + foundKeys := []string{} + for i := 0; i < 2; i++ { + require.Empty(t, bulkRes[i].Data) + require.Empty(t, bulkRes[i].ETag) + foundKeys = append(foundKeys, bulkRes[i].Key) + } + expectKeys := []string{ + testKeys[2], + testKeys[3], + } + slices.Sort(foundKeys) + slices.Sort(expectKeys) + assert.EqualValues(t, expectKeys, foundKeys) }) } else { - // Check if eTag feature is NOT listed - features := statestore.Features() - require.False(t, state.FeatureETag.IsPresent(features)) + t.Run("etag feature not present", func(t *testing.T) { + features := statestore.Features() + require.False(t, state.FeatureETag.IsPresent(features)) + }) } if config.HasOperation("first-write") { t.Run("first-write without etag", func(t *testing.T) { - testKey := "first-writeTest" + testKey := key + "-firstwrite-test" firstValue := []byte("testValue1") secondValue := []byte("testValue2") @@ -731,10 +922,11 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St }) require.NoError(t, err) + // Set the value err = statestore.Set(context.Background(), requestSet[0]) require.NoError(t, err) - // Validate the set. + // Validate the set res, err := statestore.Get(context.Background(), &state.GetRequest{ Key: testKey, }) @@ -749,7 +941,7 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St }) t.Run("first-write with etag", func(t *testing.T) { - testKey := "first-writeTest" + testKey := key + "-firstwrite-etag-test" firstValue := []byte("testValue1") secondValue := []byte("testValue2") @@ -758,13 +950,7 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St Value: firstValue, } - // Delete any potential object, it's important to start from a clean slate. - err := statestore.Delete(context.Background(), &state.DeleteRequest{ - Key: testKey, - }) - require.NoError(t, err) - - err = statestore.Set(context.Background(), request) + err := statestore.Set(context.Background(), request) require.NoError(t, err) // Validate the set. @@ -862,6 +1048,8 @@ func assertDataEquals(t *testing.T, expect any, actual []byte) { assert.Equal(t, expect, v) case []byte: assert.Equal(t, expect, actual) + case nil: + assert.Empty(t, actual) default: // Other golang primitive types (string, bool ...) if err := json.Unmarshal(actual, &v); err != nil {