diff --git a/.github/workflows/js-sdk-ci.yml b/.github/workflows/js-sdk-ci.yml index 2cbfd71..b30d0b9 100644 --- a/.github/workflows/js-sdk-ci.yml +++ b/.github/workflows/js-sdk-ci.yml @@ -28,29 +28,6 @@ jobs: - name: Run check run: npm run check:ts-compat - test-node: - runs-on: ${{ matrix.os }} - strategy: - matrix: - node-version: [14.x, 16.x, 18.x, 20.x, 22.x] - os: [ubuntu-latest, windows-latest, macOS-latest] - exclude: - - node-version: 14.x - os: macOS-latest - name: Node.js ${{ matrix.node-version }} (${{ matrix.os }}) test - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version: ${{ matrix.node-version }} - - - name: Install dependencies & build - run: npm install - - - name: Test - run: npm run test:node - test-browser-chrome: runs-on: ubuntu-latest strategy: @@ -62,7 +39,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - name: Setup chrome uses: browser-actions/setup-chrome@latest @@ -86,7 +63,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - name: Setup chrome uses: browser-actions/setup-chrome@latest @@ -110,7 +87,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - name: Setup firefox uses: browser-actions/setup-firefox@latest @@ -123,6 +100,30 @@ jobs: - name: Test run: npm run test:browser:firefox + test-bun: + runs-on: ${{ matrix.os }} + strategy: + matrix: + bun-version: ["1.1.0", "1.1.34"] + # Bun fails to run tests on ubuntu-latest and macOS-latest. + # It may not be possible at all for now: https://github.com/oven-sh/bun/issues/10001 + # Bun version "latest" (1.1.36) seems to have a regression, + # so we use 1.1.34 until it fixed. + os: [windows-latest] + name: Bun ${{ matrix.bun-version }} (${{ matrix.os }}) test + steps: + - uses: actions/checkout@v4 + + - uses: oven-sh/setup-bun@v2 + with: + bun-version: ${{ matrix.bun-version }} + + - name: Install dependencies & build + run: npm install + + - name: Test + run: npm run test:bun + test-chromium-extension-chrome: runs-on: ubuntu-latest strategy: @@ -134,7 +135,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - name: Setup chrome uses: browser-actions/setup-chrome@latest @@ -158,7 +159,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - name: Setup chrome uses: browser-actions/setup-chrome@latest @@ -171,6 +172,25 @@ jobs: - name: Test run: CHROMIUM_BIN=$(which chrome) npm run test:chromium-extension:chromium + test-cloudflare-worker: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest] + name: Cloudflare Worker (${{ matrix.os }}) test + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 18 + + - name: Install dependencies & build + run: npm install + + - name: Test + run: npm run test:cloudflare-worker + test-deno: runs-on: ${{ matrix.os }} strategy: @@ -196,13 +216,38 @@ jobs: - name: Test run: npm run test:deno + test-node: + runs-on: ${{ matrix.os }} + strategy: + matrix: + node-version: [14.x, 16.x, 18.x, 20.x, 22.x] + os: [ubuntu-latest, windows-latest, macOS-latest] + exclude: + - node-version: 14.x + os: macOS-latest + name: Node.js ${{ matrix.node-version }} (${{ matrix.os }}) test + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + + - name: Install dependencies & build + run: npm install + + - name: Test + run: npm run test:node + coverage: needs: [ check-ts-compat, - test-node, test-browser-chrome, test-browser-chromium, test-browser-firefox, + test-bun, test-chromium-extension-chrome, test-chromium-extension-chromium, - test-deno + test-cloudflare-worker, + test-deno, + test-node ] runs-on: ubuntu-latest steps: @@ -211,7 +256,7 @@ jobs: fetch-depth: 0 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - name: Install dependencies & build run: npm install @@ -240,7 +285,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 registry-url: 'https://registry.npmjs.org' - name: Install dependencies diff --git a/.gitignore b/.gitignore index a4e6304..5f0fd57 100644 --- a/.gitignore +++ b/.gitignore @@ -61,5 +61,6 @@ lib/ dist/ .idea/ .parcel-cache/ +bun.lockb deno.lock -deno.import-map.json \ No newline at end of file +deno.import-map.json diff --git a/.npmignore b/.npmignore index 2f0307b..37718ef 100644 --- a/.npmignore +++ b/.npmignore @@ -26,4 +26,5 @@ lib/**/*.map test/ tsconfig*.json types/ -webpack.*.config.js \ No newline at end of file +webpack.*.config.js +workerd.config.capnp \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index 69cb748..392f00e 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -30,6 +30,45 @@ "/base/": "${workspaceRoot}/" } }, + { + // This configuration needs the `oven.bun-vscode` extension to be installed. + "type": "bun", + "name": "Run tests (Bun)", + "request": "launch", + "cwd": "${workspaceFolder}", + "runtime": "bun", + "runtimeArgs": ["--tsconfig-override ./tsconfig.mocha.bun.json"], + "program": "./node_modules/mocha/bin/mocha.js", + "args": [ + "test/bun/index.ts", + "--fgrep", + "", + "--color", + "--exit", + "--timeout", + "30000" + ], + "noDebug": false, + }, + { + "type": "node", + "name": "Run tests (Deno)", + "request": "launch", + "cwd": "${workspaceFolder}", + "runtimeExecutable": "deno", + "runtimeArgs": [ + "run", + "--inspect", + "-A", + "test/deno/index.ts", + "--fgrep", + "", + "--timeout", + "30000" + ], + "attachSimplePort": 9229, + "outputCapture": "std" + }, { "type": "node", "request": "launch", @@ -62,25 +101,6 @@ "skipFiles": [ "/**/*.js" ] - }, - { - "type": "node", - "name": "Run tests (Deno)", - "request": "launch", - "cwd": "${workspaceFolder}", - "runtimeExecutable": "deno", - "runtimeArgs": [ - "run", - "--inspect-brk", - "-A", - "test/deno/index.ts", - "--fgrep", - "", - "--timeout", - "30000" - ], - "attachSimplePort": 9229, - "outputCapture": "std" } ] } \ No newline at end of file diff --git a/README.md b/README.md index bba4a50..c57b26d 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,22 @@ ConfigCat SDK for JavaScript provides easy integration for your application to [ConfigCat](https://configcat.com). +This repository hosts the next generation of the ConfigCat SDK for JavaScript platforms. It ships in the form of a single, unified NPM package for +different JS platforms, as opposed to the one package per platform model used before. + +The new SDK combines and, thus, supersedes these packages: +* [configcat-common](https://www.npmjs.com/package/configcat-common) +* [configcat-js](https://www.npmjs.com/package/configcat-js) +* [configcat-js-ssr](https://www.npmjs.com/package/configcat-js-ssr) +* [configcat-js-chromium-extension](https://www.npmjs.com/package/configcat-js-chromium-extension) +* [configcat-node](https://www.npmjs.com/package/configcat-node) + +The new SDK maintains backward compatibility, so it can be used as a drop-in replacement for the packages listed above. In most cases you just need to +replace the old package with the new and adjust the import specifiers (as shown [here](#1-install-and-import-package)). + +> [!CAUTION] +> Please note that the SDK is still under development and is currently in beta phase. Use it at your own risk. + ## Getting Started ### 1. Install and import package: @@ -25,7 +41,7 @@ npm i @configcat/sdk Then import it into your application: -* Frontend applications running in the browser: +* Frontend applications and Web Workers running in the browser: ```js import * as configcat from "@configcat/sdk/browser"; ``` @@ -35,6 +51,11 @@ Then import it into your application: import * as configcat from "@configcat/sdk/node"; ``` +* Bun backend applications: + ```js + import * as configcat from "@configcat/sdk/bun"; + ``` + * Deno backend applications: ```js import * as configcat from "npm:@configcat/sdk/deno"; @@ -42,6 +63,11 @@ Then import it into your application: (To make this work, you may need to enable the [unstable-byonm](https://docs.deno.com/runtime/manual/tools/unstable_flags/#--unstable-byonm) feature or adjust your [import map](https://docs.deno.com/runtime/manual/basics/import_maps/).) +* Cloudflare Workers: + ```js + import * as configcat from "@configcat/sdk/cloudflare-worker"; + ``` + * Extensions for Chromium-based browsers (Chrome, Edge, etc.): ```js import * as configcat from "@configcat/sdk/chromium-extension"; @@ -53,7 +79,7 @@ Then import it into your application: Import the package directly from a CDN server into your application: -* Frontend applications running in the browser: +* Frontend applications and Web Workers running in the browser: ```html @@ -74,7 +100,7 @@ Import the package directly from a CDN server into your application: ``` ### 2. Go to the ConfigCat Dashboard to get your *SDK Key*: -![SDK-KEY](https://raw.githubusercontent.com/ConfigCat/js-sdk/master/media/readme02-3.png "SDK-KEY") +![SDK-KEY](https://raw.githubusercontent.com/configcat/js-unified-sdk/master/media/readme02-3.png "SDK-KEY") ### 3. Create a *ConfigCat* client instance: ```js @@ -131,7 +157,7 @@ if (value) { ## Sample/Demo apps - [Plain HTML + JS](https://github.com/configcat/js-unified-sdk/tree/master/samples/html) - [Plain HTML + JS using ECMAScript module system](https://github.com/configcat/js-unified-sdk/tree/master/samples/html-esm) - - [Plain HTML + bundled TS running the SDK in a Web Worker](https://github.com/configcat/js-unified-sdk/tree/master/samples/web-worker) + - [Plain HTML + TS running the SDK in a Web Worker](https://github.com/configcat/js-unified-sdk/tree/master/samples/web-worker) - [Sample Angular web application](https://github.com/configcat/js-unified-sdk/tree/master/samples/angular-sample) - [Sample React web application](https://github.com/configcat/js-unified-sdk/tree/master/samples/react-sample) - [Sample React Native application](https://github.com/configcat/js-unified-sdk/tree/master/samples/react-native-sample) @@ -142,7 +168,9 @@ if (value) { - [Sample Node.js console application using TypeScript and ECMAScript module system](https://github.com/configcat/js-unified-sdk/tree/master/samples/ts-node-console-esm) - [Sample Node.js application using Express and Docker](https://github.com/configcat/js-unified-sdk/tree/master/samples/node-expresswithdocker) - [Sample Node.js application on how to get real time updates on feature flag changes](https://github.com/configcat/js-unified-sdk/tree/master/samples/node-realtimeupdate) + - [Sample Bun console application](https://github.com/configcat/js-unified-sdk/tree/master/samples/bun-console) - [Sample Deno console application](https://github.com/configcat/js-unified-sdk/tree/master/samples/deno-console) + - [Sample Cloudflare Worker](https://github.com/configcat/js-unified-sdk/tree/master/samples/cloudflare-worker) - [Sample Chrome extension](https://github.com/configcat/js-unified-sdk/tree/master/samples/chrome-extension) ## Polling Modes @@ -193,13 +221,17 @@ The SDK is [tested](https://github.com/configcat/js-unified-sdk/blob/master/.git - Chrome (stable, latest, beta) - Chromium (64.0.3282.0, 72.0.3626.0, 80.0.3987.0) - Firefox (latest, latest-beta, 84.0) -- @configcat/sdk/chromium-extension: - - Chrome (stable, latest, beta) - - Chromium (72.0.3626.0, 80.0.3987.0) +- @configcat/sdk/bun: + - Bun (v1.1.0, v1.1.34) on Windows - @configcat/sdk/deno: - Deno (v1.31, v1.46, latest stable) on Windows / Ubuntu / macOS - @configcat/sdk/node: - Node.js (v14.x, v16.x, v18.x, v20.x, v22.x) on Windows / Ubuntu / macOS +- @configcat/sdk/cloudflare-worker: + - Workerd (2023-02-28) +- @configcat/sdk/chromium-extension: + - Chrome (stable, latest, beta) + - Chromium (72.0.3626.0, 80.0.3987.0) The SDK should be compatible with TypeScript v4.0.2 or newer. Earlier versions may work but those are not tested, thus, not supported officially. diff --git a/media/readme02-3.png b/media/readme02-3.png new file mode 100644 index 0000000..f036542 Binary files /dev/null and b/media/readme02-3.png differ diff --git a/package-lock.json b/package-lock.json index 39a3a13..d9a04dd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,20 +1,23 @@ { "name": "@configcat/sdk", - "version": "0.0.1", + "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@configcat/sdk", - "version": "0.0.1", + "version": "0.1.0", "license": "MIT", "dependencies": { "tunnel": "^0.0.6" }, "devDependencies": { "@babel/preset-env": "^7.20.2", + "@cloudflare/workers-types": "^4.20241106.0", + "@types/bun": "^1.1.13", "@types/chai": "~4.3.4", "@types/chrome": "~0.0.270", + "@types/deno": "^2.0.0", "@types/mocha": "~10.0.1", "@types/node": "~18.19.7", "@types/tunnel": "~0.0.7", @@ -22,6 +25,7 @@ "@typescript-eslint/parser": "^5.53.0", "babel-loader": "^9.1.0", "chai": "^4.3.7", + "concurrently": "^9.1.0", "core-js": "^3.38.1", "coverage-istanbul-loader": "^3.0.5", "cross-env": "^7.0.3", @@ -52,7 +56,8 @@ "tslib": "^2.7.0", "typescript": "^5.5.4", "webpack": "^5.94.0", - "webpack-cli": "^5.1.4" + "webpack-cli": "^5.1.4", + "workerd": "^1.20241112.0" } }, "node_modules/@ampproject/remapping": { @@ -1594,6 +1599,98 @@ "node": ">=6.9.0" } }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20241112.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20241112.0.tgz", + "integrity": "sha512-6qEuouKI7mdvbQZxzTvvNQ/Po5I/K3COWcq7msULdZbFwG5nwoQW2oBrWGo9Y6ib5A70eoqqK30pNX9DyoI/aQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20241112.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20241112.0.tgz", + "integrity": "sha512-pZ3Uy8TsRScD70anjyJz7TssMJqz1P++6Yzi/5Ikw3PrDYYQ8TyUmL4isOjpy8+5W/QFPOxX7+PvdqD/WiJaJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20241112.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20241112.0.tgz", + "integrity": "sha512-flThiCPdKRrfYFISdp16XODT/iqt5WU2xhMCsvreI9W9Q4XUa0aHzUSVyHesMd1NkwWGBFs8QRzzuaBnyKy4RQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20241112.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20241112.0.tgz", + "integrity": "sha512-1pFDH2GFHB7AMsQypKaUDUi0gPDkQlfN1d3OdOnYjvU9CaLKcAMnVxVfD44RcTxPcC7VviCvwKP7tnmYuJPvow==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20241112.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20241112.0.tgz", + "integrity": "sha512-7UdKHqSxEIF5gLd1oqrNOvfluGnyKu1jSPVBAcpSXZS3/cCJ6VwziFFThGM2ysuyb7o5uSCVtx/w+mPjWU4TdA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workers-types": { + "version": "4.20241112.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20241112.0.tgz", + "integrity": "sha512-Q4p9bAWZrX14bSCKY9to19xl0KMU7nsO5sJ2cTVspHoypsjPUMeQCsjHjmsO2C4Myo8/LPeDvmqFmkyNAPPYZw==", + "dev": true, + "license": "MIT OR Apache-2.0" + }, "node_modules/@colors/colors": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", @@ -2308,6 +2405,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/bun": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.1.13.tgz", + "integrity": "sha512-KmQxSBgVWCl6RSuerlLGZlIWfdxkKqat0nxN61+qu4y1KDn0Ll3j7v1Pl8GnaL3a/U6GGWVTJh75ap62kR1E8Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "bun-types": "1.1.34" + } + }, "node_modules/@types/chai": { "version": "4.3.20", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.20.tgz", @@ -2343,6 +2450,13 @@ "@types/node": "*" } }, + "node_modules/@types/deno": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@types/deno/-/deno-2.0.0.tgz", + "integrity": "sha512-O9/jRVlq93kqfkl4sYR5N7+Pz4ukzXVIbMnE/VgvpauNHsvjQ9iBVnJ3X0gAvMa2khcoFD8DSO7mQVCuiuDMPg==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", @@ -3736,6 +3850,27 @@ "dev": true, "license": "MIT" }, + "node_modules/bun-types": { + "version": "1.1.34", + "resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.1.34.tgz", + "integrity": "sha512-br5QygTEL/TwB4uQOb96Ky22j4Gq2WxWH/8Oqv20fk5HagwKXo/akB+LiYgSfzexCt6kkcUaVm+bKiPl71xPvw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "~20.12.8", + "@types/ws": "~8.5.10" + } + }, + "node_modules/bun-types/node_modules/@types/node": { + "version": "20.12.14", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.12.14.tgz", + "integrity": "sha512-scnD59RpYD91xngrQQLGkE+6UrHUPzeKZWhhjBSa3HSkwjbQc38+q3RoIVEwxQGRw3M+j5hpNAM+lgV3cVormg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -4127,6 +4262,186 @@ "dev": true, "license": "MIT" }, + "node_modules/concurrently": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.1.0.tgz", + "integrity": "sha512-VxkzwMAn4LP7WyMnJNbHN5mKV9L2IbyDjpzemKr99sXNR3GqRNMMHdm7prV1ws9wg7ETj6WUkNOigZVsptwbgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.2", + "lodash": "^4.17.21", + "rxjs": "^7.8.1", + "shell-quote": "^1.8.1", + "supports-color": "^8.1.1", + "tree-kill": "^1.2.2", + "yargs": "^17.7.2" + }, + "bin": { + "conc": "dist/bin/concurrently.js", + "concurrently": "dist/bin/concurrently.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/open-cli-tools/concurrently?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/chalk/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/concurrently/node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/concurrently/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/concurrently/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/concurrently/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/concurrently/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/concurrently/node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/connect": { "version": "3.7.0", "resolved": "https://registry.npmjs.org/connect/-/connect-3.7.0.tgz", @@ -4325,9 +4640,9 @@ } }, "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==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, "license": "MIT", "dependencies": { @@ -10655,6 +10970,16 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/rxjs": { + "version": "7.8.1", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", + "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, "node_modules/safe-array-concat": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz", @@ -10992,6 +11317,16 @@ "node": ">=8" } }, + "node_modules/shell-quote": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.1.tgz", + "integrity": "sha512-6j1W9l1iAs/4xYBI1SYOVZyFcCis9b4KCLQ8fgAGG07QvzaRLVVRQvAy85yNmmZSjYjg4MWh4gNvlPujU/5LpA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/side-channel": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", @@ -11739,6 +12074,16 @@ "dev": true, "license": "MIT" }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, "node_modules/ts-loader": { "version": "9.5.1", "resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-9.5.1.tgz", @@ -12919,6 +13264,27 @@ "node": ">=0.10.0" } }, + "node_modules/workerd": { + "version": "1.20241112.0", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20241112.0.tgz", + "integrity": "sha512-Z9eIgNdjgiwr5C7Yzwkgn9fLY8SvElKd9hx5SPLRkavXqkkuwRpT0Pcgrs+zxjTR2S5gDpziX/urRYSqZ/fjRA==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20241112.0", + "@cloudflare/workerd-darwin-arm64": "1.20241112.0", + "@cloudflare/workerd-linux-64": "1.20241112.0", + "@cloudflare/workerd-linux-arm64": "1.20241112.0", + "@cloudflare/workerd-windows-64": "1.20241112.0" + } + }, "node_modules/workerpool": { "version": "6.5.1", "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.5.1.tgz", diff --git a/package.json b/package.json index cd5e0bc..de02a59 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@configcat/sdk", - "version": "0.0.1", + "version": "0.1.0", "description": "ConfigCat is a configuration as a service that lets you manage your features and configurations without actually deploying new code.", "main": "lib/cjs/node/index.root.js", "types": "lib/cjs/node/index.root.d.ts", @@ -8,12 +8,16 @@ "exports": { ".": { "types": { + "bun": "./lib/esm/bun/index.d.ts", "deno": "./lib/esm/deno/index.d.ts", + "workerd": "./lib/esm/cloudflare-worker/index.d.ts", "browser": "./lib/esm/browser/index.root.d.ts", "import": "./lib/esm/node/index.root.d.ts", "require": "./lib/cjs/node/index.root.d.ts" }, + "bun": "./lib/esm/bun/index.js", "deno": "./lib/esm/deno/index.js", + "workerd": "./lib/esm/cloudflare-worker/index.js", "browser": "./lib/esm/browser/index.root.js", "import": "./lib/esm/node/index.root.js", "require": "./lib/cjs/node/index.root.js" @@ -22,10 +26,18 @@ "types": "./lib/esm/browser/index.d.ts", "import": "./lib/esm/browser/index.js" }, + "./bun": { + "types": "./lib/esm/bun/index.d.ts", + "import": "./lib/esm/bun/index.js" + }, "./chromium-extension": { "types": "./lib/esm/chromium-extension/index.d.ts", "import": "./lib/esm/chromium-extension/index.js" }, + "./cloudflare-worker": { + "types": "./lib/esm/cloudflare-worker/index.d.ts", + "import": "./lib/esm/cloudflare-worker/index.js" + }, "./deno": { "types": "./lib/esm/deno/index.d.ts", "deno": "./lib/esm/deno/index.js" @@ -45,9 +57,15 @@ "#lib/browser": { "browser": "./lib/esm/browser/index.js" }, + "#lib/bun": { + "browser": "./lib/esm/bun/index.js" + }, "#lib/chromium-extension": { "browser": "./lib/esm/chromium-extension/index.js" }, + "#lib/cloudflare-worker": { + "browser": "./lib/esm/cloudflare-worker/index.js" + }, "#lib/node": { "require": "./lib/cjs/node/index.js" }, @@ -74,11 +92,13 @@ "test:browser:chrome": "karma start karma.browser.chrome.conf.js", "test:browser:chromium": "karma start karma.browser.chromium.conf.js", "test:browser:firefox": "karma start karma.browser.firefox.conf.js", + "test:bun": "bun run --tsconfig-override ./tsconfig.mocha.bun.json ./node_modules/mocha/bin/mocha.js test/bun/index.ts --timeout 30000", "test:chromium-extension:chrome": "karma start karma.chromium-extension.chrome.conf.js", "test:chromium-extension:chromium": "karma start karma.chromium-extension.chromium.conf.js", + "test:cloudflare-worker": "webpack -c webpack.workerd.cloudflare-worker.config.js && concurrently --raw --success command-1 --kill-others \"node test/cloudflare-worker/test-run-helper/server.mjs\" \"workerd test workerd.config.capnp\"", "test:deno": "node deno.import-map.generator.js && node deno.set-env.js deno run $DENO_NODE_MODULES_DIR -A test/deno/index.ts --timeout 30000", "test:node": "cross-env NODE_EXTRA_CA_CERTS=./test/node/cert/testCA.pem TS_NODE_PROJECT=./tsconfig.mocha.node.json node --expose-gc --require ts-node/register node_modules/mocha/bin/_mocha 'test/node/index.ts' --exit --timeout 30000", - "test": "npm run check:ts-compat && npm run test:node && npm run test:browser:chrome && npm run test:chromium-extension:chrome && npm run test:deno" + "test": "npm run check:ts-compat && npm run test:browser:chrome && npm run test:chromium-extension:chrome && npm run test:cloudflare-worker && npm run test:bun && npm run test:deno && npm run test:node" }, "keywords": [ "configcat", @@ -101,8 +121,11 @@ }, "devDependencies": { "@babel/preset-env": "^7.20.2", + "@cloudflare/workers-types": "^4.20241106.0", + "@types/bun": "^1.1.13", "@types/chai": "~4.3.4", "@types/chrome": "~0.0.270", + "@types/deno": "^2.0.0", "@types/mocha": "~10.0.1", "@types/node": "~18.19.7", "@types/tunnel": "~0.0.7", @@ -110,6 +133,7 @@ "@typescript-eslint/parser": "^5.53.0", "babel-loader": "^9.1.0", "chai": "^4.3.7", + "concurrently": "^9.1.0", "core-js": "^3.38.1", "coverage-istanbul-loader": "^3.0.5", "cross-env": "^7.0.3", @@ -140,7 +164,8 @@ "tslib": "^2.7.0", "typescript": "^5.5.4", "webpack": "^5.94.0", - "webpack-cli": "^5.1.4" + "webpack-cli": "^5.1.4", + "workerd": "^1.20241112.0" }, "overrides": { "cookie": "0.7.2" diff --git a/samples/angular-sample/package.json b/samples/angular-sample/package.json index a8675e6..cf5692b 100644 --- a/samples/angular-sample/package.json +++ b/samples/angular-sample/package.json @@ -18,7 +18,7 @@ "@angular/platform-browser": "^18.0.0", "@angular/platform-browser-dynamic": "^18.0.0", "@angular/router": "^18.0.0", - "@configcat/sdk": "^0.0.1", + "@configcat/sdk": "^0.1.0", "rxjs": "~7.8.0", "tslib": "^2.3.0", "zone.js": "~0.14.3" diff --git a/samples/bun-console/README.md b/samples/bun-console/README.md new file mode 100644 index 0000000..03ce911 --- /dev/null +++ b/samples/bun-console/README.md @@ -0,0 +1,15 @@ +# Sample application for Bun + +This is a simple console application to demonstrate how to use the ConfigCat SDK on Bun. + +## Install dependencies + +``` +bun install +``` + +## Run + +``` +bun index.ts +``` \ No newline at end of file diff --git a/samples/bun-console/index.ts b/samples/bun-console/index.ts new file mode 100644 index 0000000..dffd208 --- /dev/null +++ b/samples/bun-console/index.ts @@ -0,0 +1,31 @@ +import { createConsoleLogger, getClient, LogLevel, PollingMode, User } from "@configcat/sdk/bun"; + +// Creating the ConfigCat client instance using the SDK Key +const client = getClient( + "configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", + PollingMode.AutoPoll, + { + // Setting log level to Info to show detailed feature flag evaluation + logger: createConsoleLogger(LogLevel.Info), + setupHooks: hooks => hooks + .on("clientReady", () => console.log("Client is ready!")) + }); + +try { + // Creating a user object to identify the user (optional) + const user = new User(""); + user.country = "US"; + user.email = "configcat@example.com"; + user.custom = { + "subscriptionType": "Pro", + "role": "Admin", + "version": "1.0.0" + }; + + // Accessing feature flag or setting value + const value = await client.getValueAsync("isPOCFeatureEnabled", false, user); + console.log(`isPOCFeatureEnabled: ${value}`); +} +finally { + client.dispose(); +} \ No newline at end of file diff --git a/samples/bun-console/package.json b/samples/bun-console/package.json new file mode 100644 index 0000000..71e274f --- /dev/null +++ b/samples/bun-console/package.json @@ -0,0 +1,9 @@ +{ + "name": "app", + "version": "1.0.0", + "description": "Sample application for ConfigCat JS SDK", + "main": "index.js", + "dependencies": { + "@configcat/sdk": "^0.1.0" + } +} diff --git a/samples/bundler-browserify/package.json b/samples/bundler-browserify/package.json index 14f818b..66a3281 100644 --- a/samples/bundler-browserify/package.json +++ b/samples/bundler-browserify/package.json @@ -8,7 +8,7 @@ "start": "npm run build & node ../shared/server.mjs dist" }, "dependencies": { - "@configcat/sdk": "^0.0.1" + "@configcat/sdk": "^0.1.0" }, "devDependencies": { "browserify": "^17.0.0" diff --git a/samples/bundler-browserify/src/index.js b/samples/bundler-browserify/src/index.js index 8051118..a5009a1 100644 --- a/samples/bundler-browserify/src/index.js +++ b/samples/bundler-browserify/src/index.js @@ -11,7 +11,7 @@ function addComponent(value) { const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes -const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); +const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); configCatClient.getValueAsync("isAwesomeFeatureEnabled", false) .then(value => addComponent(value)); diff --git a/samples/bundler-esbuild/package.json b/samples/bundler-esbuild/package.json index c4c5102..077a1c4 100644 --- a/samples/bundler-esbuild/package.json +++ b/samples/bundler-esbuild/package.json @@ -9,7 +9,7 @@ "start": "npm run build & node ../shared/server.mjs dist" }, "dependencies": { - "@configcat/sdk": "^0.0.1" + "@configcat/sdk": "^0.1.0" }, "devDependencies": { "esbuild": "0.20.2" diff --git a/samples/bundler-esbuild/src/index.js b/samples/bundler-esbuild/src/index.js index db12187..f4cb0d9 100644 --- a/samples/bundler-esbuild/src/index.js +++ b/samples/bundler-esbuild/src/index.js @@ -11,7 +11,7 @@ function addComponent(value) { const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes -const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); +const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); configCatClient.getValueAsync("isAwesomeFeatureEnabled", false) .then(value => addComponent(value)); diff --git a/samples/bundler-parcel/package.json b/samples/bundler-parcel/package.json index 29a847c..d047bed 100644 --- a/samples/bundler-parcel/package.json +++ b/samples/bundler-parcel/package.json @@ -9,7 +9,7 @@ "start": "npm run build & node ../shared/server.mjs dist" }, "dependencies": { - "@configcat/sdk": "^0.0.1" + "@configcat/sdk": "^0.1.0" }, "devDependencies": { "parcel": "^2.12.0" diff --git a/samples/bundler-parcel/src/index.js b/samples/bundler-parcel/src/index.js index 0b93c67..3e687d7 100644 --- a/samples/bundler-parcel/src/index.js +++ b/samples/bundler-parcel/src/index.js @@ -11,7 +11,7 @@ function addComponent(value) { const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes -const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); +const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); configCatClient.getValueAsync("isAwesomeFeatureEnabled", false) .then(value => addComponent(value)); diff --git a/samples/bundler-rollup/package.json b/samples/bundler-rollup/package.json index b13e2dd..ad05b03 100644 --- a/samples/bundler-rollup/package.json +++ b/samples/bundler-rollup/package.json @@ -9,7 +9,7 @@ "start": "npm run build & node ../shared/server.mjs dist" }, "dependencies": { - "@configcat/sdk": "^0.0.1" + "@configcat/sdk": "^0.1.0" }, "devDependencies": { "@rollup/plugin-node-resolve": "^15.2.3", diff --git a/samples/bundler-rollup/src/index.js b/samples/bundler-rollup/src/index.js index 0770ec0..3231acb 100644 --- a/samples/bundler-rollup/src/index.js +++ b/samples/bundler-rollup/src/index.js @@ -11,7 +11,7 @@ function addComponent(value) { const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes -const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); +const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); configCatClient.getValueAsync("isAwesomeFeatureEnabled", false) .then(value => addComponent(value)); diff --git a/samples/bundler-webpack/package.json b/samples/bundler-webpack/package.json index fbe6023..4fcce8d 100644 --- a/samples/bundler-webpack/package.json +++ b/samples/bundler-webpack/package.json @@ -9,7 +9,7 @@ "start": "npm run build & node ../shared/server.mjs dist" }, "dependencies": { - "@configcat/sdk": "^0.0.1" + "@configcat/sdk": "^0.1.0" }, "devDependencies": { "webpack": "^5.91.0", diff --git a/samples/bundler-webpack/src/index.js b/samples/bundler-webpack/src/index.js index 0770ec0..3231acb 100644 --- a/samples/bundler-webpack/src/index.js +++ b/samples/bundler-webpack/src/index.js @@ -11,7 +11,7 @@ function addComponent(value) { const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes -const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); +const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); configCatClient.getValueAsync("isAwesomeFeatureEnabled", false) .then(value => addComponent(value)); diff --git a/samples/chrome-extension/package.json b/samples/chrome-extension/package.json index caae647..48dcbe7 100644 --- a/samples/chrome-extension/package.json +++ b/samples/chrome-extension/package.json @@ -9,7 +9,7 @@ "format": "prettier --write --ignore-unknown \"{config,public,src}/**/*.{html,css,js,ts,json}\"" }, "dependencies": { - "@configcat/sdk": "^0.0.1" + "@configcat/sdk": "^0.1.0" }, "devDependencies": { "copy-webpack-plugin": "^10.2.4", diff --git a/samples/chrome-extension/src/main.js b/samples/chrome-extension/src/main.js index 3e45aa6..7b0ed9c 100644 --- a/samples/chrome-extension/src/main.js +++ b/samples/chrome-extension/src/main.js @@ -8,7 +8,7 @@ import * as configcat from "@configcat/sdk/chromium-extension"; const logger = configcat.createConsoleLogger(LogLevel.Info); // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes - const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", PollingMode.AutoPoll, { + const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); diff --git a/samples/cloudflare-worker/.editorconfig b/samples/cloudflare-worker/.editorconfig new file mode 100644 index 0000000..848b061 --- /dev/null +++ b/samples/cloudflare-worker/.editorconfig @@ -0,0 +1,9 @@ +# http://editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/samples/cloudflare-worker/.gitignore b/samples/cloudflare-worker/.gitignore new file mode 100644 index 0000000..3b0fe33 --- /dev/null +++ b/samples/cloudflare-worker/.gitignore @@ -0,0 +1,172 @@ +# Logs + +logs +_.log +npm-debug.log_ +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) + +report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json + +# Runtime data + +pids +_.pid +_.seed +\*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover + +lib-cov + +# Coverage directory used by tools like istanbul + +coverage +\*.lcov + +# nyc test coverage + +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) + +.grunt + +# Bower dependency directory (https://bower.io/) + +bower_components + +# node-waf configuration + +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) + +build/Release + +# Dependency directories + +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) + +web_modules/ + +# TypeScript cache + +\*.tsbuildinfo + +# Optional npm cache directory + +.npm + +# Optional eslint cache + +.eslintcache + +# Optional stylelint cache + +.stylelintcache + +# Microbundle cache + +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history + +.node_repl_history + +# Output of 'npm pack' + +\*.tgz + +# Yarn Integrity file + +.yarn-integrity + +# dotenv environment variable files + +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) + +.cache +.parcel-cache + +# Next.js build output + +.next +out + +# Nuxt.js build / generate output + +.nuxt +dist + +# Gatsby files + +.cache/ + +# Comment in the public line in if your project uses Gatsby and not Next.js + +# https://nextjs.org/blog/next-9-1#public-directory-support + +# public + +# vuepress build output + +.vuepress/dist + +# vuepress v2.x temp and cache directory + +.temp +.cache + +# Docusaurus cache and generated files + +.docusaurus + +# Serverless directories + +.serverless/ + +# FuseBox cache + +.fusebox/ + +# DynamoDB Local files + +.dynamodb/ + +# TernJS port file + +.tern-port + +# Stores VSCode versions used for testing VSCode extensions + +.vscode-test + +# yarn v2 + +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.\* + +# wrangler project + +.dev.vars +.wrangler/ diff --git a/samples/cloudflare-worker/.prettierrc b/samples/cloudflare-worker/.prettierrc new file mode 100644 index 0000000..7e8a656 --- /dev/null +++ b/samples/cloudflare-worker/.prettierrc @@ -0,0 +1,7 @@ +{ + "printWidth": 140, + "singleQuote": true, + "semi": true, + "useTabs": false, + "tabWidth": 2 +} \ No newline at end of file diff --git a/samples/cloudflare-worker/README.md b/samples/cloudflare-worker/README.md new file mode 100644 index 0000000..75fcc15 --- /dev/null +++ b/samples/cloudflare-worker/README.md @@ -0,0 +1,14 @@ +# ConfigCat Sample Cloudflare Worker + +To run this sample, execute: + +```bash +npm install +npm run dev +``` + +To deploy the sample worker into Cloudflare, execute: + +```bash +npm run deploy +``` diff --git a/samples/cloudflare-worker/package.json b/samples/cloudflare-worker/package.json new file mode 100644 index 0000000..9ffc848 --- /dev/null +++ b/samples/cloudflare-worker/package.json @@ -0,0 +1,22 @@ +{ + "name": "cloudflare-worker-sample", + "version": "0.0.0", + "private": true, + "scripts": { + "deploy": "wrangler deploy", + "dev": "wrangler dev", + "start": "wrangler dev", + "test": "vitest", + "cf-typegen": "wrangler types" + }, + "devDependencies": { + "@cloudflare/vitest-pool-workers": "^0.5.2", + "@cloudflare/workers-types": "^4.20241112.0", + "typescript": "^5.5.2", + "vitest": "2.0.5", + "wrangler": "^3.60.3" + }, + "dependencies": { + "@configcat/sdk": "^0.1.0" + } +} diff --git a/samples/cloudflare-worker/src/index.ts b/samples/cloudflare-worker/src/index.ts new file mode 100644 index 0000000..60c8df4 --- /dev/null +++ b/samples/cloudflare-worker/src/index.ts @@ -0,0 +1,39 @@ +import { LogLevel, OverrideBehaviour, PollingMode, User, createConsoleLogger, createFlagOverridesFromQueryParams, getClient } from "@configcat/sdk/cloudflare-worker"; + +export default { + async fetch(request, env, ctx): Promise { + // Creating the ConfigCat client instance using the SDK Key + const client = getClient( + "configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", + // For short-lived workers it is recommended to use Lazy Loading mode + PollingMode.LazyLoad, + { + // Setting cache TTL (specify a reasonable value in your application) + cacheTimeToLiveSeconds: 10, + // Setting log level to Info to show detailed feature flag evaluation + logger: createConsoleLogger(LogLevel.Info), + // Uncomment the next line to enable flag overriding using the query string parameters of the request + // flagOverrides: createFlagOverridesFromQueryParams(OverrideBehaviour.LocalOverRemote, request) + }); + + try { + // Creating a user object to identify the user (optional) + const user = new User(""); + user.country = "US"; + user.email = "configcat@example.com"; + user.custom = { + "subscriptionType": "Pro", + "role": "Admin", + "version": "1.0.0" + }; + + // Accessing feature flag or setting value + const value = await client.getValueAsync("isPOCFeatureEnabled", false, user); + + return await Promise.resolve(new Response(`isPOCFeatureEnabled: ${value}`)); + } + finally { + client.dispose(); + } + }, +} satisfies ExportedHandler; diff --git a/samples/cloudflare-worker/tsconfig.json b/samples/cloudflare-worker/tsconfig.json new file mode 100644 index 0000000..b12af55 --- /dev/null +++ b/samples/cloudflare-worker/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "target": "es2021", + "lib": [ + "es2021" + ], + "jsx": "react-jsx", + "module": "es2022", + "moduleResolution": "Bundler", + "types": [ + "@cloudflare/workers-types/2023-07-01" + ], + "resolveJsonModule": true, + "allowJs": true, + "checkJs": false, + "noEmit": true, + "isolatedModules": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "skipLibCheck": true + }, + "exclude": [ + "test" + ], + "include": [ + "worker-configuration.d.ts", + "src/**/*.ts" + ] +} diff --git a/samples/cloudflare-worker/vitest.config.mts b/samples/cloudflare-worker/vitest.config.mts new file mode 100644 index 0000000..973627c --- /dev/null +++ b/samples/cloudflare-worker/vitest.config.mts @@ -0,0 +1,11 @@ +import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config"; + +export default defineWorkersConfig({ + test: { + poolOptions: { + workers: { + wrangler: { configPath: "./wrangler.toml" }, + }, + }, + }, +}); diff --git a/samples/cloudflare-worker/worker-configuration.d.ts b/samples/cloudflare-worker/worker-configuration.d.ts new file mode 100644 index 0000000..5b2319b --- /dev/null +++ b/samples/cloudflare-worker/worker-configuration.d.ts @@ -0,0 +1,4 @@ +// Generated by Wrangler +// After adding bindings to `wrangler.toml`, regenerate this interface via `npm run cf-typegen` +interface Env { +} diff --git a/samples/cloudflare-worker/wrangler.toml b/samples/cloudflare-worker/wrangler.toml new file mode 100644 index 0000000..01942d4 --- /dev/null +++ b/samples/cloudflare-worker/wrangler.toml @@ -0,0 +1,8 @@ +#:schema node_modules/wrangler/config-schema.json +name = "cloudflare-worker-sample" +main = "src/index.ts" +compatibility_date = "2024-11-12" +compatibility_flags = ["nodejs_compat"] + +[observability] +enabled = true diff --git a/samples/deno-console/README.md b/samples/deno-console/README.md new file mode 100644 index 0000000..4f77043 --- /dev/null +++ b/samples/deno-console/README.md @@ -0,0 +1,9 @@ +# Sample application for Deno + +This is a simple console application to demonstrate how to use the ConfigCat SDK on Deno. + +## Run + +``` +deno task start +``` \ No newline at end of file diff --git a/samples/deno-console/main.ts b/samples/deno-console/main.ts index 9643361..d58d2de 100644 --- a/samples/deno-console/main.ts +++ b/samples/deno-console/main.ts @@ -5,7 +5,7 @@ import { createConsoleLogger, getClient, LogLevel, PollingMode, User } from "../ // Creating the ConfigCat client instance using the SDK Key const client = getClient( - "PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", + "configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", PollingMode.AutoPoll, { // Setting log level to Info to show detailed feature flag evaluation diff --git a/samples/html-esm/index.html b/samples/html-esm/index.html index 0dfa8c2..f8c5158 100644 --- a/samples/html-esm/index.html +++ b/samples/html-esm/index.html @@ -10,7 +10,7 @@ // Setting log level to Info to show detailed feature flag evaluation var logger = configcat.createConsoleLogger(configcat.LogLevel.Info); - var configCatClient = configcat.getClient('PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ', configcat.PollingMode.AutoPoll, { + var configCatClient = configcat.getClient('configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw', configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); diff --git a/samples/html/dynamic.html b/samples/html/dynamic.html index 2c6ceea..efcd0e2 100644 --- a/samples/html/dynamic.html +++ b/samples/html/dynamic.html @@ -70,7 +70,7 @@

ConfigCat Sample Page

target="_blank" rel="noopener noreferrer">Login and copy your SDK Key and Feature Flag Key from ConfigCat. Or Get an SDK Key and Feature Flag Key without registering.

- + diff --git a/samples/html/index.html b/samples/html/index.html index 8a09934..c810921 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -10,7 +10,7 @@ // Setting log level to Info to show detailed feature flag evaluation var logger = configcat.createConsoleLogger(configcat.LogLevel.Info); - var configCatClient = configcat.getClient('PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ', configcat.PollingMode.AutoPoll, { + var configCatClient = configcat.getClient('configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw', configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); diff --git a/samples/node-console-esm/README.md b/samples/node-console-esm/README.md index 8b8783d..b8fd838 100644 --- a/samples/node-console-esm/README.md +++ b/samples/node-console-esm/README.md @@ -1,6 +1,6 @@ # Sample application for Node.js -This is a simple Node.js application to demonstrate how to use the ConfigCat SDK on Node.js. +This is a simple console application to demonstrate how to use the ConfigCat SDK on Node.js using ECMAScript modules. ## Install dependencies diff --git a/samples/node-console-esm/index.js b/samples/node-console-esm/index.js index f2fb56d..0a7e0b4 100644 --- a/samples/node-console-esm/index.js +++ b/samples/node-console-esm/index.js @@ -3,7 +3,7 @@ import * as configcat from "@configcat/sdk/node"; const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes -const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); +const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); const value = await configCatClient.getValueAsync("isAwesomeFeatureEnabled", false); console.log("isAwesomeFeatureEnabled: " + value); diff --git a/samples/node-console-esm/package.json b/samples/node-console-esm/package.json index 1f2c837..4cfad43 100644 --- a/samples/node-console-esm/package.json +++ b/samples/node-console-esm/package.json @@ -5,6 +5,6 @@ "type": "module", "main": "index.js", "dependencies": { - "@configcat/sdk": "^0.0.1" + "@configcat/sdk": "^0.1.0" } } diff --git a/samples/node-console/README.md b/samples/node-console/README.md index 8b8783d..475af3d 100644 --- a/samples/node-console/README.md +++ b/samples/node-console/README.md @@ -1,6 +1,6 @@ # Sample application for Node.js -This is a simple Node.js application to demonstrate how to use the ConfigCat SDK on Node.js. +This is a simple console application to demonstrate how to use the ConfigCat SDK on Node.js. ## Install dependencies diff --git a/samples/node-console/index.js b/samples/node-console/index.js index 5462608..2c89035 100644 --- a/samples/node-console/index.js +++ b/samples/node-console/index.js @@ -4,7 +4,7 @@ var configcat = require("@configcat/sdk/node"); const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes - const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); + const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); const value = await configCatClient.getValueAsync("isAwesomeFeatureEnabled", false); console.log("isAwesomeFeatureEnabled: " + value); diff --git a/samples/node-console/package.json b/samples/node-console/package.json index a4e8c88..71e274f 100644 --- a/samples/node-console/package.json +++ b/samples/node-console/package.json @@ -4,6 +4,6 @@ "description": "Sample application for ConfigCat JS SDK", "main": "index.js", "dependencies": { - "@configcat/sdk": "^0.0.1" + "@configcat/sdk": "^0.1.0" } } diff --git a/samples/node-customcache/index.js b/samples/node-customcache/index.js index af06ebd..132b8b0 100644 --- a/samples/node-customcache/index.js +++ b/samples/node-customcache/index.js @@ -4,7 +4,7 @@ const configcatRedisCache = require("./configcat-redis-cache"); const redisOptions = { host: "localhost", port: 6379 }; -const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, +const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { cache: new configcatRedisCache(redisOptions) }); diff --git a/samples/node-customcache/package.json b/samples/node-customcache/package.json index 54015cd..e39dbb7 100644 --- a/samples/node-customcache/package.json +++ b/samples/node-customcache/package.json @@ -10,7 +10,7 @@ "author": "configcat", "license": "MIT", "dependencies": { - "@configcat/sdk": "^0.0.1", + "@configcat/sdk": "^0.1.0", "redis": "^3.1.2" } } diff --git a/samples/node-expresswithdocker/index.js b/samples/node-expresswithdocker/index.js index 2970df6..207b1e6 100644 --- a/samples/node-expresswithdocker/index.js +++ b/samples/node-expresswithdocker/index.js @@ -1,4 +1,4 @@ -const SDKKEY = "PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ"; +const SDKKEY = "configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw"; const PORT = 8088; const SAMPLE_KEY = "isAwesomeFeatureEnabled"; diff --git a/samples/node-expresswithdocker/package.json b/samples/node-expresswithdocker/package.json index 320d186..d3eded5 100644 --- a/samples/node-expresswithdocker/package.json +++ b/samples/node-expresswithdocker/package.json @@ -10,7 +10,7 @@ "license": "MIT", "description": "Sample application for ConfigCat JS SDK", "dependencies": { - "@configcat/sdk": "^0.0.1", + "@configcat/sdk": "^0.1.0", "express": "^4.17.1", "semver": "^7.3.5" } diff --git a/samples/node-realtimeupdate/index.js b/samples/node-realtimeupdate/index.js index 92c8d3f..80a76bd 100644 --- a/samples/node-realtimeupdate/index.js +++ b/samples/node-realtimeupdate/index.js @@ -3,7 +3,7 @@ var PubNub = require("pubnub"); // ConfigCat related variables const configcatSettingKey = "isAwesomeFeatureEnabled"; // Copy your feature flag or setting key from https://app.configcat.com -const configcatSdkKey = "PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ"; // Copy your Configcat SDK Key: https://app.configcat.com/sdkkey +const configcatSdkKey = "configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw"; // Copy your Configcat SDK Key: https://app.configcat.com/sdkkey // PubNub related variables const pubnubSubscriberKey = "demo"; diff --git a/samples/node-realtimeupdate/package.json b/samples/node-realtimeupdate/package.json index b26eb14..3b97321 100644 --- a/samples/node-realtimeupdate/package.json +++ b/samples/node-realtimeupdate/package.json @@ -9,7 +9,7 @@ "author": "developer@configcat.com", "license": "MIT", "dependencies": { - "@configcat/sdk": "^0.0.1", + "@configcat/sdk": "^0.1.0", "pubnub": "^4.32.1" } } diff --git a/samples/react-native-sample/package.json b/samples/react-native-sample/package.json index f239ea1..cf8387b 100644 --- a/samples/react-native-sample/package.json +++ b/samples/react-native-sample/package.json @@ -9,7 +9,7 @@ "web": "expo start --web" }, "dependencies": { - "@configcat/sdk": "^0.0.1", + "@configcat/sdk": "^0.1.0", "expo": "~51.0.28", "expo-status-bar": "~1.12.1", "react": "18.2.0", diff --git a/samples/react-sample/package.json b/samples/react-sample/package.json index bedbf6e..7c30687 100644 --- a/samples/react-sample/package.json +++ b/samples/react-sample/package.json @@ -3,7 +3,7 @@ "version": "0.1.0", "private": true, "dependencies": { - "@configcat/sdk": "^0.0.1", + "@configcat/sdk": "^0.1.0", "react": "^18.3.1", "react-dom": "^18.3.1", "react-scripts": "5.0.1", diff --git a/samples/react-sample/src/App.js b/samples/react-sample/src/App.js index 1d86e41..4c07bcd 100644 --- a/samples/react-sample/src/App.js +++ b/samples/react-sample/src/App.js @@ -9,7 +9,7 @@ class App extends Component { constructor(props) { super(props) // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes - this.client = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", PollingMode.AutoPoll, { + this.client = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: configcat.createConsoleLogger(LogLevel.Info) // Setting log level to Info to show detailed feature flag evaluation }); diff --git a/samples/ts-node-console-esm/README.md b/samples/ts-node-console-esm/README.md index b696cb2..f27bbff 100644 --- a/samples/ts-node-console-esm/README.md +++ b/samples/ts-node-console-esm/README.md @@ -1,6 +1,6 @@ # Sample application for Node.js with TypeScript (ts-node) -This is a simple Node.js application to demonstrate how to use the ConfigCat SDK on Node.js. +This is a simple console application to demonstrate how to use the ConfigCat SDK on Node.js using ECMAScript modules and TypeScript. ## Install dependencies diff --git a/samples/ts-node-console-esm/index.ts b/samples/ts-node-console-esm/index.ts index f2fb56d..0a7e0b4 100644 --- a/samples/ts-node-console-esm/index.ts +++ b/samples/ts-node-console-esm/index.ts @@ -3,7 +3,7 @@ import * as configcat from "@configcat/sdk/node"; const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes -const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); +const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); const value = await configCatClient.getValueAsync("isAwesomeFeatureEnabled", false); console.log("isAwesomeFeatureEnabled: " + value); diff --git a/samples/ts-node-console-esm/package.json b/samples/ts-node-console-esm/package.json index 07bb746..cfdb508 100644 --- a/samples/ts-node-console-esm/package.json +++ b/samples/ts-node-console-esm/package.json @@ -8,7 +8,7 @@ "start": "node --loader ts-node/esm index.ts" }, "dependencies": { - "@configcat/sdk": "^0.0.1" + "@configcat/sdk": "^0.1.0" }, "devDependencies": { "ts-node": "^10.9.2", diff --git a/samples/ts-node-console/README.md b/samples/ts-node-console/README.md index b696cb2..007958b 100644 --- a/samples/ts-node-console/README.md +++ b/samples/ts-node-console/README.md @@ -1,6 +1,6 @@ # Sample application for Node.js with TypeScript (ts-node) -This is a simple Node.js application to demonstrate how to use the ConfigCat SDK on Node.js. +This is a simple console application to demonstrate how to use the ConfigCat SDK on Node.js using TypeScript. ## Install dependencies diff --git a/samples/ts-node-console/index.ts b/samples/ts-node-console/index.ts index 9cff9fa..5ddc0c1 100644 --- a/samples/ts-node-console/index.ts +++ b/samples/ts-node-console/index.ts @@ -8,7 +8,7 @@ import * as configcat from "@configcat/sdk"; const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes - const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); + const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); const value = await configCatClient.getValueAsync("isAwesomeFeatureEnabled", false); console.log("isAwesomeFeatureEnabled: " + value); diff --git a/samples/ts-node-console/package.json b/samples/ts-node-console/package.json index 19cde97..717b966 100644 --- a/samples/ts-node-console/package.json +++ b/samples/ts-node-console/package.json @@ -7,7 +7,7 @@ "start": "ts-node index.ts" }, "dependencies": { - "@configcat/sdk": "^0.0.1" + "@configcat/sdk": "^0.1.0" }, "devDependencies": { "ts-node": "^10.9.2", diff --git a/samples/vue-ssr-sample/package.json b/samples/vue-ssr-sample/package.json index af1d1cc..0e8d088 100644 --- a/samples/vue-ssr-sample/package.json +++ b/samples/vue-ssr-sample/package.json @@ -11,7 +11,7 @@ "preview": "cross-env NODE_ENV=production node server" }, "dependencies": { - "@configcat/sdk": "^0.0.1", + "@configcat/sdk": "^0.1.0", "compression": "^1.7.4", "express": "^4.18.2", "sirv": "^2.0.4", diff --git a/samples/vue-ssr-sample/src/entry-client.ts b/samples/vue-ssr-sample/src/entry-client.ts index a6374ad..843b93d 100644 --- a/samples/vue-ssr-sample/src/entry-client.ts +++ b/samples/vue-ssr-sample/src/entry-client.ts @@ -4,7 +4,7 @@ import * as configcat from "@configcat/sdk/browser"; const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation -const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); +const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes new Promise(resolve => setTimeout(() => resolve(), 3000)) diff --git a/samples/vue-ssr-sample/src/entry-server.ts b/samples/vue-ssr-sample/src/entry-server.ts index e9d15f1..c2e8aee 100644 --- a/samples/vue-ssr-sample/src/entry-server.ts +++ b/samples/vue-ssr-sample/src/entry-server.ts @@ -4,7 +4,7 @@ import * as configcat from "@configcat/sdk/node"; const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation -const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); +const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes export async function render() { diff --git a/samples/web-worker/package.json b/samples/web-worker/package.json index fbe6023..4fcce8d 100644 --- a/samples/web-worker/package.json +++ b/samples/web-worker/package.json @@ -9,7 +9,7 @@ "start": "npm run build & node ../shared/server.mjs dist" }, "dependencies": { - "@configcat/sdk": "^0.0.1" + "@configcat/sdk": "^0.1.0" }, "devDependencies": { "webpack": "^5.91.0", diff --git a/samples/web-worker/src/worker.ts b/samples/web-worker/src/worker.ts index df5c88a..813243d 100644 --- a/samples/web-worker/src/worker.ts +++ b/samples/web-worker/src/worker.ts @@ -3,7 +3,7 @@ import * as configcat from "@configcat/sdk/browser"; const logger = configcat.createConsoleLogger(configcat.LogLevel.Info); // Setting log level to Info to show detailed feature flag evaluation // You can instantiate the client with different polling modes. See the Docs: https://configcat.com/docs/sdk-reference/js/#polling-modes -const configCatClient = configcat.getClient("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); +const configCatClient = configcat.getClient("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/tiOvFw5gkky9LFu1Duuvzw", configcat.PollingMode.AutoPoll, { pollIntervalSeconds: 2, logger: logger }); onmessage = async (e) => { console.log("Feature flag key received from main script"); diff --git a/src/AutoPollConfigService.ts b/src/AutoPollConfigService.ts index 9c454e9..64fbb47 100644 --- a/src/AutoPollConfigService.ts +++ b/src/AutoPollConfigService.ts @@ -117,8 +117,8 @@ export class AutoPollConfigService extends ConfigServiceBase im } protected onConfigFetched(newConfig: ProjectConfig): void { - super.onConfigFetched(newConfig); this.signalInitialization(); + super.onConfigFetched(newConfig); } protected setOnlineCore(): void { diff --git a/src/ConfigCatClientOptions.ts b/src/ConfigCatClientOptions.ts index 397f5d4..d289900 100644 --- a/src/ConfigCatClientOptions.ts +++ b/src/ConfigCatClientOptions.ts @@ -51,9 +51,6 @@ export interface IOptions { */ baseUrl?: string | null; - /** Proxy settings (supported only in the Node SDK currently). */ - proxy?: string | null; - /** * Set this property to be in sync with the Data Governance preference on the Dashboard: * https://app.configcat.com/organization/data-governance (only Organization Admins have access). @@ -144,8 +141,6 @@ export abstract class OptionsBase { baseUrlOverriden: boolean = false; - proxy: string = ""; - dataGovernance: DataGovernance; cache: IConfigCache; @@ -210,10 +205,6 @@ export abstract class OptionsBase { this.baseUrlOverriden = true; } - if (options.proxy) { - this.proxy = options.proxy; - } - if (options.flagOverrides) { this.flagOverrides = options.flagOverrides; } diff --git a/src/ConfigServiceBase.ts b/src/ConfigServiceBase.ts index 0daa941..9639d85 100644 --- a/src/ConfigServiceBase.ts +++ b/src/ConfigServiceBase.ts @@ -135,7 +135,9 @@ export abstract class ConfigServiceBase { return [fetchResult, latestConfig]; } - protected onConfigFetched(newConfig: ProjectConfig): void { } + protected onConfigFetched(newConfig: ProjectConfig): void { + this.options.logger.debug("config fetched"); + } protected onConfigChanged(newConfig: ProjectConfig): void { this.options.logger.debug("config changed"); diff --git a/src/bun/index.ts b/src/bun/index.ts new file mode 100644 index 0000000..1b42960 --- /dev/null +++ b/src/bun/index.ts @@ -0,0 +1,52 @@ +import { EventEmitter } from "events"; +import type { IConfigCatClient } from "../ConfigCatClient"; +import type { IAutoPollOptions, ILazyLoadingOptions, IManualPollOptions } from "../ConfigCatClientOptions"; +import { PollingMode } from "../ConfigCatClientOptions"; +import { getClient as getClientCommon } from "../index.pubternals.core"; +import { NodeHttpConfigFetcher } from "../node/NodeHttpConfigFetcher"; +import CONFIGCAT_SDK_VERSION from "../Version"; + +/* Package public API for Bun */ + +/** + * Returns an instance of `ConfigCatClient` for the specified SDK Key. + * @remarks This method returns a single, shared instance per each distinct SDK Key. + * That is, a new client object is created only when there is none available for the specified SDK Key. + * Otherwise, the already created instance is returned (in which case the `pollingMode` and `options` arguments are ignored). + * So, please keep in mind that when you make multiple calls to this method using the same SDK Key, you may end up with multiple references to the same client object. + * @param sdkKey SDK Key to access the ConfigCat config. + * @param pollingMode The polling mode to use. + * @param options Options for the specified polling mode. + */ +export function getClient(sdkKey: string, pollingMode?: TMode, options?: OptionsForPollingMode): IConfigCatClient { + return getClientCommon(sdkKey, pollingMode ?? PollingMode.AutoPoll, options, + { + configFetcher: new NodeHttpConfigFetcher(), + sdkType: "ConfigCat-UnifiedJS-Bun", + sdkVersion: CONFIGCAT_SDK_VERSION, + eventEmitterFactory: () => new EventEmitter() + }); +} + +export { createConsoleLogger, createFlagOverridesFromMap, disposeAllClients } from "../index.pubternals.core"; + +/** Options used to configure the ConfigCat SDK in the case of Auto Polling mode. */ +export interface IBunAutoPollOptions extends IAutoPollOptions { +} + +/** Options used to configure the ConfigCat SDK in the case of Lazy Loading mode. */ +export interface IBunLazyLoadingOptions extends ILazyLoadingOptions { +} + +/** Options used to configure the ConfigCat SDK in the case of Manual Polling mode. */ +export interface IBunManualPollOptions extends IManualPollOptions { +} + +export type OptionsForPollingMode = + TMode extends PollingMode.AutoPoll ? IBunAutoPollOptions : + TMode extends PollingMode.ManualPoll ? IBunManualPollOptions : + TMode extends PollingMode.LazyLoad ? IBunLazyLoadingOptions : + TMode extends undefined ? IBunAutoPollOptions : + never; + +export * from ".."; diff --git a/src/cloudflare-worker/CloudflareConfigCache.ts b/src/cloudflare-worker/CloudflareConfigCache.ts new file mode 100644 index 0000000..5d04f18 --- /dev/null +++ b/src/cloudflare-worker/CloudflareConfigCache.ts @@ -0,0 +1,64 @@ +import type * as cloudflare from "@cloudflare/workers-types/2023-03-01"; +import type { IConfigCache, IConfigCatCache } from "../ConfigCatCache"; +import { ExternalConfigCache } from "../ConfigCatCache"; +import type { OptionsBase } from "../ConfigCatClientOptions"; + +const CACHE_NAME = "@configcat/sdk"; + +declare const caches: typeof cloudflare.caches; + +// eslint-disable-next-line @typescript-eslint/naming-convention +declare const Response: typeof cloudflare.Response; + +export class CloudflareConfigCache implements IConfigCatCache { + static tryGetFactory(): ((options: OptionsBase) => IConfigCache) | undefined { + const cache = getCloudflareCache(); + if (cache) { + return options => new ExternalConfigCache(new CloudflareConfigCache(cache), options.logger); + } + } + + private cache: Promise | undefined; + + constructor(cache: Promise) { + this.cache = cache; + } + + async set(key: string, value: string): Promise { + try { + const cache = await (this.cache ?? caches.open(CACHE_NAME)); + await cache.put(cacheUrlFor(key), new Response(value)); + } + catch (err) { + this.cache = void 0; + throw err; + } + } + + async get(key: string): Promise { + try { + const cache = await (this.cache ?? caches.open(CACHE_NAME)); + const response = await cache.match(cacheUrlFor(key)); + if (response) { + return await response.text(); + } + } + catch (err) { + this.cache = void 0; + throw err; + } + } +} + +export function getCloudflareCache(): Promise | undefined { + if (typeof caches !== "undefined") { + try { + return caches?.open(CACHE_NAME); + } + catch { /* intentional no-op */ } + } +} + +function cacheUrlFor(key: string) { + return `http://sdk-config-cache.configcat.com/${encodeURIComponent(key)}`; +} diff --git a/src/cloudflare-worker/index.ts b/src/cloudflare-worker/index.ts new file mode 100644 index 0000000..9d73ec4 --- /dev/null +++ b/src/cloudflare-worker/index.ts @@ -0,0 +1,108 @@ +import type * as cloudflare from "@cloudflare/workers-types/2023-03-01"; +import type { IConfigCatClient } from "../ConfigCatClient"; +import type { IAutoPollOptions, ILazyLoadingOptions, IManualPollOptions } from "../ConfigCatClientOptions"; +import { PollingMode } from "../ConfigCatClientOptions"; +import { DefaultEventEmitter } from "../DefaultEventEmitter"; +import type { FlagOverrides, IQueryStringProvider, OverrideBehaviour } from "../FlagOverrides"; +import { createFlagOverridesFromQueryParams as createFlagOverridesFromQueryParamsCommon, getClient as getClientCommon } from "../index.pubternals.core"; +import { setupPolyfills } from "../Polyfills"; +import { FetchApiConfigFetcher } from "../shared/FetchApiConfigFetcher"; +import CONFIGCAT_SDK_VERSION from "../Version"; +import { CloudflareConfigCache } from "./CloudflareConfigCache"; + +/* Package public API for Cloudflare Workers */ + +setupPolyfills(); + +/** + * Returns an instance of `ConfigCatClient` for the specified SDK Key. + * @remarks This method returns a single, shared instance per each distinct SDK Key. + * That is, a new client object is created only when there is none available for the specified SDK Key. + * Otherwise, the already created instance is returned (in which case the `pollingMode` and `options` arguments are ignored). + * So, please keep in mind that when you make multiple calls to this method using the same SDK Key, you may end up with multiple references to the same client object. + * @param sdkKey SDK Key to access the ConfigCat config. + * @param pollingMode The polling mode to use. + * @param options Options for the specified polling mode. + */ +export function getClient(sdkKey: string, pollingMode?: TMode, options?: OptionsForPollingMode): IConfigCatClient { + return getClientCommon(sdkKey, pollingMode ?? PollingMode.AutoPoll, options, { + configFetcher: new FetchApiConfigFetcher(), + sdkType: "ConfigCat-UnifiedJS-CloudflareWorker", + sdkVersion: CONFIGCAT_SDK_VERSION, + eventEmitterFactory: () => new DefaultEventEmitter(), + defaultCacheFactory: CloudflareConfigCache.tryGetFactory() + }); +} + +export { createConsoleLogger, createFlagOverridesFromMap, disposeAllClients } from "../index.pubternals.core"; + +declare const URL: typeof cloudflare.URL; + +/** + * Creates an instance of `FlagOverrides` that uses the query string parameters + * of the specified request as data source. + * @param behaviour The override behaviour. + * Specifies whether the local values should override the remote values + * or local values should only be used when a remote value doesn't exist + * or the local values should be used only. + * @param request The request. + * @param paramPrefix The parameter name prefix used to indicate which query string parameters + * specify feature flag override values. Parameters whose name doesn't start with the + * prefix will be ignored. Defaults to `cc-`. + */ +export function createFlagOverridesFromQueryParams(behaviour: OverrideBehaviour, + request: cloudflare.Request, paramPrefix?: string +): FlagOverrides; +/** + * Creates an instance of `FlagOverrides` that uses query string parameters as data source. + * @param behaviour The override behaviour. + * Specifies whether the local values should override the remote values + * or local values should only be used when a remote value doesn't exist + * or the local values should be used only. + * @param watchChanges If set to `true`, the query string will be tracked for changes. + * @param paramPrefix The parameter name prefix used to indicate which query string parameters + * specify feature flag override values. Parameters whose name doesn't start with the + * prefix will be ignored. Defaults to `cc-`. + * @param queryStringProvider The provider object used to obtain the query string. + * Defaults to a provider that returns the value of `globalThis.location.search`. + */ +export function createFlagOverridesFromQueryParams(behaviour: OverrideBehaviour, + watchChanges?: boolean, paramPrefix?: string, queryStringProvider?: IQueryStringProvider +): FlagOverrides; +export function createFlagOverridesFromQueryParams(behaviour: OverrideBehaviour, + requestOrWatchChanges?: boolean | cloudflare.Request, paramPrefix?: string, queryStringProvider?: IQueryStringProvider +): FlagOverrides { + if (!requestOrWatchChanges || typeof requestOrWatchChanges === "boolean") { + return createFlagOverridesFromQueryParamsCommon(behaviour, requestOrWatchChanges, paramPrefix, queryStringProvider); + } + + return createFlagOverridesFromQueryParamsCommon(behaviour, false, paramPrefix, { + get currentValue() { + try { return new URL(requestOrWatchChanges.url).search; } + catch { /* intentional no-op */ } + } + }); +} + +export type { IQueryStringProvider } from "../index.pubternals.core"; + +/** Options used to configure the ConfigCat SDK in the case of Auto Polling mode. */ +export interface IJSAutoPollOptions extends IAutoPollOptions { +} + +/** Options used to configure the ConfigCat SDK in the case of Lazy Loading mode. */ +export interface IJSLazyLoadingOptions extends ILazyLoadingOptions { +} + +/** Options used to configure the ConfigCat SDK in the case of Manual Polling mode. */ +export interface IJSManualPollOptions extends IManualPollOptions { +} + +export type OptionsForPollingMode = + TMode extends PollingMode.AutoPoll ? IJSAutoPollOptions : + TMode extends PollingMode.ManualPoll ? IJSManualPollOptions : + TMode extends PollingMode.LazyLoad ? IJSLazyLoadingOptions : + TMode extends undefined ? IJSAutoPollOptions : + never; + +export * from ".."; diff --git a/src/node/NodeHttpConfigFetcher.ts b/src/node/NodeHttpConfigFetcher.ts index 9993e2f..252f117 100644 --- a/src/node/NodeHttpConfigFetcher.ts +++ b/src/node/NodeHttpConfigFetcher.ts @@ -7,7 +7,18 @@ import { FormattableLogMessage, LogLevel } from "../ConfigCatLogger"; import type { IConfigFetcher, IFetchResponse } from "../ConfigFetcher"; import { FetchError } from "../ConfigFetcher"; +export interface INodeHttpConfigFetcherOptions { + /** Proxy settings. */ + proxy?: string | null; +} + export class NodeHttpConfigFetcher implements IConfigFetcher { + private readonly proxy?: string | null; + + constructor(options?: INodeHttpConfigFetcherOptions) { + this.proxy = options?.proxy; + } + private handleResponse(response: http.IncomingMessage, resolve: (value: IFetchResponse) => void, reject: (reason?: any) => void) { try { const { statusCode, statusMessage: reasonPhrase } = response as { statusCode: number; statusMessage: string }; @@ -46,9 +57,9 @@ export class NodeHttpConfigFetcher implements IConfigFetcher { const baseUrl = options.getUrl(); const isBaseUrlSecure = baseUrl.startsWith("https"); let agent: any; - if (options.proxy) { + if (this.proxy) { try { - const proxy: URL = new URL(options.proxy); + const proxy: URL = new URL(this.proxy); let agentFactory: any; if (proxy.protocol === "https:") { agentFactory = isBaseUrlSecure ? tunnel.httpsOverHttps : tunnel.httpOverHttps; @@ -65,7 +76,7 @@ export class NodeHttpConfigFetcher implements IConfigFetcher { }); } catch (err) { - options.logger.log(LogLevel.Error, 0, FormattableLogMessage.from("PROXY")`Failed to parse \`options.proxy\`: '${options.proxy}'.`, err); + options.logger.log(LogLevel.Error, 0, FormattableLogMessage.from("PROXY")`Failed to parse \`options.proxy\`: '${this.proxy}'.`, err); } } diff --git a/src/node/index.ts b/src/node/index.ts index be73fea..a611161 100644 --- a/src/node/index.ts +++ b/src/node/index.ts @@ -4,6 +4,7 @@ import type { IAutoPollOptions, ILazyLoadingOptions, IManualPollOptions } from " import { PollingMode } from "../ConfigCatClientOptions"; import { getClient as getClientCommon } from "../index.pubternals.core"; import CONFIGCAT_SDK_VERSION from "../Version"; +import type { INodeHttpConfigFetcherOptions } from "./NodeHttpConfigFetcher"; import { NodeHttpConfigFetcher } from "./NodeHttpConfigFetcher"; /* Package public API for Node.js */ @@ -21,7 +22,7 @@ import { NodeHttpConfigFetcher } from "./NodeHttpConfigFetcher"; export function getClient(sdkKey: string, pollingMode?: TMode, options?: OptionsForPollingMode): IConfigCatClient { return getClientCommon(sdkKey, pollingMode ?? PollingMode.AutoPoll, options, { - configFetcher: new NodeHttpConfigFetcher(), + configFetcher: new NodeHttpConfigFetcher(options), sdkType: "ConfigCat-UnifiedJS-Node", sdkVersion: CONFIGCAT_SDK_VERSION, eventEmitterFactory: () => new EventEmitter() @@ -31,15 +32,15 @@ export function getClient(sdkKey: string, export { createConsoleLogger, createFlagOverridesFromMap, disposeAllClients } from "../index.pubternals.core"; /** Options used to configure the ConfigCat SDK in the case of Auto Polling mode. */ -export interface INodeAutoPollOptions extends IAutoPollOptions { +export interface INodeAutoPollOptions extends IAutoPollOptions, INodeHttpConfigFetcherOptions { } /** Options used to configure the ConfigCat SDK in the case of Lazy Loading mode. */ -export interface INodeLazyLoadingOptions extends ILazyLoadingOptions { +export interface INodeLazyLoadingOptions extends ILazyLoadingOptions, INodeHttpConfigFetcherOptions { } /** Options used to configure the ConfigCat SDK in the case of Manual Polling mode. */ -export interface INodeManualPollOptions extends IManualPollOptions { +export interface INodeManualPollOptions extends IManualPollOptions, INodeHttpConfigFetcherOptions { } export type OptionsForPollingMode = diff --git a/test/ConfigCatClientOptionsTests.ts b/test/ConfigCatClientOptionsTests.ts index 09ba9fe..ebbd108 100644 --- a/test/ConfigCatClientOptionsTests.ts +++ b/test/ConfigCatClientOptionsTests.ts @@ -1,7 +1,7 @@ import { assert, expect } from "chai"; import { FakeExternalCache, createAutoPollOptions, createKernel, createLazyLoadOptions, createManualPollOptions } from "./helpers/fakes"; import { ExternalConfigCache, IConfigCache, InMemoryConfigCache } from "#lib/ConfigCatCache"; -import { AutoPollOptions, LazyLoadOptions, ManualPollOptions, OptionsBase } from "#lib/ConfigCatClientOptions"; +import { OptionsBase } from "#lib/ConfigCatClientOptions"; import { ConfigCatConsoleLogger, IConfigCatLogger, LogEventId, LogLevel, LogMessage, LoggerWrapper } from "#lib/ConfigCatLogger"; import { ProjectConfig } from "#lib/ProjectConfig"; @@ -14,7 +14,7 @@ describe("Options", () => { }); it("ManualPollOptions initialization With NULL 'defaultCache' Should init with InMemoryCache", () => { - const options: ManualPollOptions = createManualPollOptions("APIKEY"); + const options = createManualPollOptions("APIKEY"); assert.isNotNull(options.cache); assert.instanceOf(options.cache, InMemoryConfigCache); @@ -22,24 +22,23 @@ describe("Options", () => { it("ManualPollOptions initialization With 'sdkKey' Should create an instance, defaults OK", () => { const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: ManualPollOptions = createManualPollOptions("APIKEY", void 0, kernel); + const options = createManualPollOptions("APIKEY", void 0, kernel); assert.isDefined(options); assert.equal("APIKEY", options.sdkKey); assert.equal(30000, options.requestTimeoutMs); - assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/m-1.0.0", options.getUrl()); + assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/m-1.0.0", options.getRealUrl()); }); it("ManualPollOptions initialization With parameters works", () => { const fakeLogger: FakeLogger = new FakeLogger(); const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: ManualPollOptions = createManualPollOptions( + const options = createManualPollOptions( "APIKEY", { logger: fakeLogger, requestTimeoutMs: 10, - proxy: "http://fake-proxy.com:8080" }, kernel ); @@ -48,17 +47,16 @@ describe("Options", () => { assert.equal(fakeLogger, options.logger["logger"]); assert.equal("APIKEY", options.sdkKey); assert.equal(10, options.requestTimeoutMs); - assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/m-1.0.0", options.getUrl()); - assert.equal("http://fake-proxy.com:8080", options.proxy); + assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/m-1.0.0", options.getRealUrl()); }); it("ManualPollOptions initialization With 'baseUrl' Should create an instance with custom baseUrl", () => { const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: ManualPollOptions = createManualPollOptions("APIKEY", { baseUrl: "https://mycdn.example.org" }, kernel); + const options = createManualPollOptions("APIKEY", { baseUrl: "https://mycdn.example.org" }, kernel); assert.isDefined(options); - assert.equal("https://mycdn.example.org/configuration-files/APIKEY/config_v6.json?sdk=common/m-1.0.0", options.getUrl()); - assert.notEqual("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/m-1.0.0", options.getUrl()); + assert.equal("https://mycdn.example.org/configuration-files/APIKEY/config_v6.json?sdk=common/m-1.0.0", options.getRealUrl()); + assert.notEqual("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/m-1.0.0", options.getRealUrl()); }); it("AutoPollOptions initialization With -1 requestTimeoutMs ShouldThrowError", () => { @@ -69,12 +67,12 @@ describe("Options", () => { it("AutoPollOptions initialization With 'sdkKey' Should create an instance, defaults OK", () => { const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: AutoPollOptions = createAutoPollOptions("APIKEY", void 0, kernel); + const options = createAutoPollOptions("APIKEY", void 0, kernel); assert.isDefined(options); assert.isTrue(options.logger instanceof LoggerWrapper); assert.isTrue(options.logger["logger"] instanceof ConfigCatConsoleLogger); assert.equal("APIKEY", options.sdkKey); - assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/a-1.0.0", options.getUrl()); + assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/a-1.0.0", options.getRealUrl()); assert.equal(60, options.pollIntervalSeconds); assert.equal(30000, options.requestTimeoutMs); assert.isDefined(options.cache); @@ -84,23 +82,21 @@ describe("Options", () => { const fakeLogger: FakeLogger = new FakeLogger(); const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: AutoPollOptions = createAutoPollOptions( + const options = createAutoPollOptions( "APIKEY", { logger: fakeLogger, pollIntervalSeconds: 59, requestTimeoutMs: 20, - proxy: "http://fake-proxy.com:8080" }, kernel); assert.isDefined(options); assert.equal(fakeLogger, options.logger["logger"]); assert.equal("APIKEY", options.sdkKey); - assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/a-1.0.0", options.getUrl()); + assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/a-1.0.0", options.getRealUrl()); assert.equal(59, options.pollIntervalSeconds); assert.equal(20, options.requestTimeoutMs); - assert.equal("http://fake-proxy.com:8080", options.proxy); }); it("AutoPollOptions initialization With -1 'pollIntervalSeconds' ShouldThrowError", () => { @@ -149,7 +145,7 @@ describe("Options", () => { it("AutoPollOptions initialization With NULL 'defaultCache' Should set to InMemoryCache", () => { - const options: AutoPollOptions = createAutoPollOptions("APIKEY"); + const options = createAutoPollOptions("APIKEY"); assert.isNotNull(options.cache); assert.instanceOf(options.cache, InMemoryConfigCache); @@ -157,11 +153,11 @@ describe("Options", () => { it("AutoPollOptions initialization With 'baseUrl' Should create an instance with custom baseUrl", () => { const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: AutoPollOptions = createAutoPollOptions("APIKEY", { baseUrl: "https://mycdn.example.org" }, kernel); + const options = createAutoPollOptions("APIKEY", { baseUrl: "https://mycdn.example.org" }, kernel); assert.isDefined(options); - assert.equal("https://mycdn.example.org/configuration-files/APIKEY/config_v6.json?sdk=common/a-1.0.0", options.getUrl()); - assert.notEqual("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/a-1.0.0", options.getUrl()); + assert.equal("https://mycdn.example.org/configuration-files/APIKEY/config_v6.json?sdk=common/a-1.0.0", options.getRealUrl()); + assert.notEqual("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/a-1.0.0", options.getRealUrl()); }); it("AutoPollOptions initialization With NaN 'maxInitWaitTimeSeconds' ShouldThrowError", () => { @@ -197,7 +193,7 @@ describe("Options", () => { }); it("AutoPollOptions initialization With 0 'maxInitWaitTimeSeconds' Should create an instance with passed value", () => { - const options: AutoPollOptions = createAutoPollOptions("APIKEY", { maxInitWaitTimeSeconds: 0 }); + const options = createAutoPollOptions("APIKEY", { maxInitWaitTimeSeconds: 0 }); assert.isDefined(options); assert.isNotNull(options); @@ -205,7 +201,7 @@ describe("Options", () => { }); it("AutoPollOptions initialization Without 'maxInitWaitTimeSeconds' Should create an instance with default value(5)", () => { - const options: AutoPollOptions = createAutoPollOptions("APIKEY"); + const options = createAutoPollOptions("APIKEY"); assert.isDefined(options); assert.isNotNull(options); @@ -214,10 +210,10 @@ describe("Options", () => { it("LazyLoadOptions initialization With 'sdkKey' Should create an instance, defaults OK", () => { const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: LazyLoadOptions = createLazyLoadOptions("APIKEY", void 0, kernel); + const options = createLazyLoadOptions("APIKEY", void 0, kernel); assert.isDefined(options); assert.equal("APIKEY", options.sdkKey); - assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/l-1.0.0", options.getUrl()); + assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/l-1.0.0", options.getRealUrl()); assert.equal(60, options.cacheTimeToLiveSeconds); assert.equal(30000, options.requestTimeoutMs); }); @@ -226,13 +222,12 @@ describe("Options", () => { const fakeLogger: FakeLogger = new FakeLogger(); const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: LazyLoadOptions = createLazyLoadOptions( + const options = createLazyLoadOptions( "APIKEY", { logger: fakeLogger, cacheTimeToLiveSeconds: 59, - requestTimeoutMs: 20, - proxy: "http://fake-proxy.com:8080" + requestTimeoutMs: 20 }, kernel ); @@ -240,10 +235,9 @@ describe("Options", () => { assert.isDefined(options); assert.equal(fakeLogger, options.logger["logger"]); assert.equal("APIKEY", options.sdkKey); - assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/l-1.0.0", options.getUrl()); + assert.equal("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/l-1.0.0", options.getRealUrl()); assert.equal(59, options.cacheTimeToLiveSeconds); assert.equal(20, options.requestTimeoutMs); - assert.equal("http://fake-proxy.com:8080", options.proxy); }); it("LazyLoadOptions initialization With -1 'cacheTimeToLiveSeconds' ShouldThrowError", () => { @@ -259,7 +253,7 @@ describe("Options", () => { }); it("LazyLoadOptions initialization With NULL 'defaultCache' Should set to InMemoryCache", () => { - const options: LazyLoadOptions = createLazyLoadOptions("APIKEY"); + const options = createLazyLoadOptions("APIKEY"); assert.isNotNull(options.cache); assert.instanceOf(options.cache, InMemoryConfigCache); @@ -267,11 +261,11 @@ describe("Options", () => { it("LazyLoadOptions initialization With 'baseUrl' Should create an instance with custom baseUrl", () => { const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: LazyLoadOptions = createLazyLoadOptions("APIKEY", { baseUrl: "https://mycdn.example.org" }, kernel); + const options = createLazyLoadOptions("APIKEY", { baseUrl: "https://mycdn.example.org" }, kernel); assert.isDefined(options); - assert.equal("https://mycdn.example.org/configuration-files/APIKEY/config_v6.json?sdk=common/l-1.0.0", options.getUrl()); - assert.notEqual("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/l-1.0.0", options.getUrl()); + assert.equal("https://mycdn.example.org/configuration-files/APIKEY/config_v6.json?sdk=common/l-1.0.0", options.getRealUrl()); + assert.notEqual("https://cdn-global.configcat.com/configuration-files/APIKEY/config_v6.json?sdk=common/l-1.0.0", options.getRealUrl()); }); it("Options initialization With 'defaultCache' Should set option cache to passed instance", () => { @@ -308,19 +302,19 @@ describe("Options", () => { it("AutoPollOptions initialization - sdkVersion works", () => { const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: AutoPollOptions = createAutoPollOptions("APIKEY", void 0, kernel); + const options = createAutoPollOptions("APIKEY", void 0, kernel); assert.equal("common/a-1.0.0", options.clientVersion); }); it("LazyLoadOptions initialization - sdkVersion works", () => { const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: LazyLoadOptions = createLazyLoadOptions("APIKEY", void 0, kernel); + const options = createLazyLoadOptions("APIKEY", void 0, kernel); assert.equal("common/l-1.0.0", options.clientVersion); }); it("ManualPollOptions initialization - sdkVersion works", () => { const kernel = createKernel({ sdkType: "common", sdkVersion: "1.0.0" }); - const options: ManualPollOptions = createManualPollOptions("APIKEY", void 0, kernel); + const options = createManualPollOptions("APIKEY", void 0, kernel); assert.equal("common/m-1.0.0", options.clientVersion); }); diff --git a/test/ConfigCatClientTests.ts b/test/ConfigCatClientTests.ts index f1d2937..a474d36 100644 --- a/test/ConfigCatClientTests.ts +++ b/test/ConfigCatClientTests.ts @@ -595,7 +595,7 @@ describe("ConfigCatClient", () => { const actualValue = await client.getValueAsync("debug", false); const elapsedMilliseconds: number = new Date().getTime() - startDate; - assert.isAtLeast(elapsedMilliseconds, 500 - 10); // 10 ms for tolerance + assert.isAtLeast(elapsedMilliseconds, 500 - 25); // 25 ms for tolerance assert.isAtMost(elapsedMilliseconds, maxInitWaitTimeSeconds * 1000 + 75); // 75 ms for tolerance assert.equal(actualValue, true); @@ -619,7 +619,7 @@ describe("ConfigCatClient", () => { const actualDetails = await client.getValueDetailsAsync("debug", false); const elapsedMilliseconds: number = new Date().getTime() - startDate; - assert.isAtLeast(elapsedMilliseconds, 500 - 10); // 10 ms for tolerance + assert.isAtLeast(elapsedMilliseconds, 500 - 25); // 25 ms for tolerance assert.isAtMost(elapsedMilliseconds, configFetchDelay * 2 + 75); // 75 ms for tolerance assert.equal(actualDetails.isDefaultValue, true); assert.equal(actualDetails.value, false); @@ -640,7 +640,7 @@ describe("ConfigCatClient", () => { const actualValue = await client.getValueAsync("debug", false); const elapsedMilliseconds: number = new Date().getTime() - startDate; - assert.isAtLeast(elapsedMilliseconds, (maxInitWaitTimeSeconds * 1000) - 10); // 10 ms for tolerance + assert.isAtLeast(elapsedMilliseconds, (maxInitWaitTimeSeconds * 1000) - 25); // 25 ms for tolerance assert.isAtMost(elapsedMilliseconds, (maxInitWaitTimeSeconds * 1000) + 75); // 75 ms for tolerance assert.equal(actualValue, false); @@ -681,7 +681,7 @@ describe("ConfigCatClient", () => { const state = await client.waitForReady(); const elapsedMilliseconds: number = new Date().getTime() - startDate; - assert.isAtLeast(elapsedMilliseconds, (maxInitWaitTimeSeconds * 1000) - 10); // 10 ms for tolerance + assert.isAtLeast(elapsedMilliseconds, (maxInitWaitTimeSeconds * 1000) - 25); // 25 ms for tolerance assert.isAtMost(elapsedMilliseconds, (maxInitWaitTimeSeconds * 1000) + 75); // 75 ms for tolerance assert.equal(state, ClientCacheState.NoFlagData); @@ -714,7 +714,7 @@ describe("ConfigCatClient", () => { const state = await client.waitForReady(); const elapsedMilliseconds: number = new Date().getTime() - startDate; - assert.isAtLeast(elapsedMilliseconds, (maxInitWaitTimeSeconds * 1000) - 10); // 10 ms for tolerance + assert.isAtLeast(elapsedMilliseconds, (maxInitWaitTimeSeconds * 1000) - 25); // 25 ms for tolerance assert.isAtMost(elapsedMilliseconds, (maxInitWaitTimeSeconds * 1000) + 75); // 75 ms for tolerance assert.equal(state, ClientCacheState.HasCachedFlagDataOnly); diff --git a/test/DataGovernanceTests.ts b/test/DataGovernanceTests.ts index 9b1528c..9da785a 100644 --- a/test/DataGovernanceTests.ts +++ b/test/DataGovernanceTests.ts @@ -1,4 +1,5 @@ import { assert } from "chai"; +import type { AugmentedOptions } from "./helpers/platform"; import { DataGovernance, OptionsBase } from "#lib/ConfigCatClientOptions"; import { FetchResult, IConfigFetcher, IFetchResponse } from "#lib/ConfigFetcher"; import type * as ConfigJson from "#lib/ConfigJson"; @@ -266,11 +267,12 @@ export class FakeConfigFetcher implements IConfigFetcher { } fetchLogic(options: OptionsBase, lastEtag: string | null): Promise { - const projectConfig = this.responses[options.getUrl()]; + const getUrl = ((options as AugmentedOptions).getRealUrl ?? options.getUrl).bind(options); + const projectConfig = this.responses[getUrl()]; if (!projectConfig) { - assert.fail("ConfigFetcher not prepared for " + options.baseUrl); + assert.fail("ConfigFetcher not prepared for " + getUrl()); } - this.calls.push(options.getUrl()); + this.calls.push(getUrl()); return Promise.resolve({ statusCode: 200, reasonPhrase: "OK", eTag: projectConfig.config.httpETag, body: projectConfig.config.configJson }); } } diff --git a/test/browser/CacheTests.ts b/test/browser/CacheTests.ts index f81fb3b..3483fc0 100644 --- a/test/browser/CacheTests.ts +++ b/test/browser/CacheTests.ts @@ -1,6 +1,6 @@ import { assert } from "chai"; import { FakeLogger } from "../helpers/fakes"; -import { createClientWithLazyLoad } from "."; +import { platform } from "."; import { LogLevel } from "#lib"; import { LocalStorageConfigCache, fromUtf8Base64, getLocalStorage, toUtf8Base64 } from "#lib/browser/LocalStorageConfigCache"; import { ExternalConfigCache } from "#lib/ConfigCatCache"; @@ -52,7 +52,7 @@ describe("LocalStorageConfigCache tests", () => { const fakeLogger = new FakeLogger(); - const client = createClientWithLazyLoad("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/AG6C1ngVb0CvM07un6JisQ", { logger: fakeLogger }, + const client = platform.createClientWithLazyLoad("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/AG6C1ngVb0CvM07un6JisQ", { logger: fakeLogger }, kernel => { kernel.defaultCacheFactory = options => new ExternalConfigCache(new LocalStorageConfigCache(faultyLocalStorage), options.logger); return kernel; @@ -77,7 +77,7 @@ describe("LocalStorageConfigCache tests", () => { const fakeLogger = new FakeLogger(); - const client = createClientWithLazyLoad("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/AG6C1ngVb0CvM07un6JisQ", { logger: fakeLogger }, + const client = platform.createClientWithLazyLoad("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/AG6C1ngVb0CvM07un6JisQ", { logger: fakeLogger }, kernel => { kernel.defaultCacheFactory = options => new ExternalConfigCache(new LocalStorageConfigCache(faultyLocalStorage), options.logger); return kernel; diff --git a/test/browser/HttpTests.ts b/test/browser/HttpTests.ts index 9f33f92..7b555b4 100644 --- a/test/browser/HttpTests.ts +++ b/test/browser/HttpTests.ts @@ -1,7 +1,7 @@ import { assert } from "chai"; import * as mockxmlhttprequest from "mock-xmlhttprequest"; import { FakeLogger } from "../helpers/fakes"; -import { createClientWithManualPoll } from "."; +import { platform } from "."; import { LogLevel } from "#lib"; describe("HTTP tests", () => { @@ -20,7 +20,7 @@ describe("HTTP tests", () => { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs, baseUrl, logger @@ -52,7 +52,7 @@ describe("HTTP tests", () => { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs: 1000, baseUrl, logger @@ -82,7 +82,7 @@ describe("HTTP tests", () => { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs: 1000, baseUrl, logger @@ -112,7 +112,7 @@ describe("HTTP tests", () => { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs: 1000, baseUrl, logger diff --git a/test/browser/index.ts b/test/browser/index.ts index 591601d..41f5e05 100644 --- a/test/browser/index.ts +++ b/test/browser/index.ts @@ -1,76 +1,58 @@ -import { initPlatform } from "../helpers/platform"; +import { PlatformAbstractions, initPlatform } from "../helpers/platform"; +import type { IJSAutoPollOptions, IJSLazyLoadingOptions, IJSManualPollOptions } from "#lib/browser"; import { getClient } from "#lib/browser"; -import type { IConfigCatClient, IJSAutoPollOptions, IJSLazyLoadingOptions, IJSManualPollOptions } from "#lib/browser"; import { LocalStorageConfigCache } from "#lib/browser/LocalStorageConfigCache"; import { XmlHttpRequestConfigFetcher } from "#lib/browser/XmlHttpRequestConfigFetcher"; -import { ConfigCatClient } from "#lib/ConfigCatClient"; -import { AutoPollOptions, LazyLoadOptions, ManualPollOptions } from "#lib/ConfigCatClientOptions"; import { DefaultEventEmitter } from "#lib/DefaultEventEmitter"; -import type { IConfigCatKernel, IConfigFetcher } from "#lib/index.pubternals"; +import type { IConfigCatKernel } from "#lib/index.pubternals"; import sdkVersion from "#lib/Version"; const sdkType = "ConfigCat-UnifiedJS-Browser"; -export const createConfigFetcher = (): IConfigFetcher => new XmlHttpRequestConfigFetcher(); - -export const createKernel = (setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatKernel => { - const kernel: IConfigCatKernel = { configFetcher: createConfigFetcher(), sdkType, sdkVersion, eventEmitterFactory: () => new DefaultEventEmitter() }; - setupKernel ??= kernel => { - kernel.defaultCacheFactory = LocalStorageConfigCache.tryGetFactory(); - return kernel; - }; - return setupKernel(kernel); -}; - -export const createClientWithAutoPoll = (sdkKey: string, options?: IJSAutoPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new AutoPollOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; - -export const createClientWithManualPoll = (sdkKey: string, options?: IJSLazyLoadingOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new ManualPollOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; - -export const createClientWithLazyLoad = (sdkKey: string, options?: IJSManualPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new LazyLoadOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; - -export const pathJoin = (...segments: string[]): string => segments.join("/"); - -export const readFileUtf8 = (path: string): Promise => { - return new Promise((resolve, reject) => { - const request = new XMLHttpRequest(); - request.onreadystatechange = () => { - if (request.readyState === 4) { - if (request.status === 200) { - resolve(request.responseText); +type IJSOptions = IJSAutoPollOptions | IJSManualPollOptions | IJSLazyLoadingOptions; + +class BrowserPlatform extends PlatformAbstractions { + pathJoin(...segments: string[]) { return segments.join("/"); } + + readFileUtf8(path: string) { + return new Promise((resolve, reject) => { + const request = new XMLHttpRequest(); + request.onreadystatechange = () => { + if (request.readyState === 4) { + if (request.status === 200) { + resolve(request.responseText); + } + else if (request.status) { + reject(Error(`unexpected response: ${request.status} ${request.statusText}`)); + } } - else if (request.status) { - reject(Error(`unexpected response: ${request.status} ${request.statusText}`)); - } - } - }, - request.ontimeout = () => reject(Error("timeout")); - request.onabort = () => reject(Error("abort")); - request.onerror = () => reject(Error("error")); - request.open("GET", "base/" + path, true); - request.responseType = "text"; - request.send(null); - }); -}; - -initPlatform({ - pathJoin, - readFileUtf8, - createConfigFetcher, - createKernel, - createClientWithAutoPoll, - createClientWithManualPoll, - createClientWithLazyLoad, - getClient -}); + }, + request.ontimeout = () => reject(Error("timeout")); + request.onabort = () => reject(Error("abort")); + request.onerror = () => reject(Error("error")); + request.open("GET", "base/" + path, true); + request.responseType = "text"; + request.send(null); + }); + } + + createConfigFetcher(options?: IJSOptions) { return new XmlHttpRequestConfigFetcher(); } + + createKernel(setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel, options?: IJSOptions) { + const kernel: IConfigCatKernel = { configFetcher: this.createConfigFetcher(options), sdkType, sdkVersion, eventEmitterFactory: () => new DefaultEventEmitter() }; + setupKernel ??= kernel => { + kernel.defaultCacheFactory = LocalStorageConfigCache.tryGetFactory(); + return kernel; + }; + return setupKernel(kernel); + } + + protected getClientImpl = getClient; +} + +export const platform = new BrowserPlatform(); + +initPlatform(platform); /* Discover and load tests */ diff --git a/test/bun/ClientTests.ts b/test/bun/ClientTests.ts new file mode 100644 index 0000000..ba8888f --- /dev/null +++ b/test/bun/ClientTests.ts @@ -0,0 +1,24 @@ +import { assert } from "chai"; +import { FlagOverrides, IConfigCatClient, PollingMode } from "#lib"; +import * as configcatClient from "#lib/bun"; + +describe("ConfigCatClient tests", () => { + + for (const pollingMode of [PollingMode.AutoPoll, PollingMode.LazyLoad, PollingMode.ManualPoll]) { + it(`getClient() should createInstance with ${PollingMode[pollingMode]}`, () => { + + const client: IConfigCatClient = configcatClient.getClient("SDKKEY-890123456789012/1234567890123456789012", pollingMode); + + assert.isDefined(client); + + client.dispose(); + }); + } + + it("createFlagOverridesFromMap() should createOverrides", () => { + + const overrides: FlagOverrides = configcatClient.createFlagOverridesFromMap({ test: true }, configcatClient.OverrideBehaviour.LocalOnly); + + assert.isDefined(overrides); + }); +}); diff --git a/test/bun/index.ts b/test/bun/index.ts new file mode 100644 index 0000000..04c7e1f --- /dev/null +++ b/test/bun/index.ts @@ -0,0 +1,59 @@ +import "mocha"; +import { EventEmitter } from "events"; +import * as fs from "fs"; +import * as glob from "glob"; +import * as path from "path"; +import { PlatformAbstractions, initPlatform } from "../helpers/platform"; +import { normalizePathSeparator } from "../helpers/utils"; +import { isTestSpec } from "../index"; +import type { IBunAutoPollOptions, IBunLazyLoadingOptions, IBunManualPollOptions } from "#lib/bun"; +import { getClient } from "#lib/bun"; +import type { IConfigCatKernel } from "#lib/index.pubternals"; +import { NodeHttpConfigFetcher } from "#lib/node/NodeHttpConfigFetcher"; +import sdkVersion from "#lib/Version"; + +const sdkType = "ConfigCat-UnifiedJS-Bun"; + +type IBunOptions = IBunAutoPollOptions | IBunManualPollOptions | IBunLazyLoadingOptions; + +class BunPlatform extends PlatformAbstractions { + constructor() { + super(); + this.gc = () => { + Bun.gc(true); + return Promise.resolve(); + }; + } + + pathJoin(...segments: string[]) { return path.join(...segments); } + + readFileUtf8(path: string) { return fs.readFileSync(path, "utf8"); } + + createConfigFetcher(options?: IBunOptions) { return new NodeHttpConfigFetcher(options); } + + createKernel(setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel, options?: IBunOptions) { + const kernel: IConfigCatKernel = { configFetcher: this.createConfigFetcher(options), sdkType, sdkVersion, eventEmitterFactory: () => new EventEmitter() }; + return (setupKernel ?? (k => k))(kernel); + } + + protected getClientImpl = getClient; +} + +export const platform = new BunPlatform(); + +initPlatform(platform); + +/* Discover and load tests */ + +const testDir = path.resolve(__dirname, ".."); + +for (const file of glob.globIterateSync(normalizePathSeparator(testDir) + "/**/*.ts", { absolute: false })) { + const [isTest, segments] = isTestSpec(file, "bun"); + if (isTest) { + const fileName = segments[segments.length - 1]; + segments[segments.length - 1] = path.basename(fileName, path.extname(fileName)); + + /* eslint-disable @typescript-eslint/no-require-imports */ + await import("../" + segments.join("/")); + } +} diff --git a/test/bun/tsconfig.json b/test/bun/tsconfig.json new file mode 100644 index 0000000..81bb0f3 --- /dev/null +++ b/test/bun/tsconfig.json @@ -0,0 +1,7 @@ +{ + /* Override TS compiler settings for IDEs (like VSCode) */ + "extends": "../../tsconfig.json", + "compilerOptions": { + "types": ["bun", "chai", "mocha"] + } +} diff --git a/test/chromium-extension/CacheTests.ts b/test/chromium-extension/CacheTests.ts index 15eeaf8..e85fdd1 100644 --- a/test/chromium-extension/CacheTests.ts +++ b/test/chromium-extension/CacheTests.ts @@ -1,6 +1,6 @@ import { assert } from "chai"; import { FakeLogger } from "../helpers/fakes"; -import { createClientWithLazyLoad } from "."; +import { platform } from "."; import { LogLevel } from "#lib"; import { ChromeLocalStorageConfigCache, fromUtf8Base64, toUtf8Base64 } from "#lib/chromium-extension/ChromeLocalStorageConfigCache"; import { ExternalConfigCache } from "#lib/ConfigCatCache"; @@ -46,7 +46,7 @@ describe("LocalStorageConfigCache tests", () => { const fakeLogger = new FakeLogger(); - const client = createClientWithLazyLoad("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/AG6C1ngVb0CvM07un6JisQ", { logger: fakeLogger }, + const client = platform.createClientWithLazyLoad("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/AG6C1ngVb0CvM07un6JisQ", { logger: fakeLogger }, kernel => { kernel.defaultCacheFactory = options => new ExternalConfigCache(new ChromeLocalStorageConfigCache(faultyLocalStorage), options.logger); return kernel; @@ -66,7 +66,7 @@ describe("LocalStorageConfigCache tests", () => { const fakeLogger = new FakeLogger(); - const client = createClientWithLazyLoad("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/AG6C1ngVb0CvM07un6JisQ", { logger: fakeLogger }, + const client = platform.createClientWithLazyLoad("configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/AG6C1ngVb0CvM07un6JisQ", { logger: fakeLogger }, kernel => { kernel.defaultCacheFactory = options => new ExternalConfigCache(new ChromeLocalStorageConfigCache(faultyLocalStorage), options.logger); return kernel; diff --git a/test/chromium-extension/HttpTests.ts b/test/chromium-extension/HttpTests.ts index 8eefe8d..2fa8b59 100644 --- a/test/chromium-extension/HttpTests.ts +++ b/test/chromium-extension/HttpTests.ts @@ -1,7 +1,7 @@ import { assert } from "chai"; import fetchMock from "fetch-mock"; import { FakeLogger } from "../helpers/fakes"; -import { createClientWithManualPoll } from "."; +import { platform } from "."; import { LogLevel } from "#lib"; describe("HTTP tests", () => { @@ -18,7 +18,7 @@ describe("HTTP tests", () => { try { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs, baseUrl, logger @@ -47,7 +47,7 @@ describe("HTTP tests", () => { try { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs: 1000, baseUrl, logger @@ -73,7 +73,7 @@ describe("HTTP tests", () => { try { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs: 1000, baseUrl, logger @@ -100,7 +100,7 @@ describe("HTTP tests", () => { try { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs: 1000, baseUrl, logger diff --git a/test/chromium-extension/index.ts b/test/chromium-extension/index.ts index 41f2e3b..cb82ec9 100644 --- a/test/chromium-extension/index.ts +++ b/test/chromium-extension/index.ts @@ -1,64 +1,46 @@ -import { initPlatform } from "../helpers/platform"; +import { PlatformAbstractions, initPlatform } from "../helpers/platform"; +import type { IJSAutoPollOptions, IJSLazyLoadingOptions, IJSManualPollOptions } from "#lib/chromium-extension"; import { getClient } from "#lib/chromium-extension"; -import type { IConfigCatClient, IJSAutoPollOptions, IJSLazyLoadingOptions, IJSManualPollOptions } from "#lib/chromium-extension"; import { ChromeLocalStorageConfigCache } from "#lib/chromium-extension/ChromeLocalStorageConfigCache"; -import { ConfigCatClient } from "#lib/ConfigCatClient"; -import { AutoPollOptions, LazyLoadOptions, ManualPollOptions } from "#lib/ConfigCatClientOptions"; import { DefaultEventEmitter } from "#lib/DefaultEventEmitter"; -import type { IConfigCatKernel, IConfigFetcher } from "#lib/index.pubternals"; +import type { IConfigCatKernel } from "#lib/index.pubternals"; import { FetchApiConfigFetcher } from "#lib/shared/FetchApiConfigFetcher"; import sdkVersion from "#lib/Version"; const sdkType = "ConfigCat-UnifiedJS-ChromiumExtension"; -export const createConfigFetcher = (): IConfigFetcher => new FetchApiConfigFetcher(); - -export const createKernel = (setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatKernel => { - const kernel: IConfigCatKernel = { configFetcher: createConfigFetcher(), sdkType, sdkVersion, eventEmitterFactory: () => new DefaultEventEmitter() }; - setupKernel ??= kernel => { - kernel.defaultCacheFactory = ChromeLocalStorageConfigCache.tryGetFactory(); - return kernel; - }; - return setupKernel(kernel); -}; - -export const createClientWithAutoPoll = (sdkKey: string, options?: IJSAutoPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new AutoPollOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; - -export const createClientWithManualPoll = (sdkKey: string, options?: IJSLazyLoadingOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new ManualPollOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; - -export const createClientWithLazyLoad = (sdkKey: string, options?: IJSManualPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new LazyLoadOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; - -export const pathJoin = (...segments: string[]): string => segments.join("/"); - -export const readFileUtf8 = async (path: string): Promise => { - const response = await fetch("base/" + path, { method: "GET" }); - if (response.status === 200) { - return await response.text(); +type IJSOptions = IJSAutoPollOptions | IJSManualPollOptions | IJSLazyLoadingOptions; + +class ChromiumExtensionPlatform extends PlatformAbstractions { + pathJoin(...segments: string[]) { return segments.join("/"); } + + async readFileUtf8(path: string) { + const response = await fetch("base/" + path, { method: "GET" }); + if (response.status === 200) { + return await response.text(); + } + else { + throw Error(`unexpected response: ${response.status} ${response.statusText}`); + } } - else { - throw Error(`unexpected response: ${response.status} ${response.statusText}`); + + createConfigFetcher(options?: IJSOptions) { return new FetchApiConfigFetcher(); } + + createKernel(setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel, options?: IJSOptions) { + const kernel: IConfigCatKernel = { configFetcher: this.createConfigFetcher(options), sdkType, sdkVersion, eventEmitterFactory: () => new DefaultEventEmitter() }; + setupKernel ??= kernel => { + kernel.defaultCacheFactory = ChromeLocalStorageConfigCache.tryGetFactory(); + return kernel; + }; + return setupKernel(kernel); } -}; - -initPlatform({ - pathJoin, - readFileUtf8, - createConfigFetcher, - createKernel, - createClientWithAutoPoll, - createClientWithManualPoll, - createClientWithLazyLoad, - getClient -}); + + protected getClientImpl = getClient; +} + +export const platform = new ChromiumExtensionPlatform(); + +initPlatform(platform); /* Discover and load tests */ diff --git a/test/cloudflare-worker/CacheTests.ts b/test/cloudflare-worker/CacheTests.ts new file mode 100644 index 0000000..c321a5d --- /dev/null +++ b/test/cloudflare-worker/CacheTests.ts @@ -0,0 +1,16 @@ +import { assert } from "chai"; +import { CloudflareConfigCache, getCloudflareCache } from "#lib/cloudflare-worker/CloudflareConfigCache"; + +describe("CloudflareConfigCache tests", () => { + it("CloudflareConfigCache works with non latin 1 characters", async function() { + const cloudflareCahe = getCloudflareCache(); + assert.isDefined(cloudflareCahe); + + const cache = new CloudflareConfigCache(cloudflareCahe); + const key = "testkey"; + const text = "äöüÄÖÜçéèñışğ⢙✓😀"; + await cache.set(key, text); + const retrievedValue = await cache.get(key); + assert.strictEqual(retrievedValue, text); + }); +}); diff --git a/test/cloudflare-worker/IndexTests.ts b/test/cloudflare-worker/IndexTests.ts new file mode 100644 index 0000000..a9a1f05 --- /dev/null +++ b/test/cloudflare-worker/IndexTests.ts @@ -0,0 +1,22 @@ +import { assert } from "chai"; +import { FlagOverrides, IConfigCatClient, PollingMode } from "#lib"; +import * as configcatClient from "#lib/cloudflare-worker"; + +describe("ConfigCatClient index (main)", () => { + for (const pollingMode of [PollingMode.AutoPoll, PollingMode.LazyLoad, PollingMode.ManualPoll]) { + it(`getClient() should createInstance with ${PollingMode[pollingMode]}`, () => { + + const client: IConfigCatClient = configcatClient.getClient("SDKKEY-890123456789012/1234567890123456789012", pollingMode); + + assert.isDefined(client); + + client.dispose(); + }); + } + + it("createFlagOverridesFromMap ShouldCreateFlagOverrides", () => { + const overrides: FlagOverrides = configcatClient.createFlagOverridesFromMap({ test: true }, configcatClient.OverrideBehaviour.LocalOnly); + + assert.isDefined(overrides); + }); +}); diff --git a/test/cloudflare-worker/OverrideTests.ts b/test/cloudflare-worker/OverrideTests.ts new file mode 100644 index 0000000..008df01 --- /dev/null +++ b/test/cloudflare-worker/OverrideTests.ts @@ -0,0 +1,55 @@ +import type * as cloudflare from "@cloudflare/workers-types/2023-03-01"; +import { assert } from "chai"; +import { FakeConfigFetcherBase, createAutoPollOptions, createKernel } from "../helpers/fakes"; +import { createFlagOverridesFromQueryParams } from "#lib/cloudflare-worker"; +import { ConfigCatClient, IConfigCatClient } from "#lib/ConfigCatClient"; +import { AutoPollOptions } from "#lib/ConfigCatClientOptions"; +import { IQueryStringProvider, OverrideBehaviour } from "#lib/FlagOverrides"; + +// eslint-disable-next-line @typescript-eslint/naming-convention +declare const Request: typeof cloudflare.Request; + +describe("Flag Overrides (Cloudflare Workers)", () => { + it("Values from query string - using request", async () => { + const configCatKernel = createKernel({ + configFetcher: new FakeConfigFetcherBase('{"f":{"stringDefaultCat":{"t":1,"v":{"s":"CAT"}},"stringDefaultDog":{"t":1,"v":{"s":"DOG"}}}}'), + }); + + const currentQueryString = "?cc-stringDefaultCat=OVERRIDE_CAT&stringDefaultDog=OVERRIDE_DOG"; + const request = new Request("http://dummy/" + currentQueryString); + + const options: AutoPollOptions = createAutoPollOptions("localhost", { + flagOverrides: createFlagOverridesFromQueryParams(OverrideBehaviour.LocalOverRemote, request, void 0), + }, configCatKernel); + const client: IConfigCatClient = new ConfigCatClient(options, configCatKernel); + + assert.equal(await client.getValueAsync("stringDefaultCat", ""), "OVERRIDE_CAT"); + assert.equal(await client.getValueAsync("stringDefaultDog", ""), "DOG"); + + client.dispose(); + }); + + it("Values from query string - using custom query string provider", async () => { + const configCatKernel = createKernel({ + configFetcher: new FakeConfigFetcherBase('{"f":{"stringDefaultCat":{"t":1,"v":{"s":"CAT"}},"stringDefaultDog":{"t":1,"v":{"s":"DOG"}}}}'), + }); + + let currentQueryString = "?cc-stringDefaultCat=OVERRIDE_CAT&stringDefaultDog=OVERRIDE_DOG"; + const queryStringProvider: IQueryStringProvider = { get currentValue() { return currentQueryString; } }; + + const options: AutoPollOptions = createAutoPollOptions("localhost", { + flagOverrides: createFlagOverridesFromQueryParams(OverrideBehaviour.LocalOverRemote, true, void 0, queryStringProvider), + }, configCatKernel); + const client: IConfigCatClient = new ConfigCatClient(options, configCatKernel); + + assert.equal(await client.getValueAsync("stringDefaultCat", ""), "OVERRIDE_CAT"); + assert.equal(await client.getValueAsync("stringDefaultDog", ""), "DOG"); + + currentQueryString = "?cc-stringDefaultCat=CHANGED_OVERRIDE_CAT"; + + assert.equal(await client.getValueAsync("stringDefaultCat", ""), "CHANGED_OVERRIDE_CAT"); + assert.equal(await client.getValueAsync("stringDefaultDog", ""), "DOG"); + + client.dispose(); + }); +}); diff --git a/test/cloudflare-worker/index.ts b/test/cloudflare-worker/index.ts new file mode 100644 index 0000000..733054d --- /dev/null +++ b/test/cloudflare-worker/index.ts @@ -0,0 +1,135 @@ +import "mocha/mocha.js"; +import * as cloudflare from "@cloudflare/workers-types/2023-03-01"; +import { CdnConfigLocation } from "../helpers/ConfigLocation"; +import { AugmentedOptions, PlatformAbstractions, initPlatform } from "../helpers/platform"; +import type { IJSAutoPollOptions, IJSLazyLoadingOptions, IJSManualPollOptions, IOptions } from "#lib/cloudflare-worker"; +import { getClient } from "#lib/cloudflare-worker"; +import { CloudflareConfigCache } from "#lib/cloudflare-worker/CloudflareConfigCache"; +import { DefaultEventEmitter } from "#lib/DefaultEventEmitter"; +import type { IConfigCatKernel, OptionsBase } from "#lib/index.pubternals"; +import { FetchApiConfigFetcher } from "#lib/shared/FetchApiConfigFetcher"; +import sdkVersion from "#lib/Version"; + +const sdkType = "ConfigCat-UnifiedJS-CloudflareWorker"; + +// Browser-based Mocha requires `window.location` to exist. +const location = "http://localhost:0"; +if (typeof window === "undefined") { + // window global is not available in Deno 2 + (globalThis as any).window = globalThis; +} +(window as any).location = new URL(location); + +const options: Mocha.MochaOptions = { timeout: 30000 }; + +// In order to use `describe` etc. we need to set Mocha to `bdd` mode. +// We also need to set the reporter to `spec` (though other options +// are available) to prevent Mocha using the default browser reporter +// which requires access to a DOM. +mocha.setup({ ...options, ui: "bdd", reporter: "spec" }); + +// Ensure there are no leaks in our tests. +mocha.checkLeaks(); + +type IJSOptions = IJSAutoPollOptions | IJSManualPollOptions | IJSLazyLoadingOptions; + +class CloudflareWorkerPlatform extends PlatformAbstractions { + pathJoin(...segments: string[]) { return segments.join("/"); } + + async readFileUtf8(path: string) { + if (!path.startsWith("/")) path = "/" + path; + + const basePath = "/test/data"; + if (path.startsWith(basePath)) path = path.substring(basePath.length); + + const workerEnv = await workerEnvPromise; + const response = await workerEnv.data.fetch("http://dummy" + path, { method: "GET" }); + if (response.status === 200) { + return await response.text(); + } + else { + throw Error(`unexpected response: ${response.status} ${response.statusText}`); + } + } + + createConfigFetcher(options?: IJSOptions) { return new FetchApiConfigFetcher(); } + + createKernel(setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel, options?: IJSOptions) { + const kernel: IConfigCatKernel = { configFetcher: this.createConfigFetcher(options), sdkType, sdkVersion, eventEmitterFactory: () => new DefaultEventEmitter() }; + setupKernel ??= kernel => { + kernel.defaultCacheFactory = CloudflareConfigCache.tryGetFactory(); + return kernel; + }; + return setupKernel(kernel); + } + + protected getClientImpl = getClient; + + protected adjustOptions(options?: TOptions) { + options = { ...options } as TOptions; + options.baseUrl ??= CdnConfigLocation.getDefaultCdnUrl(options); + // HACK: There are issues with HTTPS in workerd (see e.g. https://github.com/cloudflare/workers-sdk/issues/4257), + // so, as a workaround, we make requests to the ConfigCat CDN thorugh a Node.js proxy server for now. + // See also: see also: test-run-helper/server.mjs + options.baseUrl = "http://localhost:9060/" + encodeURIComponent(options.baseUrl); + return options; + } + + protected augmentOptions(options: TOptions) { + const augmentedOptions = options as AugmentedOptions; + augmentedOptions.getRealUrl = function() { + const url = new URL(this.getUrl()); + const path = url.pathname + url.search; + let index = path.indexOf("/", 1); + if (index < 0) index = path.length; + return decodeURIComponent(path.substring(1, index)) + path.substring(index); + }; + return augmentedOptions; + } +} + +export const platform = new CloudflareWorkerPlatform(); + +initPlatform(platform); + +// For service bindings, see workerd.config.capnp +type WorkerEnv = { data: cloudflare.Fetcher }; + +let resolveWorkerEnv: (value: WorkerEnv) => void; +const workerEnvPromise = new Promise(resolve => resolveWorkerEnv = resolve); + +/* Discover and load tests */ + +declare const require: any; + +// Keep this in sync with the includes listed in tsconfig.karma.chromium-extension.json! + +let testsContext: Record = require.context("..", false, /\.ts$/); +includeTestModules(testsContext); + +testsContext = require.context(".", true, /\.ts$/); +includeTestModules(testsContext); + +testsContext = require.context("../helpers", true, /\.ts$/); +includeTestModules(testsContext); + +function includeTestModules(testsContext: Record) { + for (const key of testsContext.keys()) { + (testsContext as any)(key); + } +} + +export default { + test: (ctrl, env, ctx) => { + resolveWorkerEnv(env); + + return new Promise((resolve, reject) => { + mocha.run(failures => { + if (failures > 0) { + reject(Error("Test run failed.")); + } + resolve(); + }).globals(["onerror"]); + }); + } +} as cloudflare.ExportedHandler; diff --git a/test/cloudflare-worker/test-run-helper/server.mjs b/test/cloudflare-worker/test-run-helper/server.mjs new file mode 100644 index 0000000..14bef51 --- /dev/null +++ b/test/cloudflare-worker/test-run-helper/server.mjs @@ -0,0 +1,81 @@ +import * as http from "http"; +import * as https from "https"; +import { URL } from "url"; + +const proxyPort = parseInt(process.argv[2] || 9060); +const cachePort = proxyPort + 1; + +const cache = {}; + +/* A simple proxy server to work around HTTPS issues with workerd. */ +http.createServer((req, res) => { + let index = req.url.indexOf("/", 1); + if (index < 0) index = req.url.length; + let originalUrl = decodeURIComponent(req.url.substring(1, index)); + if (!originalUrl.startsWith("http:") && !originalUrl.startsWith("https:")) { + res.writeHead(404); + res.end(); + return; + } + originalUrl += req.url.substring(index); + console.log(`[PROXY] ${req.method} ${req.url} -> ${originalUrl}`); + + const { protocol, hostname, pathname, search } = new URL(originalUrl); + const serverReqOptions = { + method: req.method, + protocol, + hostname, + path: pathname + search, + headers: { ...req.headers, "host": hostname } + }; + + const isHTTPS = protocol.toLowerCase() === "https:"; + const proxy = (isHTTPS ? https : http).request(serverReqOptions, serverRes => { + res.writeHead(serverRes.statusCode, serverRes.headers); + serverRes.pipe(res, { + end: true + }); + }); + + req.pipe(proxy, { + end: true + }); +}).listen(proxyPort); + +/* A fake Cloudflare Cache API server. */ +http.createServer((req, res) => { + console.log(`[CACHE] ${req.method} ${req.url}`); + + const key = req.url; + + if (req.method === "GET") { + const message = cache[key]; + if (message != null && res.socket) { + let index = message.indexOf("\r\n"); + index = index >= 0 ? index + 2 : message.length; + res.socket.write("HTTP/1.1 200 OK\r\n"); + res.socket.write("CF-Cache-Status: HIT\r\n"); + res.socket.write(message.substring(index)); + res.socket.end(); + } + else { + res.writeHead(200, { "CF-Cache-Status": "MISS" }); + } + res.end(); + } + else if (req.method === "PUT") { + let message = ""; + req.on("data", chunk => { + message += chunk; + }); + + req.on("end", () => { + cache[key] = message; + res.writeHead(204); + res.end(); + }); + } +}).listen(cachePort); + +console.log(`Proxy server is listening at http://localhost:${proxyPort}...`); +console.log(`Fake Cloudflare Cache API server is listening at http://localhost:${cachePort}...`); diff --git a/test/deno/index.ts b/test/deno/index.ts index f78b038..567363c 100644 --- a/test/deno/index.ts +++ b/test/deno/index.ts @@ -1,13 +1,12 @@ import * as path from "https://deno.land/std@0.224.0/path/mod.ts"; // @deno-types="npm:@types/mocha" import "npm:mocha/browser-entry.js"; -import { initPlatform } from "../helpers/platform"; +import { PlatformAbstractions, initPlatform } from "../helpers/platform"; import { isTestSpec } from "../index"; -import { ConfigCatClient, IConfigCatKernel } from "#lib/ConfigCatClient"; -import { AutoPollOptions, LazyLoadOptions, ManualPollOptions } from "#lib/ConfigCatClientOptions"; -import { IConfigFetcher } from "#lib/ConfigFetcher"; +import { IConfigCatKernel } from "#lib/ConfigCatClient"; import { DefaultEventEmitter } from "#lib/DefaultEventEmitter"; -import { IConfigCatClient, IDenoAutoPollOptions, IDenoLazyLoadingOptions, IDenoManualPollOptions, getClient } from "#lib/deno"; +import type { IDenoAutoPollOptions, IDenoLazyLoadingOptions, IDenoManualPollOptions } from "#lib/deno"; +import { getClient } from "#lib/deno"; import { FetchApiConfigFetcher } from "#lib/shared/FetchApiConfigFetcher"; import sdkVersion from "#lib/Version"; @@ -51,42 +50,26 @@ mocha.setup({ ...options, ui: "bdd", reporter: "spec" }); // Ensure there are no leaks in our tests. mocha.checkLeaks(); -export const createConfigFetcher = (): IConfigFetcher => new FetchApiConfigFetcher(); - -export const createKernel = (setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatKernel => { - const kernel: IConfigCatKernel = { configFetcher: createConfigFetcher(), sdkType, sdkVersion, eventEmitterFactory: () => new DefaultEventEmitter() }; - return (setupKernel ?? (k => k))(kernel); -}; - -export const createClientWithAutoPoll = (sdkKey: string, options?: IDenoAutoPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new AutoPollOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; - -export const createClientWithManualPoll = (sdkKey: string, options?: IDenoManualPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new ManualPollOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; - -export const createClientWithLazyLoad = (sdkKey: string, options?: IDenoLazyLoadingOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new LazyLoadOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; - -export const pathJoin = (...segments: string[]): string => path.join(...segments); - -export const readFileUtf8 = (path: string): string => Deno.readTextFileSync(path); - -initPlatform({ - pathJoin, - readFileUtf8, - createConfigFetcher, - createKernel, - createClientWithAutoPoll, - createClientWithManualPoll, - createClientWithLazyLoad, - getClient -}); +type IDenoOptions = IDenoAutoPollOptions | IDenoManualPollOptions | IDenoLazyLoadingOptions; + +class DenoPlatform extends PlatformAbstractions { + pathJoin(...segments: string[]) { return path.join(...segments); } + + readFileUtf8(path: string) { return Deno.readTextFileSync(path); } + + createConfigFetcher(options?: IDenoOptions) { return new FetchApiConfigFetcher(); } + + createKernel(setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel, options?: IDenoOptions) { + const kernel: IConfigCatKernel = { configFetcher: this.createConfigFetcher(options), sdkType, sdkVersion, eventEmitterFactory: () => new DefaultEventEmitter() }; + return (setupKernel ?? (k => k))(kernel); + } + + protected getClientImpl = getClient; +} + +export const platform = new DenoPlatform(); + +initPlatform(platform); /* Discover and load tests */ diff --git a/test/helpers/ConfigLocation.ts b/test/helpers/ConfigLocation.ts index d3c9736..24129d3 100644 --- a/test/helpers/ConfigLocation.ts +++ b/test/helpers/ConfigLocation.ts @@ -1,6 +1,6 @@ import { createManualPollOptions } from "./fakes"; -import { platform } from "./platform"; -import { ManualPollOptions } from "#lib/ConfigCatClientOptions"; +import { AugmentedOptions, platform } from "./platform"; +import { DataGovernance, IOptions, ManualPollOptions } from "#lib/ConfigCatClientOptions"; import { ManualPollConfigService } from "#lib/ManualPollConfigService"; import { Config } from "#lib/ProjectConfig"; @@ -22,10 +22,19 @@ export abstract class ConfigLocation { } export class CdnConfigLocation extends ConfigLocation { - private $options?: ManualPollOptions; - get options(): ManualPollOptions { + static getDefaultCdnUrl(options?: IOptions): string { + switch (options?.dataGovernance ?? DataGovernance.Global) { + case DataGovernance.EuOnly: + return "https://cdn-eu.configcat.com"; + default: + return "https://cdn-global.configcat.com"; + } + } + + private $options?: AugmentedOptions; + get options(): AugmentedOptions { return this.$options ??= createManualPollOptions(this.sdkKey, { - baseUrl: this.baseUrl ?? "https://cdn-eu.configcat.com" + baseUrl: this.baseUrl ?? CdnConfigLocation.getDefaultCdnUrl() }); } @@ -37,7 +46,7 @@ export class CdnConfigLocation extends ConfigLocation { } getRealLocation(): string { - const url = this.options.getUrl(); + const url = this.options.getRealUrl(); const index = url.lastIndexOf("?"); return index >= 0 ? url.slice(0, index) : url; } diff --git a/test/helpers/fakes.ts b/test/helpers/fakes.ts index b73b8d3..be142f5 100644 --- a/test/helpers/fakes.ts +++ b/test/helpers/fakes.ts @@ -1,31 +1,29 @@ -import { platform } from "./platform"; +import { AugmentedOptions, platform } from "./platform"; import { IConfigCache, IConfigCatCache } from "#lib/ConfigCatCache"; import { IConfigCatClient } from "#lib/ConfigCatClient"; -import { AutoPollOptions, IAutoPollOptions, ILazyLoadingOptions, IManualPollOptions, LazyLoadOptions, ManualPollOptions, OptionsBase } from "#lib/ConfigCatClientOptions"; +import { AutoPollOptions, IAutoPollOptions, ILazyLoadingOptions, IManualPollOptions, IOptions, LazyLoadOptions, ManualPollOptions, OptionsBase } from "#lib/ConfigCatClientOptions"; import { IConfigCatLogger, LogEventId, LogLevel, LogMessage } from "#lib/ConfigCatLogger"; import { IConfigFetcher, IFetchResponse } from "#lib/ConfigFetcher"; import { IConfigCatKernel } from "#lib/index.pubternals"; import { ProjectConfig } from "#lib/ProjectConfig"; import { delay } from "#lib/Utils"; -export function createKernel(kernelOverride?: Partial): IConfigCatKernel { - return platform().createKernel(kernel => Object.assign(kernel, kernelOverride)); +export function createKernel(kernelOverride?: Partial, options?: IOptions): IConfigCatKernel { + return platform().createKernel(kernel => Object.assign(kernel, kernelOverride), options); } -export function createAutoPollOptions(sdkKey: string, options?: IAutoPollOptions, kernel?: IConfigCatKernel): AutoPollOptions { - kernel ??= createKernel(); - return new AutoPollOptions(sdkKey, kernel.sdkType, kernel.sdkVersion, options, kernel.defaultCacheFactory, kernel.eventEmitterFactory); +export function createAutoPollOptions(sdkKey: string, options?: IAutoPollOptions, kernel?: IConfigCatKernel): AugmentedOptions { + return platform().createAutoPollOptions(sdkKey, options, kernel ?? createKernel(void 0, options)); } -export function createManualPollOptions(sdkKey: string, options?: IManualPollOptions, kernel?: IConfigCatKernel): ManualPollOptions { - kernel ??= createKernel(); - return new ManualPollOptions(sdkKey, kernel.sdkType, kernel.sdkVersion, options, kernel.defaultCacheFactory, kernel.eventEmitterFactory); +export function createManualPollOptions(sdkKey: string, options?: IManualPollOptions, kernel?: IConfigCatKernel): AugmentedOptions { + return platform().createManualPollOptions(sdkKey, options, kernel ?? createKernel(void 0, options)); } -export function createLazyLoadOptions(sdkKey: string, options?: ILazyLoadingOptions, kernel?: IConfigCatKernel): LazyLoadOptions { - kernel ??= createKernel(); - return new LazyLoadOptions(sdkKey, kernel.sdkType, kernel.sdkVersion, options, kernel.defaultCacheFactory, kernel.eventEmitterFactory); +export function createLazyLoadOptions(sdkKey: string, options?: ILazyLoadingOptions, kernel?: IConfigCatKernel): AugmentedOptions { + return platform().createLazyLoadOptions(sdkKey, options, kernel ?? createKernel(void 0, options)); } + export function createClientWithAutoPoll(sdkKey: string, kernelOverride?: Partial, options?: IAutoPollOptions): IConfigCatClient { return platform().createClientWithAutoPoll(sdkKey, options, kernel => Object.assign(kernel, kernelOverride)); } diff --git a/test/helpers/platform.ts b/test/helpers/platform.ts index 97f2c45..a7f3a5b 100644 --- a/test/helpers/platform.ts +++ b/test/helpers/platform.ts @@ -1,31 +1,102 @@ -import type { IAutoPollOptions, IConfigCatClient, ILazyLoadingOptions, IManualPollOptions, PollingMode } from "#lib"; -import { OptionsForPollingMode } from "#lib/ConfigCatClientOptions"; -import type { IConfigCatKernel, IConfigFetcher } from "#lib/index.pubternals"; - -interface IPlatformAbstractions { - gc?: () => Promise; - pathJoin(...segments: string[]): string; - readFileUtf8(path: string): string | Promise; - createConfigFetcher(): IConfigFetcher; - createKernel(setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatKernel; - createClientWithAutoPoll(sdkKey: string, options?: IAutoPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient; - createClientWithManualPoll(sdkKey: string, options?: IManualPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient; - createClientWithLazyLoad(sdkKey: string, options?: ILazyLoadingOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient; - getClient(sdkKey: string, pollingMode?: TMode, options?: OptionsForPollingMode): IConfigCatClient; +import type { IAutoPollOptions, IConfigCatClient, ILazyLoadingOptions, IManualPollOptions, IOptions, PollingMode } from "#lib"; +import { ConfigCatClient } from "#lib/ConfigCatClient"; +import { AutoPollOptions, LazyLoadOptions, ManualPollOptions } from "#lib/ConfigCatClientOptions"; +import type { IConfigCatKernel, IConfigFetcher, OptionsBase } from "#lib/index.pubternals"; + +type OptionsForPollingMode< + TMode extends PollingMode | unknown, + TAutoPollOptions extends IAutoPollOptions, + TManualPollOptions extends IManualPollOptions, + TLazyLoadingOptions extends ILazyLoadingOptions +> = + TMode extends PollingMode.AutoPoll ? TAutoPollOptions : + TMode extends PollingMode.ManualPoll ? TManualPollOptions : + TMode extends PollingMode.LazyLoad ? TLazyLoadingOptions : + TMode extends undefined ? TAutoPollOptions : + never; + +export type AugmentedOptions = TOptions & { + getRealUrl(): string; +} + +export abstract class PlatformAbstractions< + TAutoPollOptions extends IAutoPollOptions = IAutoPollOptions, + TManualPollOptions extends IManualPollOptions = IManualPollOptions, + TLazyLoadingOptions extends ILazyLoadingOptions = ILazyLoadingOptions, +> { + gc?(): Promise; + + abstract pathJoin(...segments: string[]): string; + + abstract readFileUtf8(path: string): string | Promise; + + abstract createConfigFetcher(options?: TAutoPollOptions | TManualPollOptions | TLazyLoadingOptions): IConfigFetcher; + + abstract createKernel(setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel, options?: TAutoPollOptions | TManualPollOptions | TLazyLoadingOptions): IConfigCatKernel; + + createAutoPollOptions(sdkKey: string, options?: TAutoPollOptions, kernel?: IConfigCatKernel): AugmentedOptions { + kernel ??= this.createKernel(void 0, options); + return this.augmentOptions( + new AutoPollOptions(sdkKey, kernel.sdkType, kernel.sdkVersion, this.adjustOptions(options), kernel.defaultCacheFactory, kernel.eventEmitterFactory) + ); + } + + createManualPollOptions(sdkKey: string, options?: TManualPollOptions, kernel?: IConfigCatKernel): AugmentedOptions { + kernel ??= this.createKernel(void 0, options); + return this.augmentOptions( + new ManualPollOptions(sdkKey, kernel.sdkType, kernel.sdkVersion, this.adjustOptions(options), kernel.defaultCacheFactory, kernel.eventEmitterFactory) + ); + } + + createLazyLoadOptions(sdkKey: string, options?: TLazyLoadingOptions, kernel?: IConfigCatKernel): AugmentedOptions { + kernel ??= this.createKernel(void 0, options); + return this.augmentOptions( + new LazyLoadOptions(sdkKey, kernel.sdkType, kernel.sdkVersion, this.adjustOptions(options), kernel.defaultCacheFactory, kernel.eventEmitterFactory) + ); + } + + createClientWithAutoPoll = (sdkKey: string, options?: TAutoPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { + const configCatKernel = this.createKernel(setupKernel, options); + return new ConfigCatClient(this.createAutoPollOptions(sdkKey, options, configCatKernel), configCatKernel); + }; + + createClientWithManualPoll = (sdkKey: string, options?: TManualPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { + const configCatKernel = this.createKernel(setupKernel, options); + return new ConfigCatClient(this.createManualPollOptions(sdkKey, options, configCatKernel), configCatKernel); + }; + + createClientWithLazyLoad = (sdkKey: string, options?: TLazyLoadingOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { + const configCatKernel = this.createKernel(setupKernel, options); + return new ConfigCatClient(this.createLazyLoadOptions(sdkKey, options, configCatKernel), configCatKernel); + }; + + getClient(sdkKey: string, pollingMode?: TMode, options?: OptionsForPollingMode): IConfigCatClient { + return this.getClientImpl(sdkKey, pollingMode, this.adjustOptions(options)); + } + + protected abstract getClientImpl(sdkKey: string, pollingMode?: TMode, options?: OptionsForPollingMode): IConfigCatClient; + + protected adjustOptions(options?: TOptions): TOptions | undefined { return options; } + + protected augmentOptions(options: TOptions): AugmentedOptions { + const augmentedOptions = options as AugmentedOptions; + augmentedOptions.getRealUrl = function() { return this.getUrl(); }; + return augmentedOptions; + } } -let platformAbstractions: IPlatformAbstractions | undefined; +let currentPlatform: PlatformAbstractions | undefined; -export function initPlatform(pa: IPlatformAbstractions): void { - if (platformAbstractions != null) { +export function initPlatform(platform: PlatformAbstractions): void { + if (currentPlatform != null) { throw new Error("Platform abstractions have already been initialized."); } - platformAbstractions = pa; + currentPlatform = platform; } -export function platform(): IPlatformAbstractions { - if (platformAbstractions == null) { +export function platform(): PlatformAbstractions { + if (currentPlatform == null) { throw new Error("Platform abstractions have not been initialized yet."); } - return platformAbstractions; + return currentPlatform; } diff --git a/test/node/ClientTests.ts b/test/node/ClientTests.ts index 758782e..31d58c7 100644 --- a/test/node/ClientTests.ts +++ b/test/node/ClientTests.ts @@ -1,6 +1,9 @@ import { assert } from "chai"; import { FlagOverrides, IConfigCatClient, PollingMode } from "#lib"; +import { ConfigCatClient } from "#lib/ConfigCatClient"; +import { ConfigServiceBase } from "#lib/ConfigServiceBase"; import * as configcatClient from "#lib/node"; +import { NodeHttpConfigFetcher } from "#lib/node/NodeHttpConfigFetcher"; describe("ConfigCatClient tests", () => { @@ -13,6 +16,26 @@ describe("ConfigCatClient tests", () => { client.dispose(); }); + + it(`getClient() should set proxy - ${PollingMode[pollingMode]}`, () => { + const proxy = "http://fake-proxy.com:8080"; + + const client: IConfigCatClient = configcatClient.getClient("SDKKEY-890123456789012/1234567890123456789012", pollingMode, { + proxy + }); + + assert.isDefined(client); + + const configService = (client as ConfigCatClient)["configService"]; + if (!(configService instanceof ConfigServiceBase)) assert.fail(); + + const configFetcher = configService["configFetcher"]; + assert.instanceOf(configFetcher, NodeHttpConfigFetcher); + + assert.strictEqual(configFetcher["proxy"], proxy); + + client.dispose(); + }); } it("createFlagOverridesFromMap() should createOverrides", () => { diff --git a/test/node/HttpTests.ts b/test/node/HttpTests.ts index 0f53f3a..7d08a89 100644 --- a/test/node/HttpTests.ts +++ b/test/node/HttpTests.ts @@ -1,7 +1,7 @@ import { assert } from "chai"; import * as mockttp from "mockttp"; import { FakeLogger } from "../helpers/fakes"; -import { createClientWithManualPoll } from "."; +import { platform } from "."; import { LogLevel } from "#lib"; // If the tests are failing with strange https or proxy errors, it is most likely that the local .key and .pem files are expired. @@ -26,7 +26,7 @@ describe("HTTP tests", () => { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs: 1000, baseUrl: server.url, logger @@ -49,7 +49,7 @@ describe("HTTP tests", () => { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs: 1000, baseUrl: server.url, logger @@ -70,7 +70,7 @@ describe("HTTP tests", () => { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs: 1000, baseUrl: server.url, logger @@ -91,7 +91,7 @@ describe("HTTP tests", () => { const logger = new FakeLogger(); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { requestTimeoutMs: 1000, baseUrl: server.url, logger @@ -115,7 +115,7 @@ describe("HTTP tests", () => { } }); - const client = createClientWithManualPoll(sdkKey, { + const client = platform.createClientWithManualPoll(sdkKey, { proxy: server.url }); await client.forceRefreshAsync(); diff --git a/test/node/index.ts b/test/node/index.ts index bb3e9ea..3021a45 100644 --- a/test/node/index.ts +++ b/test/node/index.ts @@ -3,13 +3,11 @@ import { EventEmitter } from "events"; import * as fs from "fs"; import * as glob from "glob"; import * as path from "path"; -import { initPlatform } from "../helpers/platform"; +import { PlatformAbstractions, initPlatform } from "../helpers/platform"; import { normalizePathSeparator } from "../helpers/utils"; import { isTestSpec } from "../index"; -import { ConfigCatClient } from "#lib/ConfigCatClient"; -import { AutoPollOptions, LazyLoadOptions, ManualPollOptions } from "#lib/ConfigCatClientOptions"; -import type { IConfigCatKernel, IConfigFetcher } from "#lib/index.pubternals"; -import type { IConfigCatClient, INodeAutoPollOptions, INodeLazyLoadingOptions, INodeManualPollOptions } from "#lib/node"; +import type { IConfigCatKernel } from "#lib/index.pubternals"; +import type { INodeAutoPollOptions, INodeLazyLoadingOptions, INodeManualPollOptions } from "#lib/node"; import { getClient } from "#lib/node"; import { NodeHttpConfigFetcher } from "#lib/node/NodeHttpConfigFetcher"; // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires @@ -17,48 +15,34 @@ const sdkVersion = require("#lib/Version"); const sdkType = "ConfigCat-UnifiedJS-Node"; -export const createConfigFetcher = (): IConfigFetcher => new NodeHttpConfigFetcher(); +type INodeOptions = INodeAutoPollOptions | INodeManualPollOptions | INodeLazyLoadingOptions; -export const createKernel = (setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatKernel => { - const kernel: IConfigCatKernel = { configFetcher: createConfigFetcher(), sdkType, sdkVersion, eventEmitterFactory: () => new EventEmitter() }; - return (setupKernel ?? (k => k))(kernel); -}; +class NodePlatform extends PlatformAbstractions { + constructor() { + super(); -export const createClientWithAutoPoll = (sdkKey: string, options?: INodeAutoPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new AutoPollOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; + if (typeof gc !== "undefined") { + this.gc = () => gc!({ execution: "async", type: "major" }); + } + } -export const createClientWithManualPoll = (sdkKey: string, options?: INodeManualPollOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new ManualPollOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; + pathJoin(...segments: string[]) { return path.join(...segments); } -export const createClientWithLazyLoad = (sdkKey: string, options?: INodeLazyLoadingOptions, setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel): IConfigCatClient => { - const configCatKernel = createKernel(setupKernel); - return new ConfigCatClient(new LazyLoadOptions(sdkKey, configCatKernel.sdkType, configCatKernel.sdkVersion, options, configCatKernel.defaultCacheFactory, configCatKernel.eventEmitterFactory), configCatKernel); -}; + readFileUtf8(path: string) { return fs.readFileSync(path, "utf8"); } -let gcfunc: (() => Promise) | undefined; -if (typeof gc !== "undefined") { - gcfunc = () => gc!({ execution: "async", type: "major" }); -} + createConfigFetcher(options?: INodeOptions) { return new NodeHttpConfigFetcher(options); } -export const pathJoin = (...segments: string[]): string => path.join(...segments); + createKernel(setupKernel?: (kernel: IConfigCatKernel) => IConfigCatKernel, options?: INodeOptions) { + const kernel: IConfigCatKernel = { configFetcher: this.createConfigFetcher(options), sdkType, sdkVersion, eventEmitterFactory: () => new EventEmitter() }; + return (setupKernel ?? (k => k))(kernel); + } + + protected getClientImpl = getClient; +} -export const readFileUtf8 = (path: string): string => fs.readFileSync(path, "utf8"); +export const platform = new NodePlatform(); -initPlatform({ - gc: gcfunc, - pathJoin, - readFileUtf8, - createConfigFetcher, - createKernel, - createClientWithAutoPoll, - createClientWithManualPoll, - createClientWithLazyLoad, - getClient -}); +initPlatform(platform); /* Discover and load tests */ diff --git a/tsconfig.build.esm.json b/tsconfig.build.esm.json index 155af8f..5649dc8 100644 --- a/tsconfig.build.esm.json +++ b/tsconfig.build.esm.json @@ -11,7 +11,9 @@ }, "files": [ "src/browser/index.root.ts", + "src/bun/index.ts", "src/chromium-extension/index.ts", + "src/cloudflare-worker/index.ts", "src/deno/index.ts", "src/node/index.root.ts" ] diff --git a/tsconfig.json b/tsconfig.json index e5edb10..31fc9bd 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -13,14 +13,15 @@ ], "paths": { // Keep this in sync with the imports listed in package.json! - "#lib/browser": ["./lib/esm/browser/index.root"], + "#lib/browser": ["./lib/esm/browser/index"], + "#lib/bun": ["./lib/esm/bun/index"], "#lib/chromium-extension": ["./lib/esm/chromium-extension/index"], + "#lib/cloudflare-worker": ["./lib/esm/cloudflare-worker/index"], "#lib/deno": ["./lib/esm/deno/index"], - "#lib/node": ["./lib/esm/node/index.root"], + "#lib/node": ["./lib/esm/node/index"], "#lib": ["./lib/esm/index"], "#lib/*": ["./lib/esm/*"] }, - "typeRoots": ["./node_modules/@types", "./types"], // Prevent typings for tests (mocha, chai, etc.) from bleeding into build source files. // (Wish we had more fine-grained control over what typings are included in what part of // the project... Something like this: https://github.com/microsoft/TypeScript/issues/33407) diff --git a/tsconfig.mocha.bun.json b/tsconfig.mocha.bun.json new file mode 100644 index 0000000..ae052c9 --- /dev/null +++ b/tsconfig.mocha.bun.json @@ -0,0 +1,20 @@ +{ + /* TS compiler settings for Bun tests */ + "extends": "./tsconfig.json", + "compilerOptions": { + "target": "ES2017", + "module": "ES2015", + "moduleResolution": "NodeNext", + "paths": { + "#lib/bun": ["./lib/esm/bun/index"], + "#lib": ["./lib/esm/index"], + "#lib/*": ["./lib/esm/*"] + }, + "types": ["bun", "chai", "mocha"] + }, + "include": [ + "test/bun/**/*.ts", + "test/*.ts", + "test/helpers/**/*.ts" + ] +} diff --git a/tsconfig.workerd.cloudflare-worker.json b/tsconfig.workerd.cloudflare-worker.json new file mode 100644 index 0000000..aeefc1f --- /dev/null +++ b/tsconfig.workerd.cloudflare-worker.json @@ -0,0 +1,16 @@ +{ + /* TS compiler settings for Cloudflare Workers (workerd) */ + "extends": "./tsconfig.build.esm.json", + "compilerOptions": { + "lib": ["DOM", "ES2020", "ES2021.WeakRef", "ES2021.Promise"], + "sourceMap": true, + "declaration": false, + "types": ["chai", "mocha"] + }, + "files": [], + "include": [ + "test/*.ts", + "test/cloudflare-worker/**/*.ts", + "test/helpers/**/*.ts" + ] +} diff --git a/types/deno/index.d.ts b/types/deno/index.d.ts deleted file mode 100644 index 2ddc434..0000000 --- a/types/deno/index.d.ts +++ /dev/null @@ -1,10783 +0,0 @@ -// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. - -/// -/// -/// - -/** Deno provides extra properties on `import.meta`. These are included here - * to ensure that these are still available when using the Deno namespace in - * conjunction with other type libs, like `dom`. - * - * @category ES Modules - */ -declare interface ImportMeta { - /** A string representation of the fully qualified module URL. When the - * module is loaded locally, the value will be a file URL (e.g. - * `file:///path/module.ts`). - * - * You can also parse the string as a URL to determine more information about - * how the current module was loaded. For example to determine if a module was - * local or not: - * - * ```ts - * const url = new URL(import.meta.url); - * if (url.protocol === "file:") { - * console.log("this module was loaded locally"); - * } - * ``` - */ - url: string; - - /** A flag that indicates if the current module is the main module that was - * called when starting the program under Deno. - * - * ```ts - * if (import.meta.main) { - * // this was loaded as the main module, maybe do some bootstrapping - * } - * ``` - */ - main: boolean; - - /** A function that returns resolved specifier as if it would be imported - * using `import(specifier)`. - * - * ```ts - * console.log(import.meta.resolve("./foo.js")); - * // file:///dev/foo.js - * ``` - */ - resolve(specifier: string): string; -} - -/** Deno supports [User Timing Level 3](https://w3c.github.io/user-timing) - * which is not widely supported yet in other runtimes. - * - * Check out the - * [Performance API](https://developer.mozilla.org/en-US/docs/Web/API/Performance) - * documentation on MDN for further information about how to use the API. - * - * @category Performance - */ -declare interface Performance { - /** Stores a timestamp with the associated name (a "mark"). */ - mark(markName: string, options?: PerformanceMarkOptions): PerformanceMark; - - /** Stores the `DOMHighResTimeStamp` duration between two marks along with the - * associated name (a "measure"). */ - measure( - measureName: string, - options?: PerformanceMeasureOptions, - ): PerformanceMeasure; -} - -/** - * Options which are used in conjunction with `performance.mark`. Check out the - * MDN - * [`performance.mark()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark#markoptions) - * documentation for more details. - * - * @category Performance - */ -declare interface PerformanceMarkOptions { - /** Metadata to be included in the mark. */ - // deno-lint-ignore no-explicit-any - detail?: any; - - /** Timestamp to be used as the mark time. */ - startTime?: number; -} - -/** - * Options which are used in conjunction with `performance.measure`. Check out the - * MDN - * [`performance.mark()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/measure#measureoptions) - * documentation for more details. - * - * @category Performance - */ -declare interface PerformanceMeasureOptions { - /** Metadata to be included in the measure. */ - // deno-lint-ignore no-explicit-any - detail?: any; - - /** Timestamp to be used as the start time or string to be used as start - * mark. */ - start?: string | number; - - /** Duration between the start and end times. */ - duration?: number; - - /** Timestamp to be used as the end time or string to be used as end mark. */ - end?: string | number; -} - -/** The global namespace where Deno specific, non-standard APIs are located. */ -declare namespace Deno { - /** A set of error constructors that are raised by Deno APIs. - * - * Can be used to provide more specific handling of failures within code - * which is using Deno APIs. For example, handling attempting to open a file - * which does not exist: - * - * ```ts - * try { - * const file = await Deno.open("./some/file.txt"); - * } catch (error) { - * if (error instanceof Deno.errors.NotFound) { - * console.error("the file was not found"); - * } else { - * // otherwise re-throw - * throw error; - * } - * } - * ``` - * - * @category Errors - */ - export namespace errors { - /** - * Raised when the underlying operating system indicates that the file - * was not found. - * - * @category Errors */ - export class NotFound extends Error {} - /** - * Raised when the underlying operating system indicates the current user - * which the Deno process is running under does not have the appropriate - * permissions to a file or resource, or the user _did not_ provide required - * `--allow-*` flag. - * - * @category Errors */ - export class PermissionDenied extends Error {} - /** - * Raised when the underlying operating system reports that a connection to - * a resource is refused. - * - * @category Errors */ - export class ConnectionRefused extends Error {} - /** - * Raised when the underlying operating system reports that a connection has - * been reset. With network servers, it can be a _normal_ occurrence where a - * client will abort a connection instead of properly shutting it down. - * - * @category Errors */ - export class ConnectionReset extends Error {} - /** - * Raised when the underlying operating system reports an `ECONNABORTED` - * error. - * - * @category Errors */ - export class ConnectionAborted extends Error {} - /** - * Raised when the underlying operating system reports an `ENOTCONN` error. - * - * @category Errors */ - export class NotConnected extends Error {} - /** - * Raised when attempting to open a server listener on an address and port - * that already has a listener. - * - * @category Errors */ - export class AddrInUse extends Error {} - /** - * Raised when the underlying operating system reports an `EADDRNOTAVAIL` - * error. - * - * @category Errors */ - export class AddrNotAvailable extends Error {} - /** - * Raised when trying to write to a resource and a broken pipe error occurs. - * This can happen when trying to write directly to `stdout` or `stderr` - * and the operating system is unable to pipe the output for a reason - * external to the Deno runtime. - * - * @category Errors */ - export class BrokenPipe extends Error {} - /** - * Raised when trying to create a resource, like a file, that already - * exits. - * - * @category Errors */ - export class AlreadyExists extends Error {} - /** - * Raised when an operation to returns data that is invalid for the - * operation being performed. - * - * @category Errors */ - export class InvalidData extends Error {} - /** - * Raised when the underlying operating system reports that an I/O operation - * has timed out (`ETIMEDOUT`). - * - * @category Errors */ - export class TimedOut extends Error {} - /** - * Raised when the underlying operating system reports an `EINTR` error. In - * many cases, this underlying IO error will be handled internally within - * Deno, or result in an @{link BadResource} error instead. - * - * @category Errors */ - export class Interrupted extends Error {} - /** - * Raised when the underlying operating system would need to block to - * complete but an asynchronous (non-blocking) API is used. - * - * @category Errors */ - export class WouldBlock extends Error {} - /** - * Raised when expecting to write to a IO buffer resulted in zero bytes - * being written. - * - * @category Errors */ - export class WriteZero extends Error {} - /** - * Raised when attempting to read bytes from a resource, but the EOF was - * unexpectedly encountered. - * - * @category Errors */ - export class UnexpectedEof extends Error {} - /** - * The underlying IO resource is invalid or closed, and so the operation - * could not be performed. - * - * @category Errors */ - export class BadResource extends Error {} - /** - * Raised in situations where when attempting to load a dynamic import, - * too many redirects were encountered. - * - * @category Errors */ - export class Http extends Error {} - /** - * Raised when the underlying IO resource is not available because it is - * being awaited on in another block of code. - * - * @category Errors */ - export class Busy extends Error {} - /** - * Raised when the underlying Deno API is asked to perform a function that - * is not currently supported. - * - * @category Errors */ - export class NotSupported extends Error {} - } - - /** The current process ID of this instance of the Deno CLI. - * - * ```ts - * console.log(Deno.pid); - * ``` - * - * @category Runtime Environment - */ - export const pid: number; - - /** - * The process ID of parent process of this instance of the Deno CLI. - * - * ```ts - * console.log(Deno.ppid); - * ``` - * - * @category Runtime Environment - */ - export const ppid: number; - - /** @category Runtime Environment */ - export interface MemoryUsage { - /** The number of bytes of the current Deno's process resident set size, - * which is the amount of memory occupied in main memory (RAM). */ - rss: number; - /** The total size of the heap for V8, in bytes. */ - heapTotal: number; - /** The amount of the heap used for V8, in bytes. */ - heapUsed: number; - /** Memory, in bytes, associated with JavaScript objects outside of the - * JavaScript isolate. */ - external: number; - } - - /** - * Returns an object describing the memory usage of the Deno process and the - * V8 subsystem measured in bytes. - * - * @category Runtime Environment - */ - export function memoryUsage(): MemoryUsage; - - /** - * Get the `hostname` of the machine the Deno process is running on. - * - * ```ts - * console.log(Deno.hostname()); - * ``` - * - * Requires `allow-sys` permission. - * - * @tags allow-sys - * @category Runtime Environment - */ - export function hostname(): string; - - /** - * Returns an array containing the 1, 5, and 15 minute load averages. The - * load average is a measure of CPU and IO utilization of the last one, five, - * and 15 minute periods expressed as a fractional number. Zero means there - * is no load. On Windows, the three values are always the same and represent - * the current load, not the 1, 5 and 15 minute load averages. - * - * ```ts - * console.log(Deno.loadavg()); // e.g. [ 0.71, 0.44, 0.44 ] - * ``` - * - * Requires `allow-sys` permission. - * - * On Windows there is no API available to retrieve this information and this method returns `[ 0, 0, 0 ]`. - * - * @tags allow-sys - * @category Observability - */ - export function loadavg(): number[]; - - /** - * The information for a network interface returned from a call to - * {@linkcode Deno.networkInterfaces}. - * - * @category Network - */ - export interface NetworkInterfaceInfo { - /** The network interface name. */ - name: string; - /** The IP protocol version. */ - family: "IPv4" | "IPv6"; - /** The IP address bound to the interface. */ - address: string; - /** The netmask applied to the interface. */ - netmask: string; - /** The IPv6 scope id or `null`. */ - scopeid: number | null; - /** The CIDR range. */ - cidr: string; - /** The MAC address. */ - mac: string; - } - - /** - * Returns an array of the network interface information. - * - * ```ts - * console.log(Deno.networkInterfaces()); - * ``` - * - * Requires `allow-sys` permission. - * - * @tags allow-sys - * @category Network - */ - export function networkInterfaces(): NetworkInterfaceInfo[]; - - /** - * Displays the total amount of free and used physical and swap memory in the - * system, as well as the buffers and caches used by the kernel. - * - * This is similar to the `free` command in Linux - * - * ```ts - * console.log(Deno.systemMemoryInfo()); - * ``` - * - * Requires `allow-sys` permission. - * - * @tags allow-sys - * @category Runtime Environment - */ - export function systemMemoryInfo(): SystemMemoryInfo; - - /** - * Information returned from a call to {@linkcode Deno.systemMemoryInfo}. - * - * @category Runtime Environment - */ - export interface SystemMemoryInfo { - /** Total installed memory in bytes. */ - total: number; - /** Unused memory in bytes. */ - free: number; - /** Estimation of how much memory, in bytes, is available for starting new - * applications, without swapping. Unlike the data provided by the cache or - * free fields, this field takes into account page cache and also that not - * all reclaimable memory will be reclaimed due to items being in use. - */ - available: number; - /** Memory used by kernel buffers. */ - buffers: number; - /** Memory used by the page cache and slabs. */ - cached: number; - /** Total swap memory. */ - swapTotal: number; - /** Unused swap memory. */ - swapFree: number; - } - - /** Reflects the `NO_COLOR` environment variable at program start. - * - * When the value is `true`, the Deno CLI will attempt to not send color codes - * to `stderr` or `stdout` and other command line programs should also attempt - * to respect this value. - * - * See: https://no-color.org/ - * - * @category Runtime Environment - */ - export const noColor: boolean; - - /** - * Returns the release version of the Operating System. - * - * ```ts - * console.log(Deno.osRelease()); - * ``` - * - * Requires `allow-sys` permission. - * Under consideration to possibly move to Deno.build or Deno.versions and if - * it should depend sys-info, which may not be desirable. - * - * @tags allow-sys - * @category Runtime Environment - */ - export function osRelease(): string; - - /** - * Returns the Operating System uptime in number of seconds. - * - * ```ts - * console.log(Deno.osUptime()); - * ``` - * - * Requires `allow-sys` permission. - * - * @tags allow-sys - * @category Runtime Environment - */ - export function osUptime(): number; - - /** - * Options which define the permissions within a test or worker context. - * - * `"inherit"` ensures that all permissions of the parent process will be - * applied to the test context. `"none"` ensures the test context has no - * permissions. A `PermissionOptionsObject` provides a more specific - * set of permissions to the test context. - * - * @category Permissions */ - export type PermissionOptions = - | "inherit" - | "none" - | PermissionOptionsObject; - - /** - * A set of options which can define the permissions within a test or worker - * context at a highly specific level. - * - * @category Permissions */ - export interface PermissionOptionsObject { - /** Specifies if the `env` permission should be requested or revoked. - * If set to `"inherit"`, the current `env` permission will be inherited. - * If set to `true`, the global `env` permission will be requested. - * If set to `false`, the global `env` permission will be revoked. - * - * @default {false} - */ - env?: "inherit" | boolean | string[]; - - /** Specifies if the `sys` permission should be requested or revoked. - * If set to `"inherit"`, the current `sys` permission will be inherited. - * If set to `true`, the global `sys` permission will be requested. - * If set to `false`, the global `sys` permission will be revoked. - * - * @default {false} - */ - sys?: "inherit" | boolean | string[]; - - /** Specifies if the `hrtime` permission should be requested or revoked. - * If set to `"inherit"`, the current `hrtime` permission will be inherited. - * If set to `true`, the global `hrtime` permission will be requested. - * If set to `false`, the global `hrtime` permission will be revoked. - * - * @default {false} - */ - hrtime?: "inherit" | boolean; - - /** Specifies if the `net` permission should be requested or revoked. - * if set to `"inherit"`, the current `net` permission will be inherited. - * if set to `true`, the global `net` permission will be requested. - * if set to `false`, the global `net` permission will be revoked. - * if set to `string[]`, the `net` permission will be requested with the - * specified host strings with the format `"[:]`. - * - * @default {false} - * - * Examples: - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test({ - * name: "inherit", - * permissions: { - * net: "inherit", - * }, - * async fn() { - * const status = await Deno.permissions.query({ name: "net" }) - * assertEquals(status.state, "granted"); - * }, - * }); - * ``` - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test({ - * name: "true", - * permissions: { - * net: true, - * }, - * async fn() { - * const status = await Deno.permissions.query({ name: "net" }); - * assertEquals(status.state, "granted"); - * }, - * }); - * ``` - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test({ - * name: "false", - * permissions: { - * net: false, - * }, - * async fn() { - * const status = await Deno.permissions.query({ name: "net" }); - * assertEquals(status.state, "denied"); - * }, - * }); - * ``` - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test({ - * name: "localhost:8080", - * permissions: { - * net: ["localhost:8080"], - * }, - * async fn() { - * const status = await Deno.permissions.query({ name: "net", host: "localhost:8080" }); - * assertEquals(status.state, "granted"); - * }, - * }); - * ``` - */ - net?: "inherit" | boolean | string[]; - - /** Specifies if the `ffi` permission should be requested or revoked. - * If set to `"inherit"`, the current `ffi` permission will be inherited. - * If set to `true`, the global `ffi` permission will be requested. - * If set to `false`, the global `ffi` permission will be revoked. - * - * @default {false} - */ - ffi?: "inherit" | boolean | Array; - - /** Specifies if the `read` permission should be requested or revoked. - * If set to `"inherit"`, the current `read` permission will be inherited. - * If set to `true`, the global `read` permission will be requested. - * If set to `false`, the global `read` permission will be revoked. - * If set to `Array`, the `read` permission will be requested with the - * specified file paths. - * - * @default {false} - */ - read?: "inherit" | boolean | Array; - - /** Specifies if the `run` permission should be requested or revoked. - * If set to `"inherit"`, the current `run` permission will be inherited. - * If set to `true`, the global `run` permission will be requested. - * If set to `false`, the global `run` permission will be revoked. - * - * @default {false} - */ - run?: "inherit" | boolean | Array; - - /** Specifies if the `write` permission should be requested or revoked. - * If set to `"inherit"`, the current `write` permission will be inherited. - * If set to `true`, the global `write` permission will be requested. - * If set to `false`, the global `write` permission will be revoked. - * If set to `Array`, the `write` permission will be requested with the - * specified file paths. - * - * @default {false} - */ - write?: "inherit" | boolean | Array; - } - - /** - * Context that is passed to a testing function, which can be used to either - * gain information about the current test, or register additional test - * steps within the current test. - * - * @category Testing */ - export interface TestContext { - /** The current test name. */ - name: string; - /** The string URL of the current test. */ - origin: string; - /** If the current test is a step of another test, the parent test context - * will be set here. */ - parent?: TestContext; - - /** Run a sub step of the parent test or step. Returns a promise - * that resolves to a boolean signifying if the step completed successfully. - * - * The returned promise never rejects unless the arguments are invalid. - * - * If the test was ignored the promise returns `false`. - * - * ```ts - * Deno.test({ - * name: "a parent test", - * async fn(t) { - * console.log("before the step"); - * await t.step({ - * name: "step 1", - * fn(t) { - * console.log("current step:", t.name); - * } - * }); - * console.log("after the step"); - * } - * }); - * ``` - */ - step(definition: TestStepDefinition): Promise; - - /** Run a sub step of the parent test or step. Returns a promise - * that resolves to a boolean signifying if the step completed successfully. - * - * The returned promise never rejects unless the arguments are invalid. - * - * If the test was ignored the promise returns `false`. - * - * ```ts - * Deno.test( - * "a parent test", - * async (t) => { - * console.log("before the step"); - * await t.step( - * "step 1", - * (t) => { - * console.log("current step:", t.name); - * } - * ); - * console.log("after the step"); - * } - * ); - * ``` - */ - step( - name: string, - fn: (t: TestContext) => void | Promise, - ): Promise; - - /** Run a sub step of the parent test or step. Returns a promise - * that resolves to a boolean signifying if the step completed successfully. - * - * The returned promise never rejects unless the arguments are invalid. - * - * If the test was ignored the promise returns `false`. - * - * ```ts - * Deno.test(async function aParentTest(t) { - * console.log("before the step"); - * await t.step(function step1(t) { - * console.log("current step:", t.name); - * }); - * console.log("after the step"); - * }); - * ``` - */ - step(fn: (t: TestContext) => void | Promise): Promise; - } - - /** @category Testing */ - export interface TestStepDefinition { - /** The test function that will be tested when this step is executed. The - * function can take an argument which will provide information about the - * current step's context. */ - fn: (t: TestContext) => void | Promise; - /** The name of the step. */ - name: string; - /** If truthy the current test step will be ignored. - * - * This is a quick way to skip over a step, but also can be used for - * conditional logic, like determining if an environment feature is present. - */ - ignore?: boolean; - /** Check that the number of async completed operations after the test step - * is the same as number of dispatched operations. This ensures that the - * code tested does not start async operations which it then does - * not await. This helps in preventing logic errors and memory leaks - * in the application code. - * - * Defaults to the parent test or step's value. */ - sanitizeOps?: boolean; - /** Ensure the test step does not "leak" resources - like open files or - * network connections - by ensuring the open resources at the start of the - * step match the open resources at the end of the step. - * - * Defaults to the parent test or step's value. */ - sanitizeResources?: boolean; - /** Ensure the test step does not prematurely cause the process to exit, - * for example via a call to {@linkcode Deno.exit}. - * - * Defaults to the parent test or step's value. */ - sanitizeExit?: boolean; - } - - /** @category Testing */ - export interface TestDefinition { - fn: (t: TestContext) => void | Promise; - /** The name of the test. */ - name: string; - /** If truthy the current test step will be ignored. - * - * It is a quick way to skip over a step, but also can be used for - * conditional logic, like determining if an environment feature is present. - */ - ignore?: boolean; - /** If at least one test has `only` set to `true`, only run tests that have - * `only` set to `true` and fail the test suite. */ - only?: boolean; - /** Check that the number of async completed operations after the test step - * is the same as number of dispatched operations. This ensures that the - * code tested does not start async operations which it then does - * not await. This helps in preventing logic errors and memory leaks - * in the application code. - * - * @default {true} */ - sanitizeOps?: boolean; - /** Ensure the test step does not "leak" resources - like open files or - * network connections - by ensuring the open resources at the start of the - * test match the open resources at the end of the test. - * - * @default {true} */ - sanitizeResources?: boolean; - /** Ensure the test case does not prematurely cause the process to exit, - * for example via a call to {@linkcode Deno.exit}. - * - * @default {true} */ - sanitizeExit?: boolean; - /** Specifies the permissions that should be used to run the test. - * - * Set this to "inherit" to keep the calling runtime permissions, set this - * to "none" to revoke all permissions, or set a more specific set of - * permissions using a {@linkcode PermissionOptionsObject}. - * - * @default {"inherit"} */ - permissions?: PermissionOptions; - } - - /** Register a test which will be run when `deno test` is used on the command - * line and the containing module looks like a test module. - * - * `fn` can be async if required. - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test({ - * name: "example test", - * fn() { - * assertEquals("world", "world"); - * }, - * }); - * - * Deno.test({ - * name: "example ignored test", - * ignore: Deno.build.os === "windows", - * fn() { - * // This test is ignored only on Windows machines - * }, - * }); - * - * Deno.test({ - * name: "example async test", - * async fn() { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * } - * }); - * ``` - * - * @category Testing - */ - export function test(t: TestDefinition): void; - - /** Register a test which will be run when `deno test` is used on the command - * line and the containing module looks like a test module. - * - * `fn` can be async if required. - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test("My test description", () => { - * assertEquals("hello", "hello"); - * }); - * - * Deno.test("My async test description", async () => { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * }); - * ``` - * - * @category Testing - */ - export function test( - name: string, - fn: (t: TestContext) => void | Promise, - ): void; - - /** Register a test which will be run when `deno test` is used on the command - * line and the containing module looks like a test module. - * - * `fn` can be async if required. Declared function must have a name. - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test(function myTestName() { - * assertEquals("hello", "hello"); - * }); - * - * Deno.test(async function myOtherTestName() { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * }); - * ``` - * - * @category Testing - */ - export function test(fn: (t: TestContext) => void | Promise): void; - - /** Register a test which will be run when `deno test` is used on the command - * line and the containing module looks like a test module. - * - * `fn` can be async if required. - * - * ```ts - * import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test("My test description", { permissions: { read: true } }, (): void => { - * assertEquals("hello", "hello"); - * }); - * - * Deno.test("My async test description", { permissions: { read: false } }, async (): Promise => { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * }); - * ``` - * - * @category Testing - */ - export function test( - name: string, - options: Omit, - fn: (t: TestContext) => void | Promise, - ): void; - - /** Register a test which will be run when `deno test` is used on the command - * line and the containing module looks like a test module. - * - * `fn` can be async if required. - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test( - * { - * name: "My test description", - * permissions: { read: true }, - * }, - * () => { - * assertEquals("hello", "hello"); - * }, - * ); - * - * Deno.test( - * { - * name: "My async test description", - * permissions: { read: false }, - * }, - * async () => { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * }, - * ); - * ``` - * - * @category Testing - */ - export function test( - options: Omit, - fn: (t: TestContext) => void | Promise, - ): void; - - /** Register a test which will be run when `deno test` is used on the command - * line and the containing module looks like a test module. - * - * `fn` can be async if required. Declared function must have a name. - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test( - * { permissions: { read: true } }, - * function myTestName() { - * assertEquals("hello", "hello"); - * }, - * ); - * - * Deno.test( - * { permissions: { read: false } }, - * async function myOtherTestName() { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * }, - * ); - * ``` - * - * @category Testing - */ - export function test( - options: Omit, - fn: (t: TestContext) => void | Promise, - ): void; - - /** - * The interface for defining a benchmark test using {@linkcode Deno.bench}. - * - * @category Testing - */ - export interface BenchDefinition { - /** The test function which will be benchmarked. */ - fn: () => void | Promise; - /** The name of the test, which will be used in displaying the results. */ - name: string; - /** If truthy, the benchmark test will be ignored/skipped. */ - ignore?: boolean; - /** Group name for the benchmark. - * - * Grouped benchmarks produce a group time summary, where the difference - * in performance between each test of the group is compared. */ - group?: string; - /** Benchmark should be used as the baseline for other benchmarks. - * - * If there are multiple baselines in a group, the first one is used as the - * baseline. */ - baseline?: boolean; - /** If at least one bench has `only` set to true, only run benches that have - * `only` set to `true` and fail the bench suite. */ - only?: boolean; - /** Ensure the bench case does not prematurely cause the process to exit, - * for example via a call to {@linkcode Deno.exit}. - * - * @default {true} */ - sanitizeExit?: boolean; - /** Specifies the permissions that should be used to run the bench. - * - * Set this to `"inherit"` to keep the calling thread's permissions. - * - * Set this to `"none"` to revoke all permissions. - * - * @default {"inherit"} - */ - permissions?: PermissionOptions; - } - - /** - * Register a benchmark test which will be run when `deno bench` is used on - * the command line and the containing module looks like a bench module. - * - * If the test function (`fn`) returns a promise or is async, the test runner - * will await resolution to consider the test complete. - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.bench({ - * name: "example test", - * fn() { - * assertEquals("world", "world"); - * }, - * }); - * - * Deno.bench({ - * name: "example ignored test", - * ignore: Deno.build.os === "windows", - * fn() { - * // This test is ignored only on Windows machines - * }, - * }); - * - * Deno.bench({ - * name: "example async test", - * async fn() { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * } - * }); - * ``` - * - * @category Testing - */ - export function bench(t: BenchDefinition): void; - - /** - * Register a benchmark test which will be run when `deno bench` is used on - * the command line and the containing module looks like a bench module. - * - * If the test function (`fn`) returns a promise or is async, the test runner - * will await resolution to consider the test complete. - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.bench("My test description", () => { - * assertEquals("hello", "hello"); - * }); - * - * Deno.bench("My async test description", async () => { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * }); - * ``` - * - * @category Testing - */ - export function bench( - name: string, - fn: () => void | Promise, - ): void; - - /** - * Register a benchmark test which will be run when `deno bench` is used on - * the command line and the containing module looks like a bench module. - * - * If the test function (`fn`) returns a promise or is async, the test runner - * will await resolution to consider the test complete. - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.bench(function myTestName() { - * assertEquals("hello", "hello"); - * }); - * - * Deno.bench(async function myOtherTestName() { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * }); - * ``` - * - * @category Testing - */ - export function bench(fn: () => void | Promise): void; - - /** - * Register a benchmark test which will be run when `deno bench` is used on - * the command line and the containing module looks like a bench module. - * - * If the test function (`fn`) returns a promise or is async, the test runner - * will await resolution to consider the test complete. - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.bench( - * "My test description", - * { permissions: { read: true } }, - * () => { - * assertEquals("hello", "hello"); - * } - * ); - * - * Deno.bench( - * "My async test description", - * { permissions: { read: false } }, - * async () => { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * } - * ); - * ``` - * - * @category Testing - */ - export function bench( - name: string, - options: Omit, - fn: () => void | Promise, - ): void; - - /** - * Register a benchmark test which will be run when `deno bench` is used on - * the command line and the containing module looks like a bench module. - * - * If the test function (`fn`) returns a promise or is async, the test runner - * will await resolution to consider the test complete. - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.bench( - * { name: "My test description", permissions: { read: true } }, - * () => { - * assertEquals("hello", "hello"); - * } - * ); - * - * Deno.bench( - * { name: "My async test description", permissions: { read: false } }, - * async () => { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * } - * ); - * ``` - * - * @category Testing - */ - export function bench( - options: Omit, - fn: () => void | Promise, - ): void; - - /** - * Register a benchmark test which will be run when `deno bench` is used on - * the command line and the containing module looks like a bench module. - * - * If the test function (`fn`) returns a promise or is async, the test runner - * will await resolution to consider the test complete. - * - * ```ts - * import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.bench( - * { permissions: { read: true } }, - * function myTestName() { - * assertEquals("hello", "hello"); - * } - * ); - * - * Deno.bench( - * { permissions: { read: false } }, - * async function myOtherTestName() { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * } - * ); - * ``` - * - * @category Testing - */ - export function bench( - options: Omit, - fn: () => void | Promise, - ): void; - - /** Exit the Deno process with optional exit code. - * - * If no exit code is supplied then Deno will exit with return code of `0`. - * - * In worker contexts this is an alias to `self.close();`. - * - * ```ts - * Deno.exit(5); - * ``` - * - * @category Runtime Environment - */ - export function exit(code?: number): never; - - /** An interface containing methods to interact with the process environment - * variables. - * - * @tags allow-env - * @category Runtime Environment - */ - export interface Env { - /** Retrieve the value of an environment variable. - * - * Returns `undefined` if the supplied environment variable is not defined. - * - * ```ts - * console.log(Deno.env.get("HOME")); // e.g. outputs "/home/alice" - * console.log(Deno.env.get("MADE_UP_VAR")); // outputs "undefined" - * ``` - * - * Requires `allow-env` permission. - * - * @tags allow-env - */ - get(key: string): string | undefined; - - /** Set the value of an environment variable. - * - * ```ts - * Deno.env.set("SOME_VAR", "Value"); - * Deno.env.get("SOME_VAR"); // outputs "Value" - * ``` - * - * Requires `allow-env` permission. - * - * @tags allow-env - */ - set(key: string, value: string): void; - - /** Delete the value of an environment variable. - * - * ```ts - * Deno.env.set("SOME_VAR", "Value"); - * Deno.env.delete("SOME_VAR"); // outputs "undefined" - * ``` - * - * Requires `allow-env` permission. - * - * @tags allow-env - */ - delete(key: string): void; - - /** Check whether an environment variable is present or not. - * - * ```ts - * Deno.env.set("SOME_VAR", "Value"); - * Deno.env.has("SOME_VAR"); // outputs true - * ``` - * - * Requires `allow-env` permission. - * - * @tags allow-env - */ - has(key: string): boolean; - - /** Returns a snapshot of the environment variables at invocation as a - * simple object of keys and values. - * - * ```ts - * Deno.env.set("TEST_VAR", "A"); - * const myEnv = Deno.env.toObject(); - * console.log(myEnv.SHELL); - * Deno.env.set("TEST_VAR", "B"); - * console.log(myEnv.TEST_VAR); // outputs "A" - * ``` - * - * Requires `allow-env` permission. - * - * @tags allow-env - */ - toObject(): { [index: string]: string }; - } - - /** An interface containing methods to interact with the process environment - * variables. - * - * @tags allow-env - * @category Runtime Environment - */ - export const env: Env; - - /** - * Returns the path to the current deno executable. - * - * ```ts - * console.log(Deno.execPath()); // e.g. "/home/alice/.local/bin/deno" - * ``` - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category Runtime Environment - */ - export function execPath(): string; - - /** - * Change the current working directory to the specified path. - * - * ```ts - * Deno.chdir("/home/userA"); - * Deno.chdir("../userB"); - * Deno.chdir("C:\\Program Files (x86)\\Java"); - * ``` - * - * Throws {@linkcode Deno.errors.NotFound} if directory not found. - * - * Throws {@linkcode Deno.errors.PermissionDenied} if the user does not have - * operating system file access rights. - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category Runtime Environment - */ - export function chdir(directory: string | URL): void; - - /** - * Return a string representing the current working directory. - * - * If the current directory can be reached via multiple paths (due to symbolic - * links), `cwd()` may return any one of them. - * - * ```ts - * const currentWorkingDirectory = Deno.cwd(); - * ``` - * - * Throws {@linkcode Deno.errors.NotFound} if directory not available. - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category Runtime Environment - */ - export function cwd(): string; - - /** - * Creates `newpath` as a hard link to `oldpath`. - * - * ```ts - * await Deno.link("old/name", "new/name"); - * ``` - * - * Requires `allow-read` and `allow-write` permissions. - * - * @tags allow-read, allow-write - * @category File System - */ - export function link(oldpath: string, newpath: string): Promise; - - /** - * Synchronously creates `newpath` as a hard link to `oldpath`. - * - * ```ts - * Deno.linkSync("old/name", "new/name"); - * ``` - * - * Requires `allow-read` and `allow-write` permissions. - * - * @tags allow-read, allow-write - * @category File System - */ - export function linkSync(oldpath: string, newpath: string): void; - - /** - * A enum which defines the seek mode for IO related APIs that support - * seeking. - * - * @category I/O */ - export enum SeekMode { - /* Seek from the start of the file/resource. */ - Start = 0, - /* Seek from the current position within the file/resource. */ - Current = 1, - /* Seek from the end of the current file/resource. */ - End = 2, - } - - /** - * An abstract interface which when implemented provides an interface to read - * bytes into an array buffer asynchronously. - * - * @category I/O */ - export interface Reader { - /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number of - * bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error - * encountered. Even if `read()` resolves to `n` < `p.byteLength`, it may - * use all of `p` as scratch space during the call. If some data is - * available but not `p.byteLength` bytes, `read()` conventionally resolves - * to what is available instead of waiting for more. - * - * When `read()` encounters end-of-file condition, it resolves to EOF - * (`null`). - * - * When `read()` encounters an error, it rejects with an error. - * - * Callers should always process the `n` > `0` bytes returned before - * considering the EOF (`null`). Doing so correctly handles I/O errors that - * happen after reading some bytes and also both of the allowed EOF - * behaviors. - * - * Implementations should not retain a reference to `p`. - * - * Use - * [`itereateReader`](https://deno.land/std/streams/iterate_reader.ts?s=iterateReader) - * from - * [`std/streams/iterate_reader.ts`](https://deno.land/std/streams/iterate_reader.ts) - * to turn a `Reader` into an {@linkcode AsyncIterator}. - */ - read(p: Uint8Array): Promise; - } - - /** - * An abstract interface which when implemented provides an interface to read - * bytes into an array buffer synchronously. - * - * @category I/O */ - export interface ReaderSync { - /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number - * of bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error - * encountered. Even if `readSync()` returns `n` < `p.byteLength`, it may use - * all of `p` as scratch space during the call. If some data is available - * but not `p.byteLength` bytes, `readSync()` conventionally returns what is - * available instead of waiting for more. - * - * When `readSync()` encounters end-of-file condition, it returns EOF - * (`null`). - * - * When `readSync()` encounters an error, it throws with an error. - * - * Callers should always process the `n` > `0` bytes returned before - * considering the EOF (`null`). Doing so correctly handles I/O errors that - * happen after reading some bytes and also both of the allowed EOF - * behaviors. - * - * Implementations should not retain a reference to `p`. - * - * Use - * [`itereateReaderSync`](https://deno.land/std/streams/iterate_reader.ts?s=iterateReaderSync) - * from from - * [`std/streams/iterate_reader.ts`](https://deno.land/std/streams/iterate_reader.ts) - * to turn a `ReaderSync` into an {@linkcode Iterator}. - */ - readSync(p: Uint8Array): number | null; - } - - /** - * An abstract interface which when implemented provides an interface to write - * bytes from an array buffer to a file/resource asynchronously. - * - * @category I/O */ - export interface Writer { - /** Writes `p.byteLength` bytes from `p` to the underlying data stream. It - * resolves to the number of bytes written from `p` (`0` <= `n` <= - * `p.byteLength`) or reject with the error encountered that caused the - * write to stop early. `write()` must reject with a non-null error if - * would resolve to `n` < `p.byteLength`. `write()` must not modify the - * slice data, even temporarily. - * - * Implementations should not retain a reference to `p`. - */ - write(p: Uint8Array): Promise; - } - - /** - * An abstract interface which when implemented provides an interface to write - * bytes from an array buffer to a file/resource synchronously. - * - * @category I/O */ - export interface WriterSync { - /** Writes `p.byteLength` bytes from `p` to the underlying data - * stream. It returns the number of bytes written from `p` (`0` <= `n` - * <= `p.byteLength`) and any error encountered that caused the write to - * stop early. `writeSync()` must throw a non-null error if it returns `n` < - * `p.byteLength`. `writeSync()` must not modify the slice data, even - * temporarily. - * - * Implementations should not retain a reference to `p`. - */ - writeSync(p: Uint8Array): number; - } - - /** - * An abstract interface which when implemented provides an interface to close - * files/resources that were previously opened. - * - * @category I/O */ - export interface Closer { - /** Closes the resource, "freeing" the backing file/resource. */ - close(): void; - } - - /** - * An abstract interface which when implemented provides an interface to seek - * within an open file/resource asynchronously. - * - * @category I/O */ - export interface Seeker { - /** Seek sets the offset for the next `read()` or `write()` to offset, - * interpreted according to `whence`: `Start` means relative to the - * start of the file, `Current` means relative to the current offset, - * and `End` means relative to the end. Seek resolves to the new offset - * relative to the start of the file. - * - * Seeking to an offset before the start of the file is an error. Seeking to - * any positive offset is legal, but the behavior of subsequent I/O - * operations on the underlying object is implementation-dependent. - * - * It resolves with the updated offset. - */ - seek(offset: number | bigint, whence: SeekMode): Promise; - } - - /** - * An abstract interface which when implemented provides an interface to seek - * within an open file/resource synchronously. - * - * @category I/O */ - export interface SeekerSync { - /** Seek sets the offset for the next `readSync()` or `writeSync()` to - * offset, interpreted according to `whence`: `Start` means relative - * to the start of the file, `Current` means relative to the current - * offset, and `End` means relative to the end. - * - * Seeking to an offset before the start of the file is an error. Seeking to - * any positive offset is legal, but the behavior of subsequent I/O - * operations on the underlying object is implementation-dependent. - * - * It returns the updated offset. - */ - seekSync(offset: number, whence: SeekMode): number; - } - - /** - * Copies from `src` to `dst` until either EOF (`null`) is read from `src` or - * an error occurs. It resolves to the number of bytes copied or rejects with - * the first error encountered while copying. - * - * @deprecated Use - * [`copy`](https://deno.land/std/streams/copy.ts?s=copy) from - * [`std/streams/copy.ts`](https://deno.land/std/streams/copy.ts) - * instead. `Deno.copy` will be removed in the future. - * - * @category I/O - * - * @param src The source to copy from - * @param dst The destination to copy to - * @param options Can be used to tune size of the buffer. Default size is 32kB - */ - export function copy( - src: Reader, - dst: Writer, - options?: { bufSize?: number }, - ): Promise; - - /** - * Turns a Reader, `r`, into an async iterator. - * - * @deprecated Use - * [`iterateReader`](https://deno.land/std/streams/iterate_reader.ts?s=iterateReader) - * from - * [`std/streams/iterate_reader.ts`](https://deno.land/std/streams/iterate_reader.ts) - * instead. `Deno.iter` will be removed in the future. - * - * @category I/O - */ - export function iter( - r: Reader, - options?: { bufSize?: number }, - ): AsyncIterableIterator; - - /** - * Turns a ReaderSync, `r`, into an iterator. - * - * @deprecated Use - * [`iterateReaderSync`](https://deno.land/std/streams/iterate_reader.ts?s=iterateReaderSync) - * from - * [`std/streams/iterate_reader.ts`](https://deno.land/std/streams/iterate_reader.ts) - * instead. `Deno.iterSync` will be removed in the future. - * - * @category I/O - */ - export function iterSync( - r: ReaderSync, - options?: { - bufSize?: number; - }, - ): IterableIterator; - - /** Open a file and resolve to an instance of {@linkcode Deno.FsFile}. The - * file does not need to previously exist if using the `create` or `createNew` - * open options. It is the caller's responsibility to close the file when - * finished with it. - * - * ```ts - * const file = await Deno.open("/foo/bar.txt", { read: true, write: true }); - * // Do work with file - * file.close(); - * ``` - * - * Requires `allow-read` and/or `allow-write` permissions depending on - * options. - * - * @tags allow-read, allow-write - * @category File System - */ - export function open( - path: string | URL, - options?: OpenOptions, - ): Promise; - - /** Synchronously open a file and return an instance of - * {@linkcode Deno.FsFile}. The file does not need to previously exist if - * using the `create` or `createNew` open options. It is the caller's - * responsibility to close the file when finished with it. - * - * ```ts - * const file = Deno.openSync("/foo/bar.txt", { read: true, write: true }); - * // Do work with file - * file.close(); - * ``` - * - * Requires `allow-read` and/or `allow-write` permissions depending on - * options. - * - * @tags allow-read, allow-write - * @category File System - */ - export function openSync(path: string | URL, options?: OpenOptions): FsFile; - - /** Creates a file if none exists or truncates an existing file and resolves to - * an instance of {@linkcode Deno.FsFile}. - * - * ```ts - * const file = await Deno.create("/foo/bar.txt"); - * ``` - * - * Requires `allow-read` and `allow-write` permissions. - * - * @tags allow-read, allow-write - * @category File System - */ - export function create(path: string | URL): Promise; - - /** Creates a file if none exists or truncates an existing file and returns - * an instance of {@linkcode Deno.FsFile}. - * - * ```ts - * const file = Deno.createSync("/foo/bar.txt"); - * ``` - * - * Requires `allow-read` and `allow-write` permissions. - * - * @tags allow-read, allow-write - * @category File System - */ - export function createSync(path: string | URL): FsFile; - - /** Read from a resource ID (`rid`) into an array buffer (`buffer`). - * - * Resolves to either the number of bytes read during the operation or EOF - * (`null`) if there was nothing more to read. - * - * It is possible for a read to successfully return with `0` bytes. This does - * not indicate EOF. - * - * This function is one of the lowest level APIs and most users should not - * work with this directly, but rather use - * [`readAll()`](https://deno.land/std/streams/read_all.ts?s=readAll) from - * [`std/streams/read_all.ts`](https://deno.land/std/streams/read_all.ts) - * instead. - * - * **It is not guaranteed that the full buffer will be read in a single call.** - * - * ```ts - * // if "/foo/bar.txt" contains the text "hello world": - * const file = await Deno.open("/foo/bar.txt"); - * const buf = new Uint8Array(100); - * const numberOfBytesRead = await Deno.read(file.rid, buf); // 11 bytes - * const text = new TextDecoder().decode(buf); // "hello world" - * Deno.close(file.rid); - * ``` - * - * @category I/O - */ - export function read(rid: number, buffer: Uint8Array): Promise; - - /** Synchronously read from a resource ID (`rid`) into an array buffer - * (`buffer`). - * - * Returns either the number of bytes read during the operation or EOF - * (`null`) if there was nothing more to read. - * - * It is possible for a read to successfully return with `0` bytes. This does - * not indicate EOF. - * - * This function is one of the lowest level APIs and most users should not - * work with this directly, but rather use - * [`readAllSync()`](https://deno.land/std/streams/read_all.ts?s=readAllSync) - * from - * [`std/streams/read_all.ts`](https://deno.land/std/streams/read_all.ts) - * instead. - * - * **It is not guaranteed that the full buffer will be read in a single - * call.** - * - * ```ts - * // if "/foo/bar.txt" contains the text "hello world": - * const file = Deno.openSync("/foo/bar.txt"); - * const buf = new Uint8Array(100); - * const numberOfBytesRead = Deno.readSync(file.rid, buf); // 11 bytes - * const text = new TextDecoder().decode(buf); // "hello world" - * Deno.close(file.rid); - * ``` - * - * @category I/O - */ - export function readSync(rid: number, buffer: Uint8Array): number | null; - - /** Write to the resource ID (`rid`) the contents of the array buffer (`data`). - * - * Resolves to the number of bytes written. This function is one of the lowest - * level APIs and most users should not work with this directly, but rather use - * [`writeAll()`](https://deno.land/std/streams/write_all.ts?s=writeAll) from - * [`std/streams/write_all.ts`](https://deno.land/std/streams/write_all.ts) - * instead. - * - * **It is not guaranteed that the full buffer will be written in a single - * call.** - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world"); - * const file = await Deno.open("/foo/bar.txt", { write: true }); - * const bytesWritten = await Deno.write(file.rid, data); // 11 - * Deno.close(file.rid); - * ``` - * - * @category I/O - */ - export function write(rid: number, data: Uint8Array): Promise; - - /** Synchronously write to the resource ID (`rid`) the contents of the array - * buffer (`data`). - * - * Returns the number of bytes written. This function is one of the lowest - * level APIs and most users should not work with this directly, but rather - * use - * [`writeAllSync()`](https://deno.land/std/streams/write_all.ts?s=writeAllSync) - * from - * [`std/streams/write_all.ts`](https://deno.land/std/streams/write_all.ts) - * instead. - * - * **It is not guaranteed that the full buffer will be written in a single - * call.** - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world"); - * const file = Deno.openSync("/foo/bar.txt", { write: true }); - * const bytesWritten = Deno.writeSync(file.rid, data); // 11 - * Deno.close(file.rid); - * ``` - * - * @category I/O - */ - export function writeSync(rid: number, data: Uint8Array): number; - - /** Seek a resource ID (`rid`) to the given `offset` under mode given by `whence`. - * The call resolves to the new position within the resource (bytes from the start). - * - * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: - * const file = await Deno.open( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * await Deno.write(file.rid, new TextEncoder().encode("Hello world")); - * - * // advance cursor 6 bytes - * const cursorPosition = await Deno.seek(file.rid, 6, Deno.SeekMode.Start); - * console.log(cursorPosition); // 6 - * const buf = new Uint8Array(100); - * await file.read(buf); - * console.log(new TextDecoder().decode(buf)); // "world" - * file.close(); - * ``` - * - * The seek modes work as follows: - * - * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: - * const file = await Deno.open( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * await Deno.write(file.rid, new TextEncoder().encode("Hello world")); - * - * // Seek 6 bytes from the start of the file - * console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.Start)); // "6" - * // Seek 2 more bytes from the current position - * console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.Current)); // "8" - * // Seek backwards 2 bytes from the end of the file - * console.log(await Deno.seek(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2) - * file.close(); - * ``` - * - * @category I/O - */ - export function seek( - rid: number, - offset: number | bigint, - whence: SeekMode, - ): Promise; - - /** Synchronously seek a resource ID (`rid`) to the given `offset` under mode - * given by `whence`. The new position within the resource (bytes from the - * start) is returned. - * - * ```ts - * const file = Deno.openSync( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * Deno.writeSync(file.rid, new TextEncoder().encode("Hello world")); - * - * // advance cursor 6 bytes - * const cursorPosition = Deno.seekSync(file.rid, 6, Deno.SeekMode.Start); - * console.log(cursorPosition); // 6 - * const buf = new Uint8Array(100); - * file.readSync(buf); - * console.log(new TextDecoder().decode(buf)); // "world" - * file.close(); - * ``` - * - * The seek modes work as follows: - * - * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: - * const file = Deno.openSync( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * Deno.writeSync(file.rid, new TextEncoder().encode("Hello world")); - * - * // Seek 6 bytes from the start of the file - * console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.Start)); // "6" - * // Seek 2 more bytes from the current position - * console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.Current)); // "8" - * // Seek backwards 2 bytes from the end of the file - * console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2) - * file.close(); - * ``` - * - * @category I/O - */ - export function seekSync( - rid: number, - offset: number, - whence: SeekMode, - ): number; - - /** - * Flushes any pending data and metadata operations of the given file stream - * to disk. - * - * ```ts - * const file = await Deno.open( - * "my_file.txt", - * { read: true, write: true, create: true }, - * ); - * await Deno.write(file.rid, new TextEncoder().encode("Hello World")); - * await Deno.ftruncate(file.rid, 1); - * await Deno.fsync(file.rid); - * console.log(new TextDecoder().decode(await Deno.readFile("my_file.txt"))); // H - * ``` - * - * @category I/O - */ - export function fsync(rid: number): Promise; - - /** - * Synchronously flushes any pending data and metadata operations of the given - * file stream to disk. - * - * ```ts - * const file = Deno.openSync( - * "my_file.txt", - * { read: true, write: true, create: true }, - * ); - * Deno.writeSync(file.rid, new TextEncoder().encode("Hello World")); - * Deno.ftruncateSync(file.rid, 1); - * Deno.fsyncSync(file.rid); - * console.log(new TextDecoder().decode(Deno.readFileSync("my_file.txt"))); // H - * ``` - * - * @category I/O - */ - export function fsyncSync(rid: number): void; - - /** - * Flushes any pending data operations of the given file stream to disk. - * ```ts - * const file = await Deno.open( - * "my_file.txt", - * { read: true, write: true, create: true }, - * ); - * await Deno.write(file.rid, new TextEncoder().encode("Hello World")); - * await Deno.fdatasync(file.rid); - * console.log(new TextDecoder().decode(await Deno.readFile("my_file.txt"))); // Hello World - * ``` - * - * @category I/O - */ - export function fdatasync(rid: number): Promise; - - /** - * Synchronously flushes any pending data operations of the given file stream - * to disk. - * - * ```ts - * const file = Deno.openSync( - * "my_file.txt", - * { read: true, write: true, create: true }, - * ); - * Deno.writeSync(file.rid, new TextEncoder().encode("Hello World")); - * Deno.fdatasyncSync(file.rid); - * console.log(new TextDecoder().decode(Deno.readFileSync("my_file.txt"))); // Hello World - * ``` - * - * @category I/O - */ - export function fdatasyncSync(rid: number): void; - - /** Close the given resource ID (`rid`) which has been previously opened, such - * as via opening or creating a file. Closing a file when you are finished - * with it is important to avoid leaking resources. - * - * ```ts - * const file = await Deno.open("my_file.txt"); - * // do work with "file" object - * Deno.close(file.rid); - * ``` - * - * @category I/O - */ - export function close(rid: number): void; - - /** The Deno abstraction for reading and writing files. - * - * This is the most straight forward way of handling files within Deno and is - * recommended over using the discreet functions within the `Deno` namespace. - * - * ```ts - * const file = await Deno.open("/foo/bar.txt", { read: true }); - * const fileInfo = await file.stat(); - * if (fileInfo.isFile) { - * const buf = new Uint8Array(100); - * const numberOfBytesRead = await file.read(buf); // 11 bytes - * const text = new TextDecoder().decode(buf); // "hello world" - * } - * file.close(); - * ``` - * - * @category File System - */ - export class FsFile - implements - Reader, - ReaderSync, - Writer, - WriterSync, - Seeker, - SeekerSync, - Closer { - /** The resource ID associated with the file instance. The resource ID - * should be considered an opaque reference to resource. */ - readonly rid: number; - /** A {@linkcode ReadableStream} instance representing to the byte contents - * of the file. This makes it easy to interoperate with other web streams - * based APIs. - * - * ```ts - * const file = await Deno.open("my_file.txt", { read: true }); - * const decoder = new TextDecoder(); - * for await (const chunk of file.readable) { - * console.log(decoder.decode(chunk)); - * } - * file.close(); - * ``` - */ - readonly readable: ReadableStream; - /** A {@linkcode WritableStream} instance to write the contents of the - * file. This makes it easy to interoperate with other web streams based - * APIs. - * - * ```ts - * const items = ["hello", "world"]; - * const file = await Deno.open("my_file.txt", { write: true }); - * const encoder = new TextEncoder(); - * const writer = file.writable.getWriter(); - * for (const item of items) { - * await writer.write(encoder.encode(item)); - * } - * file.close(); - * ``` - */ - readonly writable: WritableStream; - /** The constructor which takes a resource ID. Generally `FsFile` should - * not be constructed directly. Instead use {@linkcode Deno.open} or - * {@linkcode Deno.openSync} to create a new instance of `FsFile`. */ - constructor(rid: number); - /** Write the contents of the array buffer (`p`) to the file. - * - * Resolves to the number of bytes written. - * - * **It is not guaranteed that the full buffer will be written in a single - * call.** - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world"); - * const file = await Deno.open("/foo/bar.txt", { write: true }); - * const bytesWritten = await file.write(data); // 11 - * file.close(); - * ``` - * - * @category I/O - */ - write(p: Uint8Array): Promise; - /** Synchronously write the contents of the array buffer (`p`) to the file. - * - * Returns the number of bytes written. - * - * **It is not guaranteed that the full buffer will be written in a single - * call.** - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world"); - * const file = Deno.openSync("/foo/bar.txt", { write: true }); - * const bytesWritten = file.writeSync(data); // 11 - * file.close(); - * ``` - */ - writeSync(p: Uint8Array): number; - /** Truncates (or extends) the file to reach the specified `len`. If `len` - * is not specified, then the entire file contents are truncated. - * - * ### Truncate the entire file - * - * ```ts - * const file = await Deno.open("my_file.txt", { write: true }); - * await file.truncate(); - * file.close(); - * ``` - * - * ### Truncate part of the file - * - * ```ts - * // if "my_file.txt" contains the text "hello world": - * const file = await Deno.open("my_file.txt", { write: true }); - * await file.truncate(7); - * const buf = new Uint8Array(100); - * await file.read(buf); - * const text = new TextDecoder().decode(buf); // "hello w" - * file.close(); - * ``` - */ - truncate(len?: number): Promise; - /** Synchronously truncates (or extends) the file to reach the specified - * `len`. If `len` is not specified, then the entire file contents are - * truncated. - * - * ### Truncate the entire file - * - * ```ts - * const file = Deno.openSync("my_file.txt", { write: true }); - * file.truncateSync(); - * file.close(); - * ``` - * - * ### Truncate part of the file - * - * ```ts - * // if "my_file.txt" contains the text "hello world": - * const file = Deno.openSync("my_file.txt", { write: true }); - * file.truncateSync(7); - * const buf = new Uint8Array(100); - * file.readSync(buf); - * const text = new TextDecoder().decode(buf); // "hello w" - * file.close(); - * ``` - */ - truncateSync(len?: number): void; - /** Read the file into an array buffer (`p`). - * - * Resolves to either the number of bytes read during the operation or EOF - * (`null`) if there was nothing more to read. - * - * It is possible for a read to successfully return with `0` bytes. This - * does not indicate EOF. - * - * **It is not guaranteed that the full buffer will be read in a single - * call.** - * - * ```ts - * // if "/foo/bar.txt" contains the text "hello world": - * const file = await Deno.open("/foo/bar.txt"); - * const buf = new Uint8Array(100); - * const numberOfBytesRead = await file.read(buf); // 11 bytes - * const text = new TextDecoder().decode(buf); // "hello world" - * file.close(); - * ``` - */ - read(p: Uint8Array): Promise; - /** Synchronously read from the file into an array buffer (`p`). - * - * Returns either the number of bytes read during the operation or EOF - * (`null`) if there was nothing more to read. - * - * It is possible for a read to successfully return with `0` bytes. This - * does not indicate EOF. - * - * **It is not guaranteed that the full buffer will be read in a single - * call.** - * - * ```ts - * // if "/foo/bar.txt" contains the text "hello world": - * const file = Deno.openSync("/foo/bar.txt"); - * const buf = new Uint8Array(100); - * const numberOfBytesRead = file.readSync(buf); // 11 bytes - * const text = new TextDecoder().decode(buf); // "hello world" - * file.close(); - * ``` - */ - readSync(p: Uint8Array): number | null; - /** Seek to the given `offset` under mode given by `whence`. The call - * resolves to the new position within the resource (bytes from the start). - * - * ```ts - * // Given file pointing to file with "Hello world", which is 11 bytes long: - * const file = await Deno.open( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * await file.write(new TextEncoder().encode("Hello world")); - * - * // advance cursor 6 bytes - * const cursorPosition = await file.seek(6, Deno.SeekMode.Start); - * console.log(cursorPosition); // 6 - * const buf = new Uint8Array(100); - * await file.read(buf); - * console.log(new TextDecoder().decode(buf)); // "world" - * file.close(); - * ``` - * - * The seek modes work as follows: - * - * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: - * const file = await Deno.open( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * await file.write(new TextEncoder().encode("Hello world")); - * - * // Seek 6 bytes from the start of the file - * console.log(await file.seek(6, Deno.SeekMode.Start)); // "6" - * // Seek 2 more bytes from the current position - * console.log(await file.seek(2, Deno.SeekMode.Current)); // "8" - * // Seek backwards 2 bytes from the end of the file - * console.log(await file.seek(-2, Deno.SeekMode.End)); // "9" (e.g. 11-2) - * ``` - */ - seek(offset: number | bigint, whence: SeekMode): Promise; - /** Synchronously seek to the given `offset` under mode given by `whence`. - * The new position within the resource (bytes from the start) is returned. - * - * ```ts - * const file = Deno.openSync( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * file.writeSync(new TextEncoder().encode("Hello world")); - * - * // advance cursor 6 bytes - * const cursorPosition = file.seekSync(6, Deno.SeekMode.Start); - * console.log(cursorPosition); // 6 - * const buf = new Uint8Array(100); - * file.readSync(buf); - * console.log(new TextDecoder().decode(buf)); // "world" - * file.close(); - * ``` - * - * The seek modes work as follows: - * - * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: - * const file = Deno.openSync( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * file.writeSync(new TextEncoder().encode("Hello world")); - * - * // Seek 6 bytes from the start of the file - * console.log(file.seekSync(6, Deno.SeekMode.Start)); // "6" - * // Seek 2 more bytes from the current position - * console.log(file.seekSync(2, Deno.SeekMode.Current)); // "8" - * // Seek backwards 2 bytes from the end of the file - * console.log(file.seekSync(-2, Deno.SeekMode.End)); // "9" (e.g. 11-2) - * file.close(); - * ``` - */ - seekSync(offset: number | bigint, whence: SeekMode): number; - /** Resolves to a {@linkcode Deno.FileInfo} for the file. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * - * const file = await Deno.open("hello.txt"); - * const fileInfo = await file.stat(); - * assert(fileInfo.isFile); - * file.close(); - * ``` - */ - stat(): Promise; - /** Synchronously returns a {@linkcode Deno.FileInfo} for the file. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * - * const file = Deno.openSync("hello.txt") - * const fileInfo = file.statSync(); - * assert(fileInfo.isFile); - * file.close(); - * ``` - */ - statSync(): FileInfo; - /** Close the file. Closing a file when you are finished with it is - * important to avoid leaking resources. - * - * ```ts - * const file = await Deno.open("my_file.txt"); - * // do work with "file" object - * file.close(); - * ``` - */ - close(): void; - } - - /** - * The Deno abstraction for reading and writing files. - * - * @deprecated Use {@linkcode Deno.FsFile} instead. `Deno.File` will be - * removed in the future. - * @category File System - */ - export const File: typeof FsFile; - - /** Gets the size of the console as columns/rows. - * - * ```ts - * const { columns, rows } = Deno.consoleSize(); - * ``` - * - * @category I/O - */ - export function consoleSize(): { - columns: number; - rows: number; - }; - - /** @category I/O */ - export interface SetRawOptions { - /** - * The `cbreak` option can be used to indicate that characters that - * correspond to a signal should still be generated. When disabling raw - * mode, this option is ignored. This functionality currently only works on - * Linux and Mac OS. - */ - cbreak: boolean; - } - - /** A reference to `stdin` which can be used to read directly from `stdin`. - * It implements the Deno specific {@linkcode Reader}, {@linkcode ReaderSync}, - * and {@linkcode Closer} interfaces as well as provides a - * {@linkcode ReadableStream} interface. - * - * ### Reading chunks from the readable stream - * - * ```ts - * const decoder = new TextDecoder(); - * for await (const chunk of Deno.stdin.readable) { - * const text = decoder.decode(chunk); - * // do something with the text - * } - * ``` - * - * @category I/O - */ - export const stdin: Reader & ReaderSync & Closer & { - /** The resource ID assigned to `stdin`. This can be used with the discreet - * I/O functions in the `Deno` namespace. */ - readonly rid: number; - /** A readable stream interface to `stdin`. */ - readonly readable: ReadableStream; - /** - * Set TTY to be under raw mode or not. In raw mode, characters are read and - * returned as is, without being processed. All special processing of - * characters by the terminal is disabled, including echoing input - * characters. Reading from a TTY device in raw mode is faster than reading - * from a TTY device in canonical mode. - * - * ```ts - * Deno.stdin.setRaw(true, { cbreak: true }); - * ``` - * - * @category I/O - */ - setRaw(mode: boolean, options?: SetRawOptions): void; - }; - /** A reference to `stdout` which can be used to write directly to `stdout`. - * It implements the Deno specific {@linkcode Writer}, {@linkcode WriterSync}, - * and {@linkcode Closer} interfaces as well as provides a - * {@linkcode WritableStream} interface. - * - * These are low level constructs, and the {@linkcode console} interface is a - * more straight forward way to interact with `stdout` and `stderr`. - * - * @category I/O - */ - export const stdout: Writer & WriterSync & Closer & { - /** The resource ID assigned to `stdout`. This can be used with the discreet - * I/O functions in the `Deno` namespace. */ - readonly rid: number; - /** A writable stream interface to `stdout`. */ - readonly writable: WritableStream; - }; - /** A reference to `stderr` which can be used to write directly to `stderr`. - * It implements the Deno specific {@linkcode Writer}, {@linkcode WriterSync}, - * and {@linkcode Closer} interfaces as well as provides a - * {@linkcode WritableStream} interface. - * - * These are low level constructs, and the {@linkcode console} interface is a - * more straight forward way to interact with `stdout` and `stderr`. - * - * @category I/O - */ - export const stderr: Writer & WriterSync & Closer & { - /** The resource ID assigned to `stderr`. This can be used with the discreet - * I/O functions in the `Deno` namespace. */ - readonly rid: number; - /** A writable stream interface to `stderr`. */ - readonly writable: WritableStream; - }; - - /** - * Options which can be set when doing {@linkcode Deno.open} and - * {@linkcode Deno.openSync}. - * - * @category File System */ - export interface OpenOptions { - /** Sets the option for read access. This option, when `true`, means that - * the file should be read-able if opened. - * - * @default {true} */ - read?: boolean; - /** Sets the option for write access. This option, when `true`, means that - * the file should be write-able if opened. If the file already exists, - * any write calls on it will overwrite its contents, by default without - * truncating it. - * - * @default {false} */ - write?: boolean; - /** Sets the option for the append mode. This option, when `true`, means - * that writes will append to a file instead of overwriting previous - * contents. - * - * Note that setting `{ write: true, append: true }` has the same effect as - * setting only `{ append: true }`. - * - * @default {false} */ - append?: boolean; - /** Sets the option for truncating a previous file. If a file is - * successfully opened with this option set it will truncate the file to `0` - * size if it already exists. The file must be opened with write access - * for truncate to work. - * - * @default {false} */ - truncate?: boolean; - /** Sets the option to allow creating a new file, if one doesn't already - * exist at the specified path. Requires write or append access to be - * used. - * - * @default {false} */ - create?: boolean; - /** If set to `true`, no file, directory, or symlink is allowed to exist at - * the target location. Requires write or append access to be used. When - * createNew is set to `true`, create and truncate are ignored. - * - * @default {false} */ - createNew?: boolean; - /** Permissions to use if creating the file (defaults to `0o666`, before - * the process's umask). - * - * Ignored on Windows. */ - mode?: number; - } - - /** - * Options which can be set when using {@linkcode Deno.readFile} or - * {@linkcode Deno.readFileSync}. - * - * @category File System */ - export interface ReadFileOptions { - /** - * An abort signal to allow cancellation of the file read operation. - * If the signal becomes aborted the readFile operation will be stopped - * and the promise returned will be rejected with an AbortError. - */ - signal?: AbortSignal; - } - - /** - * Check if a given resource id (`rid`) is a TTY (a terminal). - * - * ```ts - * // This example is system and context specific - * const nonTTYRid = Deno.openSync("my_file.txt").rid; - * const ttyRid = Deno.openSync("/dev/tty6").rid; - * console.log(Deno.isatty(nonTTYRid)); // false - * console.log(Deno.isatty(ttyRid)); // true - * Deno.close(nonTTYRid); - * Deno.close(ttyRid); - * ``` - * - * @category I/O - */ - export function isatty(rid: number): boolean; - - /** - * A variable-sized buffer of bytes with `read()` and `write()` methods. - * - * @deprecated Use [`Buffer`](https://deno.land/std/io/buffer.ts?s=Buffer) - * from [`std/io/buffer.ts`](https://deno.land/std/io/buffer.ts) instead. - * `Deno.Buffer` will be removed in the future. - * - * @category I/O - */ - export class Buffer implements Reader, ReaderSync, Writer, WriterSync { - constructor(ab?: ArrayBuffer); - /** Returns a slice holding the unread portion of the buffer. - * - * The slice is valid for use only until the next buffer modification (that - * is, only until the next call to a method like `read()`, `write()`, - * `reset()`, or `truncate()`). If `options.copy` is false the slice aliases the buffer content at - * least until the next buffer modification, so immediate changes to the - * slice will affect the result of future reads. - * @param options Defaults to `{ copy: true }` - */ - bytes(options?: { copy?: boolean }): Uint8Array; - /** Returns whether the unread portion of the buffer is empty. */ - empty(): boolean; - /** A read only number of bytes of the unread portion of the buffer. */ - readonly length: number; - /** The read only capacity of the buffer's underlying byte slice, that is, - * the total space allocated for the buffer's data. */ - readonly capacity: number; - /** Discards all but the first `n` unread bytes from the buffer but - * continues to use the same allocated storage. It throws if `n` is - * negative or greater than the length of the buffer. */ - truncate(n: number): void; - /** Resets the buffer to be empty, but it retains the underlying storage for - * use by future writes. `.reset()` is the same as `.truncate(0)`. */ - reset(): void; - /** Reads the next `p.length` bytes from the buffer or until the buffer is - * drained. Returns the number of bytes read. If the buffer has no data to - * return, the return is EOF (`null`). */ - readSync(p: Uint8Array): number | null; - /** Reads the next `p.length` bytes from the buffer or until the buffer is - * drained. Resolves to the number of bytes read. If the buffer has no - * data to return, resolves to EOF (`null`). - * - * NOTE: This methods reads bytes synchronously; it's provided for - * compatibility with `Reader` interfaces. - */ - read(p: Uint8Array): Promise; - writeSync(p: Uint8Array): number; - /** NOTE: This methods writes bytes synchronously; it's provided for - * compatibility with `Writer` interface. */ - write(p: Uint8Array): Promise; - /** Grows the buffer's capacity, if necessary, to guarantee space for - * another `n` bytes. After `.grow(n)`, at least `n` bytes can be written to - * the buffer without another allocation. If `n` is negative, `.grow()` will - * throw. If the buffer can't grow it will throw an error. - * - * Based on Go Lang's - * [Buffer.Grow](https://golang.org/pkg/bytes/#Buffer.Grow). */ - grow(n: number): void; - /** Reads data from `r` until EOF (`null`) and appends it to the buffer, - * growing the buffer as needed. It resolves to the number of bytes read. - * If the buffer becomes too large, `.readFrom()` will reject with an error. - * - * Based on Go Lang's - * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */ - readFrom(r: Reader): Promise; - /** Reads data from `r` until EOF (`null`) and appends it to the buffer, - * growing the buffer as needed. It returns the number of bytes read. If the - * buffer becomes too large, `.readFromSync()` will throw an error. - * - * Based on Go Lang's - * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */ - readFromSync(r: ReaderSync): number; - } - - /** - * Read Reader `r` until EOF (`null`) and resolve to the content as - * Uint8Array`. - * - * @deprecated Use - * [`readAll`](https://deno.land/std/streams/read_all.ts?s=readAll) from - * [`std/streams/read_all.ts`](https://deno.land/std/streams/read_all.ts) - * instead. `Deno.readAll` will be removed in the future. - * - * @category I/O - */ - export function readAll(r: Reader): Promise; - - /** - * Synchronously reads Reader `r` until EOF (`null`) and returns the content - * as `Uint8Array`. - * - * @deprecated Use - * [`readAllSync`](https://deno.land/std/streams/read_all.ts?s=readAllSync) - * from - * [`std/streams/read_all.ts`](https://deno.land/std/streams/read_all.ts) - * instead. `Deno.readAllSync` will be removed in the future. - * - * @category I/O - */ - export function readAllSync(r: ReaderSync): Uint8Array; - - /** - * Write all the content of the array buffer (`arr`) to the writer (`w`). - * - * @deprecated Use - * [`writeAll`](https://deno.land/std/streams/write_all.ts?s=writeAll) from - * [`std/streams/write_all.ts`](https://deno.land/std/streams/write_all.ts) - * instead. `Deno.writeAll` will be removed in the future. - * - * @category I/O - */ - export function writeAll(w: Writer, arr: Uint8Array): Promise; - - /** - * Synchronously write all the content of the array buffer (`arr`) to the - * writer (`w`). - * - * @deprecated Use - * [`writeAllSync`](https://deno.land/std/streams/write_all.ts?s=writeAllSync) - * from - * [`std/streams/write_all.ts`](https://deno.land/std/streams/write_all.ts) - * instead. `Deno.writeAllSync` will be removed in the future. - * - * @category I/O - */ - export function writeAllSync(w: WriterSync, arr: Uint8Array): void; - - /** - * Options which can be set when using {@linkcode Deno.mkdir} and - * {@linkcode Deno.mkdirSync}. - * - * @category File System */ - export interface MkdirOptions { - /** If set to `true`, means that any intermediate directories will also be - * created (as with the shell command `mkdir -p`). - * - * Intermediate directories are created with the same permissions. - * - * When recursive is set to `true`, succeeds silently (without changing any - * permissions) if a directory already exists at the path, or if the path - * is a symlink to an existing directory. - * - * @default {false} */ - recursive?: boolean; - /** Permissions to use when creating the directory (defaults to `0o777`, - * before the process's umask). - * - * Ignored on Windows. */ - mode?: number; - } - - /** Creates a new directory with the specified path. - * - * ```ts - * await Deno.mkdir("new_dir"); - * await Deno.mkdir("nested/directories", { recursive: true }); - * await Deno.mkdir("restricted_access_dir", { mode: 0o700 }); - * ``` - * - * Defaults to throwing error if the directory already exists. - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function mkdir( - path: string | URL, - options?: MkdirOptions, - ): Promise; - - /** Synchronously creates a new directory with the specified path. - * - * ```ts - * Deno.mkdirSync("new_dir"); - * Deno.mkdirSync("nested/directories", { recursive: true }); - * Deno.mkdirSync("restricted_access_dir", { mode: 0o700 }); - * ``` - * - * Defaults to throwing error if the directory already exists. - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function mkdirSync(path: string | URL, options?: MkdirOptions): void; - - /** - * Options which can be set when using {@linkcode Deno.makeTempDir}, - * {@linkcode Deno.makeTempDirSync}, {@linkcode Deno.makeTempFile}, and - * {@linkcode Deno.makeTempFileSync}. - * - * @category File System */ - export interface MakeTempOptions { - /** Directory where the temporary directory should be created (defaults to - * the env variable `TMPDIR`, or the system's default, usually `/tmp`). - * - * Note that if the passed `dir` is relative, the path returned by - * `makeTempFile()` and `makeTempDir()` will also be relative. Be mindful of - * this when changing working directory. */ - dir?: string; - /** String that should precede the random portion of the temporary - * directory's name. */ - prefix?: string; - /** String that should follow the random portion of the temporary - * directory's name. */ - suffix?: string; - } - - /** Creates a new temporary directory in the default directory for temporary - * files, unless `dir` is specified. Other optional options include - * prefixing and suffixing the directory name with `prefix` and `suffix` - * respectively. - * - * This call resolves to the full path to the newly created directory. - * - * Multiple programs calling this function simultaneously will create different - * directories. It is the caller's responsibility to remove the directory when - * no longer needed. - * - * ```ts - * const tempDirName0 = await Deno.makeTempDir(); // e.g. /tmp/2894ea76 - * const tempDirName1 = await Deno.makeTempDir({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d - * ``` - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - // TODO(ry) Doesn't check permissions. - export function makeTempDir(options?: MakeTempOptions): Promise; - - /** Synchronously creates a new temporary directory in the default directory - * for temporary files, unless `dir` is specified. Other optional options - * include prefixing and suffixing the directory name with `prefix` and - * `suffix` respectively. - * - * The full path to the newly created directory is returned. - * - * Multiple programs calling this function simultaneously will create different - * directories. It is the caller's responsibility to remove the directory when - * no longer needed. - * - * ```ts - * const tempDirName0 = Deno.makeTempDirSync(); // e.g. /tmp/2894ea76 - * const tempDirName1 = Deno.makeTempDirSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d - * ``` - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - // TODO(ry) Doesn't check permissions. - export function makeTempDirSync(options?: MakeTempOptions): string; - - /** Creates a new temporary file in the default directory for temporary - * files, unless `dir` is specified. - * - * Other options include prefixing and suffixing the directory name with - * `prefix` and `suffix` respectively. - * - * This call resolves to the full path to the newly created file. - * - * Multiple programs calling this function simultaneously will create - * different files. It is the caller's responsibility to remove the file when - * no longer needed. - * - * ```ts - * const tmpFileName0 = await Deno.makeTempFile(); // e.g. /tmp/419e0bf2 - * const tmpFileName1 = await Deno.makeTempFile({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098 - * ``` - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function makeTempFile(options?: MakeTempOptions): Promise; - - /** Synchronously creates a new temporary file in the default directory for - * temporary files, unless `dir` is specified. - * - * Other options include prefixing and suffixing the directory name with - * `prefix` and `suffix` respectively. - * - * The full path to the newly created file is returned. - * - * Multiple programs calling this function simultaneously will create - * different files. It is the caller's responsibility to remove the file when - * no longer needed. - * - * ```ts - * const tempFileName0 = Deno.makeTempFileSync(); // e.g. /tmp/419e0bf2 - * const tempFileName1 = Deno.makeTempFileSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098 - * ``` - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function makeTempFileSync(options?: MakeTempOptions): string; - - /** Changes the permission of a specific file/directory of specified path. - * Ignores the process's umask. - * - * ```ts - * await Deno.chmod("/path/to/file", 0o666); - * ``` - * - * The mode is a sequence of 3 octal numbers. The first/left-most number - * specifies the permissions for the owner. The second number specifies the - * permissions for the group. The last/right-most number specifies the - * permissions for others. For example, with a mode of 0o764, the owner (7) - * can read/write/execute, the group (6) can read/write and everyone else (4) - * can read only. - * - * | Number | Description | - * | ------ | ----------- | - * | 7 | read, write, and execute | - * | 6 | read and write | - * | 5 | read and execute | - * | 4 | read only | - * | 3 | write and execute | - * | 2 | write only | - * | 1 | execute only | - * | 0 | no permission | - * - * NOTE: This API currently throws on Windows - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function chmod(path: string | URL, mode: number): Promise; - - /** Synchronously changes the permission of a specific file/directory of - * specified path. Ignores the process's umask. - * - * ```ts - * Deno.chmodSync("/path/to/file", 0o666); - * ``` - * - * For a full description, see {@linkcode Deno.chmod}. - * - * NOTE: This API currently throws on Windows - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function chmodSync(path: string | URL, mode: number): void; - - /** Change owner of a regular file or directory. - * - * This functionality is not available on Windows. - * - * ```ts - * await Deno.chown("myFile.txt", 1000, 1002); - * ``` - * - * Requires `allow-write` permission. - * - * Throws Error (not implemented) if executed on Windows. - * - * @tags allow-write - * @category File System - * - * @param path path to the file - * @param uid user id (UID) of the new owner, or `null` for no change - * @param gid group id (GID) of the new owner, or `null` for no change - */ - export function chown( - path: string | URL, - uid: number | null, - gid: number | null, - ): Promise; - - /** Synchronously change owner of a regular file or directory. - * - * This functionality is not available on Windows. - * - * ```ts - * Deno.chownSync("myFile.txt", 1000, 1002); - * ``` - * - * Requires `allow-write` permission. - * - * Throws Error (not implemented) if executed on Windows. - * - * @tags allow-write - * @category File System - * - * @param path path to the file - * @param uid user id (UID) of the new owner, or `null` for no change - * @param gid group id (GID) of the new owner, or `null` for no change - */ - export function chownSync( - path: string | URL, - uid: number | null, - gid: number | null, - ): void; - - /** - * Options which can be set when using {@linkcode Deno.remove} and - * {@linkcode Deno.removeSync}. - * - * @category File System */ - export interface RemoveOptions { - /** If set to `true`, path will be removed even if it's a non-empty directory. - * - * @default {false} */ - recursive?: boolean; - } - - /** Removes the named file or directory. - * - * ```ts - * await Deno.remove("/path/to/empty_dir/or/file"); - * await Deno.remove("/path/to/populated_dir/or/file", { recursive: true }); - * ``` - * - * Throws error if permission denied, path not found, or path is a non-empty - * directory and the `recursive` option isn't set to `true`. - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function remove( - path: string | URL, - options?: RemoveOptions, - ): Promise; - - /** Synchronously removes the named file or directory. - * - * ```ts - * Deno.removeSync("/path/to/empty_dir/or/file"); - * Deno.removeSync("/path/to/populated_dir/or/file", { recursive: true }); - * ``` - * - * Throws error if permission denied, path not found, or path is a non-empty - * directory and the `recursive` option isn't set to `true`. - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function removeSync(path: string | URL, options?: RemoveOptions): void; - - /** Synchronously renames (moves) `oldpath` to `newpath`. Paths may be files or - * directories. If `newpath` already exists and is not a directory, - * `renameSync()` replaces it. OS-specific restrictions may apply when - * `oldpath` and `newpath` are in different directories. - * - * ```ts - * Deno.renameSync("old/path", "new/path"); - * ``` - * - * On Unix-like OSes, this operation does not follow symlinks at either path. - * - * It varies between platforms when the operation throws errors, and if so what - * they are. It's always an error to rename anything to a non-empty directory. - * - * Requires `allow-read` and `allow-write` permissions. - * - * @tags allow-read, allow-write - * @category File System - */ - export function renameSync( - oldpath: string | URL, - newpath: string | URL, - ): void; - - /** Renames (moves) `oldpath` to `newpath`. Paths may be files or directories. - * If `newpath` already exists and is not a directory, `rename()` replaces it. - * OS-specific restrictions may apply when `oldpath` and `newpath` are in - * different directories. - * - * ```ts - * await Deno.rename("old/path", "new/path"); - * ``` - * - * On Unix-like OSes, this operation does not follow symlinks at either path. - * - * It varies between platforms when the operation throws errors, and if so - * what they are. It's always an error to rename anything to a non-empty - * directory. - * - * Requires `allow-read` and `allow-write` permissions. - * - * @tags allow-read, allow-write - * @category File System - */ - export function rename( - oldpath: string | URL, - newpath: string | URL, - ): Promise; - - /** Asynchronously reads and returns the entire contents of a file as an UTF-8 - * decoded string. Reading a directory throws an error. - * - * ```ts - * const data = await Deno.readTextFile("hello.txt"); - * console.log(data); - * ``` - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function readTextFile( - path: string | URL, - options?: ReadFileOptions, - ): Promise; - - /** Synchronously reads and returns the entire contents of a file as an UTF-8 - * decoded string. Reading a directory throws an error. - * - * ```ts - * const data = Deno.readTextFileSync("hello.txt"); - * console.log(data); - * ``` - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function readTextFileSync(path: string | URL): string; - - /** Reads and resolves to the entire contents of a file as an array of bytes. - * `TextDecoder` can be used to transform the bytes to string if required. - * Reading a directory returns an empty data array. - * - * ```ts - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello.txt"); - * console.log(decoder.decode(data)); - * ``` - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function readFile( - path: string | URL, - options?: ReadFileOptions, - ): Promise; - - /** Synchronously reads and returns the entire contents of a file as an array - * of bytes. `TextDecoder` can be used to transform the bytes to string if - * required. Reading a directory returns an empty data array. - * - * ```ts - * const decoder = new TextDecoder("utf-8"); - * const data = Deno.readFileSync("hello.txt"); - * console.log(decoder.decode(data)); - * ``` - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function readFileSync(path: string | URL): Uint8Array; - - /** Provides information about a file and is returned by - * {@linkcode Deno.stat}, {@linkcode Deno.lstat}, {@linkcode Deno.statSync}, - * and {@linkcode Deno.lstatSync} or from calling `stat()` and `statSync()` - * on an {@linkcode Deno.FsFile} instance. - * - * @category File System - */ - export interface FileInfo { - /** True if this is info for a regular file. Mutually exclusive to - * `FileInfo.isDirectory` and `FileInfo.isSymlink`. */ - isFile: boolean; - /** True if this is info for a regular directory. Mutually exclusive to - * `FileInfo.isFile` and `FileInfo.isSymlink`. */ - isDirectory: boolean; - /** True if this is info for a symlink. Mutually exclusive to - * `FileInfo.isFile` and `FileInfo.isDirectory`. */ - isSymlink: boolean; - /** The size of the file, in bytes. */ - size: number; - /** The last modification time of the file. This corresponds to the `mtime` - * field from `stat` on Linux/Mac OS and `ftLastWriteTime` on Windows. This - * may not be available on all platforms. */ - mtime: Date | null; - /** The last access time of the file. This corresponds to the `atime` - * field from `stat` on Unix and `ftLastAccessTime` on Windows. This may not - * be available on all platforms. */ - atime: Date | null; - /** The creation time of the file. This corresponds to the `birthtime` - * field from `stat` on Mac/BSD and `ftCreationTime` on Windows. This may - * not be available on all platforms. */ - birthtime: Date | null; - /** ID of the device containing the file. - * - * _Linux/Mac OS only._ */ - dev: number | null; - /** Inode number. - * - * _Linux/Mac OS only._ */ - ino: number | null; - /** **UNSTABLE**: Match behavior with Go on Windows for `mode`. - * - * The underlying raw `st_mode` bits that contain the standard Unix - * permissions for this file/directory. */ - mode: number | null; - /** Number of hard links pointing to this file. - * - * _Linux/Mac OS only._ */ - nlink: number | null; - /** User ID of the owner of this file. - * - * _Linux/Mac OS only._ */ - uid: number | null; - /** Group ID of the owner of this file. - * - * _Linux/Mac OS only._ */ - gid: number | null; - /** Device ID of this file. - * - * _Linux/Mac OS only._ */ - rdev: number | null; - /** Blocksize for filesystem I/O. - * - * _Linux/Mac OS only._ */ - blksize: number | null; - /** Number of blocks allocated to the file, in 512-byte units. - * - * _Linux/Mac OS only._ */ - blocks: number | null; - } - - /** Resolves to the absolute normalized path, with symbolic links resolved. - * - * ```ts - * // e.g. given /home/alice/file.txt and current directory /home/alice - * await Deno.symlink("file.txt", "symlink_file.txt"); - * const realPath = await Deno.realPath("./file.txt"); - * const realSymLinkPath = await Deno.realPath("./symlink_file.txt"); - * console.log(realPath); // outputs "/home/alice/file.txt" - * console.log(realSymLinkPath); // outputs "/home/alice/file.txt" - * ``` - * - * Requires `allow-read` permission for the target path. - * - * Also requires `allow-read` permission for the `CWD` if the target path is - * relative. - * - * @tags allow-read - * @category File System - */ - export function realPath(path: string | URL): Promise; - - /** Synchronously returns absolute normalized path, with symbolic links - * resolved. - * - * ```ts - * // e.g. given /home/alice/file.txt and current directory /home/alice - * Deno.symlinkSync("file.txt", "symlink_file.txt"); - * const realPath = Deno.realPathSync("./file.txt"); - * const realSymLinkPath = Deno.realPathSync("./symlink_file.txt"); - * console.log(realPath); // outputs "/home/alice/file.txt" - * console.log(realSymLinkPath); // outputs "/home/alice/file.txt" - * ``` - * - * Requires `allow-read` permission for the target path. - * - * Also requires `allow-read` permission for the `CWD` if the target path is - * relative. - * - * @tags allow-read - * @category File System - */ - export function realPathSync(path: string | URL): string; - - /** - * Information about a directory entry returned from {@linkcode Deno.readDir} - * and {@linkcode Deno.readDirSync}. - * - * @category File System */ - export interface DirEntry { - /** The file name of the entry. It is just the entity name and does not - * include the full path. */ - name: string; - /** True if this is info for a regular file. Mutually exclusive to - * `DirEntry.isDirectory` and `DirEntry.isSymlink`. */ - isFile: boolean; - /** True if this is info for a regular directory. Mutually exclusive to - * `DirEntry.isFile` and `DirEntry.isSymlink`. */ - isDirectory: boolean; - /** True if this is info for a symlink. Mutually exclusive to - * `DirEntry.isFile` and `DirEntry.isDirectory`. */ - isSymlink: boolean; - } - - /** Reads the directory given by `path` and returns an async iterable of - * {@linkcode Deno.DirEntry}. - * - * ```ts - * for await (const dirEntry of Deno.readDir("/")) { - * console.log(dirEntry.name); - * } - * ``` - * - * Throws error if `path` is not a directory. - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function readDir(path: string | URL): AsyncIterable; - - /** Synchronously reads the directory given by `path` and returns an iterable - * of `Deno.DirEntry`. - * - * ```ts - * for (const dirEntry of Deno.readDirSync("/")) { - * console.log(dirEntry.name); - * } - * ``` - * - * Throws error if `path` is not a directory. - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function readDirSync(path: string | URL): Iterable; - - /** Copies the contents and permissions of one file to another specified path, - * by default creating a new file if needed, else overwriting. Fails if target - * path is a directory or is unwritable. - * - * ```ts - * await Deno.copyFile("from.txt", "to.txt"); - * ``` - * - * Requires `allow-read` permission on `fromPath`. - * - * Requires `allow-write` permission on `toPath`. - * - * @tags allow-read, allow-write - * @category File System - */ - export function copyFile( - fromPath: string | URL, - toPath: string | URL, - ): Promise; - - /** Synchronously copies the contents and permissions of one file to another - * specified path, by default creating a new file if needed, else overwriting. - * Fails if target path is a directory or is unwritable. - * - * ```ts - * Deno.copyFileSync("from.txt", "to.txt"); - * ``` - * - * Requires `allow-read` permission on `fromPath`. - * - * Requires `allow-write` permission on `toPath`. - * - * @tags allow-read, allow-write - * @category File System - */ - export function copyFileSync( - fromPath: string | URL, - toPath: string | URL, - ): void; - - /** Resolves to the full path destination of the named symbolic link. - * - * ```ts - * await Deno.symlink("./test.txt", "./test_link.txt"); - * const target = await Deno.readLink("./test_link.txt"); // full path of ./test.txt - * ``` - * - * Throws TypeError if called with a hard link. - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function readLink(path: string | URL): Promise; - - /** Synchronously returns the full path destination of the named symbolic - * link. - * - * ```ts - * Deno.symlinkSync("./test.txt", "./test_link.txt"); - * const target = Deno.readLinkSync("./test_link.txt"); // full path of ./test.txt - * ``` - * - * Throws TypeError if called with a hard link. - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function readLinkSync(path: string | URL): string; - - /** Resolves to a {@linkcode Deno.FileInfo} for the specified `path`. If - * `path` is a symlink, information for the symlink will be returned instead - * of what it points to. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * const fileInfo = await Deno.lstat("hello.txt"); - * assert(fileInfo.isFile); - * ``` - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function lstat(path: string | URL): Promise; - - /** Synchronously returns a {@linkcode Deno.FileInfo} for the specified - * `path`. If `path` is a symlink, information for the symlink will be - * returned instead of what it points to. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * const fileInfo = Deno.lstatSync("hello.txt"); - * assert(fileInfo.isFile); - * ``` - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function lstatSync(path: string | URL): FileInfo; - - /** Resolves to a {@linkcode Deno.FileInfo} for the specified `path`. Will - * always follow symlinks. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * const fileInfo = await Deno.stat("hello.txt"); - * assert(fileInfo.isFile); - * ``` - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function stat(path: string | URL): Promise; - - /** Synchronously returns a {@linkcode Deno.FileInfo} for the specified - * `path`. Will always follow symlinks. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * const fileInfo = Deno.statSync("hello.txt"); - * assert(fileInfo.isFile); - * ``` - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function statSync(path: string | URL): FileInfo; - - /** Options for writing to a file. - * - * @category File System - */ - export interface WriteFileOptions { - /** If set to `true`, will append to a file instead of overwriting previous - * contents. - * - * @default {false} */ - append?: boolean; - /** Sets the option to allow creating a new file, if one doesn't already - * exist at the specified path. - * - * @default {true} */ - create?: boolean; - /** If set to `true`, no file, directory, or symlink is allowed to exist at - * the target location. When createNew is set to `true`, `create` is ignored. - * - * @default {false} */ - createNew?: boolean; - /** Permissions always applied to file. */ - mode?: number; - /** An abort signal to allow cancellation of the file write operation. - * - * If the signal becomes aborted the write file operation will be stopped - * and the promise returned will be rejected with an {@linkcode AbortError}. - */ - signal?: AbortSignal; - } - - /** Write `data` to the given `path`, by default creating a new file if - * needed, else overwriting. - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world\n"); - * await Deno.writeFile("hello1.txt", data); // overwrite "hello1.txt" or create it - * await Deno.writeFile("hello2.txt", data, { create: false }); // only works if "hello2.txt" exists - * await Deno.writeFile("hello3.txt", data, { mode: 0o777 }); // set permissions on new file - * await Deno.writeFile("hello4.txt", data, { append: true }); // add data to the end of the file - * ``` - * - * Requires `allow-write` permission, and `allow-read` if `options.create` is - * `false`. - * - * @tags allow-read, allow-write - * @category File System - */ - export function writeFile( - path: string | URL, - data: Uint8Array | ReadableStream, - options?: WriteFileOptions, - ): Promise; - - /** Synchronously write `data` to the given `path`, by default creating a new - * file if needed, else overwriting. - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world\n"); - * Deno.writeFileSync("hello1.txt", data); // overwrite "hello1.txt" or create it - * Deno.writeFileSync("hello2.txt", data, { create: false }); // only works if "hello2.txt" exists - * Deno.writeFileSync("hello3.txt", data, { mode: 0o777 }); // set permissions on new file - * Deno.writeFileSync("hello4.txt", data, { append: true }); // add data to the end of the file - * ``` - * - * Requires `allow-write` permission, and `allow-read` if `options.create` is - * `false`. - * - * @tags allow-read, allow-write - * @category File System - */ - export function writeFileSync( - path: string | URL, - data: Uint8Array, - options?: WriteFileOptions, - ): void; - - /** Write string `data` to the given `path`, by default creating a new file if - * needed, else overwriting. - * - * ```ts - * await Deno.writeTextFile("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it - * ``` - * - * Requires `allow-write` permission, and `allow-read` if `options.create` is - * `false`. - * - * @tags allow-read, allow-write - * @category File System - */ - export function writeTextFile( - path: string | URL, - data: string | ReadableStream, - options?: WriteFileOptions, - ): Promise; - - /** Synchronously write string `data` to the given `path`, by default creating - * a new file if needed, else overwriting. - * - * ```ts - * Deno.writeTextFileSync("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it - * ``` - * - * Requires `allow-write` permission, and `allow-read` if `options.create` is - * `false`. - * - * @tags allow-read, allow-write - * @category File System - */ - export function writeTextFileSync( - path: string | URL, - data: string, - options?: WriteFileOptions, - ): void; - - /** Truncates (or extends) the specified file, to reach the specified `len`. - * If `len` is not specified then the entire file contents are truncated. - * - * ### Truncate the entire file - * ```ts - * await Deno.truncate("my_file.txt"); - * ``` - * - * ### Truncate part of the file - * - * ```ts - * const file = await Deno.makeTempFile(); - * await Deno.writeFile(file, new TextEncoder().encode("Hello World")); - * await Deno.truncate(file, 7); - * const data = await Deno.readFile(file); - * console.log(new TextDecoder().decode(data)); // "Hello W" - * ``` - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function truncate(name: string, len?: number): Promise; - - /** Synchronously truncates (or extends) the specified file, to reach the - * specified `len`. If `len` is not specified then the entire file contents - * are truncated. - * - * ### Truncate the entire file - * - * ```ts - * Deno.truncateSync("my_file.txt"); - * ``` - * - * ### Truncate part of the file - * - * ```ts - * const file = Deno.makeTempFileSync(); - * Deno.writeFileSync(file, new TextEncoder().encode("Hello World")); - * Deno.truncateSync(file, 7); - * const data = Deno.readFileSync(file); - * console.log(new TextDecoder().decode(data)); - * ``` - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function truncateSync(name: string, len?: number): void; - - /** @category Observability */ - export interface OpMetrics { - opsDispatched: number; - opsDispatchedSync: number; - opsDispatchedAsync: number; - opsDispatchedAsyncUnref: number; - opsCompleted: number; - opsCompletedSync: number; - opsCompletedAsync: number; - opsCompletedAsyncUnref: number; - bytesSentControl: number; - bytesSentData: number; - bytesReceived: number; - } - - /** @category Observability */ - export interface Metrics extends OpMetrics { - ops: Record; - } - - /** Receive metrics from the privileged side of Deno. This is primarily used - * in the development of Deno. _Ops_, also called _bindings_, are the - * go-between between Deno JavaScript sandbox and the rest of Deno. - * - * ```shell - * > console.table(Deno.metrics()) - * ┌─────────────────────────┬────────┐ - * │ (index) │ Values │ - * ├─────────────────────────┼────────┤ - * │ opsDispatched │ 3 │ - * │ opsDispatchedSync │ 2 │ - * │ opsDispatchedAsync │ 1 │ - * │ opsDispatchedAsyncUnref │ 0 │ - * │ opsCompleted │ 3 │ - * │ opsCompletedSync │ 2 │ - * │ opsCompletedAsync │ 1 │ - * │ opsCompletedAsyncUnref │ 0 │ - * │ bytesSentControl │ 73 │ - * │ bytesSentData │ 0 │ - * │ bytesReceived │ 375 │ - * └─────────────────────────┴────────┘ - * ``` - * - * @category Observability - */ - export function metrics(): Metrics; - - /** - * A map of open resources that Deno is tracking. The key is the resource ID - * (_rid_) and the value is its representation. - * - * @category Observability */ - interface ResourceMap { - [rid: number]: unknown; - } - - /** Returns a map of open resource IDs (_rid_) along with their string - * representations. This is an internal API and as such resource - * representation has `unknown` type; that means it can change any time and - * should not be depended upon. - * - * ```ts - * console.log(Deno.resources()); - * // { 0: "stdin", 1: "stdout", 2: "stderr" } - * Deno.openSync('../test.file'); - * console.log(Deno.resources()); - * // { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" } - * ``` - * - * @category Observability - */ - export function resources(): ResourceMap; - - /** - * Additional information for FsEvent objects with the "other" kind. - * - * - `"rescan"`: rescan notices indicate either a lapse in the events or a - * change in the filesystem such that events received so far can no longer - * be relied on to represent the state of the filesystem now. An - * application that simply reacts to file changes may not care about this. - * An application that keeps an in-memory representation of the filesystem - * will need to care, and will need to refresh that representation directly - * from the filesystem. - * - * @category File System - */ - export type FsEventFlag = "rescan"; - - /** - * Represents a unique file system event yielded by a - * {@linkcode Deno.FsWatcher}. - * - * @category File System */ - export interface FsEvent { - /** The kind/type of the file system event. */ - kind: "any" | "access" | "create" | "modify" | "remove" | "other"; - /** An array of paths that are associated with the file system event. */ - paths: string[]; - /** Any additional flags associated with the event. */ - flag?: FsEventFlag; - } - - /** - * Returned by {@linkcode Deno.watchFs}. It is an async iterator yielding up - * system events. To stop watching the file system by calling `.close()` - * method. - * - * @category File System - */ - export interface FsWatcher extends AsyncIterable { - /** The resource id. */ - readonly rid: number; - /** Stops watching the file system and closes the watcher resource. */ - close(): void; - /** - * Stops watching the file system and closes the watcher resource. - * - * @deprecated Will be removed in the future. - */ - return?(value?: any): Promise>; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - /** Watch for file system events against one or more `paths`, which can be - * files or directories. These paths must exist already. One user action (e.g. - * `touch test.file`) can generate multiple file system events. Likewise, - * one user action can result in multiple file paths in one event (e.g. `mv - * old_name.txt new_name.txt`). - * - * The recursive option is `true` by default and, for directories, will watch - * the specified directory and all sub directories. - * - * Note that the exact ordering of the events can vary between operating - * systems. - * - * ```ts - * const watcher = Deno.watchFs("/"); - * for await (const event of watcher) { - * console.log(">>>> event", event); - * // { kind: "create", paths: [ "/foo.txt" ] } - * } - * ``` - * - * Call `watcher.close()` to stop watching. - * - * ```ts - * const watcher = Deno.watchFs("/"); - * - * setTimeout(() => { - * watcher.close(); - * }, 5000); - * - * for await (const event of watcher) { - * console.log(">>>> event", event); - * } - * ``` - * - * Requires `allow-read` permission. - * - * @tags allow-read - * @category File System - */ - export function watchFs( - paths: string | string[], - options?: { recursive: boolean }, - ): FsWatcher; - - /** Options which can be used with {@linkcode Deno.run}. - * - * @category Sub Process */ - export interface RunOptions { - /** Arguments to pass. - * - * _Note_: the first element needs to be a path to the executable that is - * being run. */ - cmd: readonly string[] | [string | URL, ...string[]]; - /** The current working directory that should be used when running the - * sub-process. */ - cwd?: string; - /** Any environment variables to be set when running the sub-process. */ - env?: Record; - /** By default subprocess inherits `stdout` of parent process. To change - * this this option can be set to a resource ID (_rid_) of an open file, - * `"inherit"`, `"piped"`, or `"null"`: - * - * - _number_: the resource ID of an open file/resource. This allows you to - * write to a file. - * - `"inherit"`: The default if unspecified. The subprocess inherits from the - * parent. - * - `"piped"`: A new pipe should be arranged to connect the parent and child - * sub-process. - * - `"null"`: This stream will be ignored. This is the equivalent of attaching - * the stream to `/dev/null`. - */ - stdout?: "inherit" | "piped" | "null" | number; - /** By default subprocess inherits `stderr` of parent process. To change - * this this option can be set to a resource ID (_rid_) of an open file, - * `"inherit"`, `"piped"`, or `"null"`: - * - * - _number_: the resource ID of an open file/resource. This allows you to - * write to a file. - * - `"inherit"`: The default if unspecified. The subprocess inherits from the - * parent. - * - `"piped"`: A new pipe should be arranged to connect the parent and child - * sub-process. - * - `"null"`: This stream will be ignored. This is the equivalent of attaching - * the stream to `/dev/null`. - */ - stderr?: "inherit" | "piped" | "null" | number; - /** By default subprocess inherits `stdin` of parent process. To change - * this this option can be set to a resource ID (_rid_) of an open file, - * `"inherit"`, `"piped"`, or `"null"`: - * - * - _number_: the resource ID of an open file/resource. This allows you to - * read from a file. - * - `"inherit"`: The default if unspecified. The subprocess inherits from the - * parent. - * - `"piped"`: A new pipe should be arranged to connect the parent and child - * sub-process. - * - `"null"`: This stream will be ignored. This is the equivalent of attaching - * the stream to `/dev/null`. - */ - stdin?: "inherit" | "piped" | "null" | number; - } - - /** The status resolved from the `.status()` method of a - * {@linkcode Deno.Process} instance. - * - * If `success` is `true`, then `code` will be `0`, but if `success` is - * `false`, the sub-process exit code will be set in `code`. - * - * @category Sub Process */ - export type ProcessStatus = - | { - success: true; - code: 0; - signal?: undefined; - } - | { - success: false; - code: number; - signal?: number; - }; - - /** - * Represents an instance of a sub process that is returned from - * {@linkcode Deno.run} which can be used to manage the sub-process. - * - * @category Sub Process */ - export class Process { - /** The resource ID of the sub-process. */ - readonly rid: number; - /** The operating system's process ID for the sub-process. */ - readonly pid: number; - /** A reference to the sub-processes `stdin`, which allows interacting with - * the sub-process at a low level. */ - readonly stdin: T["stdin"] extends "piped" ? Writer & Closer & { - writable: WritableStream; - } - : (Writer & Closer & { writable: WritableStream }) | null; - /** A reference to the sub-processes `stdout`, which allows interacting with - * the sub-process at a low level. */ - readonly stdout: T["stdout"] extends "piped" ? Reader & Closer & { - readable: ReadableStream; - } - : (Reader & Closer & { readable: ReadableStream }) | null; - /** A reference to the sub-processes `stderr`, which allows interacting with - * the sub-process at a low level. */ - readonly stderr: T["stderr"] extends "piped" ? Reader & Closer & { - readable: ReadableStream; - } - : (Reader & Closer & { readable: ReadableStream }) | null; - /** Wait for the process to exit and return its exit status. - * - * Calling this function multiple times will return the same status. - * - * The `stdin` reference to the process will be closed before waiting to - * avoid a deadlock. - * - * If `stdout` and/or `stderr` were set to `"piped"`, they must be closed - * manually before the process can exit. - * - * To run process to completion and collect output from both `stdout` and - * `stderr` use: - * - * ```ts - * const p = Deno.run({ cmd: [ "echo", "hello world" ], stderr: 'piped', stdout: 'piped' }); - * const [status, stdout, stderr] = await Promise.all([ - * p.status(), - * p.output(), - * p.stderrOutput() - * ]); - * p.close(); - * ``` - */ - status(): Promise; - /** Buffer the stdout until EOF and return it as `Uint8Array`. - * - * You must set `stdout` to `"piped"` when creating the process. - * - * This calls `close()` on stdout after its done. */ - output(): Promise; - /** Buffer the stderr until EOF and return it as `Uint8Array`. - * - * You must set `stderr` to `"piped"` when creating the process. - * - * This calls `close()` on stderr after its done. */ - stderrOutput(): Promise; - /** Clean up resources associated with the sub-process instance. */ - close(): void; - /** Send a signal to process. - * Default signal is `"SIGTERM"`. - * - * ```ts - * const p = Deno.run({ cmd: [ "sleep", "20" ]}); - * p.kill("SIGTERM"); - * p.close(); - * ``` - */ - kill(signo?: Signal): void; - } - - /** Operating signals which can be listened for or sent to sub-processes. What - * signals and what their standard behaviors are OS dependent. - * - * @category Runtime Environment */ - export type Signal = - | "SIGABRT" - | "SIGALRM" - | "SIGBREAK" - | "SIGBUS" - | "SIGCHLD" - | "SIGCONT" - | "SIGEMT" - | "SIGFPE" - | "SIGHUP" - | "SIGILL" - | "SIGINFO" - | "SIGINT" - | "SIGIO" - | "SIGKILL" - | "SIGPIPE" - | "SIGPROF" - | "SIGPWR" - | "SIGQUIT" - | "SIGSEGV" - | "SIGSTKFLT" - | "SIGSTOP" - | "SIGSYS" - | "SIGTERM" - | "SIGTRAP" - | "SIGTSTP" - | "SIGTTIN" - | "SIGTTOU" - | "SIGURG" - | "SIGUSR1" - | "SIGUSR2" - | "SIGVTALRM" - | "SIGWINCH" - | "SIGXCPU" - | "SIGXFSZ"; - - /** Registers the given function as a listener of the given signal event. - * - * ```ts - * Deno.addSignalListener( - * "SIGTERM", - * () => { - * console.log("SIGTERM!") - * } - * ); - * ``` - * - * _Note_: On Windows only `"SIGINT"` (CTRL+C) and `"SIGBREAK"` (CTRL+Break) - * are supported. - * - * @category Runtime Environment - */ - export function addSignalListener(signal: Signal, handler: () => void): void; - - /** Removes the given signal listener that has been registered with - * {@linkcode Deno.addSignalListener}. - * - * ```ts - * const listener = () => { - * console.log("SIGTERM!") - * }; - * Deno.addSignalListener("SIGTERM", listener); - * Deno.removeSignalListener("SIGTERM", listener); - * ``` - * - * _Note_: On Windows only `"SIGINT"` (CTRL+C) and `"SIGBREAK"` (CTRL+Break) - * are supported. - * - * @category Runtime Environment - */ - export function removeSignalListener( - signal: Signal, - handler: () => void, - ): void; - - /** Spawns new subprocess. RunOptions must contain at a minimum the `opt.cmd`, - * an array of program arguments, the first of which is the binary. - * - * ```ts - * const p = Deno.run({ - * cmd: ["curl", "https://example.com"], - * }); - * const status = await p.status(); - * ``` - * - * Subprocess uses same working directory as parent process unless `opt.cwd` - * is specified. - * - * Environmental variables from parent process can be cleared using `opt.clearEnv`. - * Doesn't guarantee that only `opt.env` variables are present, - * as the OS may set environmental variables for processes. - * - * Environmental variables for subprocess can be specified using `opt.env` - * mapping. - * - * `opt.uid` sets the child process’s user ID. This translates to a setuid call - * in the child process. Failure in the setuid call will cause the spawn to fail. - * - * `opt.gid` is similar to `opt.uid`, but sets the group ID of the child process. - * This has the same semantics as the uid field. - * - * By default subprocess inherits stdio of parent process. To change - * this this, `opt.stdin`, `opt.stdout`, and `opt.stderr` can be set - * independently to a resource ID (_rid_) of an open file, `"inherit"`, - * `"piped"`, or `"null"`: - * - * - _number_: the resource ID of an open file/resource. This allows you to - * read or write to a file. - * - `"inherit"`: The default if unspecified. The subprocess inherits from the - * parent. - * - `"piped"`: A new pipe should be arranged to connect the parent and child - * sub-process. - * - `"null"`: This stream will be ignored. This is the equivalent of attaching - * the stream to `/dev/null`. - * - * Details of the spawned process are returned as an instance of - * {@linkcode Deno.Process}. - * - * Requires `allow-run` permission. - * - * @tags allow-run - * @category Sub Process - */ - export function run(opt: T): Process; - - /** Create a child process. - * - * If any stdio options are not set to `"piped"`, accessing the corresponding - * field on the `Command` or its `CommandOutput` will throw a `TypeError`. - * - * If `stdin` is set to `"piped"`, the `stdin` {@linkcode WritableStream} - * needs to be closed manually. - * - * @example Spawn a subprocess and pipe the output to a file - * - * ```ts - * const command = new Deno.Command(Deno.execPath(), { - * args: [ - * "eval", - * "console.log('Hello World')", - * ], - * stdin: "piped", - * }); - * const child = command.spawn(); - * - * // open a file and pipe the subprocess output to it. - * child.stdout.pipeTo(Deno.openSync("output").writable); - * - * // manually close stdin - * child.stdin.close(); - * const status = await child.status; - * ``` - * - * @example Spawn a subprocess and collect its output - * - * ```ts - * const command = new Deno.Command(Deno.execPath(), { - * args: [ - * "eval", - * "console.log('hello'); console.error('world')", - * ], - * }); - * const { code, stdout, stderr } = await command.output(); - * console.assert(code === 0); - * console.assert("hello\n" === new TextDecoder().decode(stdout)); - * console.assert("world\n" === new TextDecoder().decode(stderr)); - * ``` - * - * @example Spawn a subprocess and collect its output synchronously - * - * ```ts - * const command = new Deno.Command(Deno.execPath(), { - * args: [ - * "eval", - * "console.log('hello'); console.error('world')", - * ], - * }); - * const { code, stdout, stderr } = command.outputSync(); - * console.assert(code === 0); - * console.assert("hello\n" === new TextDecoder().decode(stdout)); - * console.assert("world\n" === new TextDecoder().decode(stderr)); - * ``` - * - * @category Sub Process - */ - export class Command { - constructor(command: string | URL, options?: CommandOptions); - /** - * Executes the {@linkcode Deno.Command}, waiting for it to finish and - * collecting all of its output. - * If `spawn()` was called, calling this function will collect the remaining - * output. - * - * Will throw an error if `stdin: "piped"` is set. - * - * If options `stdout` or `stderr` are not set to `"piped"`, accessing the - * corresponding field on {@linkcode Deno.CommandOutput} will throw a `TypeError`. - */ - output(): Promise; - /** - * Synchronously executes the {@linkcode Deno.Command}, waiting for it to - * finish and collecting all of its output. - * - * Will throw an error if `stdin: "piped"` is set. - * - * If options `stdout` or `stderr` are not set to `"piped"`, accessing the - * corresponding field on {@linkcode Deno.CommandOutput} will throw a `TypeError`. - */ - outputSync(): CommandOutput; - /** - * Spawns a streamable subprocess, allowing to use the other methods. - */ - spawn(): ChildProcess; - } - - /** - * The interface for handling a child process returned from - * {@linkcode Deno.Command.spawn}. - * - * @category Sub Process - */ - export class ChildProcess { - get stdin(): WritableStream; - get stdout(): ReadableStream; - get stderr(): ReadableStream; - readonly pid: number; - /** Get the status of the child. */ - readonly status: Promise; - - /** Waits for the child to exit completely, returning all its output and - * status. */ - output(): Promise; - /** Kills the process with given {@linkcode Deno.Signal}. - * - * @param [signo="SIGTERM"] - */ - kill(signo?: Signal): void; - - /** Ensure that the status of the child process prevents the Deno process - * from exiting. */ - ref(): void; - /** Ensure that the status of the child process does not block the Deno - * process from exiting. */ - unref(): void; - } - - /** - * Options which can be set when calling {@linkcode Deno.Command}. - * - * @category Sub Process - */ - export interface CommandOptions { - /** Arguments to pass to the process. */ - args?: string[]; - /** - * The working directory of the process. - * - * If not specified, the `cwd` of the parent process is used. - */ - cwd?: string | URL; - /** - * Clear environmental variables from parent process. - * - * Doesn't guarantee that only `env` variables are present, as the OS may - * set environmental variables for processes. - * - * @default {false} - */ - clearEnv?: boolean; - /** Environmental variables to pass to the subprocess. */ - env?: Record; - /** - * Sets the child process’s user ID. This translates to a setuid call in the - * child process. Failure in the set uid call will cause the spawn to fail. - */ - uid?: number; - /** Similar to `uid`, but sets the group ID of the child process. */ - gid?: number; - /** - * An {@linkcode AbortSignal} that allows closing the process using the - * corresponding {@linkcode AbortController} by sending the process a - * SIGTERM signal. - * - * Not supported in {@linkcode Deno.Command.outputSync}. - */ - signal?: AbortSignal; - - /** How `stdin` of the spawned process should be handled. - * - * Defaults to `"inherit"` for `output` & `outputSync`, - * and `"inherit"` for `spawn`. */ - stdin?: "piped" | "inherit" | "null"; - /** How `stdout` of the spawned process should be handled. - * - * Defaults to `"piped"` for `output` & `outputSync`, - * and `"inherit"` for `spawn`. */ - stdout?: "piped" | "inherit" | "null"; - /** How `stderr` of the spawned process should be handled. - * - * Defaults to `"piped"` for `output` & `outputSync`, - * and `"inherit"` for `spawn`. */ - stderr?: "piped" | "inherit" | "null"; - - /** Skips quoting and escaping of the arguments on windows. This option - * is ignored on non-windows platforms. - * - * @default {false} */ - windowsRawArguments?: boolean; - } - - /** - * @category Sub Process - */ - export interface CommandStatus { - /** If the child process exits with a 0 status code, `success` will be set - * to `true`, otherwise `false`. */ - success: boolean; - /** The exit code of the child process. */ - code: number; - /** The signal associated with the child process. */ - signal: Signal | null; - } - - /** - * The interface returned from calling {@linkcode Deno.Command.output} or - * {@linkcode Deno.Command.outputSync} which represents the result of spawning the - * child process. - * - * @category Sub Process - */ - export interface CommandOutput extends CommandStatus { - /** The buffered output from the child process' `stdout`. */ - readonly stdout: Uint8Array; - /** The buffered output from the child process' `stderr`. */ - readonly stderr: Uint8Array; - } - - /** Option which can be specified when performing {@linkcode Deno.inspect}. - * - * @category Console and Debugging */ - export interface InspectOptions { - /** Stylize output with ANSI colors. - * - * @default {false} */ - colors?: boolean; - /** Try to fit more than one entry of a collection on the same line. - * - * @default {true} */ - compact?: boolean; - /** Traversal depth for nested objects. - * - * @default {4} */ - depth?: number; - /** The maximum number of iterable entries to print. - * - * @default {100} */ - iterableLimit?: number; - /** Show a Proxy's target and handler. - * - * @default {false} */ - showProxy?: boolean; - /** Sort Object, Set and Map entries by key. - * - * @default {false} */ - sorted?: boolean; - /** Add a trailing comma for multiline collections. - * - * @default {false} */ - trailingComma?: boolean; - /** Evaluate the result of calling getters. - * - * @default {false} */ - getters?: boolean; - /** Show an object's non-enumerable properties. - * - * @default {false} */ - showHidden?: boolean; - /** The maximum length of a string before it is truncated with an - * ellipsis. */ - strAbbreviateSize?: number; - } - - /** Converts the input into a string that has the same format as printed by - * `console.log()`. - * - * ```ts - * const obj = { - * a: 10, - * b: "hello", - * }; - * const objAsString = Deno.inspect(obj); // { a: 10, b: "hello" } - * console.log(obj); // prints same value as objAsString, e.g. { a: 10, b: "hello" } - * ``` - * - * A custom inspect functions can be registered on objects, via the symbol - * `Symbol.for("Deno.customInspect")`, to control and customize the output - * of `inspect()` or when using `console` logging: - * - * ```ts - * class A { - * x = 10; - * y = "hello"; - * [Symbol.for("Deno.customInspect")]() { - * return `x=${this.x}, y=${this.y}`; - * } - * } - * - * const inStringFormat = Deno.inspect(new A()); // "x=10, y=hello" - * console.log(inStringFormat); // prints "x=10, y=hello" - * ``` - * - * A depth can be specified by using the `depth` option: - * - * ```ts - * Deno.inspect({a: {b: {c: {d: 'hello'}}}}, {depth: 2}); // { a: { b: [Object] } } - * ``` - * - * @category Console and Debugging - */ - export function inspect(value: unknown, options?: InspectOptions): string; - - /** The name of a privileged feature which needs permission. - * - * @category Permissions - */ - export type PermissionName = - | "run" - | "read" - | "write" - | "net" - | "env" - | "sys" - | "ffi" - | "hrtime"; - - /** The current status of the permission: - * - * - `"granted"` - the permission has been granted. - * - `"denied"` - the permission has been explicitly denied. - * - `"prompt"` - the permission has not explicitly granted nor denied. - * - * @category Permissions - */ - export type PermissionState = "granted" | "denied" | "prompt"; - - /** The permission descriptor for the `allow-run` permission, which controls - * access to what sub-processes can be executed by Deno. The option `command` - * allows scoping the permission to a specific executable. - * - * **Warning, in practice, `allow-run` is effectively the same as `allow-all` - * in the sense that malicious code could execute any arbitrary code on the - * host.** - * - * @category Permissions */ - export interface RunPermissionDescriptor { - name: "run"; - /** The `allow-run` permission can be scoped to a specific executable, - * which would be relative to the start-up CWD of the Deno CLI. */ - command?: string | URL; - } - - /** The permission descriptor for the `allow-read` permissions, which controls - * access to reading resources from the local host. The option `path` allows - * scoping the permission to a specific path (and if the path is a directory - * any sub paths). - * - * Permission granted under `allow-read` only allows runtime code to attempt - * to read, the underlying operating system may apply additional permissions. - * - * @category Permissions */ - export interface ReadPermissionDescriptor { - name: "read"; - /** The `allow-read` permission can be scoped to a specific path (and if - * the path is a directory, any sub paths). */ - path?: string | URL; - } - - /** The permission descriptor for the `allow-write` permissions, which - * controls access to writing to resources from the local host. The option - * `path` allow scoping the permission to a specific path (and if the path is - * a directory any sub paths). - * - * Permission granted under `allow-write` only allows runtime code to attempt - * to write, the underlying operating system may apply additional permissions. - * - * @category Permissions */ - export interface WritePermissionDescriptor { - name: "write"; - /** The `allow-write` permission can be scoped to a specific path (and if - * the path is a directory, any sub paths). */ - path?: string | URL; - } - - /** The permission descriptor for the `allow-net` permissions, which controls - * access to opening network ports and connecting to remote hosts via the - * network. The option `host` allows scoping the permission for outbound - * connection to a specific host and port. - * - * @category Permissions */ - export interface NetPermissionDescriptor { - name: "net"; - /** Optional host string of the form `"[:]"`. Examples: - * - * "github.com" - * "deno.land:8080" - */ - host?: string; - } - - /** The permission descriptor for the `allow-env` permissions, which controls - * access to being able to read and write to the process environment variables - * as well as access other information about the environment. The option - * `variable` allows scoping the permission to a specific environment - * variable. - * - * @category Permissions */ - export interface EnvPermissionDescriptor { - name: "env"; - /** Optional environment variable name (e.g. `PATH`). */ - variable?: string; - } - - /** The permission descriptor for the `allow-sys` permissions, which controls - * access to sensitive host system information, which malicious code might - * attempt to exploit. The option `kind` allows scoping the permission to a - * specific piece of information. - * - * @category Permissions */ - export interface SysPermissionDescriptor { - name: "sys"; - /** The specific information to scope the permission to. */ - kind?: - | "loadavg" - | "hostname" - | "systemMemoryInfo" - | "networkInterfaces" - | "osRelease" - | "osUptime" - | "uid" - | "gid"; - } - - /** The permission descriptor for the `allow-ffi` permissions, which controls - * access to loading _foreign_ code and interfacing with it via the - * [Foreign Function Interface API](https://deno.land/manual/runtime/ffi_api) - * available in Deno. The option `path` allows scoping the permission to a - * specific path on the host. - * - * @category Permissions */ - export interface FfiPermissionDescriptor { - name: "ffi"; - /** Optional path on the local host to scope the permission to. */ - path?: string | URL; - } - - /** The permission descriptor for the `allow-hrtime` permission, which - * controls if the runtime code has access to high resolution time. High - * resolution time is consider sensitive information, because it can be used - * by malicious code to gain information about the host that it might - * otherwise have access to. - * - * @category Permissions */ - export interface HrtimePermissionDescriptor { - name: "hrtime"; - } - - /** Permission descriptors which define a permission and can be queried, - * requested, or revoked. - * - * View the specifics of the individual descriptors for more information about - * each permission kind. - * - * @category Permissions - */ - export type PermissionDescriptor = - | RunPermissionDescriptor - | ReadPermissionDescriptor - | WritePermissionDescriptor - | NetPermissionDescriptor - | EnvPermissionDescriptor - | SysPermissionDescriptor - | FfiPermissionDescriptor - | HrtimePermissionDescriptor; - - /** The interface which defines what event types are supported by - * {@linkcode PermissionStatus} instances. - * - * @category Permissions */ - export interface PermissionStatusEventMap { - "change": Event; - } - - /** An {@linkcode EventTarget} returned from the {@linkcode Deno.permissions} - * API which can provide updates to any state changes of the permission. - * - * @category Permissions */ - export class PermissionStatus extends EventTarget { - // deno-lint-ignore no-explicit-any - onchange: ((this: PermissionStatus, ev: Event) => any) | null; - readonly state: PermissionState; - addEventListener( - type: K, - listener: ( - this: PermissionStatus, - ev: PermissionStatusEventMap[K], - ) => any, - options?: boolean | AddEventListenerOptions, - ): void; - addEventListener( - type: string, - listener: EventListenerOrEventListenerObject, - options?: boolean | AddEventListenerOptions, - ): void; - removeEventListener( - type: K, - listener: ( - this: PermissionStatus, - ev: PermissionStatusEventMap[K], - ) => any, - options?: boolean | EventListenerOptions, - ): void; - removeEventListener( - type: string, - listener: EventListenerOrEventListenerObject, - options?: boolean | EventListenerOptions, - ): void; - } - - /** - * Deno's permission management API. - * - * The class which provides the interface for the {@linkcode Deno.permissions} - * global instance and is based on the web platform - * [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API), - * though some proposed parts of the API which are useful in a server side - * runtime context were removed or abandoned in the web platform specification - * which is why it was chosen to locate it in the {@linkcode Deno} namespace - * instead. - * - * By default, if the `stdin`/`stdout` is TTY for the Deno CLI (meaning it can - * send and receive text), then the CLI will prompt the user to grant - * permission when an un-granted permission is requested. This behavior can - * be changed by using the `--no-prompt` command at startup. When prompting - * the CLI will request the narrowest permission possible, potentially making - * it annoying to the user. The permissions APIs allow the code author to - * request a wider set of permissions at one time in order to provide a better - * user experience. - * - * @category Permissions */ - export class Permissions { - /** Resolves to the current status of a permission. - * - * Note, if the permission is already granted, `request()` will not prompt - * the user again, therefore `query()` is only necessary if you are going - * to react differently existing permissions without wanting to modify them - * or prompt the user to modify them. - * - * ```ts - * const status = await Deno.permissions.query({ name: "read", path: "/etc" }); - * console.log(status.state); - * ``` - */ - query(desc: PermissionDescriptor): Promise; - - /** Returns the current status of a permission. - * - * Note, if the permission is already granted, `request()` will not prompt - * the user again, therefore `querySync()` is only necessary if you are going - * to react differently existing permissions without wanting to modify them - * or prompt the user to modify them. - * - * ```ts - * const status = Deno.permissions.querySync({ name: "read", path: "/etc" }); - * console.log(status.state); - * ``` - */ - querySync(desc: PermissionDescriptor): PermissionStatus; - - /** Revokes a permission, and resolves to the state of the permission. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * - * const status = await Deno.permissions.revoke({ name: "run" }); - * assert(status.state !== "granted") - * ``` - */ - revoke(desc: PermissionDescriptor): Promise; - - /** Revokes a permission, and returns the state of the permission. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * - * const status = Deno.permissions.revokeSync({ name: "run" }); - * assert(status.state !== "granted") - * ``` - */ - revokeSync(desc: PermissionDescriptor): PermissionStatus; - - /** Requests the permission, and resolves to the state of the permission. - * - * If the permission is already granted, the user will not be prompted to - * grant the permission again. - * - * ```ts - * const status = await Deno.permissions.request({ name: "env" }); - * if (status.state === "granted") { - * console.log("'env' permission is granted."); - * } else { - * console.log("'env' permission is denied."); - * } - * ``` - */ - request(desc: PermissionDescriptor): Promise; - - - /** Requests the permission, and returns the state of the permission. - * - * If the permission is already granted, the user will not be prompted to - * grant the permission again. - * - * ```ts - * const status = Deno.permissions.requestSync({ name: "env" }); - * if (status.state === "granted") { - * console.log("'env' permission is granted."); - * } else { - * console.log("'env' permission is denied."); - * } - * ``` - */ - requestSync(desc: PermissionDescriptor): PermissionStatus; - } - - /** Deno's permission management API. - * - * It is a singleton instance of the {@linkcode Permissions} object and is - * based on the web platform - * [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API), - * though some proposed parts of the API which are useful in a server side - * runtime context were removed or abandoned in the web platform specification - * which is why it was chosen to locate it in the {@linkcode Deno} namespace - * instead. - * - * By default, if the `stdin`/`stdout` is TTY for the Deno CLI (meaning it can - * send and receive text), then the CLI will prompt the user to grant - * permission when an un-granted permission is requested. This behavior can - * be changed by using the `--no-prompt` command at startup. When prompting - * the CLI will request the narrowest permission possible, potentially making - * it annoying to the user. The permissions APIs allow the code author to - * request a wider set of permissions at one time in order to provide a better - * user experience. - * - * Requesting already granted permissions will not prompt the user and will - * return that the permission was granted. - * - * ### Querying - * - * ```ts - * const status = await Deno.permissions.query({ name: "read", path: "/etc" }); - * console.log(status.state); - * ``` - * - * ```ts - * const status = Deno.permissions.querySync({ name: "read", path: "/etc" }); - * console.log(status.state); - * ``` - * - * ### Revoking - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * - * const status = await Deno.permissions.revoke({ name: "run" }); - * assert(status.state !== "granted") - * ``` - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * - * const status = Deno.permissions.revokeSync({ name: "run" }); - * assert(status.state !== "granted") - * ``` - * - * ### Requesting - * - * ```ts - * const status = await Deno.permissions.request({ name: "env" }); - * if (status.state === "granted") { - * console.log("'env' permission is granted."); - * } else { - * console.log("'env' permission is denied."); - * } - * ``` - * - * ```ts - * const status = Deno.permissions.requestSync({ name: "env" }); - * if (status.state === "granted") { - * console.log("'env' permission is granted."); - * } else { - * console.log("'env' permission is denied."); - * } - * ``` - * - * @category Permissions - */ - export const permissions: Permissions; - - /** Information related to the build of the current Deno runtime. - * - * Users are discouraged from code branching based on this information, as - * assumptions about what is available in what build environment might change - * over time. Developers should specifically sniff out the features they - * intend to use. - * - * The intended use for the information is for logging and debugging purposes. - * - * @category Runtime Environment - */ - export const build: { - /** The [LLVM](https://llvm.org/) target triple, which is the combination - * of `${arch}-${vendor}-${os}` and represent the specific build target that - * the current runtime was built for. */ - target: string; - /** Instruction set architecture that the Deno CLI was built for. */ - arch: "x86_64" | "aarch64"; - /** The operating system that the Deno CLI was built for. `"darwin"` is - * also known as OSX or MacOS. */ - os: "darwin" | "linux" | "windows" | "freebsd" | "netbsd" | "aix" | "solaris" | "illumos"; - /** The computer vendor that the Deno CLI was built for. */ - vendor: string; - /** Optional environment flags that were set for this build of Deno CLI. */ - env?: string; - }; - - /** Version information related to the current Deno CLI runtime environment. - * - * Users are discouraged from code branching based on this information, as - * assumptions about what is available in what build environment might change - * over time. Developers should specifically sniff out the features they - * intend to use. - * - * The intended use for the information is for logging and debugging purposes. - * - * @category Runtime Environment - */ - export const version: { - /** Deno CLI's version. For example: `"1.26.0"`. */ - deno: string; - /** The V8 version used by Deno. For example: `"10.7.100.0"`. - * - * V8 is the underlying JavaScript runtime platform that Deno is built on - * top of. */ - v8: string; - /** The TypeScript version used by Deno. For example: `"4.8.3"`. - * - * A version of the TypeScript type checker and language server is built-in - * to the Deno CLI. */ - typescript: string; - }; - - /** Returns the script arguments to the program. - * - * Give the following command line invocation of Deno: - * - * ```sh - * deno run --allow-read https://deno.land/std/examples/cat.ts /etc/passwd - * ``` - * - * Then `Deno.args` will contain: - * - * ```ts - * [ "/etc/passwd" ] - * ``` - * - * If you are looking for a structured way to parse arguments, there is the - * [`std/flags`](https://deno.land/std/flags) module as part of the Deno - * standard library. - * - * @category Runtime Environment - */ - export const args: string[]; - - /** - * A symbol which can be used as a key for a custom method which will be - * called when `Deno.inspect()` is called, or when the object is logged to - * the console. - * - * @deprecated This symbol is deprecated since 1.9. Use - * `Symbol.for("Deno.customInspect")` instead. - * - * @category Console and Debugging - */ - export const customInspect: unique symbol; - - /** The URL of the entrypoint module entered from the command-line. It - * requires read permission to the CWD. - * - * Also see {@linkcode ImportMeta} for other related information. - * - * @tags allow-read - * @category Runtime Environment - */ - export const mainModule: string; - - /** Options that can be used with {@linkcode symlink} and - * {@linkcode symlinkSync}. - * - * @category File System */ - export interface SymlinkOptions { - /** If the symbolic link should be either a file or directory. This option - * only applies to Windows and is ignored on other operating systems. */ - type: "file" | "dir"; - } - - /** - * Creates `newpath` as a symbolic link to `oldpath`. - * - * The `options.type` parameter can be set to `"file"` or `"dir"`. This - * argument is only available on Windows and ignored on other platforms. - * - * ```ts - * await Deno.symlink("old/name", "new/name"); - * ``` - * - * Requires full `allow-read` and `allow-write` permissions. - * - * @tags allow-read, allow-write - * @category File System - */ - export function symlink( - oldpath: string | URL, - newpath: string | URL, - options?: SymlinkOptions, - ): Promise; - - /** - * Creates `newpath` as a symbolic link to `oldpath`. - * - * The `options.type` parameter can be set to `"file"` or `"dir"`. This - * argument is only available on Windows and ignored on other platforms. - * - * ```ts - * Deno.symlinkSync("old/name", "new/name"); - * ``` - * - * Requires full `allow-read` and `allow-write` permissions. - * - * @tags allow-read, allow-write - * @category File System - */ - export function symlinkSync( - oldpath: string | URL, - newpath: string | URL, - options?: SymlinkOptions, - ): void; - - /** - * Truncates or extends the specified file stream, to reach the specified - * `len`. - * - * If `len` is not specified then the entire file contents are truncated as if - * `len` was set to `0`. - * - * If the file previously was larger than this new length, the extra data is - * lost. - * - * If the file previously was shorter, it is extended, and the extended part - * reads as null bytes ('\0'). - * - * ### Truncate the entire file - * - * ```ts - * const file = await Deno.open( - * "my_file.txt", - * { read: true, write: true, create: true } - * ); - * await Deno.ftruncate(file.rid); - * ``` - * - * ### Truncate part of the file - * - * ```ts - * const file = await Deno.open( - * "my_file.txt", - * { read: true, write: true, create: true } - * ); - * await Deno.write(file.rid, new TextEncoder().encode("Hello World")); - * await Deno.ftruncate(file.rid, 7); - * const data = new Uint8Array(32); - * await Deno.read(file.rid, data); - * console.log(new TextDecoder().decode(data)); // Hello W - * ``` - * - * @category File System - */ - export function ftruncate(rid: number, len?: number): Promise; - - /** - * Synchronously truncates or extends the specified file stream, to reach the - * specified `len`. - * - * If `len` is not specified then the entire file contents are truncated as if - * `len` was set to `0`. - * - * If the file previously was larger than this new length, the extra data is - * lost. - * - * If the file previously was shorter, it is extended, and the extended part - * reads as null bytes ('\0'). - * - * ### Truncate the entire file - * - * ```ts - * const file = Deno.openSync( - * "my_file.txt", - * { read: true, write: true, truncate: true, create: true } - * ); - * Deno.ftruncateSync(file.rid); - * ``` - * - * ### Truncate part of the file - * - * ```ts - * const file = Deno.openSync( - * "my_file.txt", - * { read: true, write: true, create: true } - * ); - * Deno.writeSync(file.rid, new TextEncoder().encode("Hello World")); - * Deno.ftruncateSync(file.rid, 7); - * Deno.seekSync(file.rid, 0, Deno.SeekMode.Start); - * const data = new Uint8Array(32); - * Deno.readSync(file.rid, data); - * console.log(new TextDecoder().decode(data)); // Hello W - * ``` - * - * @category File System - */ - export function ftruncateSync(rid: number, len?: number): void; - - /** - * Synchronously changes the access (`atime`) and modification (`mtime`) times - * of a file stream resource referenced by `rid`. Given times are either in - * seconds (UNIX epoch time) or as `Date` objects. - * - * ```ts - * const file = Deno.openSync("file.txt", { create: true, write: true }); - * Deno.futimeSync(file.rid, 1556495550, new Date()); - * ``` - * - * @category File System - */ - export function futimeSync( - rid: number, - atime: number | Date, - mtime: number | Date, - ): void; - - /** - * Changes the access (`atime`) and modification (`mtime`) times of a file - * stream resource referenced by `rid`. Given times are either in seconds - * (UNIX epoch time) or as `Date` objects. - * - * ```ts - * const file = await Deno.open("file.txt", { create: true, write: true }); - * await Deno.futime(file.rid, 1556495550, new Date()); - * ``` - * - * @category File System - */ - export function futime( - rid: number, - atime: number | Date, - mtime: number | Date, - ): Promise; - - /** - * Returns a `Deno.FileInfo` for the given file stream. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * - * const file = await Deno.open("file.txt", { read: true }); - * const fileInfo = await Deno.fstat(file.rid); - * assert(fileInfo.isFile); - * ``` - * - * @category File System - */ - export function fstat(rid: number): Promise; - - /** - * Synchronously returns a {@linkcode Deno.FileInfo} for the given file - * stream. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * - * const file = Deno.openSync("file.txt", { read: true }); - * const fileInfo = Deno.fstatSync(file.rid); - * assert(fileInfo.isFile); - * ``` - * - * @category File System - */ - export function fstatSync(rid: number): FileInfo; - - /** - * Synchronously changes the access (`atime`) and modification (`mtime`) times - * of a file system object referenced by `path`. Given times are either in - * seconds (UNIX epoch time) or as `Date` objects. - * - * ```ts - * Deno.utimeSync("myfile.txt", 1556495550, new Date()); - * ``` - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function utimeSync( - path: string | URL, - atime: number | Date, - mtime: number | Date, - ): void; - - /** - * Changes the access (`atime`) and modification (`mtime`) times of a file - * system object referenced by `path`. Given times are either in seconds - * (UNIX epoch time) or as `Date` objects. - * - * ```ts - * await Deno.utime("myfile.txt", 1556495550, new Date()); - * ``` - * - * Requires `allow-write` permission. - * - * @tags allow-write - * @category File System - */ - export function utime( - path: string | URL, - atime: number | Date, - mtime: number | Date, - ): Promise; - - /** The event yielded from an {@linkcode HttpConn} which represents an HTTP - * request from a remote client. - * - * @category HTTP Server */ - export interface RequestEvent { - /** The request from the client in the form of the web platform - * {@linkcode Request}. */ - readonly request: Request; - /** The method to be used to respond to the event. The response needs to - * either be an instance of {@linkcode Response} or a promise that resolves - * with an instance of `Response`. - * - * When the response is successfully processed then the promise returned - * will be resolved. If there are any issues with sending the response, - * the promise will be rejected. */ - respondWith(r: Response | PromiseLike): Promise; - } - - /** The async iterable that is returned from {@linkcode Deno.serveHttp} which - * yields up {@linkcode RequestEvent} events, representing individual - * requests on the HTTP server connection. - * - * @category HTTP Server */ - export interface HttpConn extends AsyncIterable { - /** The resource ID associated with this connection. Generally users do not - * need to be aware of this identifier. */ - readonly rid: number; - - /** An alternative to the async iterable interface which provides promises - * which resolve with either a {@linkcode RequestEvent} when there is - * another request or `null` when the client has closed the connection. */ - nextRequest(): Promise; - /** Initiate a server side closure of the connection, indicating to the - * client that you refuse to accept any more requests on this connection. - * - * Typically the client closes the connection, which will result in the - * async iterable terminating or the `nextRequest()` method returning - * `null`. */ - close(): void; - } - - /** - * Provides an interface to handle HTTP request and responses over TCP or TLS - * connections. The method returns an {@linkcode HttpConn} which yields up - * {@linkcode RequestEvent} events, which utilize the web platform standard - * {@linkcode Request} and {@linkcode Response} objects to handle the request. - * - * ```ts - * const conn = Deno.listen({ port: 80 }); - * const httpConn = Deno.serveHttp(await conn.accept()); - * const e = await httpConn.nextRequest(); - * if (e) { - * e.respondWith(new Response("Hello World")); - * } - * ``` - * - * Alternatively, you can also use the async iterator approach: - * - * ```ts - * async function handleHttp(conn: Deno.Conn) { - * for await (const e of Deno.serveHttp(conn)) { - * e.respondWith(new Response("Hello World")); - * } - * } - * - * for await (const conn of Deno.listen({ port: 80 })) { - * handleHttp(conn); - * } - * ``` - * - * If `httpConn.nextRequest()` encounters an error or returns `null` then the - * underlying {@linkcode HttpConn} resource is closed automatically. - * - * Also see the experimental Flash HTTP server {@linkcode Deno.serve} which - * provides a ground up rewrite of handling of HTTP requests and responses - * within the Deno CLI. - * - * Note that this function *consumes* the given connection passed to it, thus - * the original connection will be unusable after calling this. Additionally, - * you need to ensure that the connection is not being used elsewhere when - * calling this function in order for the connection to be consumed properly. - * - * For instance, if there is a `Promise` that is waiting for read operation on - * the connection to complete, it is considered that the connection is being - * used elsewhere. In such a case, this function will fail. - * - * @category HTTP Server - */ - export function serveHttp(conn: Conn): HttpConn; - - /** The object that is returned from a {@linkcode Deno.upgradeWebSocket} - * request. - * - * @category Web Sockets */ - export interface WebSocketUpgrade { - /** The response object that represents the HTTP response to the client, - * which should be used to the {@linkcode RequestEvent} `.respondWith()` for - * the upgrade to be successful. */ - response: Response; - /** The {@linkcode WebSocket} interface to communicate to the client via a - * web socket. */ - socket: WebSocket; - } - - /** Options which can be set when performing a - * {@linkcode Deno.upgradeWebSocket} upgrade of a {@linkcode Request} - * - * @category Web Sockets */ - export interface UpgradeWebSocketOptions { - /** Sets the `.protocol` property on the client side web socket to the - * value provided here, which should be one of the strings specified in the - * `protocols` parameter when requesting the web socket. This is intended - * for clients and servers to specify sub-protocols to use to communicate to - * each other. */ - protocol?: string; - /** If the client does not respond to this frame with a - * `pong` within the timeout specified, the connection is deemed - * unhealthy and is closed. The `close` and `error` event will be emitted. - * - * The default is 120 seconds. Set to `0` to disable timeouts. */ - idleTimeout?: number; - } - - /** - * Upgrade an incoming HTTP request to a WebSocket. - * - * Given a {@linkcode Request}, returns a pair of {@linkcode WebSocket} and - * {@linkcode Response} instances. The original request must be responded to - * with the returned response for the websocket upgrade to be successful. - * - * ```ts - * const conn = Deno.listen({ port: 80 }); - * const httpConn = Deno.serveHttp(await conn.accept()); - * const e = await httpConn.nextRequest(); - * if (e) { - * const { socket, response } = Deno.upgradeWebSocket(e.request); - * socket.onopen = () => { - * socket.send("Hello World!"); - * }; - * socket.onmessage = (e) => { - * console.log(e.data); - * socket.close(); - * }; - * socket.onclose = () => console.log("WebSocket has been closed."); - * socket.onerror = (e) => console.error("WebSocket error:", e); - * e.respondWith(response); - * } - * ``` - * - * If the request body is disturbed (read from) before the upgrade is - * completed, upgrading fails. - * - * This operation does not yet consume the request or open the websocket. This - * only happens once the returned response has been passed to `respondWith()`. - * - * @category Web Sockets - */ - export function upgradeWebSocket( - request: Request, - options?: UpgradeWebSocketOptions, - ): WebSocketUpgrade; - - /** Send a signal to process under given `pid`. The value and meaning of the - * `signal` to the process is operating system and process dependant. - * {@linkcode Signal} provides the most common signals. Default signal - * is `"SIGTERM"`. - * - * The term `kill` is adopted from the UNIX-like command line command `kill` - * which also signals processes. - * - * If `pid` is negative, the signal will be sent to the process group - * identified by `pid`. An error will be thrown if a negative `pid` is used on - * Windows. - * - * ```ts - * const p = Deno.run({ - * cmd: ["sleep", "10000"] - * }); - * - * Deno.kill(p.pid, "SIGINT"); - * ``` - * - * Requires `allow-run` permission. - * - * @tags allow-run - * @category Sub Process - */ - export function kill(pid: number, signo?: Signal): void; - - /** The type of the resource record to resolve via DNS using - * {@linkcode Deno.resolveDns}. - * - * Only the listed types are supported currently. - * - * @category Network - */ - export type RecordType = - | "A" - | "AAAA" - | "ANAME" - | "CAA" - | "CNAME" - | "MX" - | "NAPTR" - | "NS" - | "PTR" - | "SOA" - | "SRV" - | "TXT"; - - /** - * Options which can be set when using {@linkcode Deno.resolveDns}. - * - * @category Network */ - export interface ResolveDnsOptions { - /** The name server to be used for lookups. - * - * If not specified, defaults to the system configuration. For example - * `/etc/resolv.conf` on Unix-like systems. */ - nameServer?: { - /** The IP address of the name server. */ - ipAddr: string; - /** The port number the query will be sent to. - * - * @default {53} */ - port?: number; - }; - /** - * An abort signal to allow cancellation of the DNS resolution operation. - * If the signal becomes aborted the resolveDns operation will be stopped - * and the promise returned will be rejected with an AbortError. - */ - signal?: AbortSignal; - } - - /** If {@linkcode Deno.resolveDns} is called with `"CAA"` record type - * specified, it will resolve with an array of objects with this interface. - * - * @category Network - */ - export interface CAARecord { - /** If `true`, indicates that the corresponding property tag **must** be - * understood if the semantics of the CAA record are to be correctly - * interpreted by an issuer. - * - * Issuers **must not** issue certificates for a domain if the relevant CAA - * Resource Record set contains unknown property tags that have `critical` - * set. */ - critical: boolean; - /** An string that represents the identifier of the property represented by - * the record. */ - tag: string; - /** The value associated with the tag. */ - value: string; - } - - /** If {@linkcode Deno.resolveDns} is called with `"MX"` record type - * specified, it will return an array of objects with this interface. - * - * @category Network */ - export interface MXRecord { - /** A priority value, which is a relative value compared to the other - * preferences of MX records for the domain. */ - preference: number; - /** The server that mail should be delivered to. */ - exchange: string; - } - - /** If {@linkcode Deno.resolveDns} is called with `"NAPTR"` record type - * specified, it will return an array of objects with this interface. - * - * @category Network */ - export interface NAPTRRecord { - order: number; - preference: number; - flags: string; - services: string; - regexp: string; - replacement: string; - } - - /** If {@linkcode Deno.resolveDns} is called with `"SOA"` record type - * specified, it will return an array of objects with this interface. - * - * @category Network */ - export interface SOARecord { - mname: string; - rname: string; - serial: number; - refresh: number; - retry: number; - expire: number; - minimum: number; - } - - /** If {@linkcode Deno.resolveDns} is called with `"SRV"` record type - * specified, it will return an array of objects with this interface. - * - * @category Network - */ - export interface SRVRecord { - priority: number; - weight: number; - port: number; - target: string; - } - - /** - * Performs DNS resolution against the given query, returning resolved - * records. - * - * Fails in the cases such as: - * - * - the query is in invalid format. - * - the options have an invalid parameter. For example `nameServer.port` is - * beyond the range of 16-bit unsigned integer. - * - the request timed out. - * - * ```ts - * const a = await Deno.resolveDns("example.com", "A"); - * - * const aaaa = await Deno.resolveDns("example.com", "AAAA", { - * nameServer: { ipAddr: "8.8.8.8", port: 53 }, - * }); - * ``` - * - * Requires `allow-net` permission. - * - * @tags allow-net - * @category Network - */ - export function resolveDns( - query: string, - recordType: "A" | "AAAA" | "ANAME" | "CNAME" | "NS" | "PTR", - options?: ResolveDnsOptions, - ): Promise; - - /** - * Performs DNS resolution against the given query, returning resolved - * records. - * - * Fails in the cases such as: - * - * - the query is in invalid format. - * - the options have an invalid parameter. For example `nameServer.port` is - * beyond the range of 16-bit unsigned integer. - * - the request timed out. - * - * ```ts - * const a = await Deno.resolveDns("example.com", "A"); - * - * const aaaa = await Deno.resolveDns("example.com", "AAAA", { - * nameServer: { ipAddr: "8.8.8.8", port: 53 }, - * }); - * ``` - * - * Requires `allow-net` permission. - * - * @tags allow-net - * @category Network - */ - export function resolveDns( - query: string, - recordType: "CAA", - options?: ResolveDnsOptions, - ): Promise; - - /** - * Performs DNS resolution against the given query, returning resolved - * records. - * - * Fails in the cases such as: - * - * - the query is in invalid format. - * - the options have an invalid parameter. For example `nameServer.port` is - * beyond the range of 16-bit unsigned integer. - * - the request timed out. - * - * ```ts - * const a = await Deno.resolveDns("example.com", "A"); - * - * const aaaa = await Deno.resolveDns("example.com", "AAAA", { - * nameServer: { ipAddr: "8.8.8.8", port: 53 }, - * }); - * ``` - * - * Requires `allow-net` permission. - * - * @tags allow-net - * @category Network - */ - export function resolveDns( - query: string, - recordType: "MX", - options?: ResolveDnsOptions, - ): Promise; - - /** - * Performs DNS resolution against the given query, returning resolved - * records. - * - * Fails in the cases such as: - * - * - the query is in invalid format. - * - the options have an invalid parameter. For example `nameServer.port` is - * beyond the range of 16-bit unsigned integer. - * - the request timed out. - * - * ```ts - * const a = await Deno.resolveDns("example.com", "A"); - * - * const aaaa = await Deno.resolveDns("example.com", "AAAA", { - * nameServer: { ipAddr: "8.8.8.8", port: 53 }, - * }); - * ``` - * - * Requires `allow-net` permission. - * - * @tags allow-net - * @category Network - */ - export function resolveDns( - query: string, - recordType: "NAPTR", - options?: ResolveDnsOptions, - ): Promise; - - /** - * Performs DNS resolution against the given query, returning resolved - * records. - * - * Fails in the cases such as: - * - * - the query is in invalid format. - * - the options have an invalid parameter. For example `nameServer.port` is - * beyond the range of 16-bit unsigned integer. - * - the request timed out. - * - * ```ts - * const a = await Deno.resolveDns("example.com", "A"); - * - * const aaaa = await Deno.resolveDns("example.com", "AAAA", { - * nameServer: { ipAddr: "8.8.8.8", port: 53 }, - * }); - * ``` - * - * Requires `allow-net` permission. - * - * @tags allow-net - * @category Network - */ - export function resolveDns( - query: string, - recordType: "SOA", - options?: ResolveDnsOptions, - ): Promise; - - /** - * Performs DNS resolution against the given query, returning resolved - * records. - * - * Fails in the cases such as: - * - * - the query is in invalid format. - * - the options have an invalid parameter. For example `nameServer.port` is - * beyond the range of 16-bit unsigned integer. - * - the request timed out. - * - * ```ts - * const a = await Deno.resolveDns("example.com", "A"); - * - * const aaaa = await Deno.resolveDns("example.com", "AAAA", { - * nameServer: { ipAddr: "8.8.8.8", port: 53 }, - * }); - * ``` - * - * Requires `allow-net` permission. - * - * @tags allow-net - * @category Network - */ - export function resolveDns( - query: string, - recordType: "SRV", - options?: ResolveDnsOptions, - ): Promise; - - /** - * Performs DNS resolution against the given query, returning resolved - * records. - * - * Fails in the cases such as: - * - * - the query is in invalid format. - * - the options have an invalid parameter. For example `nameServer.port` is - * beyond the range of 16-bit unsigned integer. - * - the request timed out. - * - * ```ts - * const a = await Deno.resolveDns("example.com", "A"); - * - * const aaaa = await Deno.resolveDns("example.com", "AAAA", { - * nameServer: { ipAddr: "8.8.8.8", port: 53 }, - * }); - * ``` - * - * Requires `allow-net` permission. - * - * @tags allow-net - * @category Network - */ - export function resolveDns( - query: string, - recordType: "TXT", - options?: ResolveDnsOptions, - ): Promise; - - /** - * Performs DNS resolution against the given query, returning resolved - * records. - * - * Fails in the cases such as: - * - * - the query is in invalid format. - * - the options have an invalid parameter. For example `nameServer.port` is - * beyond the range of 16-bit unsigned integer. - * - the request timed out. - * - * ```ts - * const a = await Deno.resolveDns("example.com", "A"); - * - * const aaaa = await Deno.resolveDns("example.com", "AAAA", { - * nameServer: { ipAddr: "8.8.8.8", port: 53 }, - * }); - * ``` - * - * Requires `allow-net` permission. - * - * @tags allow-net - * @category Network - */ - export function resolveDns( - query: string, - recordType: RecordType, - options?: ResolveDnsOptions, - ): Promise< - | string[] - | CAARecord[] - | MXRecord[] - | NAPTRRecord[] - | SOARecord[] - | SRVRecord[] - | string[][] - >; - - /** - * Make the timer of the given `id` block the event loop from finishing. - * - * @category Timers - */ - export function refTimer(id: number): void; - - /** - * Make the timer of the given `id` not block the event loop from finishing. - * - * @category Timers - */ - export function unrefTimer(id: number): void; - - /** - * Returns the user id of the process on POSIX platforms. Returns null on Windows. - * - * ```ts - * console.log(Deno.uid()); - * ``` - * - * Requires `allow-sys` permission. - * - * @tags allow-sys - * @category Runtime Environment - */ - export function uid(): number | null; - - /** - * Returns the group id of the process on POSIX platforms. Returns null on windows. - * - * ```ts - * console.log(Deno.gid()); - * ``` - * - * Requires `allow-sys` permission. - * - * @tags allow-sys - * @category Runtime Environment - */ - export function gid(): number | null; -} - -// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. - -// deno-lint-ignore-file no-explicit-any - -/// -/// - -/** @category Console and Debugging */ -declare interface Console { - assert(condition?: boolean, ...data: any[]): void; - clear(): void; - count(label?: string): void; - countReset(label?: string): void; - debug(...data: any[]): void; - dir(item?: any, options?: any): void; - dirxml(...data: any[]): void; - error(...data: any[]): void; - group(...data: any[]): void; - groupCollapsed(...data: any[]): void; - groupEnd(): void; - info(...data: any[]): void; - log(...data: any[]): void; - table(tabularData?: any, properties?: string[]): void; - time(label?: string): void; - timeEnd(label?: string): void; - timeLog(label?: string, ...data: any[]): void; - trace(...data: any[]): void; - warn(...data: any[]): void; - - /** This method is a noop, unless used in inspector */ - timeStamp(label?: string): void; - - /** This method is a noop, unless used in inspector */ - profile(label?: string): void; - - /** This method is a noop, unless used in inspector */ - profileEnd(label?: string): void; -} - -// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. - -// deno-lint-ignore-file no-explicit-any - -/// -/// - -/** @category Web APIs */ -declare class URLSearchParams { - constructor( - init?: string[][] | Record | string | URLSearchParams, - ); - static toString(): string; - - /** Appends a specified key/value pair as a new search parameter. - * - * ```ts - * let searchParams = new URLSearchParams(); - * searchParams.append('name', 'first'); - * searchParams.append('name', 'second'); - * ``` - */ - append(name: string, value: string): void; - - /** Deletes the given search parameter and its associated value, - * from the list of all search parameters. - * - * ```ts - * let searchParams = new URLSearchParams([['name', 'value']]); - * searchParams.delete('name'); - * ``` - */ - delete(name: string): void; - - /** Returns all the values associated with a given search parameter - * as an array. - * - * ```ts - * searchParams.getAll('name'); - * ``` - */ - getAll(name: string): string[]; - - /** Returns the first value associated to the given search parameter. - * - * ```ts - * searchParams.get('name'); - * ``` - */ - get(name: string): string | null; - - /** Returns a Boolean that indicates whether a parameter with the - * specified name exists. - * - * ```ts - * searchParams.has('name'); - * ``` - */ - has(name: string): boolean; - - /** Sets the value associated with a given search parameter to the - * given value. If there were several matching values, this method - * deletes the others. If the search parameter doesn't exist, this - * method creates it. - * - * ```ts - * searchParams.set('name', 'value'); - * ``` - */ - set(name: string, value: string): void; - - /** Sort all key/value pairs contained in this object in place and - * return undefined. The sort order is according to Unicode code - * points of the keys. - * - * ```ts - * searchParams.sort(); - * ``` - */ - sort(): void; - - /** Calls a function for each element contained in this object in - * place and return undefined. Optionally accepts an object to use - * as this when executing callback as second argument. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * params.forEach((value, key, parent) => { - * console.log(value, key, parent); - * }); - * ``` - */ - forEach( - callbackfn: (value: string, key: string, parent: this) => void, - thisArg?: any, - ): void; - - /** Returns an iterator allowing to go through all keys contained - * in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const key of params.keys()) { - * console.log(key); - * } - * ``` - */ - keys(): IterableIterator; - - /** Returns an iterator allowing to go through all values contained - * in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const value of params.values()) { - * console.log(value); - * } - * ``` - */ - values(): IterableIterator; - - /** Returns an iterator allowing to go through all key/value - * pairs contained in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const [key, value] of params.entries()) { - * console.log(key, value); - * } - * ``` - */ - entries(): IterableIterator<[string, string]>; - - /** Returns an iterator allowing to go through all key/value - * pairs contained in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const [key, value] of params) { - * console.log(key, value); - * } - * ``` - */ - [Symbol.iterator](): IterableIterator<[string, string]>; - - /** Returns a query string suitable for use in a URL. - * - * ```ts - * searchParams.toString(); - * ``` - */ - toString(): string; -} - -/** The URL interface represents an object providing static methods used for - * creating object URLs. - * - * @category Web APIs - */ -declare class URL { - constructor(url: string | URL, base?: string | URL); - static createObjectURL(blob: Blob): string; - static revokeObjectURL(url: string): void; - - hash: string; - host: string; - hostname: string; - href: string; - toString(): string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - readonly searchParams: URLSearchParams; - username: string; - toJSON(): string; -} - -/** @category Web APIs */ -declare interface URLPatternInit { - protocol?: string; - username?: string; - password?: string; - hostname?: string; - port?: string; - pathname?: string; - search?: string; - hash?: string; - baseURL?: string; -} - -/** @category Web APIs */ -declare type URLPatternInput = string | URLPatternInit; - -/** @category Web APIs */ -declare interface URLPatternComponentResult { - input: string; - groups: Record; -} - -/** `URLPatternResult` is the object returned from `URLPattern.exec`. - * - * @category Web APIs - */ -declare interface URLPatternResult { - /** The inputs provided when matching. */ - inputs: [URLPatternInit] | [URLPatternInit, string]; - - /** The matched result for the `protocol` matcher. */ - protocol: URLPatternComponentResult; - /** The matched result for the `username` matcher. */ - username: URLPatternComponentResult; - /** The matched result for the `password` matcher. */ - password: URLPatternComponentResult; - /** The matched result for the `hostname` matcher. */ - hostname: URLPatternComponentResult; - /** The matched result for the `port` matcher. */ - port: URLPatternComponentResult; - /** The matched result for the `pathname` matcher. */ - pathname: URLPatternComponentResult; - /** The matched result for the `search` matcher. */ - search: URLPatternComponentResult; - /** The matched result for the `hash` matcher. */ - hash: URLPatternComponentResult; -} - -/** - * The URLPattern API provides a web platform primitive for matching URLs based - * on a convenient pattern syntax. - * - * The syntax is based on path-to-regexp. Wildcards, named capture groups, - * regular groups, and group modifiers are all supported. - * - * ```ts - * // Specify the pattern as structured data. - * const pattern = new URLPattern({ pathname: "/users/:user" }); - * const match = pattern.exec("https://blog.example.com/users/joe"); - * console.log(match.pathname.groups.user); // joe - * ``` - * - * ```ts - * // Specify a fully qualified string pattern. - * const pattern = new URLPattern("https://example.com/books/:id"); - * console.log(pattern.test("https://example.com/books/123")); // true - * console.log(pattern.test("https://deno.land/books/123")); // false - * ``` - * - * ```ts - * // Specify a relative string pattern with a base URL. - * const pattern = new URLPattern("/article/:id", "https://blog.example.com"); - * console.log(pattern.test("https://blog.example.com/article")); // false - * console.log(pattern.test("https://blog.example.com/article/123")); // true - * ``` - * - * @category Web APIs - */ -declare class URLPattern { - constructor(input: URLPatternInput, baseURL?: string); - - /** - * Test if the given input matches the stored pattern. - * - * The input can either be provided as an absolute URL string with an optional base, - * relative URL string with a required base, or as individual components - * in the form of an `URLPatternInit` object. - * - * ```ts - * const pattern = new URLPattern("https://example.com/books/:id"); - * - * // Test an absolute url string. - * console.log(pattern.test("https://example.com/books/123")); // true - * - * // Test a relative url with a base. - * console.log(pattern.test("/books/123", "https://example.com")); // true - * - * // Test an object of url components. - * console.log(pattern.test({ pathname: "/books/123" })); // true - * ``` - */ - test(input: URLPatternInput, baseURL?: string): boolean; - - /** - * Match the given input against the stored pattern. - * - * The input can either be provided as an absolute URL string with an optional base, - * relative URL string with a required base, or as individual components - * in the form of an `URLPatternInit` object. - * - * ```ts - * const pattern = new URLPattern("https://example.com/books/:id"); - * - * // Match an absolute url string. - * let match = pattern.exec("https://example.com/books/123"); - * console.log(match.pathname.groups.id); // 123 - * - * // Match a relative url with a base. - * match = pattern.exec("/books/123", "https://example.com"); - * console.log(match.pathname.groups.id); // 123 - * - * // Match an object of url components. - * match = pattern.exec({ pathname: "/books/123" }); - * console.log(match.pathname.groups.id); // 123 - * ``` - */ - exec(input: URLPatternInput, baseURL?: string): URLPatternResult | null; - - /** The pattern string for the `protocol`. */ - readonly protocol: string; - /** The pattern string for the `username`. */ - readonly username: string; - /** The pattern string for the `password`. */ - readonly password: string; - /** The pattern string for the `hostname`. */ - readonly hostname: string; - /** The pattern string for the `port`. */ - readonly port: string; - /** The pattern string for the `pathname`. */ - readonly pathname: string; - /** The pattern string for the `search`. */ - readonly search: string; - /** The pattern string for the `hash`. */ - readonly hash: string; -} - -// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. - -// deno-lint-ignore-file no-explicit-any no-var - -/// -/// - -/** @category DOM Events */ -declare class DOMException extends Error { - constructor(message?: string, name?: string); - readonly name: string; - readonly message: string; - readonly code: number; -} - -/** @category DOM Events */ -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; -} - -/** An event which takes place in the DOM. - * - * @category DOM Events - */ -declare class Event { - constructor(type: string, eventInitDict?: EventInit); - /** Returns true or false depending on how event was initialized. True if - * event goes through its target's ancestors in reverse tree order, and - * false otherwise. */ - readonly bubbles: boolean; - cancelBubble: boolean; - /** Returns true or false depending on how event was initialized. Its return - * value does not always carry meaning, but true can indicate that part of the - * operation during which event was dispatched, can be canceled by invoking - * the preventDefault() method. */ - readonly cancelable: boolean; - /** Returns true or false depending on how event was initialized. True if - * event invokes listeners past a ShadowRoot node that is the root of its - * target, and false otherwise. */ - readonly composed: boolean; - /** Returns the object whose event listener's callback is currently being - * invoked. */ - readonly currentTarget: EventTarget | null; - /** Returns true if preventDefault() was invoked successfully to indicate - * cancellation, and false otherwise. */ - readonly defaultPrevented: boolean; - /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, - * AT_TARGET, and BUBBLING_PHASE. */ - readonly eventPhase: number; - /** Returns true if event was dispatched by the user agent, and false - * otherwise. */ - readonly isTrusted: boolean; - /** Returns the object to which event is dispatched (its target). */ - readonly target: EventTarget | null; - /** Returns the event's timestamp as the number of milliseconds measured - * relative to the time origin. */ - readonly timeStamp: number; - /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ - readonly type: string; - /** Returns the invocation target objects of event's path (objects on which - * listeners will be invoked), except for any nodes in shadow trees of which - * the shadow root's mode is "closed" that are not reachable from event's - * currentTarget. */ - composedPath(): EventTarget[]; - /** If invoked when the cancelable attribute value is true, and while - * executing a listener for the event with passive set to false, signals to - * the operation that caused event to be dispatched that it needs to be - * canceled. */ - preventDefault(): void; - /** Invoking this method prevents event from reaching any registered event - * listeners after the current one finishes running and, when dispatched in a - * tree, also prevents event from reaching any other objects. */ - stopImmediatePropagation(): void; - /** When dispatched in a tree, invoking this method prevents event from - * reaching any objects other than the current object. */ - stopPropagation(): void; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; - readonly NONE: number; - static readonly AT_TARGET: number; - static readonly BUBBLING_PHASE: number; - static readonly CAPTURING_PHASE: number; - static readonly NONE: number; -} - -/** - * EventTarget is a DOM interface implemented by objects that can receive events - * and may have listeners for them. - * - * @category DOM Events - */ -declare class EventTarget { - /** Appends an event listener for events whose type attribute value is type. - * The callback argument sets the callback that will be invoked when the event - * is dispatched. - * - * The options argument sets listener-specific options. For compatibility this - * can be a boolean, in which case the method behaves exactly as if the value - * was specified as options's capture. - * - * When set to true, options's capture prevents callback from being invoked - * when the event's eventPhase attribute value is BUBBLING_PHASE. When false - * (or not present), callback will not be invoked when event's eventPhase - * attribute value is CAPTURING_PHASE. Either way, callback will be invoked if - * event's eventPhase attribute value is AT_TARGET. - * - * When set to true, options's passive indicates that the callback will not - * cancel the event by invoking preventDefault(). This is used to enable - * performance optimizations described in § 2.8 Observing event listeners. - * - * When set to true, options's once indicates that the callback will only be - * invoked once after which the event listener will be removed. - * - * The event listener is appended to target's event listener list and is not - * appended if it has the same type, callback, and capture. */ - addEventListener( - type: string, - listener: EventListenerOrEventListenerObject | null, - options?: boolean | AddEventListenerOptions, - ): void; - /** Dispatches a synthetic event event to target and returns true if either - * event's cancelable attribute value is false or its preventDefault() method - * was not invoked, and false otherwise. */ - dispatchEvent(event: Event): boolean; - /** Removes the event listener in target's event listener list with the same - * type, callback, and options. */ - removeEventListener( - type: string, - callback: EventListenerOrEventListenerObject | null, - options?: EventListenerOptions | boolean, - ): void; -} - -/** @category DOM Events */ -interface EventListener { - (evt: Event): void | Promise; -} - -/** @category DOM Events */ -interface EventListenerObject { - handleEvent(evt: Event): void | Promise; -} - -/** @category DOM Events */ -declare type EventListenerOrEventListenerObject = - | EventListener - | EventListenerObject; - -/** @category DOM Events */ -interface AddEventListenerOptions extends EventListenerOptions { - once?: boolean; - passive?: boolean; - signal?: AbortSignal; -} - -/** @category DOM Events */ -interface EventListenerOptions { - capture?: boolean; -} - -/** @category DOM Events */ -interface ProgressEventInit extends EventInit { - lengthComputable?: boolean; - loaded?: number; - total?: number; -} - -/** Events measuring progress of an underlying process, like an HTTP request - * (for an XMLHttpRequest, or the loading of the underlying resource of an - * ,