Файловый менеджер - Редактировать - /home/gqdcvggs/go.imators.com/81b3c76afcd2c892.tar
Назад
package.json 0000664 00000000172 15114743311 0007034 0 ustar 00 { "dependencies": { "heroui-cli": "^1.2.3" }, "_npx": { "packages": [ "heroui-cli@latest" ] } } package-lock.json 0000664 00000073007 15114743311 0007771 0 ustar 00 { "name": "81b3c76afcd2c892", "lockfileVersion": 3, "requires": true, "packages": { "": { "dependencies": { "heroui-cli": "^1.2.3" } }, "node_modules/@clack/core": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/@clack/core/-/core-0.3.5.tgz", "integrity": "sha512-5cfhQNH+1VQ2xLQlmzXMqUoiaH0lRBq9/CLW9lTyMbuKLC3+xEK01tHVvyut++mLOn5urSHmkm6I0Lg9MaJSTQ==", "dependencies": { "picocolors": "^1.0.0", "sisteransi": "^1.0.5" } }, "node_modules/@clack/prompts": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-0.7.0.tgz", "integrity": "sha512-0MhX9/B4iL6Re04jPrttDm+BsP8y6mS7byuv0BvXgdXhbV5PdlsHt55dvNsuBCPZ7xq1oTAOOuotR9NFbQyMSA==", "bundleDependencies": [ "is-unicode-supported" ], "dependencies": { "@clack/core": "^0.3.3", "is-unicode-supported": "*", "picocolors": "^1.0.0", "sisteransi": "^1.0.5" } }, "node_modules/@clack/prompts/node_modules/is-unicode-supported": { "version": "1.3.0", "inBundle": true, "license": "MIT", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" }, "engines": { "node": ">= 8" } }, "node_modules/@nodelib/fs.stat": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", "engines": { "node": ">= 8" } }, "node_modules/@nodelib/fs.walk": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" }, "engines": { "node": ">= 8" } }, "node_modules/@types/tinycolor2": { "version": "1.4.6", "resolved": "https://registry.npmjs.org/@types/tinycolor2/-/tinycolor2-1.4.6.tgz", "integrity": "sha512-iEN8J0BoMnsWBqjVbWH/c0G0Hh7O21lpR2/+PrvAVgWdzL7eexIFm4JN/Wn10PTcmNdtS6U67r499mlWMXOxNw==" }, "node_modules/@winches/prompts": { "version": "0.0.7", "resolved": "https://registry.npmjs.org/@winches/prompts/-/prompts-0.0.7.tgz", "integrity": "sha512-H/UlFlm83C6zkYn3CK4GF2VMpAlyjO3o623yamOyHwSaehhnj7oAJmklvr73UVMqu6Q+rl4Bzs3PBmxGB8cJVg==", "dependencies": { "kleur": "^4.0.1", "sisteransi": "^1.0.5" }, "engines": { "node": ">= 14" } }, "node_modules/ansi-regex": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, "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==", "dependencies": { "color-convert": "^2.0.1" }, "engines": { "node": ">=8" }, "funding": { "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, "node_modules/async-retry": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/async-retry/-/async-retry-1.3.3.tgz", "integrity": "sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw==", "dependencies": { "retry": "0.13.1" } }, "node_modules/braces": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "dependencies": { "fill-range": "^7.1.1" }, "engines": { "node": ">=8" } }, "node_modules/chalk": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", "engines": { "node": "^12.17.0 || ^14.13 || >=16.0.0" }, "funding": { "url": "https://github.com/chalk/chalk?sponsor=1" } }, "node_modules/chownr": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", "engines": { "node": ">=10" } }, "node_modules/cli-cursor": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", "dependencies": { "restore-cursor": "^4.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/cli-spinners": { "version": "2.9.2", "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", "engines": { "node": ">=6" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "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==", "dependencies": { "color-name": "~1.1.4" }, "engines": { "node": ">=7.0.0" } }, "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==" }, "node_modules/commander": { "version": "11.0.0", "resolved": "https://registry.npmjs.org/commander/-/commander-11.0.0.tgz", "integrity": "sha512-9HMlXtt/BNoYr8ooyjjNRdIilOTkVJXB+GhxMTtOKwk0R4j4lS4NpjuqmRxroBfnfTSHQIHQB7wryHhXarNjmQ==", "engines": { "node": ">=16" } }, "node_modules/compare-versions": { "version": "6.1.1", "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz", "integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==" }, "node_modules/emoji-regex": { "version": "10.4.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.4.0.tgz", "integrity": "sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw==" }, "node_modules/fast-glob": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.4" }, "engines": { "node": ">=8.6.0" } }, "node_modules/fastq": { "version": "1.19.1", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", "dependencies": { "reusify": "^1.0.4" } }, "node_modules/fill-range": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "dependencies": { "to-regex-range": "^5.0.1" }, "engines": { "node": ">=8" } }, "node_modules/find-up": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-7.0.0.tgz", "integrity": "sha512-YyZM99iHrqLKjmt4LJDj58KI+fYyufRLBSYcqycxf//KpBk9FoewoGX0450m9nB44qrZnovzC2oeP5hUibxc/g==", "dependencies": { "locate-path": "^7.2.0", "path-exists": "^5.0.0", "unicorn-magic": "^0.1.0" }, "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/fs-minipass": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", "dependencies": { "minipass": "^3.0.0" }, "engines": { "node": ">= 8" } }, "node_modules/fs-minipass/node_modules/minipass": { "version": "3.3.6", "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", "dependencies": { "yallist": "^4.0.0" }, "engines": { "node": ">=8" } }, "node_modules/get-east-asian-width": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.3.0.tgz", "integrity": "sha512-vpeMIQKxczTD/0s2CdEWHcb0eeJe6TFjxb+J5xgX7hScxqrGuyjmv4c1D4A/gelKfyox0gJJwIHF+fLjeaM8kQ==", "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/glob-parent": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dependencies": { "is-glob": "^4.0.1" }, "engines": { "node": ">= 6" } }, "node_modules/gradient-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/gradient-string/-/gradient-string-2.0.2.tgz", "integrity": "sha512-rEDCuqUQ4tbD78TpzsMtt5OIf0cBCSDWSJtUDaF6JsAh+k0v9r++NzxNEG87oDZx9ZwGhD8DaezR2L/yrw0Jdw==", "dependencies": { "chalk": "^4.1.2", "tinygradient": "^1.1.5" }, "engines": { "node": ">=10" } }, "node_modules/gradient-string/node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "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/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "engines": { "node": ">=8" } }, "node_modules/heroui-cli": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/heroui-cli/-/heroui-cli-1.2.3.tgz", "integrity": "sha512-q5Cs+jjogTI5LQLKatQtp1XAn/rpgB30G+IUvVtzwEX4NTl3mNM2RCZzlRvf3mNqltGtiyBq2hoBZyLr/XMl1g==", "dependencies": { "@clack/prompts": "0.7.0", "@winches/prompts": "0.0.7", "async-retry": "1.3.3", "chalk": "5.3.0", "commander": "11.0.0", "compare-versions": "6.1.1", "fast-glob": "3.3.2", "find-up": "7.0.0", "gradient-string": "2.0.2", "ora": "8.0.1", "pathe": "1.1.2", "tar": "6.2.1" }, "bin": { "heroui": "dist/index.js" }, "engines": { "pnpm": ">=9.x" } }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", "engines": { "node": ">=0.10.0" } }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dependencies": { "is-extglob": "^2.1.1" }, "engines": { "node": ">=0.10.0" } }, "node_modules/is-interactive": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "engines": { "node": ">=0.12.0" } }, "node_modules/is-unicode-supported": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/kleur": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", "engines": { "node": ">=6" } }, "node_modules/locate-path": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-7.2.0.tgz", "integrity": "sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==", "dependencies": { "p-locate": "^6.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/log-symbols": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-6.0.0.tgz", "integrity": "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw==", "dependencies": { "chalk": "^5.3.0", "is-unicode-supported": "^1.3.0" }, "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/log-symbols/node_modules/is-unicode-supported": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", "engines": { "node": ">= 8" } }, "node_modules/micromatch": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" }, "engines": { "node": ">=8.6" } }, "node_modules/mimic-fn": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", "engines": { "node": ">=6" } }, "node_modules/minipass": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", "engines": { "node": ">=8" } }, "node_modules/minizlib": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", "dependencies": { "minipass": "^3.0.0", "yallist": "^4.0.0" }, "engines": { "node": ">= 8" } }, "node_modules/minizlib/node_modules/minipass": { "version": "3.3.6", "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", "dependencies": { "yallist": "^4.0.0" }, "engines": { "node": ">=8" } }, "node_modules/mkdirp": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", "bin": { "mkdirp": "bin/cmd.js" }, "engines": { "node": ">=10" } }, "node_modules/onetime": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", "dependencies": { "mimic-fn": "^2.1.0" }, "engines": { "node": ">=6" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/ora": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/ora/-/ora-8.0.1.tgz", "integrity": "sha512-ANIvzobt1rls2BDny5fWZ3ZVKyD6nscLvfFRpQgfWsythlcsVUC9kL0zq6j2Z5z9wwp1kd7wpsD/T9qNPVLCaQ==", "dependencies": { "chalk": "^5.3.0", "cli-cursor": "^4.0.0", "cli-spinners": "^2.9.2", "is-interactive": "^2.0.0", "is-unicode-supported": "^2.0.0", "log-symbols": "^6.0.0", "stdin-discarder": "^0.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" }, "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/p-limit": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-4.0.0.tgz", "integrity": "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==", "dependencies": { "yocto-queue": "^1.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/p-locate": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-6.0.0.tgz", "integrity": "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==", "dependencies": { "p-limit": "^4.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/path-exists": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-5.0.0.tgz", "integrity": "sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } }, "node_modules/pathe": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz", "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==" }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "engines": { "node": ">=8.6" }, "funding": { "url": "https://github.com/sponsors/jonschlinkert" } }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ] }, "node_modules/restore-cursor": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/retry": { "version": "0.13.1", "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", "engines": { "node": ">= 4" } }, "node_modules/reusify": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", "engines": { "iojs": ">=1.0.0", "node": ">=0.10.0" } }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ], "dependencies": { "queue-microtask": "^1.2.2" } }, "node_modules/signal-exit": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" }, "node_modules/sisteransi": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==" }, "node_modules/stdin-discarder": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.2.2.tgz", "integrity": "sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==", "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/string-width": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" }, "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/strip-ansi": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", "dependencies": { "ansi-regex": "^6.0.1" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, "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==", "dependencies": { "has-flag": "^4.0.0" }, "engines": { "node": ">=8" } }, "node_modules/tar": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", "dependencies": { "chownr": "^2.0.0", "fs-minipass": "^2.0.0", "minipass": "^5.0.0", "minizlib": "^2.1.1", "mkdirp": "^1.0.3", "yallist": "^4.0.0" }, "engines": { "node": ">=10" } }, "node_modules/tinycolor2": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz", "integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==" }, "node_modules/tinygradient": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/tinygradient/-/tinygradient-1.1.5.tgz", "integrity": "sha512-8nIfc2vgQ4TeLnk2lFj4tRLvvJwEfQuabdsmvDdQPT0xlk9TaNtpGd6nNRxXoK6vQhN6RSzj+Cnp5tTQmpxmbw==", "dependencies": { "@types/tinycolor2": "^1.4.0", "tinycolor2": "^1.0.0" } }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dependencies": { "is-number": "^7.0.0" }, "engines": { "node": ">=8.0" } }, "node_modules/unicorn-magic": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.1.0.tgz", "integrity": "sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ==", "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "node_modules/yocto-queue": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.1.tgz", "integrity": "sha512-AyeEbWOu/TAXdxlV9wmGcR0+yh2j3vYPGOECcIj2S7MkrLyC7ne+oye2BKTItt0ii2PHk4cDy+95+LshzbXnGg==", "engines": { "node": ">=12.20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } } } } node_modules/pathe/utils.d.ts 0000664 00000000036 15114743311 0012255 0 ustar 00 export * from "./dist/utils"; node_modules/pathe/package.json 0000664 00000002435 15114743311 0012616 0 ustar 00 { "name": "pathe", "version": "1.1.2", "description": "Universal filesystem path utils", "repository": "unjs/pathe", "license": "MIT", "sideEffects": false, "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.cjs" }, "./utils": { "types": "./dist/utils.d.ts", "import": "./dist/utils.mjs", "require": "./dist/utils.cjs" } }, "main": "./dist/index.cjs", "types": "./dist/index.d.ts", "files": [ "dist", "utils.d.ts" ], "devDependencies": { "@types/node": "^20.10.8", "@vitest/coverage-v8": "^1.1.3", "changelogen": "^0.5.5", "eslint": "^8.56.0", "eslint-config-unjs": "^0.2.1", "jiti": "^1.21.0", "prettier": "^3.1.1", "typescript": "^5.3.3", "unbuild": "^2.0.0", "vitest": "^1.1.3" }, "packageManager": "pnpm@8.14.0", "scripts": { "build": "unbuild", "dev": "vitest", "lint": "eslint --ext .ts . && prettier -c src test", "lint:fix": "eslint --cache --ext .ts,.js,.mjs,.cjs . --fix && prettier -c src test -w", "release": "pnpm test && pnpm build && changelogen --release && pnpm publish && git push --follow-tags", "test": "pnpm lint && vitest run --coverage", "test:types": "tsc --noEmit" } } node_modules/pathe/LICENSE 0000664 00000004333 15114743311 0011334 0 ustar 00 MIT License Copyright (c) Pooya Parsa <pooya@pi0.io> - Daniel Roe <daniel@roe.dev> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- Copyright Joyent, Inc. and other Node contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/pathe/dist/index.d.mts 0000664 00000003622 15114743311 0013350 0 ustar 00 import path$1 from 'node:path'; declare const sep = "/"; declare const delimiter = ":"; declare const normalize: typeof path$1.normalize; declare const join: typeof path$1.join; declare const resolve: typeof path$1.resolve; declare function normalizeString(path: string, allowAboveRoot: boolean): string; declare const isAbsolute: typeof path$1.isAbsolute; declare const toNamespacedPath: typeof path$1.toNamespacedPath; declare const extname: typeof path$1.extname; declare const relative: typeof path$1.relative; declare const dirname: typeof path$1.dirname; declare const format: typeof path$1.format; declare const basename: typeof path$1.basename; declare const parse: typeof path$1.parse; declare const path_basename: typeof basename; declare const path_delimiter: typeof delimiter; declare const path_dirname: typeof dirname; declare const path_extname: typeof extname; declare const path_format: typeof format; declare const path_isAbsolute: typeof isAbsolute; declare const path_join: typeof join; declare const path_normalize: typeof normalize; declare const path_normalizeString: typeof normalizeString; declare const path_parse: typeof parse; declare const path_relative: typeof relative; declare const path_resolve: typeof resolve; declare const path_sep: typeof sep; declare const path_toNamespacedPath: typeof toNamespacedPath; declare namespace path { export { path_basename as basename, path_delimiter as delimiter, path_dirname as dirname, path_extname as extname, path_format as format, path_isAbsolute as isAbsolute, path_join as join, path_normalize as normalize, path_normalizeString as normalizeString, path_parse as parse, path_relative as relative, path_resolve as resolve, path_sep as sep, path_toNamespacedPath as toNamespacedPath }; } export { basename, path as default, delimiter, dirname, extname, format, isAbsolute, join, normalize, normalizeString, parse, relative, resolve, sep, toNamespacedPath }; node_modules/pathe/dist/utils.d.ts 0000664 00000000432 15114743311 0013220 0 ustar 00 declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>; declare function resolveAlias(path: string, aliases: Record<string, string>): string; declare function filename(path: string): string; export { filename, normalizeAliases, resolveAlias }; node_modules/pathe/dist/utils.cjs 0000664 00000003365 15114743311 0013137 0 ustar 00 'use strict'; const index = require('./shared/pathe.1f0a373c.cjs'); const pathSeparators = /* @__PURE__ */ new Set(["/", "\\", void 0]); const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias"); function normalizeAliases(_aliases) { if (_aliases[normalizedAliasSymbol]) { return _aliases; } const aliases = Object.fromEntries( Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b)) ); for (const key in aliases) { for (const alias in aliases) { if (alias === key || key.startsWith(alias)) { continue; } if (aliases[key].startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) { aliases[key] = aliases[alias] + aliases[key].slice(alias.length); } } } Object.defineProperty(aliases, normalizedAliasSymbol, { value: true, enumerable: false }); return aliases; } function resolveAlias(path, aliases) { const _path = index.normalizeWindowsPath(path); aliases = normalizeAliases(aliases); for (const [alias, to] of Object.entries(aliases)) { if (!_path.startsWith(alias)) { continue; } const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias; if (hasTrailingSlash(_path[_alias.length])) { return index.join(to, _path.slice(alias.length)); } } return _path; } const FILENAME_RE = /(^|[/\\])([^/\\]+?)(?=(\.[^.]+)?$)/; function filename(path) { return path.match(FILENAME_RE)?.[2]; } function _compareAliases(a, b) { return b.split("/").length - a.split("/").length; } function hasTrailingSlash(path = "/") { const lastChar = path[path.length - 1]; return lastChar === "/" || lastChar === "\\"; } exports.filename = filename; exports.normalizeAliases = normalizeAliases; exports.resolveAlias = resolveAlias; node_modules/pathe/dist/index.d.ts 0000664 00000003622 15114743311 0013173 0 ustar 00 import path$1 from 'node:path'; declare const sep = "/"; declare const delimiter = ":"; declare const normalize: typeof path$1.normalize; declare const join: typeof path$1.join; declare const resolve: typeof path$1.resolve; declare function normalizeString(path: string, allowAboveRoot: boolean): string; declare const isAbsolute: typeof path$1.isAbsolute; declare const toNamespacedPath: typeof path$1.toNamespacedPath; declare const extname: typeof path$1.extname; declare const relative: typeof path$1.relative; declare const dirname: typeof path$1.dirname; declare const format: typeof path$1.format; declare const basename: typeof path$1.basename; declare const parse: typeof path$1.parse; declare const path_basename: typeof basename; declare const path_delimiter: typeof delimiter; declare const path_dirname: typeof dirname; declare const path_extname: typeof extname; declare const path_format: typeof format; declare const path_isAbsolute: typeof isAbsolute; declare const path_join: typeof join; declare const path_normalize: typeof normalize; declare const path_normalizeString: typeof normalizeString; declare const path_parse: typeof parse; declare const path_relative: typeof relative; declare const path_resolve: typeof resolve; declare const path_sep: typeof sep; declare const path_toNamespacedPath: typeof toNamespacedPath; declare namespace path { export { path_basename as basename, path_delimiter as delimiter, path_dirname as dirname, path_extname as extname, path_format as format, path_isAbsolute as isAbsolute, path_join as join, path_normalize as normalize, path_normalizeString as normalizeString, path_parse as parse, path_relative as relative, path_resolve as resolve, path_sep as sep, path_toNamespacedPath as toNamespacedPath }; } export { basename, path as default, delimiter, dirname, extname, format, isAbsolute, join, normalize, normalizeString, parse, relative, resolve, sep, toNamespacedPath }; node_modules/pathe/dist/utils.d.mts 0000664 00000000432 15114743311 0013375 0 ustar 00 declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>; declare function resolveAlias(path: string, aliases: Record<string, string>): string; declare function filename(path: string): string; export { filename, normalizeAliases, resolveAlias }; node_modules/pathe/dist/utils.mjs 0000664 00000003276 15114743311 0013152 0 ustar 00 import { n as normalizeWindowsPath, j as join } from './shared/pathe.ff20891b.mjs'; const pathSeparators = /* @__PURE__ */ new Set(["/", "\\", void 0]); const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias"); function normalizeAliases(_aliases) { if (_aliases[normalizedAliasSymbol]) { return _aliases; } const aliases = Object.fromEntries( Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b)) ); for (const key in aliases) { for (const alias in aliases) { if (alias === key || key.startsWith(alias)) { continue; } if (aliases[key].startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) { aliases[key] = aliases[alias] + aliases[key].slice(alias.length); } } } Object.defineProperty(aliases, normalizedAliasSymbol, { value: true, enumerable: false }); return aliases; } function resolveAlias(path, aliases) { const _path = normalizeWindowsPath(path); aliases = normalizeAliases(aliases); for (const [alias, to] of Object.entries(aliases)) { if (!_path.startsWith(alias)) { continue; } const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias; if (hasTrailingSlash(_path[_alias.length])) { return join(to, _path.slice(alias.length)); } } return _path; } const FILENAME_RE = /(^|[/\\])([^/\\]+?)(?=(\.[^.]+)?$)/; function filename(path) { return path.match(FILENAME_RE)?.[2]; } function _compareAliases(a, b) { return b.split("/").length - a.split("/").length; } function hasTrailingSlash(path = "/") { const lastChar = path[path.length - 1]; return lastChar === "/" || lastChar === "\\"; } export { filename, normalizeAliases, resolveAlias }; node_modules/pathe/dist/index.mjs 0000664 00000000420 15114743311 0013105 0 ustar 00 export { h as basename, p as default, d as delimiter, f as dirname, e as extname, g as format, i as isAbsolute, j as join, a as normalize, b as normalizeString, k as parse, c as relative, r as resolve, s as sep, t as toNamespacedPath } from './shared/pathe.ff20891b.mjs'; node_modules/pathe/dist/shared/pathe.1f0a373c.cjs 0000664 00000015171 15114743311 0015472 0 ustar 00 'use strict'; const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; function normalizeWindowsPath(input = "") { if (!input) { return input; } return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); } const _UNC_REGEX = /^[/\\]{2}/; const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/; const sep = "/"; const delimiter = ":"; const normalize = function(path) { if (path.length === 0) { return "."; } path = normalizeWindowsPath(path); const isUNCPath = path.match(_UNC_REGEX); const isPathAbsolute = isAbsolute(path); const trailingSeparator = path[path.length - 1] === "/"; path = normalizeString(path, !isPathAbsolute); if (path.length === 0) { if (isPathAbsolute) { return "/"; } return trailingSeparator ? "./" : "."; } if (trailingSeparator) { path += "/"; } if (_DRIVE_LETTER_RE.test(path)) { path += "/"; } if (isUNCPath) { if (!isPathAbsolute) { return `//./${path}`; } return `//${path}`; } return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; }; const join = function(...arguments_) { if (arguments_.length === 0) { return "."; } let joined; for (const argument of arguments_) { if (argument && argument.length > 0) { if (joined === void 0) { joined = argument; } else { joined += `/${argument}`; } } } if (joined === void 0) { return "."; } return normalize(joined.replace(/\/\/+/g, "/")); }; function cwd() { if (typeof process !== "undefined" && typeof process.cwd === "function") { return process.cwd().replace(/\\/g, "/"); } return "/"; } const resolve = function(...arguments_) { arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); let resolvedPath = ""; let resolvedAbsolute = false; for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { const path = index >= 0 ? arguments_[index] : cwd(); if (!path || path.length === 0) { continue; } resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = isAbsolute(path); } resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); if (resolvedAbsolute && !isAbsolute(resolvedPath)) { return `/${resolvedPath}`; } return resolvedPath.length > 0 ? resolvedPath : "."; }; function normalizeString(path, allowAboveRoot) { let res = ""; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let char = null; for (let index = 0; index <= path.length; ++index) { if (index < path.length) { char = path[index]; } else if (char === "/") { break; } else { char = "/"; } if (char === "/") { if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { if (res.length > 2) { const lastSlashIndex = res.lastIndexOf("/"); if (lastSlashIndex === -1) { res = ""; lastSegmentLength = 0; } else { res = res.slice(0, lastSlashIndex); lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); } lastSlash = index; dots = 0; continue; } else if (res.length > 0) { res = ""; lastSegmentLength = 0; lastSlash = index; dots = 0; continue; } } if (allowAboveRoot) { res += res.length > 0 ? "/.." : ".."; lastSegmentLength = 2; } } else { if (res.length > 0) { res += `/${path.slice(lastSlash + 1, index)}`; } else { res = path.slice(lastSlash + 1, index); } lastSegmentLength = index - lastSlash - 1; } lastSlash = index; dots = 0; } else if (char === "." && dots !== -1) { ++dots; } else { dots = -1; } } return res; } const isAbsolute = function(p) { return _IS_ABSOLUTE_RE.test(p); }; const toNamespacedPath = function(p) { return normalizeWindowsPath(p); }; const _EXTNAME_RE = /.(\.[^./]+)$/; const extname = function(p) { const match = _EXTNAME_RE.exec(normalizeWindowsPath(p)); return match && match[1] || ""; }; const relative = function(from, to) { const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"); const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/"); if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) { return _to.join("/"); } const _fromCopy = [..._from]; for (const segment of _fromCopy) { if (_to[0] !== segment) { break; } _from.shift(); _to.shift(); } return [..._from.map(() => ".."), ..._to].join("/"); }; const dirname = function(p) { const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { segments[0] += "/"; } return segments.join("/") || (isAbsolute(p) ? "/" : "."); }; const format = function(p) { const segments = [p.root, p.dir, p.base ?? p.name + p.ext].filter(Boolean); return normalizeWindowsPath( p.root ? resolve(...segments) : segments.join("/") ); }; const basename = function(p, extension) { const lastSegment = normalizeWindowsPath(p).split("/").pop(); return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment; }; const parse = function(p) { const root = normalizeWindowsPath(p).split("/").shift() || "/"; const base = basename(p); const extension = extname(base); return { root, dir: dirname(p), base, ext: extension, name: base.slice(0, base.length - extension.length) }; }; const path = { __proto__: null, basename: basename, delimiter: delimiter, dirname: dirname, extname: extname, format: format, isAbsolute: isAbsolute, join: join, normalize: normalize, normalizeString: normalizeString, parse: parse, relative: relative, resolve: resolve, sep: sep, toNamespacedPath: toNamespacedPath }; exports.basename = basename; exports.delimiter = delimiter; exports.dirname = dirname; exports.extname = extname; exports.format = format; exports.isAbsolute = isAbsolute; exports.join = join; exports.normalize = normalize; exports.normalizeString = normalizeString; exports.normalizeWindowsPath = normalizeWindowsPath; exports.parse = parse; exports.path = path; exports.relative = relative; exports.resolve = resolve; exports.sep = sep; exports.toNamespacedPath = toNamespacedPath; node_modules/pathe/dist/shared/pathe.ff20891b.mjs 0000664 00000014613 15114743311 0015516 0 ustar 00 const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; function normalizeWindowsPath(input = "") { if (!input) { return input; } return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); } const _UNC_REGEX = /^[/\\]{2}/; const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/; const sep = "/"; const delimiter = ":"; const normalize = function(path) { if (path.length === 0) { return "."; } path = normalizeWindowsPath(path); const isUNCPath = path.match(_UNC_REGEX); const isPathAbsolute = isAbsolute(path); const trailingSeparator = path[path.length - 1] === "/"; path = normalizeString(path, !isPathAbsolute); if (path.length === 0) { if (isPathAbsolute) { return "/"; } return trailingSeparator ? "./" : "."; } if (trailingSeparator) { path += "/"; } if (_DRIVE_LETTER_RE.test(path)) { path += "/"; } if (isUNCPath) { if (!isPathAbsolute) { return `//./${path}`; } return `//${path}`; } return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; }; const join = function(...arguments_) { if (arguments_.length === 0) { return "."; } let joined; for (const argument of arguments_) { if (argument && argument.length > 0) { if (joined === void 0) { joined = argument; } else { joined += `/${argument}`; } } } if (joined === void 0) { return "."; } return normalize(joined.replace(/\/\/+/g, "/")); }; function cwd() { if (typeof process !== "undefined" && typeof process.cwd === "function") { return process.cwd().replace(/\\/g, "/"); } return "/"; } const resolve = function(...arguments_) { arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); let resolvedPath = ""; let resolvedAbsolute = false; for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { const path = index >= 0 ? arguments_[index] : cwd(); if (!path || path.length === 0) { continue; } resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = isAbsolute(path); } resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); if (resolvedAbsolute && !isAbsolute(resolvedPath)) { return `/${resolvedPath}`; } return resolvedPath.length > 0 ? resolvedPath : "."; }; function normalizeString(path, allowAboveRoot) { let res = ""; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let char = null; for (let index = 0; index <= path.length; ++index) { if (index < path.length) { char = path[index]; } else if (char === "/") { break; } else { char = "/"; } if (char === "/") { if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { if (res.length > 2) { const lastSlashIndex = res.lastIndexOf("/"); if (lastSlashIndex === -1) { res = ""; lastSegmentLength = 0; } else { res = res.slice(0, lastSlashIndex); lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); } lastSlash = index; dots = 0; continue; } else if (res.length > 0) { res = ""; lastSegmentLength = 0; lastSlash = index; dots = 0; continue; } } if (allowAboveRoot) { res += res.length > 0 ? "/.." : ".."; lastSegmentLength = 2; } } else { if (res.length > 0) { res += `/${path.slice(lastSlash + 1, index)}`; } else { res = path.slice(lastSlash + 1, index); } lastSegmentLength = index - lastSlash - 1; } lastSlash = index; dots = 0; } else if (char === "." && dots !== -1) { ++dots; } else { dots = -1; } } return res; } const isAbsolute = function(p) { return _IS_ABSOLUTE_RE.test(p); }; const toNamespacedPath = function(p) { return normalizeWindowsPath(p); }; const _EXTNAME_RE = /.(\.[^./]+)$/; const extname = function(p) { const match = _EXTNAME_RE.exec(normalizeWindowsPath(p)); return match && match[1] || ""; }; const relative = function(from, to) { const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"); const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/"); if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) { return _to.join("/"); } const _fromCopy = [..._from]; for (const segment of _fromCopy) { if (_to[0] !== segment) { break; } _from.shift(); _to.shift(); } return [..._from.map(() => ".."), ..._to].join("/"); }; const dirname = function(p) { const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { segments[0] += "/"; } return segments.join("/") || (isAbsolute(p) ? "/" : "."); }; const format = function(p) { const segments = [p.root, p.dir, p.base ?? p.name + p.ext].filter(Boolean); return normalizeWindowsPath( p.root ? resolve(...segments) : segments.join("/") ); }; const basename = function(p, extension) { const lastSegment = normalizeWindowsPath(p).split("/").pop(); return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment; }; const parse = function(p) { const root = normalizeWindowsPath(p).split("/").shift() || "/"; const base = basename(p); const extension = extname(base); return { root, dir: dirname(p), base, ext: extension, name: base.slice(0, base.length - extension.length) }; }; const path = { __proto__: null, basename: basename, delimiter: delimiter, dirname: dirname, extname: extname, format: format, isAbsolute: isAbsolute, join: join, normalize: normalize, normalizeString: normalizeString, parse: parse, relative: relative, resolve: resolve, sep: sep, toNamespacedPath: toNamespacedPath }; export { normalize as a, normalizeString as b, relative as c, delimiter as d, extname as e, dirname as f, format as g, basename as h, isAbsolute as i, join as j, parse as k, normalizeWindowsPath as n, path as p, resolve as r, sep as s, toNamespacedPath as t }; node_modules/pathe/dist/index.d.cts 0000664 00000003622 15114743311 0013336 0 ustar 00 import path$1 from 'node:path'; declare const sep = "/"; declare const delimiter = ":"; declare const normalize: typeof path$1.normalize; declare const join: typeof path$1.join; declare const resolve: typeof path$1.resolve; declare function normalizeString(path: string, allowAboveRoot: boolean): string; declare const isAbsolute: typeof path$1.isAbsolute; declare const toNamespacedPath: typeof path$1.toNamespacedPath; declare const extname: typeof path$1.extname; declare const relative: typeof path$1.relative; declare const dirname: typeof path$1.dirname; declare const format: typeof path$1.format; declare const basename: typeof path$1.basename; declare const parse: typeof path$1.parse; declare const path_basename: typeof basename; declare const path_delimiter: typeof delimiter; declare const path_dirname: typeof dirname; declare const path_extname: typeof extname; declare const path_format: typeof format; declare const path_isAbsolute: typeof isAbsolute; declare const path_join: typeof join; declare const path_normalize: typeof normalize; declare const path_normalizeString: typeof normalizeString; declare const path_parse: typeof parse; declare const path_relative: typeof relative; declare const path_resolve: typeof resolve; declare const path_sep: typeof sep; declare const path_toNamespacedPath: typeof toNamespacedPath; declare namespace path { export { path_basename as basename, path_delimiter as delimiter, path_dirname as dirname, path_extname as extname, path_format as format, path_isAbsolute as isAbsolute, path_join as join, path_normalize as normalize, path_normalizeString as normalizeString, path_parse as parse, path_relative as relative, path_resolve as resolve, path_sep as sep, path_toNamespacedPath as toNamespacedPath }; } export { basename, path as default, delimiter, dirname, extname, format, isAbsolute, join, normalize, normalizeString, parse, relative, resolve, sep, toNamespacedPath }; node_modules/pathe/dist/utils.d.cts 0000664 00000000432 15114743311 0013363 0 ustar 00 declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>; declare function resolveAlias(path: string, aliases: Record<string, string>): string; declare function filename(path: string): string; export { filename, normalizeAliases, resolveAlias }; node_modules/pathe/dist/index.cjs 0000664 00000001224 15114743311 0013076 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); const index = require('./shared/pathe.1f0a373c.cjs'); exports.basename = index.basename; exports.default = index.path; exports.delimiter = index.delimiter; exports.dirname = index.dirname; exports.extname = index.extname; exports.format = index.format; exports.isAbsolute = index.isAbsolute; exports.join = index.join; exports.normalize = index.normalize; exports.normalizeString = index.normalizeString; exports.parse = index.parse; exports.relative = index.relative; exports.resolve = index.resolve; exports.sep = index.sep; exports.toNamespacedPath = index.toNamespacedPath; node_modules/pathe/README.md 0000664 00000005341 15114743311 0011606 0 ustar 00 # 🛣️ pathe > Universal filesystem path utils [![version][npm-v-src]][npm-v-href] [![downloads][npm-d-src]][npm-d-href] [![size][size-src]][size-href] > **❓ Why** > > For [historical reasons](https://docs.microsoft.com/en-us/archive/blogs/larryosterman/why-is-the-dos-path-character), windows followed MS-DOS and using backslash for separating paths rather than slash used for macOS, Linux, and other Posix operating systems. Nowadays, [Windows](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN) supports both Slash and Backslash for paths. [Node.js's built in `path` module](https://nodejs.org/api/path.html) in the default operation of the path module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the path module will assume that Windows-style paths are being used. **This makes inconsistent code behavior between Windows and POSIX.** > Compared to popular [upath](https://github.com/anodynos/upath), pathe is providing **identical exports** of Node.js with normalization on **all operations** and written in modern **ESM/Typescript** and has **no dependency on Node.js**! This package is a drop-in replacement of the Node.js's [path module](https://nodejs.org/api/path.html) module and ensures paths are normalized with slash `/` and work in environments including Node.js. ## 💿 Usage Install using npm or yarn: ```bash # npm npm i pathe # yarn yarn add pathe # pnpm pnpm i pathe ``` Import: ```js // ESM / Typescript import { resolve } from 'pathe' // CommonJS const { resolve } = require('pathe') ``` Read more about path utils from [Node.js documentation](https://nodejs.org/api/path.html) and rest assured behavior is ALWAYS like POSIX regardless of your input paths format and running platform! ### Extra utilties Pathe exports some extra utilities that do not exist in standard Node.js [path module](https://nodejs.org/api/path.html). In order to use them, you can import from `pathe/utils` subpath: ```js import { filename, normalizeAliases, resolveAlias } from 'pathe/utils' ``` ## License MIT. Made with 💖 Some code used from Node.js project. See [LICENSE](./LICENSE). <!-- Refs --> [npm-v-src]: https://img.shields.io/npm/v/pathe?style=flat-square [npm-v-href]: https://npmjs.com/package/pathe [npm-d-src]: https://img.shields.io/npm/dm/pathe?style=flat-square [npm-d-href]: https://npmjs.com/package/pathe [github-actions-src]: https://img.shields.io/github/workflow/status/unjs/pathe/ci/main?style=flat-square [github-actions-href]: https://github.com/unjs/pathe/actions?query=workflow%3Aci [size-src]: https://packagephobia.now.sh/badge?p=pathe [size-href]: https://packagephobia.now.sh/result?p=pathe node_modules/signal-exit/signals.js 0000664 00000002417 15114743311 0013451 0 ustar 00 // This is not the set of all possible signals. // // It IS, however, the set of all signals that trigger // an exit on either Linux or BSD systems. Linux is a // superset of the signal names supported on BSD, and // the unknown signals just fail to register, so we can // catch that easily enough. // // Don't bother with SIGKILL. It's uncatchable, which // means that we can't fire any callbacks anyway. // // If a user does happen to register a handler on a non- // fatal signal like SIGWINCH or something, and then // exit, it'll end up firing `process.emit('exit')`, so // the handler will be fired anyway. // // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised // artificially, inherently leave the process in a // state from which it is not safe to try and enter JS // listeners. module.exports = [ 'SIGABRT', 'SIGALRM', 'SIGHUP', 'SIGINT', 'SIGTERM' ] if (process.platform !== 'win32') { module.exports.push( 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT' // should detect profiler and enable/disable accordingly. // see #21 // 'SIGPROF' ) } if (process.platform === 'linux') { module.exports.push( 'SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED' ) } node_modules/signal-exit/package.json 0000664 00000001540 15114743311 0013735 0 ustar 00 { "name": "signal-exit", "version": "3.0.7", "description": "when you want to fire an event no matter how a process exits.", "main": "index.js", "scripts": { "test": "tap", "snap": "tap", "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags" }, "files": [ "index.js", "signals.js" ], "repository": { "type": "git", "url": "https://github.com/tapjs/signal-exit.git" }, "keywords": [ "signal", "exit" ], "author": "Ben Coe <ben@npmjs.com>", "license": "ISC", "bugs": { "url": "https://github.com/tapjs/signal-exit/issues" }, "homepage": "https://github.com/tapjs/signal-exit", "devDependencies": { "chai": "^3.5.0", "coveralls": "^3.1.1", "nyc": "^15.1.0", "standard-version": "^9.3.1", "tap": "^15.1.1" } } node_modules/signal-exit/LICENSE.txt 0000664 00000001354 15114743311 0013275 0 ustar 00 The ISC License Copyright (c) 2015, Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node_modules/signal-exit/index.js 0000664 00000013114 15114743311 0013114 0 ustar 00 // Note: since nyc uses this module to output coverage, any lines // that are in the direct sync flow of nyc's outputCoverage are // ignored, since we can never get coverage for them. // grab a reference to node's real process object right away var process = global.process const processOk = function (process) { return process && typeof process === 'object' && typeof process.removeListener === 'function' && typeof process.emit === 'function' && typeof process.reallyExit === 'function' && typeof process.listeners === 'function' && typeof process.kill === 'function' && typeof process.pid === 'number' && typeof process.on === 'function' } // some kind of non-node environment, just no-op /* istanbul ignore if */ if (!processOk(process)) { module.exports = function () { return function () {} } } else { var assert = require('assert') var signals = require('./signals.js') var isWin = /^win/i.test(process.platform) var EE = require('events') /* istanbul ignore if */ if (typeof EE !== 'function') { EE = EE.EventEmitter } var emitter if (process.__signal_exit_emitter__) { emitter = process.__signal_exit_emitter__ } else { emitter = process.__signal_exit_emitter__ = new EE() emitter.count = 0 emitter.emitted = {} } // Because this emitter is a global, we have to check to see if a // previous version of this library failed to enable infinite listeners. // I know what you're about to say. But literally everything about // signal-exit is a compromise with evil. Get used to it. if (!emitter.infinite) { emitter.setMaxListeners(Infinity) emitter.infinite = true } module.exports = function (cb, opts) { /* istanbul ignore if */ if (!processOk(global.process)) { return function () {} } assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') if (loaded === false) { load() } var ev = 'exit' if (opts && opts.alwaysLast) { ev = 'afterexit' } var remove = function () { emitter.removeListener(ev, cb) if (emitter.listeners('exit').length === 0 && emitter.listeners('afterexit').length === 0) { unload() } } emitter.on(ev, cb) return remove } var unload = function unload () { if (!loaded || !processOk(global.process)) { return } loaded = false signals.forEach(function (sig) { try { process.removeListener(sig, sigListeners[sig]) } catch (er) {} }) process.emit = originalProcessEmit process.reallyExit = originalProcessReallyExit emitter.count -= 1 } module.exports.unload = unload var emit = function emit (event, code, signal) { /* istanbul ignore if */ if (emitter.emitted[event]) { return } emitter.emitted[event] = true emitter.emit(event, code, signal) } // { <signal>: <listener fn>, ... } var sigListeners = {} signals.forEach(function (sig) { sigListeners[sig] = function listener () { /* istanbul ignore if */ if (!processOk(global.process)) { return } // If there are no other listeners, an exit is coming! // Simplest way: remove us and then re-send the signal. // We know that this will kill the process, so we can // safely emit now. var listeners = process.listeners(sig) if (listeners.length === emitter.count) { unload() emit('exit', null, sig) /* istanbul ignore next */ emit('afterexit', null, sig) /* istanbul ignore next */ if (isWin && sig === 'SIGHUP') { // "SIGHUP" throws an `ENOSYS` error on Windows, // so use a supported signal instead sig = 'SIGINT' } /* istanbul ignore next */ process.kill(process.pid, sig) } } }) module.exports.signals = function () { return signals } var loaded = false var load = function load () { if (loaded || !processOk(global.process)) { return } loaded = true // This is the number of onSignalExit's that are in play. // It's important so that we can count the correct number of // listeners on signals, and don't wait for the other one to // handle it instead of us. emitter.count += 1 signals = signals.filter(function (sig) { try { process.on(sig, sigListeners[sig]) return true } catch (er) { return false } }) process.emit = processEmit process.reallyExit = processReallyExit } module.exports.load = load var originalProcessReallyExit = process.reallyExit var processReallyExit = function processReallyExit (code) { /* istanbul ignore if */ if (!processOk(global.process)) { return } process.exitCode = code || /* istanbul ignore next */ 0 emit('exit', process.exitCode, null) /* istanbul ignore next */ emit('afterexit', process.exitCode, null) /* istanbul ignore next */ originalProcessReallyExit.call(process, process.exitCode) } var originalProcessEmit = process.emit var processEmit = function processEmit (ev, arg) { if (ev === 'exit' && processOk(global.process)) { /* istanbul ignore else */ if (arg !== undefined) { process.exitCode = arg } var ret = originalProcessEmit.apply(this, arguments) /* istanbul ignore next */ emit('exit', process.exitCode, null) /* istanbul ignore next */ emit('afterexit', process.exitCode, null) /* istanbul ignore next */ return ret } else { return originalProcessEmit.apply(this, arguments) } } } node_modules/signal-exit/README.md 0000664 00000002477 15114743311 0012740 0 ustar 00 # signal-exit [](https://travis-ci.org/tapjs/signal-exit) [](https://coveralls.io/r/tapjs/signal-exit?branch=master) [](https://www.npmjs.com/package/signal-exit) [](https://github.com/conventional-changelog/standard-version) When you want to fire an event no matter how a process exits: * reaching the end of execution. * explicitly having `process.exit(code)` called. * having `process.kill(pid, sig)` called. * receiving a fatal signal from outside the process Use `signal-exit`. ```js var onExit = require('signal-exit') onExit(function (code, signal) { console.log('process exited!') }) ``` ## API `var remove = onExit(function (code, signal) {}, options)` The return value of the function is a function that will remove the handler. Note that the function *only* fires for signals if the signal would cause the process to exit. That is, there are no other listeners, and it is a fatal signal. ## Options * `alwaysLast`: Run this handler after any other signal or exit handlers. This causes `process.emit` to be monkeypatched. node_modules/heroui-cli/dist/index.js 0000775 00000153411 15114743311 0013703 0 ustar 00 #!/usr/bin/env node import R from 'chalk'; import { Command } from 'commander'; import kt, { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, readdirSync, statSync } from 'node:fs'; import { join as join$1, basename as basename$1 } from 'node:path'; import * as V from '@clack/prompts'; import { spinner, text, select, cancel, isCancel, confirm } from '@clack/prompts'; import Tn, { resolve, join, basename } from 'pathe'; import { findUp } from 'find-up'; import { fileURLToPath } from 'node:url'; import at from '@winches/prompts'; import Dt from 'gradient-string'; import { exec, execSync } from 'node:child_process'; import { validate, compareVersions } from 'compare-versions'; import Xn from 'fast-glob'; import Io from 'async-retry'; import _n, { oraPromise } from 'ora'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import gr from 'tar'; var _=process.cwd(),P=e=>resolve(_,e),$e=resolve(fileURLToPath(import.meta.url),"../components.json");var Lt=["#F54180","#338EF7"],st=Dt(...Lt),Sn=st("HeroUI CLI:"),a=class{constructor(){}static log(...t){console.log(...t);}static info(...t){console.info(...t.map(o=>R.blue(o)));}static success(...t){console.info(...t.map(o=>R.green(o)));}static warn(...t){console.warn(...t.map(o=>R.yellow(o)));}static error(...t){console.error(...t.map(o=>R.red(o)));}static grey(...t){console.log(...t.map(o=>R.gray(o)));}static gradient(t,o){this.log(Dt(...o?.colors??Lt)(String(t)));}static prefix(t,...o){return this[t](Sn,...o)}static newLine(t){t||(t=1);for(let o=0;o<t;o++)this.log();}};var pt={onCancel:()=>{a.log(`${R.red("\u2716")} Operation cancelled`),process.exit(0);}};async function ye(e,t){return (await at({hint:"- Space to select. Return to submit",message:e,min:1,name:"value",type:"autocompleteMultiselect",...t?{choices:t}:{}},pt)).value}async function se(e,t){return (await at({message:e,name:"value",type:"select",...t?{choices:t}:{}},pt)).value}async function Mt(e,t){return (await at({hint:"- Space to select. Return to submit",message:e,min:1,name:"value",type:"multiselect",...t?{choices:t}:{}},pt)).value}var _e=["npm","bun","pnpm","yarn"];var Ot={"bun.lockb":"bun","npm-shrinkwrap.json":"npm","package-lock.json":"npm","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn"};async function N(e=_){let t,o=await findUp(Object.keys(Ot),{cwd:e});return o?t=Ot[Tn.basename(o)]:t=await se("No agent found, please choose one",_e.map(r=>({title:r,value:r}))),t}var ct={bold:{bottomLeft:"\u2517",bottomRight:"\u251B",horizontal:"\u2501",topLeft:"\u250F",topRight:"\u2513",vertical:"\u2503"},classic:{bottomLeft:"+",bottomRight:"+",horizontal:"-",topLeft:"+",topRight:"+",vertical:"|"},double:{bottomLeft:"\u255A",bottomRight:"\u255D",horizontal:"\u2550",topLeft:"\u2554",topRight:"\u2557",vertical:"\u2551"},doubleSingle:{bottomLeft:"\u2558",bottomRight:"\u255B",horizontal:"\u2550",topLeft:"\u2552",topRight:"\u2555",vertical:"\u2502"},round:{bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",topLeft:"\u256D",topRight:"\u256E",vertical:"\u2502"},single:{bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",topLeft:"\u250C",topRight:"\u2510",vertical:"\u2502"},singleDouble:{bottomLeft:"\u2559",bottomRight:"\u255C",horizontal:"\u2500",topLeft:"\u2553",topRight:"\u2556",vertical:"\u2551"}};function E(e="",t=""){if(!validate(e))return -1;try{return compareVersions(e,t)}catch{return 0}}async function jn(){if(!existsSync($e)){await _t();return}let e=JSON.parse(readFileSync($e,"utf-8")),t=e.version,o=e.betaVersion,r=await ae("latestVersion"),n=await ae("betaVersion");(E(t,r)===-1||o&&E(o,n)===-1)&&await _t(r,n);}async function lt(){let e={};await jn();try{e=JSON.parse(readFileSync($e,"utf-8"));}catch(t){}return e}async function mt(e,t){t=t??`Executing ${e}`;let o=_n({discardStdin:!1,spinner:{frames:[`\u280B ${R.gray(`${t}.`)}`,`\u2819 ${R.gray(`${t}..`)}`,`\u2839 ${R.gray(`${t}...`)}`,`\u2838 ${R.gray(`${t}.`)}`,`\u283C ${R.gray(`${t}..`)}`,`\u2834 ${R.gray(`${t}...`)}`,`\u2826 ${R.gray(`${t}.`)}`,`\u2827 ${R.gray(`${t}..`)}`,`\u2807 ${R.gray(`${t}...`)}`,`\u280F ${R.gray(`${t}.`)}`],interval:150}});o.start();let r=await new Promise(n=>{exec(e,(i,s)=>{i&&(a.error(`Exec cmd ${e} error`),process.exit(1)),n(s.trim());});});return o.stop(),r}async function J(e){return g.heroUIComponentsPackageMap[e]?g.heroUIComponentsPackageMap[e].version:(await Vt(e)).version}var Ht=e=>`https://unpkg.com/@heroui/react@${e}/dist/components.json`;async function _t(e,t){[e,t]=await Promise.all([e||ae("latestVersion"),t||ae("betaVersion")]);let o=Ht(e),[r,n]=await Promise.all([Nt(o),L("beta")&&t?Nt(Ht(t),!1):Promise.resolve([])]),i=n.filter(p=>!r.find(m=>m.name===p.name));r.push(...i);let s={betaComponents:n,betaVersion:t,components:r,version:e};return writeFileSync($e,JSON.stringify(s,null,2),"utf-8"),s}async function Nt(e,t=!0){let o;return await oraPromise(Io(async r=>{try{let n=await fetch(e,{body:null,headers:{"Content-Type":"application/json",accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"},method:"GET",mode:"cors"});o=JSON.parse(await n.text());}catch(n){r(n);}},{retries:3}),{failText(r){t&&a.prefix("error",`Update components data error: ${r}`),process.exit(1);},...t?{successText:R.greenBright(`Components data updated successfully! `)}:{},text:"Fetching components data..."}),o}process.env.CI==="true";var Kt=resolve(fileURLToPath(import.meta.url),"../.."),ut=e=>resolve(Kt,e),Yt=resolve(fileURLToPath(import.meta.url),".."),Fn=existsSync(join(Yt,"components.json")),Ne=Fn?resolve(`${Yt}/.heroui-cli-cache`):resolve(join(Kt,".."),"node_modules/.heroui-cli-cache"),je=resolve(`${Ne}/data.json`);var Bn=30*6e4,ft=!1;function dt(e=ft){ft=!!e,!existsSync(Ne)&&(mkdirSync(Ne,{recursive:!0}),writeFileSync(je,JSON.stringify({}),"utf8"));}function Ve(){let e=readFileSync(je,"utf8");return JSON.parse(e)}function zt(e,t,o){dt();let r=o??Ve(),n=new Date,i=+n+Bn;r[e]={...t,date:n,expiredDate:i,expiredFormatDate:new Date(i).toString(),formatDate:n.toString()},writeFileSync(je,JSON.stringify(r,void 0,2),"utf-8");}function zn(){return +new Date}function Jn(e){return zn()-e}function Jt(e,t){if(ft)return !0;let r=(t??Ve())[e];return r?.expiredDate?Jn(r.expiredDate)>0:!0}async function Vt(e){let t=Ve();if(Jt(e,t)){let n={version:await mt(`npm view ${e} version`,`Fetching ${e} latest version`)};return zt(e,n,t),n}return t[e]}async function W(e,t){let o=Ve();if(Jt(e,o)){let i={execResult:await mt(e,t)};return zt(e,i,o),i.execResult}return o[e].execResult}async function Fe(e){return await W(`npm view ${e} dist-tags --json`,`Fetching ${e} tags`)}function Wt(e){return `@heroui/${e.replace("@heroui/","")}`}async function Se(e){if(g.betaHeroUIComponentsPackageMap[e])return g.betaHeroUIComponentsPackageMap[e].version;let t=await Fe(e);try{return JSON.parse(t).beta}catch(o){a.error(`Get beta version error: ${o}`),process.exit(1);}}async function Gt(e){return await Promise.all(e.map(Wt).map(async o=>{let r=await Se(o);return `${Wt(o)}@${r}`}))}function A(e,t=!0){let o;try{o=JSON.parse(readFileSync(e,"utf-8"));}catch(c){a.prefix("error",`Error reading package.json file: ${e} Error: ${c}`);}let r=o.devDependencies||{},n=o.dependencies||{},i={...r,...n},s=new Set(Object.keys(i)),p=g.heroUIComponents.map(c=>{let u=c.version,y=c.versionMode;if(s.has(c.package)){let f=G(i,c.package);u=t?`${f.currentVersion} new: ${u}`:f.currentVersion,y=f.versionMode;}return {...c,version:u,versionMode:y}}).filter(c=>s.has(c.package)),m=s.has(I);return {allDependencies:i,allDependenciesKeys:s,currentComponents:p,dependencies:n,devDependencies:r,isAllComponents:m,packageJson:o}}function Xt(e){return e.map(t=>{let r=g.heroUIComponentsMap[t]?.package;return r||t})}async function Qt(e,t,o=!0){let r=[];for(let n of e){let{currentVersion:i}=G(t,n),{versionMode:s}=G(t,n),p=(await W(`npm show ${n} homepage`)||"").replace(/\n/,""),m=(await W(`npm show ${n} description`)||"").replace(/\n/,""),c=g.heroUIComponentsPackageMap[n]?.version||await J(n);i=o?`${i} new: ${c}`:i;let u={description:m||"",docs:p||"",name:n,package:n,peerDependencies:{},status:"stable",style:"",version:i,versionMode:s};r.push(u);}return r}var Zt="heroui-cli",qe="framer-motion",Ke="tailwindcss",I="@heroui/react",F="@heroui/theme",oe="@heroui/system";var eo="@heroui",gt="https://heroui.com/docs/guide/installation#global-installation",Ye="https://heroui.com/docs/guide/installation#tailwind-css-setup";var to="https://heroui.com/docs/guide/installation#setup-pnpm-optional",Be="https://heroui.com/docs/guide/installation#provider-setup",v={checkPluginsRegex:/heroui(([\W\w]+)?)/,content:"./node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}",darkMode:'darkMode: "class"',importContent:(e=!1)=>e?"import {heroui} from '@heroui/theme';":"const {heroui} = require('@heroui/theme');",plugins:"heroui()"},ze={content:(e,t)=>{e.forEach(n=>{let i=oo(n,t);e.push(...i);});let o=[...new Set(e.map(n=>n.style||n.name))];return o.length===1?`./node_modules/@heroui/theme/dist/components/${o[0]}.js`:`./node_modules/@heroui/theme/dist/components/(${o.reduce((n,i)=>n+=`${i}|`,"").replace(/\|$/,"")}).js`},plugins:"heroui()"},ht={import:"HeroUIProvider"},O={content:"public-hoist-pattern[]=*@heroui/*"};function oo(e,t){let o=e.name,r=P(`node_modules/@heroui/${o}`),n=[e];if(!existsSync(r)&&t){let s=P("node_modules/.pnpm"),p=Xn.sync(`**/@heroui/${o}`,{absolute:!0,cwd:s,onlyDirectories:!0})[0];if(p)r=p;else return n}let{currentComponents:i}=A(join(r,"package.json"));if(i.length)for(let s of i){let p=oo(s,t);n.push(...p);}return n}var g={debug:!1,beta:!1,cliLatestVersion:"",latestVersion:"",betaVersion:"",betaHeroUIComponents:[],betaHeroUIIComponentsKeys:[],betaHeroUIComponentsKeysSet:new Set,betaHeroUIComponentsMap:{},betaHeroUIComponentsPackageMap:{},betaHeroUIcomponentsPackages:[],heroUIComponents:[],heroUIComponentsKeys:[],heroUIComponentsKeysSet:new Set,heroUIComponentsMap:{},heroUIComponentsPackageMap:{},heroUIcomponentsPackages:[]};async function ae(e){let t=g[e];return t||(e==="latestVersion"?(t=await J(I),g[e]=t):e==="cliLatestVersion"?(t=await J(Zt),g[e]=t):e==="betaVersion"&&(t=await Se(I),g[e]=t)),t}function L(e){return g[e]}function Zn(e){let t=e.map(s=>s.name),o=e.map(s=>s.package),r=new Set(t),n=e.reduce((s,p)=>(s[p.name]=p,s),{}),i=e.reduce((s,p)=>(s[p.package]=p,s),{});return {heroUIComponentsKeys:t,heroUIComponentsKeysSet:r,heroUIComponentsMap:n,heroUIComponentsPackageMap:i,heroUIcomponentsPackages:o}}function yt({beta:e,heroUIComponents:t}){let{heroUIComponentsKeys:o,heroUIComponentsKeysSet:r,heroUIComponentsMap:n,heroUIComponentsPackageMap:i,heroUIcomponentsPackages:s}=Zn(t);e?(g.betaHeroUIComponents=t,g.betaHeroUIIComponentsKeys=o,g.betaHeroUIComponentsKeysSet=r,g.betaHeroUIComponentsMap=n,g.betaHeroUIComponentsPackageMap=i,g.betaHeroUIcomponentsPackages=s):(g.heroUIComponents=t,g.heroUIComponentsKeys=o,g.heroUIComponentsKeysSet=r,g.heroUIComponentsMap=n,g.heroUIComponentsPackageMap=i,g.heroUIcomponentsPackages=s);}var Je=["package","version","status","docs"],no=["package","version","status"];function ro(){return g.beta?{components:g.betaHeroUIComponents,componentsKeys:g.betaHeroUIIComponentsKeys,componentsKeysSet:g.betaHeroUIComponentsKeysSet,componentsMap:g.betaHeroUIComponentsMap,componentsPackageMap:g.betaHeroUIComponentsPackageMap,componentsPackages:g.betaHeroUIcomponentsPackages}:{components:g.heroUIComponents,componentsKeys:g.heroUIComponentsKeys,componentsKeysSet:g.heroUIComponentsKeysSet,componentsMap:g.heroUIComponentsMap,componentsPackageMap:g.heroUIComponentsPackageMap,componentsPackages:g.heroUIcomponentsPackages}}var M=/\u001b\[[\d;]+m/g,U=ct.round,xt=" ",Ue=`${U.vertical}${xt}`,io=`${xt}${U.vertical}${xt}`,so=/([\W\w]+)\snew:/,ao=/new:\s([\W\w]+)/;function pe({commandName:e,components:t,message:o=`Current installed components: `,warnError:r=!0}){if(!t.length){r&&a.prefix("warn","No components found");return}let n={description:0,docs:0,name:0,originVersion:0,package:0,peerDependencies:0,status:0,style:0,version:0};for(let u of t)for(let y in u){let f=String(u[y]);if(y==="version"){let d=f.match(ao)?.[1],l=f.match(so)?.[1],x=D(po(l,d));n[y]=Math.max(n[y],Math.max(x.length,7)),n.originVersion=Math.max(n.originVersion,l.length);continue}n[y]=Math.max(n[y],f.length);}let i=t.reduce((u,y)=>{let f=Ue;for(let d of Je){let l=ne(y[d],n[d]);if(e!=="list"&&d==="version"){let x=l.match(so)?.[1]?.trim(),C=l.match(ao)?.[1]?.trim();x===C?(l=l.replace(/\snew:\s[\W\w]+(\s+)?/,""),l=ne(`${ne(l,n.originVersion)} \u{1F680}latest`,n[d]),l=l.replace("latest",R.magentaBright.underline("latest"))):C&&(l=ne(po(ne(x,n.originVersion),C),n[d]));}y.status==="stable"&&no.includes(d)?l=R.greenBright(l):y.status==="new"?l=R.magentaBright(l):y.status==="updated"&&(l=R.blueBright(l)),f+=l+io;}return u.push(f),u},[]),s=U.topLeft+Ue.replace(/.*/g,U.horizontal).slice(1),p=Ue,m=U.vertical+Ue.replace(/.*/g,U.horizontal).slice(1);for(let u of Je)s+=`${U.horizontal.padEnd(n[u]+7,U.horizontal)}`,p+=R.redBright(lo(u).padEnd(n[u]))+io,m+=`${U.horizontal.padEnd(n[u]+7,U.horizontal)}`;s=s.slice(0,-2)+U.topRight,m=m.slice(0,-2)+U.vertical;let c=U.bottomLeft+Ue.replace(/.*/g,U.horizontal).slice(1);for(let u of Je)c+=`${U.horizontal.padEnd(n[u]+7,U.horizontal)}`;c=c.slice(0,-2)+U.bottomRight,i=[s,p,m,...i,c],a.info(o),a.log(i.join(` `));}function co(){a.newLine(),a.log(R.redBright("Environment Info:")),a.log(R.blueBright(" System:")),a.log(R.blueBright(" OS:"),process.platform),a.log(R.blueBright(" CPU:"),process.arch),a.log(R.greenBright(" Binaries:")),a.log(R.greenBright(" Node:"),process.version),a.newLine();}function Ee({align:e="center",borderStyle:t="round",center:o=!1,color:r,log:n=!0,padding:i=0,text:s,title:p}){let m=ct[t],c=r?Object.fromEntries(Object.entries(m).map(([S,T])=>[S,R[r](T)])):m,u=s.split(` `),y=u.map(S=>S.replace(M,"")),f=i>0,d=i,l=o||f,x=y.reduce((S,T)=>T.length>S?T.length:S,0);x=f?x+d*4:x;let C=p?p.replace(M,""):"",h=p?C.length:0,b=x-h,w=2;for(;h+w+d>=x;)x+=Math.floor(h/2);b=x-h;let k=(()=>{if(p)if(e==="center"){let S=Math.floor(b/2)-1,T=Math.ceil(b/2)-1,it=S>0?c.horizontal.repeat(S):"",te=T>0?c.horizontal.repeat(T):"";return `${it} ${p} ${te}`}else return e==="left"?` ${p} ${c.horizontal.repeat(b-2)}`:`${c.horizontal.repeat(b-2)} ${p} `;return c.horizontal.repeat(x)})(),$=c.topLeft+k+c.topRight,H=c.bottomLeft+c.horizontal.repeat(x)+c.bottomRight,ee=u.reduce((S,T)=>{let it=T.replace(M,""),te=x-it.length,In=" ".repeat(te),Et=Math.floor(te/2),Tt=Math.ceil(te/2),Pn=Et>0?" ".repeat(Et):"",An=Tt>0?" ".repeat(Tt):"";if(o)S.push(`${c.vertical}${te?`${Pn}${T}${An}`:T}${c.vertical}`);else if(i){let $n=te-d*2;S.push(`${c.vertical}${" ".repeat(d*2)}${T}${" ".repeat($n)}${c.vertical}`);}else S.push(`${c.vertical}${te>0?`${T}${In}`:T}${c.vertical}`);return S},[]);if(l)for(let S=0;S<d;S++)ee.unshift(`${c.vertical}${" ".repeat(x)}${c.vertical}`),ee.push(`${c.vertical}${" ".repeat(x)}${c.vertical}`);return ee=[$,...ee,H],n&&a.log(ee.join(` `)),ee.join(` `)}function po(e,t){return `${R.white(`${e} ->`)} ${R.yellowBright(`${t} (new)`)}`}var We=/([\^~])/;function fo(e,t){return a.gradient(e),t}function lo(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}var le=(e,t)=>Xn.sync(e,{absolute:!0,cwd:_,deep:5,ignore:["node_modules/**","dist/**","build/**","coverage/**","public/**","out/**"],onlyFiles:!0,...t});function Qe(e){return e==="false"?!1:!!e}function go(e,t){return Object.fromEntries(Object.entries(e).filter(([o])=>!t.includes(o)))}function X(e,t){return e=q(e),t=q(t),Ge(e,t)?Ge(e,t):Xe(e,t)?Xe(e,t):uo(e,t)?uo(e,t):t}function Ge(e,t){let o=e.split("."),r=t.split(".");return o[0]!==r[0]?R.redBright(r.join(".")):""}function Xe(e,t){let o=e.split("."),r=t.split(".");return o[1]!==r[1]?`${R.white(r[0])}${R.white(".")}${R.cyanBright(r.slice(1).join("."))}`:""}function uo(e,t){let o=e.split("."),r=t.split(".");return o[2]!==r[2]?`${R.white(r.slice(0,2).join("."))}${R.white(".")}${R.greenBright(r.slice(2).join("."))}`:""}function G(e,t){let o=e[t].replace(We,""),r=e[t].match(We)?.[1]||"";return {currentVersion:o,versionMode:r}}function Ce(e){return {bun:{install:"add",remove:"remove",run:"run"},npm:{install:"install",remove:"uninstall",run:"run"},pnpm:{install:"add",remove:"remove",run:"run"},yarn:{install:"add",remove:"remove",run:"run"}}[e]}function q(e,t=!1){return e.split("||").map(n=>n.trim()).map(n=>n.replace(/^[<=>^~]+\s*/,"").trim()).sort((n,i)=>t?compareVersions(i,n):compareVersions(n,i))[0]}function ne(e,t){let o=e.replace(M,""),r=t-o.length>0?" ".repeat(t-o.length):"";return `${e}${r}`}function D(e){return e.replace(M,"")}var Ct=new Map;async function K(e,t){return new Promise((o,r)=>{try{let{cache:n=!0,logCmd:i=!0}=t||{};Ct.has(e)&&n&&o(Ct.get(e)),i&&(a.newLine(),a.log(`${e}`));let s=execSync(e,{stdio:"inherit",...t?go(t,["logCmd"]):{}});if(s){let p=s.toString();o(p),Ct.set(e,p);}o("");}catch(n){r(n);}})}var wt=e=>{isCancel(e)&&(cancel(`${R.red("\u2716")} Operation cancelled`),process.exit(0));},xo=async e=>{let t=await text(e);return wt(t),t},we=async e=>{let t=await select(e);return wt(t),t};var ho=spinner(),Co=async e=>{let{failText:t,successText:o,task:r,text:n}=e,i=null;try{ho.start(n),i=await(r instanceof Promise?r:Promise.resolve(r)),ho.stop(o);}catch{cancel(t??i??"Task failed"),process.exit(0);}return i},wo=async e=>{let t=await confirm(e);return wt(t),t},ko=async()=>{let t=readdirSync(process.cwd()).filter(r=>statSync(join(process.cwd(),r)).isDirectory()).map(r=>({label:r,value:r})).filter(r=>!["node_modules","dist","build","output",/^\./].some(n=>typeof n=="string"?r.value.includes(n):n.test(r.value)));return t.length?await we({message:"Please select the directory to add the codebase",options:t}):"src"};async function bo(e){let t=e.match(/^https?:\/\//)?.[0]??"",[o,r,n,i,s]=e.replace(t,"").split("/");return {baseStorageUrl:`${t}${o}/sandbox/files/${n}?sandboxId=${i}`,chatTitle:s,sandboxId:i,userId:r??""}}async function hr(e){let t=await fetch(e);if(!t.body)throw new Error(`Failed to download: ${e}`);return Readable.fromWeb(t.body)}async function Po(e,t){await Io(async o=>{try{await pipeline(await hr(t),gr.x({cwd:e}));}catch(r){o(new Error(`Failed to download ${t} Error: ${r}`));}},{retries:3});}async function Ao(e,t){let{fetchInfo:o,throwError:r=!0,...n}=t??{},i=`Fetching ${o??basename$1(e)}`,s=_n({discardStdin:!1,spinner:{frames:[`\u280B ${R.gray(`${i}.`)}`,`\u2819 ${R.gray(`${i}..`)}`,`\u2839 ${R.gray(`${i}...`)}`,`\u2838 ${R.gray(`${i}.`)}`,`\u283C ${R.gray(`${i}..`)}`,`\u2834 ${R.gray(`${i}...`)}`,`\u2826 ${R.gray(`${i}.`)}`,`\u2827 ${R.gray(`${i}..`)}`,`\u2807 ${R.gray(`${i}...`)}`,`\u280F ${R.gray(`${i}.`)}`],interval:150}});s.start();try{return await Io(async()=>{let p=await fetch(e,{...n,headers:{Accept:"application/json",...n?.headers}});if(!p.ok&&r)throw new Error(`Request failed with status ${p.status}`);return p},{retries:2})}catch(p){throw p instanceof Error&&p.message.includes("fetch failed")?new Error("Connection failed. Please check your network connection."):p}finally{s.stop();}}async function $o(e,t){return (await(await Ao(e,{fetchInfo:"codebase files",headers:{userId:t}})).json()).entries??{}}function Ze(e){let t=/import {?\s*([\W\w]+?)\s*}? from ["'](.+)["']/g,o=e.match(t)??[],r=[];for(let i of o)r.push(n(i));return r.length?r:[];function n(i){let s=/import {?\s*([\W\w]+?)\s*}? from ["'](.+)["']/,p=i.match(s)??[];return [p[1]??"",p[2]??""]}}function vo(e){return e.replace(/^["'`](.*)["'`]$/,"$1")}function B(e,t){let o=new RegExp(`\\s*${e}:\\s\\[([\\w\\W]*?)\\]\\s*`);return o.test(t)?t.match(o)?.[1]?.split(/,\s/g).map(r=>vo(r.trim())).filter(Boolean)??[]:[]}function ke(e,t,o,r){let n=new RegExp(`\\s*${e}:\\s\\[([\\w\\W]*?)\\]\\s*`),i=r??o.map(u=>JSON.stringify(u)).join(", ");if(n.test(t)){let u=e==="content"?` ${e}: [${i}]`:` ${e}: [${o}]`;return t.replace(n,u)}let s=t.split(` `),p=s.findIndex(u=>u.includes("content:")),m=s.findIndex(u=>u.includes("module.exports =")),c=p!==-1?p-1:m!==-1?m:0;return e==="content"?s.splice(c+1,0,` ${e}: [${i}],`):s.splice(c+1,0,` ${e}: [${o.map(u=>vo(u))}],`),s.join(` `)}function yr(e){return Ze(e).map(r=>r.find(n=>n.includes("./"))).filter(Boolean)}async function Uo(e){let{content:t,entries:o,filePath:r}=e,n=[];async function i(s){let p=yr(s);p.length!==0&&await Promise.all(p.map(async m=>{let c=o?.find(l=>basename$1(l.name).includes(basename$1(m))),u=c?.name.split(".").pop(),y=`${m.split("/").pop()}`,f=`src/${m.replace(/.*?\//,"")}${u?`.${u}`:""}`;if(n.some(l=>l.fileName===y))return;let d=c?.content??"";n.push({fileContent:d,fileName:y,filePath:f}),await i(d);}));}try{await i(t),n.push({fileContent:t,fileName:r.split("/").pop(),filePath:r});}catch(s){a.error(s),process.exit(1);}return n}function bt(e,t,o){if(t.includes("/")){let r=t.split("/").slice(0,-1).join("/");kt.mkdirSync(`${e}/${r}`,{recursive:!0}),kt.writeFileSync(`${e}/${t}`,o,"utf8");}else kt.writeFileSync(`${e}/${t}`,o,"utf8");}var kr=/^https?:\/\//,It="App.tsx";function et(e){return e.some(t=>kr.test(t))}async function To(e,t){V.intro(R.cyan("Starting to add HeroUI Chat codebase"));let o=resolve(process.cwd(),t.directory??await ko()),{baseStorageUrl:r,chatTitle:n,userId:i}=await bo(e[0]),s=n?`${n}.tsx`:void 0;kt.existsSync(o)||(a.error(`Directory ${o} does not exist`),process.exit(1));let m=await $o(r,i),c=m.find(y=>y.name.includes(It)),u=m.find(y=>y.name.includes("package.json"))?.content;if(c){let y=await Uo({content:c.content,entries:m,filePath:"src/App.tsx"});for(let f of y){if(f.fileName.includes(It)){bt(o,`${s||It}`,f.fileContent);continue}bt(o,`${f.filePath.replace("src/","")}`,f.fileContent);}}if(u){let y=JSON.parse(u),{allDependenciesKeys:f}=A(join$1(process.cwd(),"package.json")),d=Object.keys(y.dependencies).filter(l=>!f.has(l));if(d.length>0){V.log.warn(`The project is missing the following dependencies to run the codebase: ${d.join(", ")}`);let l=await wo({message:"Do you want to add the missing dependencies?"}),x=await N(),h=`${x} ${x==="npm"?"install":"add"} ${d.map(b=>`${b}@${y.dependencies[b]}`).join(" ")}`;if(l)try{await K(h);}catch{V.log.error(`Failed to install dependencies. Please add ${d.join(" ")} manually.`);}else V.note(`Run \`${h}\` to start!`,"Next steps");}}V.outro(R.green("\u2705 HeroUI Chat codebase added successfully!"));}function br(e,t){let o=0,r=e.length,n=t.length,i=0,s=0;for(;i<r&&s<n;)e[i]===t[s]&&(o++,s++),i++;return o}function Te(e,t){let o=0,r="";for(let n of e){let i=br(n,t);i>o&&(o=i,r=n);}return r!==""?r:null}function Pt(e,t){let o=Te(e,t);o?a.error(`Unknown option '${t}', Did you mean '${o}'?`):a.error(`Unknown option '${t}'`),process.exit(1);}var tt={name:"heroui-cli",private:!1,type:"module",license:"MIT",version:"1.2.3",homepage:"https://github.com/heroui-inc/heroui-cli#readme",description:"A CLI tool that unlocks seamless HeroUI integration (Previously NextUI CLI)",keywords:["UI","CLI","Tool","NextUI","Template","Integration","Add Component","HeroUI"],author:{name:"HeroUI",email:"support@heroui.com",url:"https://github.com/heroui-inc"},repository:{type:"git",url:"https://github.com/heroui-inc/heroui-cli.git"},bugs:{url:"https://github.com/heroui-inc/heroui-cli/issues"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},files:["dist"],bin:{heroui:"./dist/index.js"},main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",scripts:{dev:"tsup --watch","link:cli":"pnpm link --global","link:remove":"pnpm uninstall --global heroui-cli",build:"tsup","update:components":"tsx src/scripts/update/update-components.ts","sync:docs":"tsx src/scripts/sync/sync.ts","clean:cache":"tsx src/scripts/cache/clean.ts",lint:"eslint . --max-warnings=0","lint:fix":"eslint . --max-warnings=0 --fix","check:prettier":"prettier --check .","check:types":"tsc --noEmit",changelog:"npx conventional-changelog -p angular -i CHANGELOG.md -s --commit-path .",release:"bumpp --execute='pnpm run changelog' --all",prepare:"husky install",prebuild:"pnpm run update:components",prepublishOnly:"pnpm run build"},dependencies:{"@clack/prompts":"0.7.0","@winches/prompts":"0.0.7","async-retry":"1.3.3",chalk:"5.3.0",commander:"11.0.0","compare-versions":"6.1.1","fast-glob":"3.3.2","find-up":"7.0.0","gradient-string":"2.0.2",ora:"8.0.1",pathe:"1.1.2",tar:"6.2.1"},devDependencies:{"@commitlint/cli":"17.7.1","@commitlint/config-conventional":"17.7.0","@types/gradient-string":"1.1.3","@types/node":"20.11.30","@typescript-eslint/eslint-plugin":"6.7.2","@typescript-eslint/parser":"6.7.2",bumpp:"9.4.0","clean-package":"2.2.0","commitlint-plugin-function-rules":"2.0.2","conventional-changelog-cli":"4.1.0",eslint:"8.50.0","eslint-config-prettier":"9.0.0","eslint-import-resolver-typescript":"3.6.1","eslint-plugin-import":"2.28.1","eslint-plugin-prettier":"5.0.0","eslint-plugin-sort-destructure-keys":"1.5.0","eslint-plugin-sort-keys-fix":"1.1.2","eslint-plugin-unicorn":"52.0.0","eslint-plugin-unused-imports":"3.0.0",husky:"8.0.3","lint-staged":"14.0.1",prettier:"3.3.2",tsup:"7.2.0",tsx:"4.7.1",typescript:"5.2.2"},engines:{pnpm:">=9.x"},packageManager:"pnpm@9.6.0"};function Ro(e,t=!0){let r=ro().components.filter(i=>i.peerDependencies[e]),n="";return t?n=r.map(p=>p.peerDependencies[e]).reduce((p,m)=>E(p,m)>0?m:p)||"":n=r[0]?.version||"",q(n)}async function me(e){return g.beta?await Se(e):await J(e)}async function Do(e){let o=Object.keys(e).filter(n=>!g.heroUIcomponentsPackages.includes(n)&&n.startsWith(eo));return o.length?await Promise.all(o.map(async n=>{let{currentVersion:i,versionMode:s}=G(e,n),p=await me(n),m=E(i,p)>=0;return {isLatest:m,latestVersion:X(i,m?i:p),package:n,version:i,versionMode:s}})):[]}var ue="".padEnd(7),Mo="Missing";async function Oo(e){let{all:t,allDependencies:o,isHeroUIAll:r,upgradeOptionList:n}=e,i=[],s=new Set,p=await Ar(t,r,o,s),m=await Do(o),c=n.map(l=>({...l,latestVersion:X(l.version,l.latestVersion)})),u=await Promise.all(n.map(l=>Re(l.package,o,s,l.peerDependencies))),y=await $r([...s]),f=[...c,...p.allOutputList],d=[...m,...u.flat(),...p.allPeerDepList,...y].filter((l,x,C)=>x===C.findIndex(h=>h.package===l.package)&&!f.some(h=>h.package===l.package));return Pr(f,d),i=[...f,...d].filter((l,x,C)=>!l.isLatest&&x===C.findIndex(h=>h.package===l.package)),vr(i),i}function Lo(e,t=!1){if(!e.length)return "";let o=[],r={latestVersion:0,package:0,version:0};for(let n of e)for(let i in n){if(!Object.prototype.hasOwnProperty.call(n,i)||!n[i])continue;i==="version"&&(n[i]=n[i].replace(We,""));let s=i==="version"?n[i].replace(M,"").length:n[i].length;r[i]=Math.max(r[i],s);}for(let n of e){if(n.isLatest){if(t)continue;o.push(` ${R.white(`${`${n.package}@${n.versionMode||""}${n.latestVersion}`.padEnd(r.package+ue.length+ue.length)}`)}${ue}${R.greenBright("latest").padStart(r.version)}${ue}`);continue}o.push(` ${R.white(`${n.package.padEnd(r.package+ue.length)}${ue}${ne(`${n.versionMode||""}${n.version}`,r.version)} -> ${n.versionMode||""}${n.latestVersion}`)}${ue}`);}return o.join(` `)}async function Re(e,t,o,r){if(r=r||JSON.parse(await W(`npm show ${e} peerDependencies --json`))||{},!r||!Object.keys(r).length)return [];let n=[];for(let[i,s]of Object.entries(r)){if(n.some(y=>y.package===i))continue;let p=t[i],m=q(s);if(!p){o.add({name:i,version:m});continue}let{versionMode:c}=G(t,i),u=E(p,m)>=0;u?m=q(p):m=await J(i),n.push({isLatest:u,latestVersion:u?m:X(p,m),package:i,version:p,versionMode:c});}return n}function Pr(e,t){let o=e.length===1?"Component":"Components",r={components:{color:"blue",text:"",title:R.blue(o)},peerDependencies:{color:"yellow",text:"",title:R.yellow("PeerDependencies")}},n=Lo(e),i=Lo(t,!0),s=t.filter(p=>!p.isLatest);n.length&&Ee({...r.components,text:n}),a.newLine(),s.length&&a.log(R.gray(`Required min version: ${s.map(p=>`${p.package}>=${p.latestVersion.replace(M,"")}`).join(", ")}`)),i.length&&Ee({...r.peerDependencies,text:i});}async function Ar(e,t,o,r){if(!e||!t)return {allOutputList:[],allPeerDepList:[]};let n=await me(I),{currentVersion:i,versionMode:s}=G(o,I),p=X(i,n),m=E(i,n)>=0,c=await Re(I,o,r),u=await Re(F,o,r),y=[{isLatest:m,latestVersion:p,package:I,version:i,versionMode:s}],f=[...c,...u];return {allOutputList:y,allPeerDepList:f}}async function $r(e){let t=[];for(let o of e){let r={isLatest:!1,latestVersion:o.version,package:o.name,version:R.red(Mo),versionMode:""};t.push(r);}return t}function vr(e){let t={major:0,minor:0,patch:0};for(let r of e){if(r.version===Mo){t.major++;continue}let n=D(r.latestVersion);Ge(r.version,n)?t.major++:Xe(r.version,n)?t.minor++:t.patch++;}let o=Object.entries(t).reduce((r,[n,i])=>i?`${r}${R.yellowBright(i)} ${n}, `:r,"").replace(/, $/,"");return o&&(a.log(o),a.newLine()),t}function Ho({dependencies:e,devDependencies:t,upgradePackageList:o}){for(let r of o){let n=D(r.latestVersion);if(t[r.package]){t[r.package]=n;continue}e[r.package]=n;}}function fe(e,t){let{errorInfo:o,missingDependencies:r,tailwindName:n}=t;return e==="missingDependencies"?{level:"error",name:"missingDependencies",outputFn:()=>{a.log("You have not installed the required dependencies"),a.newLine(),a.log("The required dependencies are:"),r.forEach(i=>{a.log(`- ${i}`);}),a.newLine(),a.log(`See more info here: ${R.underline(gt)}`);}}:e==="incorrectTailwind"?{level:"error",name:"incorrectTailwind",outputFn:()=>{a.log(`Your ${n} is incorrect`),a.newLine(),a.log("The missing part is:"),o.forEach(i=>{a.log(`- need to add ${i}`);}),a.newLine(),a.log(`See more info here: ${R.underline(`${Ye}-1`)}`);}}:{level:"error",name:"incorrectApp",outputFn:()=>{a.log("Your App.tsx is incorrect"),a.newLine(),a.log("The missing part is:"),o.forEach(i=>{a.log(`- need to add ${i}`);}),a.newLine(),a.log(`See more info here: ${R.underline(gt)}`);}}}async function de(e,t,o){let r=[],{allDependencies:n,beta:i,packageNames:s,peerDependencies:p}=o??{},m=[],c=t.has(qe),u=t.has(Ke),y=`${Ke}@${Ro(Ke)}`;if(p){let f=await Sr({allDependencies:n,packageNames:s});m.push(...f);}if(e==="all"){let f=t.has(I);if(f&&c&&u&&!m.length)return [!0];!f&&r.push(i?`${I}@${g.betaVersion}`:I),!c&&r.push(qe),!u&&r.push(y);}else if(e==="partial"){let f=t.has(oe),d=t.has(F);if(c&&f&&d&&u&&!m.length)return [!0];let l=await Fe(oe),x=await Fe(F);!c&&r.push(qe),!f&&r.push(i?`${oe}@${l}`:oe),!d&&r.push(i?`${F}@${x}`:F),!u&&r.push(y);}return [!1,...r,...p?m:[]]}async function Sr(e){let{allDependencies:t,packageNames:o}=e,r=[];for(let n of o){let i=await Re(n,t,new Set);for(let s of i)if(!s.isLatest){let p=r.findIndex(u=>u.includes(s.package)),c=D(r[p]||"")?.match(/@([\d.]+)/)?.[1];c&&E(c,D(s.latestVersion))<=0&&r.splice(p,1),r.push(`${s.package}@${s.latestVersion}`);}}return r}function ge(e,t,o,r,n,i){if(e==="partial"&&!o.length)return [!0];let s=[],p=n??readFileSync(t,"utf-8"),m=B("content",p),c=B("plugins",p);if(e==="all"){let y=B("darkMode",p).some(l=>l.includes("class"))||/darkMode:\s*["'`]class/.test(p),f=m.some(l=>l.includes(v.content.replace("{js,ts,jsx,tsx}",""))),d=c.some(l=>v.checkPluginsRegex.test(l));if(y&&f&&d)return [!0];!y&&s.push(v.darkMode),!f&&s.push(v.content),!d&&s.push(v.plugins);}else if(e==="partial"){let u=ze.content(o,r),y=!1,f=m.some(l=>l.includes(v.content.replace("{js,ts,jsx,tsx}",""))?(y=!0,!0):l.includes(u));i&&y&&a.log(` ${R.yellow("Attention")} Individual components from HeroUI do not require the "${R.bold(v.content)}" in the tailwind config For optimized bundle sizes, consider using "${R.bold(u)}" instead`);let d=c.some(l=>v.checkPluginsRegex.test(l));if(f&&d)return [!0];!f&&s.push(u),!d&&s.push(v.plugins);}return [!1,...s]}function De(e,t){let o=[];if(e==="all"||e==="partial"){let r=readFileSync(t,"utf-8"),i=Ze(r).some(([s])=>s.includes(ht.import));if(i)return [!0];!i&&o.push(ht.import);}return [!1,...o]}function be(e){let t=[],o;if(e){try{o=readFileSync(e,"utf-8");let r=o.includes(O.content);if(r)return [!0];!r&&t.push(O.content);}catch(r){t.push(`Error reading .npmrc file: ${e} Error: ${r}`);}return [!1,...t]}return [!1,...t]}async function Ie(e=[],t=!0){let o=[];for(let r of e)if(!g.heroUIComponentsKeysSet.has(r)){let n=Te(g.heroUIComponentsKeys,r);o.push([r,n]);}if(o.length){let[r,n]=o.reduce((i,[s,p])=>[i[0]+R.underline(s)+", ",i[1]+(p?R.underline(p)+", ":"")],["",""]);return t&&a.prefix("error",`Illegal components: ${r.replace(/, $/,"")}${n?` ${"".padEnd(12)}It may be a typo, did you mean ${n.replace(/, $/,"")}?`:""}`),!1}return !0}async function ot(e){try{await e();}catch(t){t&&(await we({message:`${R.red("Error: ")}a unexpected error occurred, run "pnpm install" maybe can fix it or report it as a bug`,options:[{label:"Re-run pnpm install",value:"re-run-pnpm-install"},{label:"Exit",value:"exit"}]})==="exit"&&process.exit(1),await K("pnpm install --force"),await e());}}async function $t(e,t=[]){if(L("debug"))for(let o of t)a.warn(`Debug: ${o}`);else await ot(()=>K(e));}function No(e,t){if(!e.length||!L("debug"))return;let{dependencies:o,packageJson:r}=A(t);for(let n of e){let i=g.heroUIComponentsMap[n];i&&(o[i.package]=`${i.package}@${i.version}`);}writeFileSync(t,JSON.stringify({...r,dependencies:o},null,2),"utf-8");}function jo(e,t){if(!e.length||!L("debug"))return;let{dependencies:o,packageJson:r}=A(t);for(let n of e){let i=g.heroUIComponentsMap[n];i&&delete o[i.package];}writeFileSync(t,JSON.stringify({...r,dependencies:o},null,2),"utf-8");}function Vo(e,t){let{format:o=!1,write:r=!0}=t,n=readFileSync(e,"utf-8");n=`import {HeroUIProvider} from "@heroui/react"; ${n}`,n=Tr(n),r&&writeFileSync(e,n,"utf-8"),o&&execSync(`npx prettier --write ${e}`,{stdio:"ignore"});}function Tr(e){let t=/return\s*\(([\S\s]*?)\);/g;return e.replace(t,(r,n)=>`return ( <HeroUIProvider> ${n.trim()} </HeroUIProvider> );`)}function rt(e,t){let{errorInfoList:o,format:r=!1,tailwindPath:n,write:i=!0}=t;if(!o.length)return;let s=readFileSync(n,"utf-8"),p=B("content",s),m=B("plugins",s);for(let c of o){let[u,y]=Rr(c);if(u==="content"){if(p.includes(v.content))continue;p=p.filter(d=>!d.includes("@heroui/theme/dist/")),p.push(y),s=ke("content",s,p,p.map((d,l,x)=>l===0?x.length===1?` ${JSON.stringify(d)} `:` ${JSON.stringify(d)}`:x.length-1===l?` ${JSON.stringify(d)} `:` ${JSON.stringify(d)}`).join(`, `));}else u==="plugins"&&(m.push(y),s=ke("plugins",s,m),s=`${v.importContent(n.endsWith(".ts"))} ${s}`);if(e==="all"&&u==="darkMode"){let f=s.indexOf("plugins")-1,d=v.darkMode;s=`${s.slice(0,f)} ${d}, ${s.slice(f)}`;}}if(i&&writeFileSync(n,s,"utf-8"),r)try{execSync(`npx prettier --write ${n}`,{stdio:"ignore"});}catch{a.warn(`Prettier failed to format ${n}`);}}function Rr(e){return v.darkMode.includes(e)?["darkMode",e]:v.plugins.includes(e)?["plugins",e]:["content",e]}function Pe(e,t=!0,o=!0,r=void 0){if(!existsSync(e))t&&writeFileSync(e,O.content,"utf-8");else {let n=readFileSync(e,"utf-8");n=`${O.content} ${n}`,t&&writeFileSync(e,n,"utf-8");}if(!r){a.newLine(),a.log(`Added the required content in file: ${e}`),o&&!L("debug")&&(a.newLine(),a.log("Pnpm restructure will be run now"),execSync("pnpm install",{stdio:"inherit"}));return}r({message:`Added the required content in file: ${e}`,runInstall:o});}var Fo="https://codeload.github.com/heroui-inc/next-app-template/tar.gz/main",qo="https://codeload.github.com/heroui-inc/next-pages-template/tar.gz/main",Ko="https://codeload.github.com/heroui-inc/vite-template/tar.gz/main",Yo="https://codeload.github.com/heroui-inc/remix-template/tar.gz/main",Bo="https://github.com/heroui-inc/laravel-template/archive/refs/heads/master.zip",zo="next-app-template-main",Jo="next-pages-template-main",Wo="vite-template-main",Go="remix-template-main",Xo="laravel-template-main",Qo="next-app-template",Zo="next-pages-template",en="vite-template",tn="remix-template",on="laravel-template";function nn(e,t){return e==="all"?`// tailwind.config.js const {heroui} = require("@heroui/react"); /** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}", ], theme: { extend: {}, }, darkMode: "class", plugins: [heroui()], };`:`// tailwind.config.js const {heroui} = require("@heroui/theme"); /** @type {import('tailwindcss').Config} */ module.exports = { content: [ ${JSON.stringify(t)}, ], theme: { extend: {}, }, darkMode: "class", plugins: [heroui()], };`}async function an(e,t){et(e)&&(await To(e,t),process.exit(0));let{addApp:o=!1,all:r=!1,appPath:n,beta:i=!1,packagePath:s=P("package.json"),tailwindPath:p=le("**/tailwind.config.(j|t)s")[0]}=t;var{allDependencies:m,allDependenciesKeys:x,currentComponents:C}=A(s);let c=t.prettier??x.has("prettier"),u=!!m[I];if(!e.length&&!r){let w=g.heroUIComponents.filter(k=>!C.some($=>$.name===k.name));w.length||(a.success("\u2705 All components have been added"),process.exit(0)),e=await ye("Which components would you like to add?",w.map(k=>({description:k.description,title:k.name,value:k.name})));}else r&&(e=[I]);if(!r&&!Ie(e,!0))return;var{allDependenciesKeys:x,currentComponents:C}=A(s);let y=C.map(w=>w.name),f=e.filter(w=>y.includes(w)||u&&w===I);if(f.length&&!L("debug")){a.prefix("error",`\u274C You have already added the following components: ${f.map(w=>R.underline(w)).join(", ")}`);return}if(o&&!n){a.prefix("error","\u274C App.(j|t)sx file not found. Please specify the appPath if the default search path does not locate your file. 'add --appPath=yourAppPath'");return}let d=await N(),l=d==="npm"?"install":"add";if(r){let[,...w]=await de("all",x,{allDependencies:m,beta:i,packageNames:[I],peerDependencies:!0});w=w.map(k=>D(k)),w.length&&(a.info(`Adding required dependencies: ${[...w].map(k=>R.underline(k)).join(", ")}`),await $t(`${d} ${l} ${[...w].join(" ")}`,w));}else {let w=i?await Gt(e):e.map(H=>g.heroUIComponentsMap[H].package),[,...k]=await de("partial",x,{allDependencies:m,beta:i,packageNames:w,peerDependencies:!0}),$=[...k,...w].map(H=>D(H));a.info(`Adding required dependencies: ${[...$].map(H=>R.underline(H)).join(", ")}`),await $t(`${d} ${l} ${[...$].join(" ")}`,$);}L("debug")&&No(e,s);var{allDependenciesKeys:x,currentComponents:C}=A(s);let h=r?"all":"partial",b=d==="pnpm";if(p){let[,...w]=ge(h,p,C,b,void 0,!0);rt(h,{errorInfoList:w,format:c,tailwindPath:p}),a.newLine(),a.log(`Tailwind CSS settings have been updated in: ${p}`);}else {let w=ze.content(C,b),k=nn(h,w),$=P("tailwind.config.js");writeFileSync($,k,"utf-8"),a.newLine(),a.info(`Tailwind CSS configuration file created at: ${$}`);}if(o&&n&&existsSync(n)){let[w]=De(h,n);w||(Vo(n,{format:c}),a.newLine(),a.info(`HeroUIProvider successfully added to the App file at: ${n}`),a.warn("Please check the placement of HeroUIProvider in the App file to ensure it's correctly integrated.'"));}if(d==="pnpm"){let w=P(".npmrc");if(!existsSync(w))writeFileSync(P(".npmrc"),O.content,"utf-8");else {let[k]=be(w);k||Pe(w);}}a.newLine(),a.success("\u2705 Components added successfully"),(x.has(I)||r)&&C.length&&(a.newLine(),a.log(`${R.yellow("Attention")} Individual components from HeroUI do not require the \`@heroui/react\` package. For optimized bundle sizes, consider using individual components.`),a.log("The redundant dependencies are:"),[...new Set(C)].forEach(w=>{a.log(`- ${w.package}`);})),a.newLine(),a.grey(`Please check the ${R.bold("HeroUIProvider")} whether in the correct place (ignore if added) See more info here: ${Be}`),L("debug")&&jo(e,s),process.exit(0);}async function cn(e){let{appPath:t=le("**/App.(j|t)sx")[0],checkApp:o=!1,checkPnpm:r=!0,checkTailwind:n=!0,packagePath:i=P("package.json"),tailwindPath:s=le("**/tailwind.config.(j|t)s")}=e,p=Qe(o),m=Qe(r),c=Qe(n),u=[s].flat(),{allDependencies:y,allDependenciesKeys:f,currentComponents:d,isAllComponents:l}=A(i);if(!d.length&&!l){a.prefix("error",`\u274C No ${R.underline("HeroUI components")} found in your project. Please consult the installation guide at: https://heroui.com/docs/guide/installation#global-installation`);return}let x=[];if(l&&d.length&&x.push({level:"warn",name:"redundantDependencies",outputFn:()=>{a.log("You have installed some unnecessary dependencies. Consider removing them for optimal performance."),a.newLine(),a.log("The following dependencies are redundant:"),d.forEach(C=>{a.log(`- ${C.package}`);});}}),c&&!u.length&&x.push({level:"error",name:"missingTailwind",outputFn:()=>{a.log("Missing tailwind.config.(j|t)s file. To set up, visit: "+R.underline(Ye));}}),p&&!t&&x.push({level:"error",name:"missingApp",outputFn:()=>{a.log("App.(j|t)sx file not found. Please specify the path using: doctor --appPath=[yourAppPath]");}}),l){let[C,...h]=await de("all",f,{allDependencies:y,packageNames:[I],peerDependencies:!0});if(d.length){let[b,...w]=await de("partial",f,{allDependencies:y,packageNames:d.map(k=>k.package),peerDependencies:!0});C=b||C,h=[...w,...h].filter((k,$,H)=>(k=D(k).replace(/@[\d.]+/g,""),H.findIndex(ee=>D(ee).replace(/@[\d.]+/g,"")===k)===$));}if(C||x.push(fe("missingDependencies",{missingDependencies:h})),c)for(let b of u){let[w,...k]=ge("all",b);if(!w){let $=basename(b);x.push(fe("incorrectTailwind",{errorInfo:k,tailwindName:$}));}}if(p&&t){let[b,...w]=De("all",t);b||x.push(fe("incorrectApp",{errorInfo:w}));}}else if(d.length){let[C,...h]=await de("partial",f,{allDependencies:y,packageNames:d.map(b=>b.package),peerDependencies:!0});if(C||x.push(fe("missingDependencies",{missingDependencies:h})),c){let b=await N()==="pnpm";for(let w of u){let[k,...$]=ge("partial",w,d,b,void 0,!0);if(!k){let H=basename(w);x.push(fe("incorrectTailwind",{errorInfo:$,tailwindName:H}));}}}if(p&&t){let[b,...w]=De("partial",t);b||x.push(fe("incorrectApp",{errorInfo:w}));}}if(m&&await N()==="pnpm"){let h=P(".npmrc"),[b,...w]=be(h);b||x.push({level:"error",name:"incorrectPnpm",outputFn:()=>{a.log(`The pnpm setup is incorrect Please update your configuration according to the guidelines provided at: `+R.underline(to)),a.newLine(),a.log("Required changes:"),w.forEach(k=>{a.log(`- Add ${k}`);});}});}if(!x.length){a.newLine(),a.success("\u2705 Your project has no detected issues.");return}a.prefix("error",`\u274C Your project has ${R.underline(x.length)} issue${x.length===1?"":"s"} that require attention`),a.newLine();for(let C=0;C<x.length;C++){let h=x[C];a[h.level](`\u2757\uFE0FIssue ${C+1}: ${R.bold(h.name)}`),a.newLine(),h.outputFn(),a.newLine();}process.exit(0);}async function ln(e){let{packagePath:t=P("package.json")}=e,{currentComponents:o}=A(t);pe({components:o}),co(),process.exit(0);}var Lr="package-lock=true";function mn(e){writeFileSync(e,Lr,"utf-8");}function un(e,t){e&&(Object.keys(he).includes(e)||Pt(Object.keys(he),e)),t&&(_e.includes(t)||Pt(_e,t));}var he={app:Qo,laravel:on,pages:Zo,remix:tn,vite:en};async function dn(e,t){let{package:o="npm",template:r}=t;un(r,o),V.intro(R.cyanBright("Create a new project"));let{packageName:n,projectName:i,template:s}=await Hr(o,e,r),{run:p}=Ce(n);existsSync(ut(`${_}/${i}`))&&(V.cancel(`The project name ${R.redBright(i)} already exists`),process.exit(1)),s==="app"?(await Oe(Fo),He(zo,i)):s==="pages"?(await Oe(qo),He(Jo,i)):s==="vite"?(await Oe(Ko),He(Wo,i)):s==="remix"?(await Oe(Yo),He(Go,i)):s==="laravel"?(await Oe(Bo),He(Xo,i)):_exhaustiveCheck=s;let m=ut(`${_}/${i}/.npmrc`);mn(m),n==="pnpm"&&Pe(m,!0,!1,({message:c})=>{V.log.message(c);}),V.note(`cd ${R.cyanBright(i)} ${R.cyanBright(n)} install`,"Next steps"),V.outro(`\u{1F680} Get started with ${R.cyanBright(`${n} ${p} dev`)}`),process.exit(0);}async function Oe(e){await Co({failText:"Template creation failed",successText:"Template created successfully!",task:Po(_,e),text:"Creating template..."});}function He(e,t){try{renameSync(join(_,e),join(_,t));}catch(o){o&&(V.cancel(`rename Error: ${o}`),process.exit(0));}}async function Hr(e,t,o){return o=await we({initialValue:o,message:"Select a template (Enter to select)",options:[{hint:"A Next.js 15 with app directory template pre-configured with HeroUI (v2) and Tailwind CSS.",label:"App",value:"app"},{hint:"A Next.js 15 with pages directory template pre-configured with HeroUI (v2) and Tailwind CSS.",label:"Pages",value:"pages"},{hint:"A Vite template pre-configured with HeroUI (v2) and Tailwind CSS.",label:"Vite",value:"vite"},{hint:"A Remix template pre-configured with HeroUI (v2) and Tailwind CSS.",label:"Remix",value:"remix"},{hint:"A Laravel template pre-configured with HeroUI (v2) and Tailwind CSS.",label:"Laravel",value:"laravel"}]}),t=await xo({initialValue:t??he[o],message:"New project name (Enter to skip with default name)",placeholder:t??he[o]}),e=await we({initialValue:e,message:"Select a package manager (Enter to select)",options:[{label:R.gray("npm"),value:"npm"},{label:R.gray("yarn"),value:"yarn"},{label:R.gray("pnpm"),value:"pnpm"},{label:R.gray("bun"),value:"bun"}]}),{packageName:e,projectName:t,template:o}}async function gn(e){let{packagePath:t=P("package.json"),remote:o=!1}=e,r=g.heroUIComponents;try{if(!o){let{currentComponents:n}=await A(t);r=n;}if(!r.length){a.warn(`No HeroUI components detected in the specified package.json at: ${t}`);return}o?pe({commandName:"list",components:r}):pe({components:r});}catch(n){a.prefix("error",`An error occurred while attempting to list the components: ${n}`);}process.exit(0);}async function hn(e,t){let{remove:o}=Ce(t);await K(`${t} ${o} ${e.join(" ")}`);}async function yn(e,t){let{currentComponents:o,isHeroUIAll:r,isPnpm:n,prettier:i,tailwindPath:s}=t;if(s&&!existsSync(s)){a.prefix("warn","No tailwind.config.(j|t)s found remove action skipped");return}let p=readFileSync(s,"utf-8"),m=B("content",p),c=B("plugins",p),u=m.some(f=>f.includes(v.content));if(!o.length&&!r){let f=c.findIndex(d=>d.includes("heroui"));f!==-1&&c.splice(f,1),p=ke("plugins",p,c),p=p.replace(/(const|var|let|import)[\W\w]+?heroui.*?;\n/,"");}if(!u){for(;m.some(f=>f.includes("heroui"));)m.splice(m.findIndex(f=>f.includes("heroui")),1);p=ke("content",p,m);}writeFileSync(s,p,"utf-8");let[,...y]=ge(e,s,o,n,void 0,!0);rt(e,{errorInfoList:y,format:i,tailwindPath:s}),a.newLine(),a.info(`Remove the removed components tailwind content in file: ${s}`);}async function Cn(e,t){let{all:o=!1,packagePath:r=P("package.json"),tailwindPath:n=le("**/tailwind.config.(j|t)s")[0]}=t;var{allDependencies:d,allDependenciesKeys:i,currentComponents:l}=A(r);let s=await N(),p=t.prettier??i.has("prettier"),m=!!d[I];if(!l.length&&!m){a.prefix("error",`No HeroUI components detected in your package.json at: ${r}`);return}if(o||m)e=m?[I]:l.map(C=>C.package);else if(!e.length)e=await ye("Select the components to remove",l.map(C=>({title:C.package,value:C.package})));else {if(!Ie(e))return;e=Xt(e);}let c=e.includes(I)?await Qt(e,d):l.filter(C=>e.some(h=>h.includes(C.package)||h.includes(C.name)));pe({components:c,message:R.yellowBright("\u2757\uFE0F Components slated for removal:")}),await se("Confirm removal of these components:",[{title:"Yes",value:!0},{title:"No",value:!1}])||process.exit(0);let y=[...e];l.filter(C=>!e.includes(C.package)).length||(d[F]&&y.push(F),d[oe]&&y.push(oe)),await hn(y,s);var{allDependencies:d,currentComponents:l}=A(r,!1);if(m=!!d[I],yn(m?"all":"partial",{currentComponents:l,isHeroUIAll:m,isPnpm:s==="pnpm",prettier:p,tailwindPath:n}),!l.length&&!m){if(s==="pnpm"){let C=P(".npmrc");if(existsSync(C)){let h=readFileSync(C,"utf-8");h=h.replace(O.content,""),a.newLine(),a.info("Removing specified .npmrc file content"),writeFileSync(C,h,"utf-8");}}a.newLine(),a.warn(`No HeroUI components remain installed. Ensure the HeroUIProvider is also removed if necessary. For more information, visit: ${Be}`);}a.newLine(),a.success(`\u2705 Successfully removed the specified HeroUI components: ${e.map(C=>R.underline(C)).join(", ")}`),process.exit(0);}async function wn(e){if(e==="pnpm"){let t=P(".npmrc");if(!existsSync(t))writeFileSync(P(".npmrc"),O.content,"utf-8");else {let[o]=be(t);o||Pe(t);}}}function kn(e,t,o){let r=e.match(/(^\w+$)/)?.[1];if(r)return t.includes(r);let n=E(e,t);return o&&n===1&&!e.includes("beta")?!1:n>=0}async function bn(e,t){let{all:o=!1,beta:r=!1,packagePath:n=P("package.json"),write:i=!1}=t,{allDependencies:s,currentComponents:p,dependencies:m,devDependencies:c,packageJson:u}=A(n,!1),y=!!s[I],f=[];if(await Promise.all(p.map(async h=>{let b=await me(h.package),w=kn(h.version,b,r);f.push({...h,isLatest:w,latestVersion:b});})),!f.length&&!y){a.prefix("error",`No HeroUI components detected in your package.json at: ${n}`);return}if(o)e=p.map(h=>h.package);else if(e.length){if(!Ie(e))return}else {if(y){let h=await me(I),b={isLatest:E(h,q(s[I]))<=0,latestVersion:h,package:I,version:q(s[I])};f.push(b);}f.every(h=>h.isLatest)&&(a.success("\u2705 All HeroUI packages are up to date"),process.exit(0)),e=await ye("Select the components to upgrade",f.map(h=>{let b=kn(h.version,h.latestVersion,r);return {disabled:b,disabledMessage:"Already up to date",title:`${h.package}${b?"":`@${h.version} -> ${X(h.version,h.latestVersion)}`}`,value:h.package}}));}e=e.map(h=>g.heroUIComponentsMap[h]?.package?g.heroUIComponentsMap[h].package:h);let d=f.filter(h=>e.includes(h.package)),l=await Oo({all:o,allDependencies:s,isHeroUIAll:y,upgradeOptionList:d}),x=[],C=await N();if(l.length){let h=await se("Would you like to proceed with the upgrade?",[{title:"Yes",value:!0},{description:"Select this if you wish to exclude certain packages from the upgrade",title:"No",value:!1}]),{install:b}=Ce(C);h||await se("Would you like to exclude any packages from the upgrade?",[{description:"Select this to choose packages to exclude",title:"Yes",value:!0},{description:"Select this to proceed without excluding any packages",title:"No",value:!1}])&&(x=await Mt("Select the packages you want to exclude from the upgrade:",l.map(k=>({description:`${k.version} -> ${X(k.version,k.latestVersion)}`,title:k.package,value:k.package})))),l=l.filter(w=>!x.some(k=>w.package===k)),i?(Ho({dependencies:m,devDependencies:c,upgradePackageList:l}),kt.writeFileSync(n,JSON.stringify(u,null,2),"utf-8"),a.newLine(),a.success("\u2705 Upgrade version written to package.json"),process.exit(0)):await ot(()=>K(`${C} ${b} ${l.reduce((w,k,$)=>`${w}${$===0?"":" "}${k.package}@${k.latestVersion.replace(M,"")}`,"")}`));}wn(C),a.newLine(),a.success("\u2705 Upgrade complete. All components are up to date."),process.exit(0);}var Ut=["add","env","init","list","upgrade","doctor","remove"],z=new Command;z.name("heroui").usage("[command]").description(fo(` HeroUI CLI v${tt.version} `,"")).version(tt.version,"-v, --version","Output the current version").helpOption("-h, --help","Display help for command").allowUnknownOption().option("--no-cache","Disable cache, by default data will be cached for 30m after the first request").option("-d, --debug","Debug mode will not install dependencies").action(async(e,t)=>{let o=!1;if(t){let r=t.args?.[0];if(r&&!Ut.includes(r)){o=!0;let n=Te(Ut,r);n?a.error(`Unknown command '${r}', Did you mean '${R.underline(n)}'?`):a.error(`Unknown command '${r}'`);}}if(!o){let n=(await W("heroui --help")).split(` `);n=n.filter(i=>i&&!i.includes("HeroUI CLI v")),n=n.map(i=>{let s=i.match(/(\w+)\s\[/)?.[1];return s?i.replace(s,R.cyan(s)):i}),a.log(n.join(` `));}process.exit(0);});z.command("init").description("Initializes a new project").argument("[projectName]","Name of the project to initialize").option("-t --template [string]",`Specify a template for the new project, e.g. ${Object.keys(he).join(", ")}`).option("-p --package [string]","The package manager to use for the new project","npm").action(dn);z.command("add").description(`1. Adds components to your project 2. Adds HeroUI Chat codebase to your project`).argument("[targets...]","Names of components, HeroUI Chat codebase url to add").option("-a --all [boolean]","Add all components",!1).option("-p --packagePath [string]","Specify the path to the package.json file").option("-tw --tailwindPath [string]","Specify the path to the tailwind.config.js file").option("-app --appPath [string]","Specify the path to the App.tsx file").option("--prettier [boolean]","Apply Prettier formatting to the added content").option("--addApp [boolean]","Include App.tsx file content that requires a provider",!1).option("-b --beta [boolean]","Add beta components",!1).option("-d --directory [string]","Add HeroUI Chat codebase to a specific directory").action(an);z.command("upgrade").description("Upgrades project components to the latest versions").argument("[components...]","Names of components to upgrade").option("-p --packagePath [string]","Specify the path to the package.json file").option("-a --all [boolean]","Upgrade all components",!1).option("-w --write [boolean]","Write the upgrade version to package.json file",!1).option("-b --beta [boolean]","Upgrade beta components",!1).action(bn);z.command("remove").description("Removes components from the project").argument("[components...]","Names of components to remove").option("-p --packagePath [string]","Specify the path to the package.json file").option("-a --all [boolean]","Remove all components",!1).option("-tw --tailwindPath [string]","Specify the path to the tailwind.config.js file").option("--prettier [boolean]","Apply Prettier formatting to the added content").action(Cn);z.command("list").description("Lists all components, showing status, descriptions, and versions").option("-p --packagePath [string]","Specify the path to the package.json file").option("-r --remote","List all components available remotely").action(gn);z.command("env").description("Displays debugging information for the local environment").option("-p --packagePath [string]","Specify the path to the package.json file").action(ln);z.command("doctor").description("Checks for issues in the project").option("-p --packagePath [string]","Specify the path to the package.json file").option("-tw --tailwindPath [string]","Specify the path to the tailwind.config.js file").option("-app --appPath [string]","Specify the path to the App.tsx file").option("-ca --checkApp [boolean]","Check the App.tsx file",!1).option("-ct --checkTailwind [boolean]","Check the tailwind.config.js file",!0).option("-cp --checkPnpm [boolean]","Check for Pnpm",!0).action(cn);z.hook("preAction",async e=>{let t=e.args?.[0],o=e.rawArgs.slice(2),r=o.includes("--no-cache"),n=o.includes("--debug")||o.includes("-d"),i=e.args?.slice(1);if(et(i)||!t)return;if(dt(r),g.debug=n,g.beta=o.includes("-b")||o.includes("--beta"),t&&Ut.includes(t)){let m=(await lt()).components,c=(await lt()).betaComponents;yt({beta:!1,heroUIComponents:m}),g.beta&&yt({beta:!0,heroUIComponents:c});}let[s]=await Promise.all([ae("cliLatestVersion")]);g.cliLatestVersion=s;let p=tt.version;E(p,s)===-1&&(Ee({center:!0,color:"yellow",padding:1,text:`${R.gray(`Available upgrade: v${p} -> ${R.greenBright(`v${s}`)} Run \`${R.cyan("npm install -g heroui-cli@latest")}\` to upgrade Changelog: ${R.underline("https://github.com/heroui-inc/heroui-cli/releases")}`)}`,title:st("HeroUI CLI")}),a.newLine());});z.parseAsync(process.argv).catch(async e=>{a.newLine(),a.error("Unexpected error. Please report it as a bug:"),a.log(e),a.newLine(),process.exit(1);}); //# sourceMappingURL=out.js.map //# sourceMappingURL=index.js.map node_modules/mkdirp/bin/cmd.js 0000775 00000003446 15114743311 0012374 0 ustar 00 #!/usr/bin/env node const usage = () => ` usage: mkdirp [DIR1,DIR2..] {OPTIONS} Create each supplied directory including any necessary parent directories that don't yet exist. If the directory already exists, do nothing. OPTIONS are: -m<mode> If a directory needs to be created, set the mode as an octal --mode=<mode> permission string. -v --version Print the mkdirp version number -h --help Print this helpful banner -p --print Print the first directories created for each path provided --manual Use manual implementation, even if native is available ` const dirs = [] const opts = {} let print = false let dashdash = false let manual = false for (const arg of process.argv.slice(2)) { if (dashdash) dirs.push(arg) else if (arg === '--') dashdash = true else if (arg === '--manual') manual = true else if (/^-h/.test(arg) || /^--help/.test(arg)) { console.log(usage()) process.exit(0) } else if (arg === '-v' || arg === '--version') { console.log(require('../package.json').version) process.exit(0) } else if (arg === '-p' || arg === '--print') { print = true } else if (/^-m/.test(arg) || /^--mode=/.test(arg)) { const mode = parseInt(arg.replace(/^(-m|--mode=)/, ''), 8) if (isNaN(mode)) { console.error(`invalid mode argument: ${arg}\nMust be an octal number.`) process.exit(1) } opts.mode = mode } else dirs.push(arg) } const mkdirp = require('../') const impl = manual ? mkdirp.manual : mkdirp if (dirs.length === 0) console.error(usage()) Promise.all(dirs.map(dir => impl(dir, opts))) .then(made => print ? made.forEach(m => m && console.log(m)) : null) .catch(er => { console.error(er.message) if (er.code) console.error(' code: ' + er.code) process.exit(1) }) node_modules/fast-glob/out/utils/string.d.ts 0000664 00000000174 15114743311 0015152 0 ustar 00 export declare function isString(input: unknown): input is string; export declare function isEmpty(input: string): boolean; node_modules/fast-glob/out/utils/path.js 0000664 00000005702 15114743311 0014346 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0; const os = require("os"); const path = require("path"); const IS_WINDOWS_PLATFORM = os.platform() === 'win32'; const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ /** * All non-escaped special characters. * Posix: ()*?[]{|}, !+@ before (, ! at the beginning, \\ before non-special characters. * Windows: (){}[], !+@ before (, ! at the beginning. */ const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g; /** * The device path (\\.\ or \\?\). * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths */ const DOS_DEVICE_PATH_RE = /^\\\\([.?])/; /** * All backslashes except those escaping special characters. * Windows: !()+@{} * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions */ const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g; /** * Designed to work only with simple paths: `dir\\file`. */ function unixify(filepath) { return filepath.replace(/\\/g, '/'); } exports.unixify = unixify; function makeAbsolute(cwd, filepath) { return path.resolve(cwd, filepath); } exports.makeAbsolute = makeAbsolute; function removeLeadingDotSegment(entry) { // We do not use `startsWith` because this is 10x slower than current implementation for some cases. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with if (entry.charAt(0) === '.') { const secondCharactery = entry.charAt(1); if (secondCharactery === '/' || secondCharactery === '\\') { return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); } } return entry; } exports.removeLeadingDotSegment = removeLeadingDotSegment; exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; function escapeWindowsPath(pattern) { return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); } exports.escapeWindowsPath = escapeWindowsPath; function escapePosixPath(pattern) { return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); } exports.escapePosixPath = escapePosixPath; exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; function convertWindowsPathToPattern(filepath) { return escapeWindowsPath(filepath) .replace(DOS_DEVICE_PATH_RE, '//$1') .replace(WINDOWS_BACKSLASHES_RE, '/'); } exports.convertWindowsPathToPattern = convertWindowsPathToPattern; function convertPosixPathToPattern(filepath) { return escapePosixPath(filepath); } exports.convertPosixPathToPattern = convertPosixPathToPattern; node_modules/fast-glob/out/utils/array.d.ts 0000664 00000000221 15114743311 0014753 0 ustar 00 export declare function flatten<T>(items: T[][]): T[]; export declare function splitWhen<T>(items: T[], predicate: (item: T) => boolean): T[][]; node_modules/fast-glob/out/utils/fs.js 0000664 00000001364 15114743311 0014022 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createDirentFromStats = void 0; class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } } function createDirentFromStats(name, stats) { return new DirentFromStats(name, stats); } exports.createDirentFromStats = createDirentFromStats; node_modules/fast-glob/out/utils/pattern.js 0000664 00000017437 15114743311 0015077 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; const path = require("path"); const globParent = require("glob-parent"); const micromatch = require("micromatch"); const GLOBSTAR = '**'; const ESCAPE_SYMBOL = '\\'; const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; /** * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. * The latter is due to the presence of the device path at the beginning of the UNC path. */ const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; function isStaticPattern(pattern, options = {}) { return !isDynamicPattern(pattern, options); } exports.isStaticPattern = isStaticPattern; function isDynamicPattern(pattern, options = {}) { /** * A special case with an empty string is necessary for matching patterns that start with a forward slash. * An empty string cannot be a dynamic pattern. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. */ if (pattern === '') { return false; } /** * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check * filepath directly (without read directory). */ if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { return true; } if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { return true; } if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { return true; } if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { return true; } return false; } exports.isDynamicPattern = isDynamicPattern; function hasBraceExpansion(pattern) { const openingBraceIndex = pattern.indexOf('{'); if (openingBraceIndex === -1) { return false; } const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1); if (closingBraceIndex === -1) { return false; } const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); } function convertToPositivePattern(pattern) { return isNegativePattern(pattern) ? pattern.slice(1) : pattern; } exports.convertToPositivePattern = convertToPositivePattern; function convertToNegativePattern(pattern) { return '!' + pattern; } exports.convertToNegativePattern = convertToNegativePattern; function isNegativePattern(pattern) { return pattern.startsWith('!') && pattern[1] !== '('; } exports.isNegativePattern = isNegativePattern; function isPositivePattern(pattern) { return !isNegativePattern(pattern); } exports.isPositivePattern = isPositivePattern; function getNegativePatterns(patterns) { return patterns.filter(isNegativePattern); } exports.getNegativePatterns = getNegativePatterns; function getPositivePatterns(patterns) { return patterns.filter(isPositivePattern); } exports.getPositivePatterns = getPositivePatterns; /** * Returns patterns that can be applied inside the current directory. * * @example * // ['./*', '*', 'a/*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsInsideCurrentDirectory(patterns) { return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); } exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; /** * Returns patterns to be expanded relative to (outside) the current directory. * * @example * // ['../*', './../*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsOutsideCurrentDirectory(patterns) { return patterns.filter(isPatternRelatedToParentDirectory); } exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; function isPatternRelatedToParentDirectory(pattern) { return pattern.startsWith('..') || pattern.startsWith('./..'); } exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; function getBaseDirectory(pattern) { return globParent(pattern, { flipBackslashes: false }); } exports.getBaseDirectory = getBaseDirectory; function hasGlobStar(pattern) { return pattern.includes(GLOBSTAR); } exports.hasGlobStar = hasGlobStar; function endsWithSlashGlobStar(pattern) { return pattern.endsWith('/' + GLOBSTAR); } exports.endsWithSlashGlobStar = endsWithSlashGlobStar; function isAffectDepthOfReadingPattern(pattern) { const basename = path.basename(pattern); return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); } exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; function expandPatternsWithBraceExpansion(patterns) { return patterns.reduce((collection, pattern) => { return collection.concat(expandBraceExpansion(pattern)); }, []); } exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; function expandBraceExpansion(pattern) { const patterns = micromatch.braces(pattern, { expand: true, nodupes: true, keepEscaping: true }); /** * Sort the patterns by length so that the same depth patterns are processed side by side. * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']` */ patterns.sort((a, b) => a.length - b.length); /** * Micromatch can return an empty string in the case of patterns like `{a,}`. */ return patterns.filter((pattern) => pattern !== ''); } exports.expandBraceExpansion = expandBraceExpansion; function getPatternParts(pattern, options) { let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); /** * The scan method returns an empty array in some cases. * See micromatch/picomatch#58 for more details. */ if (parts.length === 0) { parts = [pattern]; } /** * The scan method does not return an empty part for the pattern with a forward slash. * This is another part of micromatch/picomatch#58. */ if (parts[0].startsWith('/')) { parts[0] = parts[0].slice(1); parts.unshift(''); } return parts; } exports.getPatternParts = getPatternParts; function makeRe(pattern, options) { return micromatch.makeRe(pattern, options); } exports.makeRe = makeRe; function convertPatternsToRe(patterns, options) { return patterns.map((pattern) => makeRe(pattern, options)); } exports.convertPatternsToRe = convertPatternsToRe; function matchAny(entry, patternsRe) { return patternsRe.some((patternRe) => patternRe.test(entry)); } exports.matchAny = matchAny; /** * This package only works with forward slashes as a path separator. * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. */ function removeDuplicateSlashes(pattern) { return pattern.replace(DOUBLE_SLASH_RE, '/'); } exports.removeDuplicateSlashes = removeDuplicateSlashes; node_modules/fast-glob/out/utils/string.js 0000664 00000000452 15114743311 0014715 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isEmpty = exports.isString = void 0; function isString(input) { return typeof input === 'string'; } exports.isString = isString; function isEmpty(input) { return input === ''; } exports.isEmpty = isEmpty; node_modules/fast-glob/out/utils/index.d.ts 0000664 00000000452 15114743311 0014752 0 ustar 00 import * as array from './array'; import * as errno from './errno'; import * as fs from './fs'; import * as path from './path'; import * as pattern from './pattern'; import * as stream from './stream'; import * as string from './string'; export { array, errno, fs, path, pattern, stream, string }; node_modules/fast-glob/out/utils/stream.d.ts 0000664 00000000254 15114743311 0015136 0 ustar 00 /// <reference types="node" /> /// <reference types="node" /> import { Readable } from 'stream'; export declare function merge(streams: Readable[]): NodeJS.ReadableStream; node_modules/fast-glob/out/utils/array.js 0000664 00000001140 15114743311 0014520 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.splitWhen = exports.flatten = void 0; function flatten(items) { return items.reduce((collection, item) => [].concat(collection, item), []); } exports.flatten = flatten; function splitWhen(items, predicate) { const result = [[]]; let groupIndex = 0; for (const item of items) { if (predicate(item)) { groupIndex++; result[groupIndex] = []; } else { result[groupIndex].push(item); } } return result; } exports.splitWhen = splitWhen; node_modules/fast-glob/out/utils/path.d.ts 0000664 00000001343 15114743311 0014577 0 ustar 00 import { Pattern } from '../types'; /** * Designed to work only with simple paths: `dir\\file`. */ export declare function unixify(filepath: string): string; export declare function makeAbsolute(cwd: string, filepath: string): string; export declare function removeLeadingDotSegment(entry: string): string; export declare const escape: typeof escapeWindowsPath; export declare function escapeWindowsPath(pattern: Pattern): Pattern; export declare function escapePosixPath(pattern: Pattern): Pattern; export declare const convertPathToPattern: typeof convertWindowsPathToPattern; export declare function convertWindowsPathToPattern(filepath: string): Pattern; export declare function convertPosixPathToPattern(filepath: string): Pattern; node_modules/fast-glob/out/utils/stream.js 0000664 00000001165 15114743311 0014704 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.merge = void 0; const merge2 = require("merge2"); function merge(streams) { const mergedStream = merge2(streams); streams.forEach((stream) => { stream.once('error', (error) => mergedStream.emit('error', error)); }); mergedStream.once('close', () => propagateCloseEventToSources(streams)); mergedStream.once('end', () => propagateCloseEventToSources(streams)); return mergedStream; } exports.merge = merge; function propagateCloseEventToSources(streams) { streams.forEach((stream) => stream.emit('close')); } node_modules/fast-glob/out/utils/index.js 0000664 00000001124 15114743311 0014513 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; const array = require("./array"); exports.array = array; const errno = require("./errno"); exports.errno = errno; const fs = require("./fs"); exports.fs = fs; const path = require("./path"); exports.path = path; const pattern = require("./pattern"); exports.pattern = pattern; const stream = require("./stream"); exports.stream = stream; const string = require("./string"); exports.string = string; node_modules/fast-glob/out/utils/errno.d.ts 0000664 00000000166 15114743311 0014772 0 ustar 00 import { ErrnoException } from '../types'; export declare function isEnoentCodeError(error: ErrnoException): boolean; node_modules/fast-glob/out/utils/errno.js 0000664 00000000352 15114743311 0014533 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isEnoentCodeError = void 0; function isEnoentCodeError(error) { return error.code === 'ENOENT'; } exports.isEnoentCodeError = isEnoentCodeError; node_modules/fast-glob/out/utils/fs.d.ts 0000664 00000000272 15114743311 0014253 0 ustar 00 /// <reference types="node" /> import * as fs from 'fs'; import { Dirent } from '@nodelib/fs.walk'; export declare function createDirentFromStats(name: string, stats: fs.Stats): Dirent; node_modules/fast-glob/out/utils/pattern.d.ts 0000664 00000005070 15114743311 0015321 0 ustar 00 import { MicromatchOptions, Pattern, PatternRe } from '../types'; type PatternTypeOptions = { braceExpansion?: boolean; caseSensitiveMatch?: boolean; extglob?: boolean; }; export declare function isStaticPattern(pattern: Pattern, options?: PatternTypeOptions): boolean; export declare function isDynamicPattern(pattern: Pattern, options?: PatternTypeOptions): boolean; export declare function convertToPositivePattern(pattern: Pattern): Pattern; export declare function convertToNegativePattern(pattern: Pattern): Pattern; export declare function isNegativePattern(pattern: Pattern): boolean; export declare function isPositivePattern(pattern: Pattern): boolean; export declare function getNegativePatterns(patterns: Pattern[]): Pattern[]; export declare function getPositivePatterns(patterns: Pattern[]): Pattern[]; /** * Returns patterns that can be applied inside the current directory. * * @example * // ['./*', '*', 'a/*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ export declare function getPatternsInsideCurrentDirectory(patterns: Pattern[]): Pattern[]; /** * Returns patterns to be expanded relative to (outside) the current directory. * * @example * // ['../*', './../*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ export declare function getPatternsOutsideCurrentDirectory(patterns: Pattern[]): Pattern[]; export declare function isPatternRelatedToParentDirectory(pattern: Pattern): boolean; export declare function getBaseDirectory(pattern: Pattern): string; export declare function hasGlobStar(pattern: Pattern): boolean; export declare function endsWithSlashGlobStar(pattern: Pattern): boolean; export declare function isAffectDepthOfReadingPattern(pattern: Pattern): boolean; export declare function expandPatternsWithBraceExpansion(patterns: Pattern[]): Pattern[]; export declare function expandBraceExpansion(pattern: Pattern): Pattern[]; export declare function getPatternParts(pattern: Pattern, options: MicromatchOptions): Pattern[]; export declare function makeRe(pattern: Pattern, options: MicromatchOptions): PatternRe; export declare function convertPatternsToRe(patterns: Pattern[], options: MicromatchOptions): PatternRe[]; export declare function matchAny(entry: string, patternsRe: PatternRe[]): boolean; /** * This package only works with forward slashes as a path separator. * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. */ export declare function removeDuplicateSlashes(pattern: string): string; export {}; node_modules/fast-glob/out/settings.d.ts 0000664 00000010037 15114743311 0014343 0 ustar 00 import { FileSystemAdapter, Pattern } from './types'; export declare const DEFAULT_FILE_SYSTEM_ADAPTER: FileSystemAdapter; export type Options = { /** * Return the absolute path for entries. * * @default false */ absolute?: boolean; /** * If set to `true`, then patterns without slashes will be matched against * the basename of the path if it contains slashes. * * @default false */ baseNameMatch?: boolean; /** * Enables Bash-like brace expansion. * * @default true */ braceExpansion?: boolean; /** * Enables a case-sensitive mode for matching files. * * @default true */ caseSensitiveMatch?: boolean; /** * Specifies the maximum number of concurrent requests from a reader to read * directories. * * @default os.cpus().length */ concurrency?: number; /** * The current working directory in which to search. * * @default process.cwd() */ cwd?: string; /** * Specifies the maximum depth of a read directory relative to the start * directory. * * @default Infinity */ deep?: number; /** * Allow patterns to match entries that begin with a period (`.`). * * @default false */ dot?: boolean; /** * Enables Bash-like `extglob` functionality. * * @default true */ extglob?: boolean; /** * Indicates whether to traverse descendants of symbolic link directories. * * @default true */ followSymbolicLinks?: boolean; /** * Custom implementation of methods for working with the file system. * * @default fs.* */ fs?: Partial<FileSystemAdapter>; /** * Enables recursively repeats a pattern containing `**`. * If `false`, `**` behaves exactly like `*`. * * @default true */ globstar?: boolean; /** * An array of glob patterns to exclude matches. * This is an alternative way to use negative patterns. * * @default [] */ ignore?: Pattern[]; /** * Mark the directory path with the final slash. * * @default false */ markDirectories?: boolean; /** * Returns objects (instead of strings) describing entries. * * @default false */ objectMode?: boolean; /** * Return only directories. * * @default false */ onlyDirectories?: boolean; /** * Return only files. * * @default true */ onlyFiles?: boolean; /** * Enables an object mode (`objectMode`) with an additional `stats` field. * * @default false */ stats?: boolean; /** * By default this package suppress only `ENOENT` errors. * Set to `true` to suppress any error. * * @default false */ suppressErrors?: boolean; /** * Throw an error when symbolic link is broken if `true` or safely * return `lstat` call if `false`. * * @default false */ throwErrorOnBrokenSymbolicLink?: boolean; /** * Ensures that the returned entries are unique. * * @default true */ unique?: boolean; }; export default class Settings { private readonly _options; readonly absolute: boolean; readonly baseNameMatch: boolean; readonly braceExpansion: boolean; readonly caseSensitiveMatch: boolean; readonly concurrency: number; readonly cwd: string; readonly deep: number; readonly dot: boolean; readonly extglob: boolean; readonly followSymbolicLinks: boolean; readonly fs: FileSystemAdapter; readonly globstar: boolean; readonly ignore: Pattern[]; readonly markDirectories: boolean; readonly objectMode: boolean; readonly onlyDirectories: boolean; readonly onlyFiles: boolean; readonly stats: boolean; readonly suppressErrors: boolean; readonly throwErrorOnBrokenSymbolicLink: boolean; readonly unique: boolean; constructor(_options?: Options); private _getValue; private _getFileSystemMethods; } node_modules/fast-glob/out/settings.js 0000664 00000005441 15114743311 0014112 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; const fs = require("fs"); const os = require("os"); /** * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 */ const CPU_COUNT = Math.max(os.cpus().length, 1); exports.DEFAULT_FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, lstatSync: fs.lstatSync, stat: fs.stat, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; class Settings { constructor(_options = {}) { this._options = _options; this.absolute = this._getValue(this._options.absolute, false); this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); this.braceExpansion = this._getValue(this._options.braceExpansion, true); this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); this.cwd = this._getValue(this._options.cwd, process.cwd()); this.deep = this._getValue(this._options.deep, Infinity); this.dot = this._getValue(this._options.dot, false); this.extglob = this._getValue(this._options.extglob, true); this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); this.fs = this._getFileSystemMethods(this._options.fs); this.globstar = this._getValue(this._options.globstar, true); this.ignore = this._getValue(this._options.ignore, []); this.markDirectories = this._getValue(this._options.markDirectories, false); this.objectMode = this._getValue(this._options.objectMode, false); this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); this.onlyFiles = this._getValue(this._options.onlyFiles, true); this.stats = this._getValue(this._options.stats, false); this.suppressErrors = this._getValue(this._options.suppressErrors, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); this.unique = this._getValue(this._options.unique, true); if (this.onlyDirectories) { this.onlyFiles = false; } if (this.stats) { this.objectMode = true; } // Remove the cast to the array in the next major (#404). this.ignore = [].concat(this.ignore); } _getValue(option, value) { return option === undefined ? value : option; } _getFileSystemMethods(methods = {}) { return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); } } exports.default = Settings; node_modules/fast-glob/out/index.d.ts 0000664 00000004200 15114743311 0013605 0 ustar 00 /// <reference types="node" /> import * as taskManager from './managers/tasks'; import { Options as OptionsInternal } from './settings'; import { Entry as EntryInternal, FileSystemAdapter as FileSystemAdapterInternal, Pattern as PatternInternal } from './types'; type EntryObjectModePredicate = { [TKey in keyof Pick<OptionsInternal, 'objectMode'>]-?: true; }; type EntryStatsPredicate = { [TKey in keyof Pick<OptionsInternal, 'stats'>]-?: true; }; type EntryObjectPredicate = EntryObjectModePredicate | EntryStatsPredicate; declare function FastGlob(source: PatternInternal | PatternInternal[], options: OptionsInternal & EntryObjectPredicate): Promise<EntryInternal[]>; declare function FastGlob(source: PatternInternal | PatternInternal[], options?: OptionsInternal): Promise<string[]>; declare namespace FastGlob { type Options = OptionsInternal; type Entry = EntryInternal; type Task = taskManager.Task; type Pattern = PatternInternal; type FileSystemAdapter = FileSystemAdapterInternal; const glob: typeof FastGlob; const globSync: typeof sync; const globStream: typeof stream; const async: typeof FastGlob; function sync(source: PatternInternal | PatternInternal[], options: OptionsInternal & EntryObjectPredicate): EntryInternal[]; function sync(source: PatternInternal | PatternInternal[], options?: OptionsInternal): string[]; function stream(source: PatternInternal | PatternInternal[], options?: OptionsInternal): NodeJS.ReadableStream; function generateTasks(source: PatternInternal | PatternInternal[], options?: OptionsInternal): Task[]; function isDynamicPattern(source: PatternInternal, options?: OptionsInternal): boolean; function escapePath(source: string): PatternInternal; function convertPathToPattern(source: string): PatternInternal; namespace posix { function escapePath(source: string): PatternInternal; function convertPathToPattern(source: string): PatternInternal; } namespace win32 { function escapePath(source: string): PatternInternal; function convertPathToPattern(source: string): PatternInternal; } } export = FastGlob; node_modules/fast-glob/out/types/index.d.ts 0000664 00000002114 15114743311 0014753 0 ustar 00 /// <reference types="node" /> import * as fsWalk from '@nodelib/fs.walk'; export type ErrnoException = NodeJS.ErrnoException; export type Entry = fsWalk.Entry; export type EntryItem = string | Entry; export type Pattern = string; export type PatternRe = RegExp; export type PatternsGroup = Record<string, Pattern[]>; export type ReaderOptions = fsWalk.Options & { transform(entry: Entry): EntryItem; deepFilter: DeepFilterFunction; entryFilter: EntryFilterFunction; errorFilter: ErrorFilterFunction; fs: FileSystemAdapter; stats: boolean; }; export type ErrorFilterFunction = fsWalk.ErrorFilterFunction; export type EntryFilterFunction = fsWalk.EntryFilterFunction; export type DeepFilterFunction = fsWalk.DeepFilterFunction; export type EntryTransformerFunction = (entry: Entry) => EntryItem; export type MicromatchOptions = { dot?: boolean; matchBase?: boolean; nobrace?: boolean; nocase?: boolean; noext?: boolean; noglobstar?: boolean; posix?: boolean; strictSlashes?: boolean; }; export type FileSystemAdapter = fsWalk.FileSystemAdapter; node_modules/fast-glob/out/types/index.js 0000664 00000000115 15114743311 0014516 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); node_modules/fast-glob/out/providers/transformers/entry.js 0000664 00000001515 15114743311 0020153 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils = require("../../utils"); class EntryTransformer { constructor(_settings) { this._settings = _settings; } getTransformer() { return (entry) => this._transform(entry); } _transform(entry) { let filepath = entry.path; if (this._settings.absolute) { filepath = utils.path.makeAbsolute(this._settings.cwd, filepath); filepath = utils.path.unixify(filepath); } if (this._settings.markDirectories && entry.dirent.isDirectory()) { filepath += '/'; } if (!this._settings.objectMode) { return filepath; } return Object.assign(Object.assign({}, entry), { path: filepath }); } } exports.default = EntryTransformer; node_modules/fast-glob/out/providers/transformers/entry.d.ts 0000664 00000000427 15114743311 0020410 0 ustar 00 import Settings from '../../settings'; import { EntryTransformerFunction } from '../../types'; export default class EntryTransformer { private readonly _settings; constructor(_settings: Settings); getTransformer(): EntryTransformerFunction; private _transform; } node_modules/fast-glob/out/providers/provider.d.ts 0000664 00000001461 15114743311 0016353 0 ustar 00 import { Task } from '../managers/tasks'; import Settings from '../settings'; import { MicromatchOptions, ReaderOptions } from '../types'; import DeepFilter from './filters/deep'; import EntryFilter from './filters/entry'; import ErrorFilter from './filters/error'; import EntryTransformer from './transformers/entry'; export default abstract class Provider<T> { protected readonly _settings: Settings; readonly errorFilter: ErrorFilter; readonly entryFilter: EntryFilter; readonly deepFilter: DeepFilter; readonly entryTransformer: EntryTransformer; constructor(_settings: Settings); abstract read(_task: Task): T; protected _getRootDirectory(task: Task): string; protected _getReaderOptions(task: Task): ReaderOptions; protected _getMicromatchOptions(): MicromatchOptions; } node_modules/fast-glob/out/providers/filters/error.d.ts 0000664 00000000411 15114743311 0017314 0 ustar 00 import Settings from '../../settings'; import { ErrorFilterFunction } from '../../types'; export default class ErrorFilter { private readonly _settings; constructor(_settings: Settings); getFilter(): ErrorFilterFunction; private _isNonFatalError; } node_modules/fast-glob/out/providers/filters/deep.d.ts 0000664 00000001224 15114743311 0017103 0 ustar 00 import { MicromatchOptions, EntryFilterFunction, Pattern } from '../../types'; import Settings from '../../settings'; export default class DeepFilter { private readonly _settings; private readonly _micromatchOptions; constructor(_settings: Settings, _micromatchOptions: MicromatchOptions); getFilter(basePath: string, positive: Pattern[], negative: Pattern[]): EntryFilterFunction; private _getMatcher; private _getNegativePatternsRe; private _filter; private _isSkippedByDeep; private _getEntryLevel; private _isSkippedSymbolicLink; private _isSkippedByPositivePatterns; private _isSkippedByNegativePatterns; } node_modules/fast-glob/out/providers/filters/deep.js 0000664 00000004642 15114743311 0016656 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils = require("../../utils"); const partial_1 = require("../matchers/partial"); class DeepFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; } getFilter(basePath, positive, negative) { const matcher = this._getMatcher(positive); const negativeRe = this._getNegativePatternsRe(negative); return (entry) => this._filter(basePath, entry, matcher, negativeRe); } _getMatcher(patterns) { return new partial_1.default(patterns, this._settings, this._micromatchOptions); } _getNegativePatternsRe(patterns) { const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); } _filter(basePath, entry, matcher, negativeRe) { if (this._isSkippedByDeep(basePath, entry.path)) { return false; } if (this._isSkippedSymbolicLink(entry)) { return false; } const filepath = utils.path.removeLeadingDotSegment(entry.path); if (this._isSkippedByPositivePatterns(filepath, matcher)) { return false; } return this._isSkippedByNegativePatterns(filepath, negativeRe); } _isSkippedByDeep(basePath, entryPath) { /** * Avoid unnecessary depth calculations when it doesn't matter. */ if (this._settings.deep === Infinity) { return false; } return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; } _getEntryLevel(basePath, entryPath) { const entryPathDepth = entryPath.split('/').length; if (basePath === '') { return entryPathDepth; } const basePathDepth = basePath.split('/').length; return entryPathDepth - basePathDepth; } _isSkippedSymbolicLink(entry) { return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); } _isSkippedByPositivePatterns(entryPath, matcher) { return !this._settings.baseNameMatch && !matcher.match(entryPath); } _isSkippedByNegativePatterns(entryPath, patternsRe) { return !utils.pattern.matchAny(entryPath, patternsRe); } } exports.default = DeepFilter; node_modules/fast-glob/out/providers/filters/error.js 0000664 00000000671 15114743311 0017070 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils = require("../../utils"); class ErrorFilter { constructor(_settings) { this._settings = _settings; } getFilter() { return (error) => this._isNonFatalError(error); } _isNonFatalError(error) { return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors; } } exports.default = ErrorFilter; node_modules/fast-glob/out/providers/filters/entry.js 0000664 00000005176 15114743311 0017105 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils = require("../../utils"); class EntryFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; this.index = new Map(); } getFilter(positive, negative) { const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions); const negativeRe = utils.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })); return (entry) => this._filter(entry, positiveRe, negativeRe); } _filter(entry, positiveRe, negativeRe) { const filepath = utils.path.removeLeadingDotSegment(entry.path); if (this._settings.unique && this._isDuplicateEntry(filepath)) { return false; } if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { return false; } if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) { return false; } const isDirectory = entry.dirent.isDirectory(); const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory); if (this._settings.unique && isMatched) { this._createIndexRecord(filepath); } return isMatched; } _isDuplicateEntry(filepath) { return this.index.has(filepath); } _createIndexRecord(filepath) { this.index.set(filepath, undefined); } _onlyFileFilter(entry) { return this._settings.onlyFiles && !entry.dirent.isFile(); } _onlyDirectoryFilter(entry) { return this._settings.onlyDirectories && !entry.dirent.isDirectory(); } _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { if (!this._settings.absolute) { return false; } const fullpath = utils.path.makeAbsolute(this._settings.cwd, entryPath); return utils.pattern.matchAny(fullpath, patternsRe); } _isMatchToPatterns(filepath, patternsRe, isDirectory) { // Trying to match files and directories by patterns. const isMatched = utils.pattern.matchAny(filepath, patternsRe); // A pattern with a trailling slash can be used for directory matching. // To apply such pattern, we need to add a tralling slash to the path. if (!isMatched && isDirectory) { return utils.pattern.matchAny(filepath + '/', patternsRe); } return isMatched; } } exports.default = EntryFilter; node_modules/fast-glob/out/providers/filters/entry.d.ts 0000664 00000001220 15114743311 0017323 0 ustar 00 import Settings from '../../settings'; import { EntryFilterFunction, MicromatchOptions, Pattern } from '../../types'; export default class EntryFilter { private readonly _settings; private readonly _micromatchOptions; readonly index: Map<string, undefined>; constructor(_settings: Settings, _micromatchOptions: MicromatchOptions); getFilter(positive: Pattern[], negative: Pattern[]): EntryFilterFunction; private _filter; private _isDuplicateEntry; private _createIndexRecord; private _onlyFileFilter; private _onlyDirectoryFilter; private _isSkippedByAbsoluteNegativePatterns; private _isMatchToPatterns; } node_modules/fast-glob/out/providers/provider.js 0000664 00000003720 15114743311 0016117 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const path = require("path"); const deep_1 = require("./filters/deep"); const entry_1 = require("./filters/entry"); const error_1 = require("./filters/error"); const entry_2 = require("./transformers/entry"); class Provider { constructor(_settings) { this._settings = _settings; this.errorFilter = new error_1.default(this._settings); this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); this.entryTransformer = new entry_2.default(this._settings); } _getRootDirectory(task) { return path.resolve(this._settings.cwd, task.base); } _getReaderOptions(task) { const basePath = task.base === '.' ? '' : task.base; return { basePath, pathSegmentSeparator: '/', concurrency: this._settings.concurrency, deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), entryFilter: this.entryFilter.getFilter(task.positive, task.negative), errorFilter: this.errorFilter.getFilter(), followSymbolicLinks: this._settings.followSymbolicLinks, fs: this._settings.fs, stats: this._settings.stats, throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, transform: this.entryTransformer.getTransformer() }; } _getMicromatchOptions() { return { dot: this._settings.dot, matchBase: this._settings.baseNameMatch, nobrace: !this._settings.braceExpansion, nocase: !this._settings.caseSensitiveMatch, noext: !this._settings.extglob, noglobstar: !this._settings.globstar, posix: true, strictSlashes: false }; } } exports.default = Provider; node_modules/fast-glob/out/providers/stream.d.ts 0000664 00000000664 15114743311 0016020 0 ustar 00 /// <reference types="node" /> import { Readable } from 'stream'; import { Task } from '../managers/tasks'; import ReaderStream from '../readers/stream'; import { ReaderOptions } from '../types'; import Provider from './provider'; export default class ProviderStream extends Provider<Readable> { protected _reader: ReaderStream; read(task: Task): Readable; api(root: string, task: Task, options: ReaderOptions): Readable; } node_modules/fast-glob/out/providers/stream.js 0000664 00000002256 15114743311 0015563 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const stream_1 = require("stream"); const stream_2 = require("../readers/stream"); const provider_1 = require("./provider"); class ProviderStream extends provider_1.default { constructor() { super(...arguments); this._reader = new stream_2.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const source = this.api(root, task, options); const destination = new stream_1.Readable({ objectMode: true, read: () => { } }); source .once('error', (error) => destination.emit('error', error)) .on('data', (entry) => destination.emit('data', options.transform(entry))) .once('end', () => destination.emit('end')); destination .once('close', () => source.destroy()); return destination; } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } exports.default = ProviderStream; node_modules/fast-glob/out/providers/sync.d.ts 0000664 00000000601 15114743311 0015470 0 ustar 00 import { Task } from '../managers/tasks'; import ReaderSync from '../readers/sync'; import { Entry, EntryItem, ReaderOptions } from '../types'; import Provider from './provider'; export default class ProviderSync extends Provider<EntryItem[]> { protected _reader: ReaderSync; read(task: Task): EntryItem[]; api(root: string, task: Task, options: ReaderOptions): Entry[]; } node_modules/fast-glob/out/providers/sync.js 0000664 00000001413 15114743311 0015236 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const sync_1 = require("../readers/sync"); const provider_1 = require("./provider"); class ProviderSync extends provider_1.default { constructor() { super(...arguments); this._reader = new sync_1.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = this.api(root, task, options); return entries.map(options.transform); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } exports.default = ProviderSync; node_modules/fast-glob/out/providers/matchers/matcher.js 0000664 00000003040 15114743311 0017511 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils = require("../../utils"); class Matcher { constructor(_patterns, _settings, _micromatchOptions) { this._patterns = _patterns; this._settings = _settings; this._micromatchOptions = _micromatchOptions; this._storage = []; this._fillStorage(); } _fillStorage() { for (const pattern of this._patterns) { const segments = this._getPatternSegments(pattern); const sections = this._splitSegmentsIntoSections(segments); this._storage.push({ complete: sections.length <= 1, pattern, segments, sections }); } } _getPatternSegments(pattern) { const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions); return parts.map((part) => { const dynamic = utils.pattern.isDynamicPattern(part, this._settings); if (!dynamic) { return { dynamic: false, pattern: part }; } return { dynamic: true, pattern: part, patternRe: utils.pattern.makeRe(part, this._micromatchOptions) }; }); } _splitSegmentsIntoSections(segments) { return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); } } exports.default = Matcher; node_modules/fast-glob/out/providers/matchers/partial.js 0000664 00000002615 15114743311 0017531 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const matcher_1 = require("./matcher"); class PartialMatcher extends matcher_1.default { match(filepath) { const parts = filepath.split('/'); const levels = parts.length; const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); for (const pattern of patterns) { const section = pattern.sections[0]; /** * In this case, the pattern has a globstar and we must read all directories unconditionally, * but only if the level has reached the end of the first group. * * fixtures/{a,b}/** * ^ true/false ^ always true */ if (!pattern.complete && levels > section.length) { return true; } const match = parts.every((part, index) => { const segment = pattern.segments[index]; if (segment.dynamic && segment.patternRe.test(part)) { return true; } if (!segment.dynamic && segment.pattern === part) { return true; } return false; }); if (match) { return true; } } return false; } } exports.default = PartialMatcher; node_modules/fast-glob/out/providers/matchers/matcher.d.ts 0000664 00000002025 15114743311 0017747 0 ustar 00 import { Pattern, MicromatchOptions, PatternRe } from '../../types'; import Settings from '../../settings'; export type PatternSegment = StaticPatternSegment | DynamicPatternSegment; type StaticPatternSegment = { dynamic: false; pattern: Pattern; }; type DynamicPatternSegment = { dynamic: true; pattern: Pattern; patternRe: PatternRe; }; export type PatternSection = PatternSegment[]; export type PatternInfo = { /** * Indicates that the pattern has a globstar (more than a single section). */ complete: boolean; pattern: Pattern; segments: PatternSegment[]; sections: PatternSection[]; }; export default abstract class Matcher { private readonly _patterns; private readonly _settings; private readonly _micromatchOptions; protected readonly _storage: PatternInfo[]; constructor(_patterns: Pattern[], _settings: Settings, _micromatchOptions: MicromatchOptions); private _fillStorage; private _getPatternSegments; private _splitSegmentsIntoSections; } export {}; node_modules/fast-glob/out/providers/matchers/partial.d.ts 0000664 00000000177 15114743311 0017766 0 ustar 00 import Matcher from './matcher'; export default class PartialMatcher extends Matcher { match(filepath: string): boolean; } node_modules/fast-glob/out/providers/async.d.ts 0000664 00000000640 15114743311 0015634 0 ustar 00 import { Task } from '../managers/tasks'; import { Entry, EntryItem, ReaderOptions } from '../types'; import ReaderAsync from '../readers/async'; import Provider from './provider'; export default class ProviderAsync extends Provider<Promise<EntryItem[]>> { protected _reader: ReaderAsync; read(task: Task): Promise<EntryItem[]>; api(root: string, task: Task, options: ReaderOptions): Promise<Entry[]>; } node_modules/fast-glob/out/providers/async.js 0000664 00000001456 15114743311 0015406 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const async_1 = require("../readers/async"); const provider_1 = require("./provider"); class ProviderAsync extends provider_1.default { constructor() { super(...arguments); this._reader = new async_1.default(this._settings); } async read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = await this.api(root, task, options); return entries.map((entry) => options.transform(entry)); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } exports.default = ProviderAsync; node_modules/fast-glob/out/managers/tasks.js 0000664 00000012633 15114743311 0015175 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; const utils = require("../utils"); function generate(input, settings) { const patterns = processPatterns(input, settings); const ignore = processPatterns(settings.ignore, settings); const positivePatterns = getPositivePatterns(patterns); const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); return staticTasks.concat(dynamicTasks); } exports.generate = generate; function processPatterns(input, settings) { let patterns = input; /** * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry * and some problems with the micromatch package (see fast-glob issues: #365, #394). * * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown * in matching in the case of a large set of patterns after expansion. */ if (settings.braceExpansion) { patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns); } /** * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used * at any nesting level. * * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change * the pattern in the filter before creating a regular expression. There is no need to change the patterns * in the application. Only on the input. */ if (settings.baseNameMatch) { patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`); } /** * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion. */ return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern)); } /** * Returns tasks grouped by basic pattern directories. * * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. * This is necessary because directory traversal starts at the base directory and goes deeper. */ function convertPatternsToTasks(positive, negative, dynamic) { const tasks = []; const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive); const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive); const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); /* * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. */ if ('.' in insideCurrentDirectoryGroup) { tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); } else { tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); } return tasks; } exports.convertPatternsToTasks = convertPatternsToTasks; function getPositivePatterns(patterns) { return utils.pattern.getPositivePatterns(patterns); } exports.getPositivePatterns = getPositivePatterns; function getNegativePatternsAsPositive(patterns, ignore) { const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore); const positive = negative.map(utils.pattern.convertToPositivePattern); return positive; } exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; function groupPatternsByBaseDirectory(patterns) { const group = {}; return patterns.reduce((collection, pattern) => { const base = utils.pattern.getBaseDirectory(pattern); if (base in collection) { collection[base].push(pattern); } else { collection[base] = [pattern]; } return collection; }, group); } exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; function convertPatternGroupsToTasks(positive, negative, dynamic) { return Object.keys(positive).map((base) => { return convertPatternGroupToTask(base, positive[base], negative, dynamic); }); } exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; function convertPatternGroupToTask(base, positive, negative, dynamic) { return { dynamic, positive, negative, base, patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern)) }; } exports.convertPatternGroupToTask = convertPatternGroupToTask; node_modules/fast-glob/out/managers/tasks.d.ts 0000664 00000002306 15114743311 0015425 0 ustar 00 import Settings from '../settings'; import { Pattern, PatternsGroup } from '../types'; export type Task = { base: string; dynamic: boolean; patterns: Pattern[]; positive: Pattern[]; negative: Pattern[]; }; export declare function generate(input: Pattern[], settings: Settings): Task[]; /** * Returns tasks grouped by basic pattern directories. * * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. * This is necessary because directory traversal starts at the base directory and goes deeper. */ export declare function convertPatternsToTasks(positive: Pattern[], negative: Pattern[], dynamic: boolean): Task[]; export declare function getPositivePatterns(patterns: Pattern[]): Pattern[]; export declare function getNegativePatternsAsPositive(patterns: Pattern[], ignore: Pattern[]): Pattern[]; export declare function groupPatternsByBaseDirectory(patterns: Pattern[]): PatternsGroup; export declare function convertPatternGroupsToTasks(positive: PatternsGroup, negative: Pattern[], dynamic: boolean): Task[]; export declare function convertPatternGroupToTask(base: string, positive: Pattern[], negative: Pattern[], dynamic: boolean): Task; node_modules/fast-glob/out/index.js 0000664 00000007773 15114743311 0013373 0 ustar 00 "use strict"; const taskManager = require("./managers/tasks"); const async_1 = require("./providers/async"); const stream_1 = require("./providers/stream"); const sync_1 = require("./providers/sync"); const settings_1 = require("./settings"); const utils = require("./utils"); async function FastGlob(source, options) { assertPatternsInput(source); const works = getWorks(source, async_1.default, options); const result = await Promise.all(works); return utils.array.flatten(result); } // https://github.com/typescript-eslint/typescript-eslint/issues/60 // eslint-disable-next-line no-redeclare (function (FastGlob) { FastGlob.glob = FastGlob; FastGlob.globSync = sync; FastGlob.globStream = stream; FastGlob.async = FastGlob; function sync(source, options) { assertPatternsInput(source); const works = getWorks(source, sync_1.default, options); return utils.array.flatten(works); } FastGlob.sync = sync; function stream(source, options) { assertPatternsInput(source); const works = getWorks(source, stream_1.default, options); /** * The stream returned by the provider cannot work with an asynchronous iterator. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. * This affects performance (+25%). I don't see best solution right now. */ return utils.stream.merge(works); } FastGlob.stream = stream; function generateTasks(source, options) { assertPatternsInput(source); const patterns = [].concat(source); const settings = new settings_1.default(options); return taskManager.generate(patterns, settings); } FastGlob.generateTasks = generateTasks; function isDynamicPattern(source, options) { assertPatternsInput(source); const settings = new settings_1.default(options); return utils.pattern.isDynamicPattern(source, settings); } FastGlob.isDynamicPattern = isDynamicPattern; function escapePath(source) { assertPatternsInput(source); return utils.path.escape(source); } FastGlob.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils.path.convertPathToPattern(source); } FastGlob.convertPathToPattern = convertPathToPattern; let posix; (function (posix) { function escapePath(source) { assertPatternsInput(source); return utils.path.escapePosixPath(source); } posix.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils.path.convertPosixPathToPattern(source); } posix.convertPathToPattern = convertPathToPattern; })(posix = FastGlob.posix || (FastGlob.posix = {})); let win32; (function (win32) { function escapePath(source) { assertPatternsInput(source); return utils.path.escapeWindowsPath(source); } win32.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils.path.convertWindowsPathToPattern(source); } win32.convertPathToPattern = convertPathToPattern; })(win32 = FastGlob.win32 || (FastGlob.win32 = {})); })(FastGlob || (FastGlob = {})); function getWorks(source, _Provider, options) { const patterns = [].concat(source); const settings = new settings_1.default(options); const tasks = taskManager.generate(patterns, settings); const provider = new _Provider(settings); return tasks.map(provider.read, provider); } function assertPatternsInput(input) { const source = [].concat(input); const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); if (!isValidSource) { throw new TypeError('Patterns must be a string (non empty) or an array of strings'); } } module.exports = FastGlob; node_modules/fast-glob/out/readers/reader.js 0000664 00000002047 15114743311 0015140 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const path = require("path"); const fsStat = require("@nodelib/fs.stat"); const utils = require("../utils"); class Reader { constructor(_settings) { this._settings = _settings; this._fsStatSettings = new fsStat.Settings({ followSymbolicLink: this._settings.followSymbolicLinks, fs: this._settings.fs, throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks }); } _getFullEntryPath(filepath) { return path.resolve(this._settings.cwd, filepath); } _makeEntry(stats, pattern) { const entry = { name: pattern, path: pattern, dirent: utils.fs.createDirentFromStats(pattern, stats) }; if (this._settings.stats) { entry.stats = stats; } return entry; } _isFatalError(error) { return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; } } exports.default = Reader; node_modules/fast-glob/out/readers/reader.d.ts 0000664 00000001312 15114743311 0015366 0 ustar 00 /// <reference types="node" /> import * as fs from 'fs'; import * as fsStat from '@nodelib/fs.stat'; import Settings from '../settings'; import { Entry, ErrnoException, Pattern, ReaderOptions } from '../types'; export default abstract class Reader<T> { protected readonly _settings: Settings; protected readonly _fsStatSettings: fsStat.Settings; constructor(_settings: Settings); abstract dynamic(root: string, options: ReaderOptions): T; abstract static(patterns: Pattern[], options: ReaderOptions): T; protected _getFullEntryPath(filepath: string): string; protected _makeEntry(stats: fs.Stats, pattern: Pattern): Entry; protected _isFatalError(error: ErrnoException): boolean; } node_modules/fast-glob/out/readers/stream.d.ts 0000664 00000001066 15114743311 0015425 0 ustar 00 /// <reference types="node" /> import { Readable } from 'stream'; import * as fsStat from '@nodelib/fs.stat'; import * as fsWalk from '@nodelib/fs.walk'; import { Pattern, ReaderOptions } from '../types'; import Reader from './reader'; export default class ReaderStream extends Reader<Readable> { protected _walkStream: typeof fsWalk.walkStream; protected _stat: typeof fsStat.stat; dynamic(root: string, options: ReaderOptions): Readable; static(patterns: Pattern[], options: ReaderOptions): Readable; private _getEntry; private _getStat; } node_modules/fast-glob/out/readers/stream.js 0000664 00000003516 15114743311 0015173 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const stream_1 = require("stream"); const fsStat = require("@nodelib/fs.stat"); const fsWalk = require("@nodelib/fs.walk"); const reader_1 = require("./reader"); class ReaderStream extends reader_1.default { constructor() { super(...arguments); this._walkStream = fsWalk.walkStream; this._stat = fsStat.stat; } dynamic(root, options) { return this._walkStream(root, options); } static(patterns, options) { const filepaths = patterns.map(this._getFullEntryPath, this); const stream = new stream_1.PassThrough({ objectMode: true }); stream._write = (index, _enc, done) => { return this._getEntry(filepaths[index], patterns[index], options) .then((entry) => { if (entry !== null && options.entryFilter(entry)) { stream.push(entry); } if (index === filepaths.length - 1) { stream.end(); } done(); }) .catch(done); }; for (let i = 0; i < filepaths.length; i++) { stream.write(i); } return stream; } _getEntry(filepath, pattern, options) { return this._getStat(filepath) .then((stats) => this._makeEntry(stats, pattern)) .catch((error) => { if (options.errorFilter(error)) { return null; } throw error; }); } _getStat(filepath) { return new Promise((resolve, reject) => { this._stat(filepath, this._fsStatSettings, (error, stats) => { return error === null ? resolve(stats) : reject(error); }); }); } } exports.default = ReaderStream; node_modules/fast-glob/out/readers/sync.d.ts 0000664 00000000772 15114743311 0015111 0 ustar 00 import * as fsStat from '@nodelib/fs.stat'; import * as fsWalk from '@nodelib/fs.walk'; import { Entry, Pattern, ReaderOptions } from '../types'; import Reader from './reader'; export default class ReaderSync extends Reader<Entry[]> { protected _walkSync: typeof fsWalk.walkSync; protected _statSync: typeof fsStat.statSync; dynamic(root: string, options: ReaderOptions): Entry[]; static(patterns: Pattern[], options: ReaderOptions): Entry[]; private _getEntry; private _getStat; } node_modules/fast-glob/out/readers/sync.js 0000664 00000002462 15114743311 0014653 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const fsStat = require("@nodelib/fs.stat"); const fsWalk = require("@nodelib/fs.walk"); const reader_1 = require("./reader"); class ReaderSync extends reader_1.default { constructor() { super(...arguments); this._walkSync = fsWalk.walkSync; this._statSync = fsStat.statSync; } dynamic(root, options) { return this._walkSync(root, options); } static(patterns, options) { const entries = []; for (const pattern of patterns) { const filepath = this._getFullEntryPath(pattern); const entry = this._getEntry(filepath, pattern, options); if (entry === null || !options.entryFilter(entry)) { continue; } entries.push(entry); } return entries; } _getEntry(filepath, pattern, options) { try { const stats = this._getStat(filepath); return this._makeEntry(stats, pattern); } catch (error) { if (options.errorFilter(error)) { return null; } throw error; } } _getStat(filepath) { return this._statSync(filepath, this._fsStatSettings); } } exports.default = ReaderSync; node_modules/fast-glob/out/readers/async.d.ts 0000664 00000000731 15114743311 0015245 0 ustar 00 import * as fsWalk from '@nodelib/fs.walk'; import { Entry, ReaderOptions, Pattern } from '../types'; import Reader from './reader'; import ReaderStream from './stream'; export default class ReaderAsync extends Reader<Promise<Entry[]>> { protected _walkAsync: typeof fsWalk.walk; protected _readerStream: ReaderStream; dynamic(root: string, options: ReaderOptions): Promise<Entry[]>; static(patterns: Pattern[], options: ReaderOptions): Promise<Entry[]>; } node_modules/fast-glob/out/readers/async.js 0000664 00000002275 15114743311 0015016 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const fsWalk = require("@nodelib/fs.walk"); const reader_1 = require("./reader"); const stream_1 = require("./stream"); class ReaderAsync extends reader_1.default { constructor() { super(...arguments); this._walkAsync = fsWalk.walk; this._readerStream = new stream_1.default(this._settings); } dynamic(root, options) { return new Promise((resolve, reject) => { this._walkAsync(root, options, (error, entries) => { if (error === null) { resolve(entries); } else { reject(error); } }); }); } async static(patterns, options) { const entries = []; const stream = this._readerStream.static(patterns, options); // After #235, replace it with an asynchronous iterator. return new Promise((resolve, reject) => { stream.once('error', reject); stream.on('data', (entry) => entries.push(entry)); stream.once('end', () => resolve(entries)); }); } } exports.default = ReaderAsync; node_modules/fast-glob/package.json 0000664 00000005356 15114743311 0013400 0 ustar 00 { "name": "fast-glob", "version": "3.3.2", "description": "It's a very fast and efficient glob library for Node.js", "license": "MIT", "repository": "mrmlnc/fast-glob", "author": { "name": "Denis Malinochkin", "url": "https://mrmlnc.com" }, "engines": { "node": ">=8.6.0" }, "main": "out/index.js", "typings": "out/index.d.ts", "files": [ "out", "!out/{benchmark,tests}", "!out/**/*.map", "!out/**/*.spec.*" ], "keywords": [ "glob", "patterns", "fast", "implementation" ], "devDependencies": { "@nodelib/fs.macchiato": "^1.0.1", "@types/glob-parent": "^5.1.0", "@types/merge2": "^1.1.4", "@types/micromatch": "^4.0.0", "@types/mocha": "^5.2.7", "@types/node": "^14.18.53", "@types/picomatch": "^2.3.0", "@types/sinon": "^7.5.0", "bencho": "^0.1.1", "eslint": "^6.5.1", "eslint-config-mrmlnc": "^1.1.0", "execa": "^7.1.1", "fast-glob": "^3.0.4", "fdir": "^6.0.1", "glob": "^10.0.0", "hereby": "^1.8.1", "mocha": "^6.2.1", "rimraf": "^5.0.0", "sinon": "^7.5.0", "snap-shot-it": "^7.9.10", "typescript": "^4.9.5" }, "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.4" }, "scripts": { "clean": "rimraf out", "lint": "eslint \"src/**/*.ts\" --cache", "compile": "tsc", "test": "mocha \"out/**/*.spec.js\" -s 0", "test:e2e": "mocha \"out/**/*.e2e.js\" -s 0", "test:e2e:sync": "mocha \"out/**/*.e2e.js\" -s 0 --grep \"\\(sync\\)\"", "test:e2e:async": "mocha \"out/**/*.e2e.js\" -s 0 --grep \"\\(async\\)\"", "test:e2e:stream": "mocha \"out/**/*.e2e.js\" -s 0 --grep \"\\(stream\\)\"", "build": "npm run clean && npm run compile && npm run lint && npm test", "watch": "npm run clean && npm run compile -- --sourceMap --watch", "bench:async": "npm run bench:product:async && npm run bench:regression:async", "bench:stream": "npm run bench:product:stream && npm run bench:regression:stream", "bench:sync": "npm run bench:product:sync && npm run bench:regression:sync", "bench:product": "npm run bench:product:async && npm run bench:product:sync && npm run bench:product:stream", "bench:product:async": "hereby bench:product:async", "bench:product:sync": "hereby bench:product:sync", "bench:product:stream": "hereby bench:product:stream", "bench:regression": "npm run bench:regression:async && npm run bench:regression:sync && npm run bench:regression:stream", "bench:regression:async": "hereby bench:regression:async", "bench:regression:sync": "hereby bench:regression:sync", "bench:regression:stream": "hereby bench:regression:stream" } } node_modules/fast-glob/LICENSE 0000664 00000002067 15114743311 0012113 0 ustar 00 The MIT License (MIT) Copyright (c) Denis Malinochkin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/fast-glob/README.md 0000664 00000063061 15114743311 0012366 0 ustar 00 # fast-glob > It's a very fast and efficient [glob][glob_definition] library for [Node.js][node_js]. This package provides methods for traversing the file system and returning pathnames that matched a defined set of a specified pattern according to the rules used by the Unix Bash shell with some simplifications, meanwhile results are returned in **arbitrary order**. Quick, simple, effective. ## Table of Contents <details> <summary><strong>Details</strong></summary> * [Highlights](#highlights) * [Old and modern mode](#old-and-modern-mode) * [Pattern syntax](#pattern-syntax) * [Basic syntax](#basic-syntax) * [Advanced syntax](#advanced-syntax) * [Installation](#installation) * [API](#api) * [Asynchronous](#asynchronous) * [Synchronous](#synchronous) * [Stream](#stream) * [patterns](#patterns) * [[options]](#options) * [Helpers](#helpers) * [generateTasks](#generatetaskspatterns-options) * [isDynamicPattern](#isdynamicpatternpattern-options) * [escapePath](#escapepathpath) * [convertPathToPattern](#convertpathtopatternpath) * [Options](#options-3) * [Common](#common) * [concurrency](#concurrency) * [cwd](#cwd) * [deep](#deep) * [followSymbolicLinks](#followsymboliclinks) * [fs](#fs) * [ignore](#ignore) * [suppressErrors](#suppresserrors) * [throwErrorOnBrokenSymbolicLink](#throwerroronbrokensymboliclink) * [Output control](#output-control) * [absolute](#absolute) * [markDirectories](#markdirectories) * [objectMode](#objectmode) * [onlyDirectories](#onlydirectories) * [onlyFiles](#onlyfiles) * [stats](#stats) * [unique](#unique) * [Matching control](#matching-control) * [braceExpansion](#braceexpansion) * [caseSensitiveMatch](#casesensitivematch) * [dot](#dot) * [extglob](#extglob) * [globstar](#globstar) * [baseNameMatch](#basenamematch) * [FAQ](#faq) * [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern) * [How to write patterns on Windows?](#how-to-write-patterns-on-windows) * [Why are parentheses match wrong?](#why-are-parentheses-match-wrong) * [How to exclude directory from reading?](#how-to-exclude-directory-from-reading) * [How to use UNC path?](#how-to-use-unc-path) * [Compatible with `node-glob`?](#compatible-with-node-glob) * [Benchmarks](#benchmarks) * [Server](#server) * [Nettop](#nettop) * [Changelog](#changelog) * [License](#license) </details> ## Highlights * Fast. Probably the fastest. * Supports multiple and negative patterns. * Synchronous, Promise and Stream API. * Object mode. Can return more than just strings. * Error-tolerant. ## Old and modern mode This package works in two modes, depending on the environment in which it is used. * **Old mode**. Node.js below 10.10 or when the [`stats`](#stats) option is *enabled*. * **Modern mode**. Node.js 10.10+ and the [`stats`](#stats) option is *disabled*. The modern mode is faster. Learn more about the [internal mechanism][nodelib_fs_scandir_old_and_modern_modern]. ## Pattern syntax > :warning: Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. There is more than one form of syntax: basic and advanced. Below is a brief overview of the supported features. Also pay attention to our [FAQ](#faq). > :book: This package uses [`micromatch`][micromatch] as a library for pattern matching. ### Basic syntax * An asterisk (`*`) — matches everything except slashes (path separators), hidden files (names starting with `.`). * A double star or globstar (`**`) — matches zero or more directories. * Question mark (`?`) – matches any single character except slashes (path separators). * Sequence (`[seq]`) — matches any character in sequence. > :book: A few additional words about the [basic matching behavior][picomatch_matching_behavior]. Some examples: * `src/**/*.js` — matches all files in the `src` directory (any level of nesting) that have the `.js` extension. * `src/*.??` — matches all files in the `src` directory (only first level of nesting) that have a two-character extension. * `file-[01].js` — matches files: `file-0.js`, `file-1.js`. ### Advanced syntax * [Escapes characters][micromatch_backslashes] (`\\`) — matching special characters (`$^*+?()[]`) as literals. * [POSIX character classes][picomatch_posix_brackets] (`[[:digit:]]`). * [Extended globs][micromatch_extglobs] (`?(pattern-list)`). * [Bash style brace expansions][micromatch_braces] (`{}`). * [Regexp character classes][micromatch_regex_character_classes] (`[1-5]`). * [Regex groups][regular_expressions_brackets] (`(a|b)`). > :book: A few additional words about the [advanced matching behavior][micromatch_extended_globbing]. Some examples: * `src/**/*.{css,scss}` — matches all files in the `src` directory (any level of nesting) that have the `.css` or `.scss` extension. * `file-[[:digit:]].js` — matches files: `file-0.js`, `file-1.js`, …, `file-9.js`. * `file-{1..3}.js` — matches files: `file-1.js`, `file-2.js`, `file-3.js`. * `file-(1|2)` — matches files: `file-1.js`, `file-2.js`. ## Installation ```console npm install fast-glob ``` ## API ### Asynchronous ```js fg(patterns, [options]) fg.async(patterns, [options]) fg.glob(patterns, [options]) ``` Returns a `Promise` with an array of matching entries. ```js const fg = require('fast-glob'); const entries = await fg(['.editorconfig', '**/index.js'], { dot: true }); // ['.editorconfig', 'services/index.js'] ``` ### Synchronous ```js fg.sync(patterns, [options]) fg.globSync(patterns, [options]) ``` Returns an array of matching entries. ```js const fg = require('fast-glob'); const entries = fg.sync(['.editorconfig', '**/index.js'], { dot: true }); // ['.editorconfig', 'services/index.js'] ``` ### Stream ```js fg.stream(patterns, [options]) fg.globStream(patterns, [options]) ``` Returns a [`ReadableStream`][node_js_stream_readable_streams] when the `data` event will be emitted with matching entry. ```js const fg = require('fast-glob'); const stream = fg.stream(['.editorconfig', '**/index.js'], { dot: true }); for await (const entry of stream) { // .editorconfig // services/index.js } ``` #### patterns * Required: `true` * Type: `string | string[]` Any correct pattern(s). > :1234: [Pattern syntax](#pattern-syntax) > > :warning: This package does not respect the order of patterns. First, all the negative patterns are applied, and only then the positive patterns. If you want to get a certain order of records, use sorting or split calls. #### [options] * Required: `false` * Type: [`Options`](#options-3) See [Options](#options-3) section. ### Helpers #### `generateTasks(patterns, [options])` Returns the internal representation of patterns ([`Task`](./src/managers/tasks.ts) is a combining patterns by base directory). ```js fg.generateTasks('*'); [{ base: '.', // Parent directory for all patterns inside this task dynamic: true, // Dynamic or static patterns are in this task patterns: ['*'], positive: ['*'], negative: [] }] ``` ##### patterns * Required: `true` * Type: `string | string[]` Any correct pattern(s). ##### [options] * Required: `false` * Type: [`Options`](#options-3) See [Options](#options-3) section. #### `isDynamicPattern(pattern, [options])` Returns `true` if the passed pattern is a dynamic pattern. > :1234: [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern) ```js fg.isDynamicPattern('*'); // true fg.isDynamicPattern('abc'); // false ``` ##### pattern * Required: `true` * Type: `string` Any correct pattern. ##### [options] * Required: `false` * Type: [`Options`](#options-3) See [Options](#options-3) section. #### `escapePath(path)` Returns the path with escaped special characters depending on the platform. * Posix: * `*?|(){}[]`; * `!` at the beginning of line; * `@+!` before the opening parenthesis; * `\\` before non-special characters; * Windows: * `(){}[]` * `!` at the beginning of line; * `@+!` before the opening parenthesis; * Characters like `*?|` cannot be used in the path ([windows_naming_conventions][windows_naming_conventions]), so they will not be escaped; ```js fg.escapePath('!abc'); // \\!abc fg.escapePath('[OpenSource] mrmlnc – fast-glob (Deluxe Edition) 2014') + '/*.flac' // \\[OpenSource\\] mrmlnc – fast-glob \\(Deluxe Edition\\) 2014/*.flac fg.posix.escapePath('C:\\Program Files (x86)\\**\\*'); // C:\\\\Program Files \\(x86\\)\\*\\*\\* fg.win32.escapePath('C:\\Program Files (x86)\\**\\*'); // Windows: C:\\Program Files \\(x86\\)\\**\\* ``` #### `convertPathToPattern(path)` Converts a path to a pattern depending on the platform, including special character escaping. * Posix. Works similarly to the `fg.posix.escapePath` method. * Windows. Works similarly to the `fg.win32.escapePath` method, additionally converting backslashes to forward slashes in cases where they are not escape characters (`!()+@{}[]`). ```js fg.convertPathToPattern('[OpenSource] mrmlnc – fast-glob (Deluxe Edition) 2014') + '/*.flac'; // \\[OpenSource\\] mrmlnc – fast-glob \\(Deluxe Edition\\) 2014/*.flac fg.convertPathToPattern('C:/Program Files (x86)/**/*'); // Posix: C:/Program Files \\(x86\\)/\\*\\*/\\* // Windows: C:/Program Files \\(x86\\)/**/* fg.convertPathToPattern('C:\\Program Files (x86)\\**\\*'); // Posix: C:\\\\Program Files \\(x86\\)\\*\\*\\* // Windows: C:/Program Files \\(x86\\)/**/* fg.posix.convertPathToPattern('\\\\?\\c:\\Program Files (x86)') + '/**/*'; // Posix: \\\\\\?\\\\c:\\\\Program Files \\(x86\\)/**/* (broken pattern) fg.win32.convertPathToPattern('\\\\?\\c:\\Program Files (x86)') + '/**/*'; // Windows: //?/c:/Program Files \\(x86\\)/**/* ``` ## Options ### Common options #### concurrency * Type: `number` * Default: `os.cpus().length` Specifies the maximum number of concurrent requests from a reader to read directories. > :book: The higher the number, the higher the performance and load on the file system. If you want to read in quiet mode, set the value to a comfortable number or `1`. <details> <summary>More details</summary> In Node, there are [two types of threads][nodejs_thread_pool]: Event Loop (code) and a Thread Pool (fs, dns, …). The thread pool size controlled by the `UV_THREADPOOL_SIZE` environment variable. Its default size is 4 ([documentation][libuv_thread_pool]). The pool is one for all tasks within a single Node process. Any code can make 4 real concurrent accesses to the file system. The rest of the FS requests will wait in the queue. > :book: Each new instance of FG in the same Node process will use the same Thread pool. But this package also has the `concurrency` option. This option allows you to control the number of concurrent accesses to the FS at the package level. By default, this package has a value equal to the number of cores available for the current Node process. This allows you to set a value smaller than the pool size (`concurrency: 1`) or, conversely, to prepare tasks for the pool queue more quickly (`concurrency: Number.POSITIVE_INFINITY`). So, in fact, this package can **only make 4 concurrent requests to the FS**. You can increase this value by using an environment variable (`UV_THREADPOOL_SIZE`), but in practice this does not give a multiple advantage. </details> #### cwd * Type: `string` * Default: `process.cwd()` The current working directory in which to search. #### deep * Type: `number` * Default: `Infinity` Specifies the maximum depth of a read directory relative to the start directory. For example, you have the following tree: ```js dir/ └── one/ // 1 └── two/ // 2 └── file.js // 3 ``` ```js // With base directory fg.sync('dir/**', { onlyFiles: false, deep: 1 }); // ['dir/one'] fg.sync('dir/**', { onlyFiles: false, deep: 2 }); // ['dir/one', 'dir/one/two'] // With cwd option fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 1 }); // ['one'] fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 2 }); // ['one', 'one/two'] ``` > :book: If you specify a pattern with some base directory, this directory will not participate in the calculation of the depth of the found directories. Think of it as a [`cwd`](#cwd) option. #### followSymbolicLinks * Type: `boolean` * Default: `true` Indicates whether to traverse descendants of symbolic link directories when expanding `**` patterns. > :book: Note that this option does not affect the base directory of the pattern. For example, if `./a` is a symlink to directory `./b` and you specified `['./a**', './b/**']` patterns, then directory `./a` will still be read. > :book: If the [`stats`](#stats) option is specified, the information about the symbolic link (`fs.lstat`) will be replaced with information about the entry (`fs.stat`) behind it. #### fs * Type: `FileSystemAdapter` * Default: `fs.*` Custom implementation of methods for working with the file system. ```ts export interface FileSystemAdapter { lstat?: typeof fs.lstat; stat?: typeof fs.stat; lstatSync?: typeof fs.lstatSync; statSync?: typeof fs.statSync; readdir?: typeof fs.readdir; readdirSync?: typeof fs.readdirSync; } ``` #### ignore * Type: `string[]` * Default: `[]` An array of glob patterns to exclude matches. This is an alternative way to use negative patterns. ```js dir/ ├── package-lock.json └── package.json ``` ```js fg.sync(['*.json', '!package-lock.json']); // ['package.json'] fg.sync('*.json', { ignore: ['package-lock.json'] }); // ['package.json'] ``` #### suppressErrors * Type: `boolean` * Default: `false` By default this package suppress only `ENOENT` errors. Set to `true` to suppress any error. > :book: Can be useful when the directory has entries with a special level of access. #### throwErrorOnBrokenSymbolicLink * Type: `boolean` * Default: `false` Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. > :book: This option has no effect on errors when reading the symbolic link directory. ### Output control #### absolute * Type: `boolean` * Default: `false` Return the absolute path for entries. ```js fg.sync('*.js', { absolute: false }); // ['index.js'] fg.sync('*.js', { absolute: true }); // ['/home/user/index.js'] ``` > :book: This option is required if you want to use negative patterns with absolute path, for example, `!${__dirname}/*.js`. #### markDirectories * Type: `boolean` * Default: `false` Mark the directory path with the final slash. ```js fg.sync('*', { onlyFiles: false, markDirectories: false }); // ['index.js', 'controllers'] fg.sync('*', { onlyFiles: false, markDirectories: true }); // ['index.js', 'controllers/'] ``` #### objectMode * Type: `boolean` * Default: `false` Returns objects (instead of strings) describing entries. ```js fg.sync('*', { objectMode: false }); // ['src/index.js'] fg.sync('*', { objectMode: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent> }] ``` The object has the following fields: * name (`string`) — the last part of the path (basename) * path (`string`) — full path relative to the pattern base directory * dirent ([`fs.Dirent`][node_js_fs_class_fs_dirent]) — instance of `fs.Dirent` > :book: An object is an internal representation of entry, so getting it does not affect performance. #### onlyDirectories * Type: `boolean` * Default: `false` Return only directories. ```js fg.sync('*', { onlyDirectories: false }); // ['index.js', 'src'] fg.sync('*', { onlyDirectories: true }); // ['src'] ``` > :book: If `true`, the [`onlyFiles`](#onlyfiles) option is automatically `false`. #### onlyFiles * Type: `boolean` * Default: `true` Return only files. ```js fg.sync('*', { onlyFiles: false }); // ['index.js', 'src'] fg.sync('*', { onlyFiles: true }); // ['index.js'] ``` #### stats * Type: `boolean` * Default: `false` Enables an [object mode](#objectmode) with an additional field: * stats ([`fs.Stats`][node_js_fs_class_fs_stats]) — instance of `fs.Stats` ```js fg.sync('*', { stats: false }); // ['src/index.js'] fg.sync('*', { stats: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent>, stats: <fs.Stats> }] ``` > :book: Returns `fs.stat` instead of `fs.lstat` for symbolic links when the [`followSymbolicLinks`](#followsymboliclinks) option is specified. > > :warning: Unlike [object mode](#objectmode) this mode requires additional calls to the file system. On average, this mode is slower at least twice. See [old and modern mode](#old-and-modern-mode) for more details. #### unique * Type: `boolean` * Default: `true` Ensures that the returned entries are unique. ```js fg.sync(['*.json', 'package.json'], { unique: false }); // ['package.json', 'package.json'] fg.sync(['*.json', 'package.json'], { unique: true }); // ['package.json'] ``` If `true` and similar entries are found, the result is the first found. ### Matching control #### braceExpansion * Type: `boolean` * Default: `true` Enables Bash-like brace expansion. > :1234: [Syntax description][bash_hackers_syntax_expansion_brace] or more [detailed description][micromatch_braces]. ```js dir/ ├── abd ├── acd └── a{b,c}d ``` ```js fg.sync('a{b,c}d', { braceExpansion: false }); // ['a{b,c}d'] fg.sync('a{b,c}d', { braceExpansion: true }); // ['abd', 'acd'] ``` #### caseSensitiveMatch * Type: `boolean` * Default: `true` Enables a [case-sensitive][wikipedia_case_sensitivity] mode for matching files. ```js dir/ ├── file.txt └── File.txt ``` ```js fg.sync('file.txt', { caseSensitiveMatch: false }); // ['file.txt', 'File.txt'] fg.sync('file.txt', { caseSensitiveMatch: true }); // ['file.txt'] ``` #### dot * Type: `boolean` * Default: `false` Allow patterns to match entries that begin with a period (`.`). > :book: Note that an explicit dot in a portion of the pattern will always match dot files. ```js dir/ ├── .editorconfig └── package.json ``` ```js fg.sync('*', { dot: false }); // ['package.json'] fg.sync('*', { dot: true }); // ['.editorconfig', 'package.json'] ``` #### extglob * Type: `boolean` * Default: `true` Enables Bash-like `extglob` functionality. > :1234: [Syntax description][micromatch_extglobs]. ```js dir/ ├── README.md └── package.json ``` ```js fg.sync('*.+(json|md)', { extglob: false }); // [] fg.sync('*.+(json|md)', { extglob: true }); // ['README.md', 'package.json'] ``` #### globstar * Type: `boolean` * Default: `true` Enables recursively repeats a pattern containing `**`. If `false`, `**` behaves exactly like `*`. ```js dir/ └── a └── b ``` ```js fg.sync('**', { onlyFiles: false, globstar: false }); // ['a'] fg.sync('**', { onlyFiles: false, globstar: true }); // ['a', 'a/b'] ``` #### baseNameMatch * Type: `boolean` * Default: `false` If set to `true`, then patterns without slashes will be matched against the basename of the path if it contains slashes. ```js dir/ └── one/ └── file.md ``` ```js fg.sync('*.md', { baseNameMatch: false }); // [] fg.sync('*.md', { baseNameMatch: true }); // ['one/file.md'] ``` ## FAQ ## What is a static or dynamic pattern? All patterns can be divided into two types: * **static**. A pattern is considered static if it can be used to get an entry on the file system without using matching mechanisms. For example, the `file.js` pattern is a static pattern because we can just verify that it exists on the file system. * **dynamic**. A pattern is considered dynamic if it cannot be used directly to find occurrences without using a matching mechanisms. For example, the `*` pattern is a dynamic pattern because we cannot use this pattern directly. A pattern is considered dynamic if it contains the following characters (`…` — any characters or their absence) or options: * The [`caseSensitiveMatch`](#casesensitivematch) option is disabled * `\\` (the escape character) * `*`, `?`, `!` (at the beginning of line) * `[…]` * `(…|…)` * `@(…)`, `!(…)`, `*(…)`, `?(…)`, `+(…)` (respects the [`extglob`](#extglob) option) * `{…,…}`, `{…..…}` (respects the [`braceExpansion`](#braceexpansion) option) ## How to write patterns on Windows? Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. With the [`cwd`](#cwd) option use a convenient format. **Bad** ```ts [ 'directory\\*', path.join(process.cwd(), '**') ] ``` **Good** ```ts [ 'directory/*', fg.convertPathToPattern(process.cwd()) + '/**' ] ``` > :book: Use the [`.convertPathToPattern`](#convertpathtopatternpath) package to convert Windows-style path to a Unix-style path. Read more about [matching with backslashes][micromatch_backslashes]. ## Why are parentheses match wrong? ```js dir/ └── (special-*file).txt ``` ```js fg.sync(['(special-*file).txt']) // [] ``` Refers to Bash. You need to escape special characters: ```js fg.sync(['\\(special-*file\\).txt']) // ['(special-*file).txt'] ``` Read more about [matching special characters as literals][picomatch_matching_special_characters_as_literals]. Or use the [`.escapePath`](#escapepathpath). ## How to exclude directory from reading? You can use a negative pattern like this: `!**/node_modules` or `!**/node_modules/**`. Also you can use [`ignore`](#ignore) option. Just look at the example below. ```js first/ ├── file.md └── second/ └── file.txt ``` If you don't want to read the `second` directory, you must write the following pattern: `!**/second` or `!**/second/**`. ```js fg.sync(['**/*.md', '!**/second']); // ['first/file.md'] fg.sync(['**/*.md'], { ignore: ['**/second/**'] }); // ['first/file.md'] ``` > :warning: When you write `!**/second/**/*` it means that the directory will be **read**, but all the entries will not be included in the results. You have to understand that if you write the pattern to exclude directories, then the directory will not be read under any circumstances. ## How to use UNC path? You cannot use [Uniform Naming Convention (UNC)][unc_path] paths as patterns (due to syntax) directly, but you can use them as [`cwd`](#cwd) directory or use the `fg.convertPathToPattern` method. ```ts // cwd fg.sync('*', { cwd: '\\\\?\\C:\\Python27' /* or //?/C:/Python27 */ }); fg.sync('Python27/*', { cwd: '\\\\?\\C:\\' /* or //?/C:/ */ }); // .convertPathToPattern fg.sync(fg.convertPathToPattern('\\\\?\\c:\\Python27') + '/*'); ``` ## Compatible with `node-glob`? | node-glob | fast-glob | | :----------: | :-------: | | `cwd` | [`cwd`](#cwd) | | `root` | – | | `dot` | [`dot`](#dot) | | `nomount` | – | | `mark` | [`markDirectories`](#markdirectories) | | `nosort` | – | | `nounique` | [`unique`](#unique) | | `nobrace` | [`braceExpansion`](#braceexpansion) | | `noglobstar` | [`globstar`](#globstar) | | `noext` | [`extglob`](#extglob) | | `nocase` | [`caseSensitiveMatch`](#casesensitivematch) | | `matchBase` | [`baseNameMatch`](#basenamematch) | | `nodir` | [`onlyFiles`](#onlyfiles) | | `ignore` | [`ignore`](#ignore) | | `follow` | [`followSymbolicLinks`](#followsymboliclinks) | | `realpath` | – | | `absolute` | [`absolute`](#absolute) | ## Benchmarks You can see results [here](https://github.com/mrmlnc/fast-glob/actions/workflows/benchmark.yml?query=branch%3Amaster) for every commit into the `main` branch. * **Product benchmark** – comparison with the main competitors. * **Regress benchmark** – regression between the current version and the version from the npm registry. ## Changelog See the [Releases section of our GitHub project][github_releases] for changelog for each release version. ## License This software is released under the terms of the MIT license. [bash_hackers_syntax_expansion_brace]: https://wiki.bash-hackers.org/syntax/expansion/brace [github_releases]: https://github.com/mrmlnc/fast-glob/releases [glob_definition]: https://en.wikipedia.org/wiki/Glob_(programming) [glob_linux_man]: http://man7.org/linux/man-pages/man3/glob.3.html [micromatch_backslashes]: https://github.com/micromatch/micromatch#backslashes [micromatch_braces]: https://github.com/micromatch/braces [micromatch_extended_globbing]: https://github.com/micromatch/micromatch#extended-globbing [micromatch_extglobs]: https://github.com/micromatch/micromatch#extglobs [micromatch_regex_character_classes]: https://github.com/micromatch/micromatch#regex-character-classes [micromatch]: https://github.com/micromatch/micromatch [node_js_fs_class_fs_dirent]: https://nodejs.org/api/fs.html#fs_class_fs_dirent [node_js_fs_class_fs_stats]: https://nodejs.org/api/fs.html#fs_class_fs_stats [node_js_stream_readable_streams]: https://nodejs.org/api/stream.html#stream_readable_streams [node_js]: https://nodejs.org/en [nodelib_fs_scandir_old_and_modern_modern]: https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode [npm_normalize_path]: https://www.npmjs.com/package/normalize-path [npm_unixify]: https://www.npmjs.com/package/unixify [picomatch_matching_behavior]: https://github.com/micromatch/picomatch#matching-behavior-vs-bash [picomatch_matching_special_characters_as_literals]: https://github.com/micromatch/picomatch#matching-special-characters-as-literals [picomatch_posix_brackets]: https://github.com/micromatch/picomatch#posix-brackets [regular_expressions_brackets]: https://www.regular-expressions.info/brackets.html [unc_path]: https://learn.microsoft.com/openspecs/windows_protocols/ms-dtyp/62e862f4-2a51-452e-8eeb-dc4ff5ee33cc [wikipedia_case_sensitivity]: https://en.wikipedia.org/wiki/Case_sensitivity [nodejs_thread_pool]: https://nodejs.org/en/docs/guides/dont-block-the-event-loop [libuv_thread_pool]: http://docs.libuv.org/en/v1.x/threadpool.html [windows_naming_conventions]: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions node_modules/braces/package.json 0000664 00000003157 15114743311 0012756 0 ustar 00 { "name": "braces", "description": "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.", "version": "3.0.3", "homepage": "https://github.com/micromatch/braces", "author": "Jon Schlinkert (https://github.com/jonschlinkert)", "contributors": [ "Brian Woodward (https://twitter.com/doowb)", "Elan Shanker (https://github.com/es128)", "Eugene Sharygin (https://github.com/eush77)", "hemanth.hm (http://h3manth.com)", "Jon Schlinkert (http://twitter.com/jonschlinkert)" ], "repository": "micromatch/braces", "bugs": { "url": "https://github.com/micromatch/braces/issues" }, "license": "MIT", "files": [ "index.js", "lib" ], "main": "index.js", "engines": { "node": ">=8" }, "scripts": { "test": "mocha", "benchmark": "node benchmark" }, "dependencies": { "fill-range": "^7.1.1" }, "devDependencies": { "ansi-colors": "^3.2.4", "bash-path": "^2.0.1", "gulp-format-md": "^2.0.0", "mocha": "^6.1.1" }, "keywords": [ "alpha", "alphabetical", "bash", "brace", "braces", "expand", "expansion", "filepath", "fill", "fs", "glob", "globbing", "letter", "match", "matches", "matching", "number", "numerical", "path", "range", "ranges", "sh" ], "verb": { "toc": false, "layout": "default", "tasks": [ "readme" ], "lint": { "reflinks": true }, "plugins": [ "gulp-format-md" ] } } node_modules/braces/LICENSE 0000664 00000002103 15114743311 0011463 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-present, Jon Schlinkert. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/braces/lib/utils.js 0000664 00000004726 15114743311 0012737 0 ustar 00 'use strict'; exports.isInteger = num => { if (typeof num === 'number') { return Number.isInteger(num); } if (typeof num === 'string' && num.trim() !== '') { return Number.isInteger(Number(num)); } return false; }; /** * Find a node of the given type */ exports.find = (node, type) => node.nodes.find(node => node.type === type); /** * Find a node of the given type */ exports.exceedsLimit = (min, max, step = 1, limit) => { if (limit === false) return false; if (!exports.isInteger(min) || !exports.isInteger(max)) return false; return ((Number(max) - Number(min)) / Number(step)) >= limit; }; /** * Escape the given node with '\\' before node.value */ exports.escapeNode = (block, n = 0, type) => { const node = block.nodes[n]; if (!node) return; if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { if (node.escaped !== true) { node.value = '\\' + node.value; node.escaped = true; } } }; /** * Returns true if the given brace node should be enclosed in literal braces */ exports.encloseBrace = node => { if (node.type !== 'brace') return false; if ((node.commas >> 0 + node.ranges >> 0) === 0) { node.invalid = true; return true; } return false; }; /** * Returns true if a brace node is invalid. */ exports.isInvalidBrace = block => { if (block.type !== 'brace') return false; if (block.invalid === true || block.dollar) return true; if ((block.commas >> 0 + block.ranges >> 0) === 0) { block.invalid = true; return true; } if (block.open !== true || block.close !== true) { block.invalid = true; return true; } return false; }; /** * Returns true if a node is an open or close node */ exports.isOpenOrClose = node => { if (node.type === 'open' || node.type === 'close') { return true; } return node.open === true || node.close === true; }; /** * Reduce an array of text nodes. */ exports.reduce = nodes => nodes.reduce((acc, node) => { if (node.type === 'text') acc.push(node.value); if (node.type === 'range') node.type = 'text'; return acc; }, []); /** * Flatten an array */ exports.flatten = (...args) => { const result = []; const flat = arr => { for (let i = 0; i < arr.length; i++) { const ele = arr[i]; if (Array.isArray(ele)) { flat(ele); continue; } if (ele !== undefined) { result.push(ele); } } return result; }; flat(args); return result; }; node_modules/braces/lib/stringify.js 0000664 00000001304 15114743311 0013602 0 ustar 00 'use strict'; const utils = require('./utils'); module.exports = (ast, options = {}) => { const stringify = (node, parent = {}) => { const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); const invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ''; if (node.value) { if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { return '\\' + node.value; } return node.value; } if (node.value) { return node.value; } if (node.nodes) { for (const child of node.nodes) { output += stringify(child); } } return output; }; return stringify(ast); }; node_modules/braces/lib/parse.js 0000664 00000015363 15114743311 0012710 0 ustar 00 'use strict'; const stringify = require('./stringify'); /** * Constants */ const { MAX_LENGTH, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_RIGHT_SQUARE_BRACKET, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = require('./constants'); /** * parse */ const parse = (input, options = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } const opts = options || {}; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } const ast = { type: 'root', input, nodes: [] }; const stack = [ast]; let block = ast; let prev = ast; let brackets = 0; const length = input.length; let index = 0; let depth = 0; let value; /** * Helpers */ const advance = () => input[index++]; const push = node => { if (node.type === 'text' && prev.type === 'dot') { prev.type = 'text'; } if (prev && prev.type === 'text' && node.type === 'text') { prev.value += node.value; return; } block.nodes.push(node); node.parent = block; node.prev = prev; prev = node; return node; }; push({ type: 'bos' }); while (index < length) { block = stack[stack.length - 1]; value = advance(); /** * Invalid chars */ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { continue; } /** * Escaped chars */ if (value === CHAR_BACKSLASH) { push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); continue; } /** * Right square bracket (literal): ']' */ if (value === CHAR_RIGHT_SQUARE_BRACKET) { push({ type: 'text', value: '\\' + value }); continue; } /** * Left square bracket: '[' */ if (value === CHAR_LEFT_SQUARE_BRACKET) { brackets++; let next; while (index < length && (next = advance())) { value += next; if (next === CHAR_LEFT_SQUARE_BRACKET) { brackets++; continue; } if (next === CHAR_BACKSLASH) { value += advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET) { brackets--; if (brackets === 0) { break; } } } push({ type: 'text', value }); continue; } /** * Parentheses */ if (value === CHAR_LEFT_PARENTHESES) { block = push({ type: 'paren', nodes: [] }); stack.push(block); push({ type: 'text', value }); continue; } if (value === CHAR_RIGHT_PARENTHESES) { if (block.type !== 'paren') { push({ type: 'text', value }); continue; } block = stack.pop(); push({ type: 'text', value }); block = stack[stack.length - 1]; continue; } /** * Quotes: '|"|` */ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { const open = value; let next; if (options.keepQuotes !== true) { value = ''; } while (index < length && (next = advance())) { if (next === CHAR_BACKSLASH) { value += next + advance(); continue; } if (next === open) { if (options.keepQuotes === true) value += next; break; } value += next; } push({ type: 'text', value }); continue; } /** * Left curly brace: '{' */ if (value === CHAR_LEFT_CURLY_BRACE) { depth++; const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; const brace = { type: 'brace', open: true, close: false, dollar, depth, commas: 0, ranges: 0, nodes: [] }; block = push(brace); stack.push(block); push({ type: 'open', value }); continue; } /** * Right curly brace: '}' */ if (value === CHAR_RIGHT_CURLY_BRACE) { if (block.type !== 'brace') { push({ type: 'text', value }); continue; } const type = 'close'; block = stack.pop(); block.close = true; push({ type, value }); depth--; block = stack[stack.length - 1]; continue; } /** * Comma: ',' */ if (value === CHAR_COMMA && depth > 0) { if (block.ranges > 0) { block.ranges = 0; const open = block.nodes.shift(); block.nodes = [open, { type: 'text', value: stringify(block) }]; } push({ type: 'comma', value }); block.commas++; continue; } /** * Dot: '.' */ if (value === CHAR_DOT && depth > 0 && block.commas === 0) { const siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: 'text', value }); continue; } if (prev.type === 'dot') { block.range = []; prev.value += value; prev.type = 'range'; if (block.nodes.length !== 3 && block.nodes.length !== 5) { block.invalid = true; block.ranges = 0; prev.type = 'text'; continue; } block.ranges++; block.args = []; continue; } if (prev.type === 'range') { siblings.pop(); const before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; continue; } push({ type: 'dot', value }); continue; } /** * Text */ push({ type: 'text', value }); } // Mark imbalanced braces and brackets as invalid do { block = stack.pop(); if (block.type !== 'root') { block.nodes.forEach(node => { if (!node.nodes) { if (node.type === 'open') node.isOpen = true; if (node.type === 'close') node.isClose = true; if (!node.nodes) node.type = 'text'; node.invalid = true; } }); // get the location of the block on parent.nodes (block's siblings) const parent = stack[stack.length - 1]; const index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes parent.nodes.splice(index, 1, ...block.nodes); } } while (stack.length > 0); push({ type: 'eos' }); return ast; }; module.exports = parse; node_modules/braces/lib/expand.js 0000664 00000005355 15114743311 0013055 0 ustar 00 'use strict'; const fill = require('fill-range'); const stringify = require('./stringify'); const utils = require('./utils'); const append = (queue = '', stash = '', enclose = false) => { const result = []; queue = [].concat(queue); stash = [].concat(stash); if (!stash.length) return queue; if (!queue.length) { return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; } for (const item of queue) { if (Array.isArray(item)) { for (const value of item) { result.push(append(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); } } } return utils.flatten(result); }; const expand = (ast, options = {}) => { const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; const walk = (node, parent = {}) => { node.queue = []; let p = parent; let q = parent.queue; while (p.type !== 'brace' && p.type !== 'root' && p.parent) { p = p.parent; q = p.queue; } if (node.invalid || node.dollar) { q.push(append(q.pop(), stringify(node, options))); return; } if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { q.push(append(q.pop(), ['{}'])); return; } if (node.nodes && node.ranges > 0) { const args = utils.reduce(node.nodes); if (utils.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); } let range = fill(...args, options); if (range.length === 0) { range = stringify(node, options); } q.push(append(q.pop(), range)); node.nodes = []; return; } const enclose = utils.encloseBrace(node); let queue = node.queue; let block = node; while (block.type !== 'brace' && block.type !== 'root' && block.parent) { block = block.parent; queue = block.queue; } for (let i = 0; i < node.nodes.length; i++) { const child = node.nodes[i]; if (child.type === 'comma' && node.type === 'brace') { if (i === 1) queue.push(''); queue.push(''); continue; } if (child.type === 'close') { q.push(append(q.pop(), queue, enclose)); continue; } if (child.value && child.type !== 'open') { queue.push(append(queue.pop(), child.value)); continue; } if (child.nodes) { walk(child, node); } } return queue; }; return utils.flatten(walk(ast)); }; module.exports = expand; node_modules/braces/lib/constants.js 0000664 00000003065 15114743311 0013606 0 ustar 00 'use strict'; module.exports = { MAX_LENGTH: 10000, // Digits CHAR_0: '0', /* 0 */ CHAR_9: '9', /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 'A', /* A */ CHAR_LOWERCASE_A: 'a', /* a */ CHAR_UPPERCASE_Z: 'Z', /* Z */ CHAR_LOWERCASE_Z: 'z', /* z */ CHAR_LEFT_PARENTHESES: '(', /* ( */ CHAR_RIGHT_PARENTHESES: ')', /* ) */ CHAR_ASTERISK: '*', /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: '&', /* & */ CHAR_AT: '@', /* @ */ CHAR_BACKSLASH: '\\', /* \ */ CHAR_BACKTICK: '`', /* ` */ CHAR_CARRIAGE_RETURN: '\r', /* \r */ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ CHAR_COLON: ':', /* : */ CHAR_COMMA: ',', /* , */ CHAR_DOLLAR: '$', /* . */ CHAR_DOT: '.', /* . */ CHAR_DOUBLE_QUOTE: '"', /* " */ CHAR_EQUAL: '=', /* = */ CHAR_EXCLAMATION_MARK: '!', /* ! */ CHAR_FORM_FEED: '\f', /* \f */ CHAR_FORWARD_SLASH: '/', /* / */ CHAR_HASH: '#', /* # */ CHAR_HYPHEN_MINUS: '-', /* - */ CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ CHAR_LEFT_CURLY_BRACE: '{', /* { */ CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ CHAR_LINE_FEED: '\n', /* \n */ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ CHAR_PERCENT: '%', /* % */ CHAR_PLUS: '+', /* + */ CHAR_QUESTION_MARK: '?', /* ? */ CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ CHAR_RIGHT_CURLY_BRACE: '}', /* } */ CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ CHAR_SEMICOLON: ';', /* ; */ CHAR_SINGLE_QUOTE: '\'', /* ' */ CHAR_SPACE: ' ', /* */ CHAR_TAB: '\t', /* \t */ CHAR_UNDERSCORE: '_', /* _ */ CHAR_VERTICAL_LINE: '|', /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ }; node_modules/braces/lib/compile.js 0000664 00000002735 15114743311 0013225 0 ustar 00 'use strict'; const fill = require('fill-range'); const utils = require('./utils'); const compile = (ast, options = {}) => { const walk = (node, parent = {}) => { const invalidBlock = utils.isInvalidBrace(parent); const invalidNode = node.invalid === true && options.escapeInvalid === true; const invalid = invalidBlock === true || invalidNode === true; const prefix = options.escapeInvalid === true ? '\\' : ''; let output = ''; if (node.isOpen === true) { return prefix + node.value; } if (node.isClose === true) { console.log('node.isClose', prefix, node.value); return prefix + node.value; } if (node.type === 'open') { return invalid ? prefix + node.value : '('; } if (node.type === 'close') { return invalid ? prefix + node.value : ')'; } if (node.type === 'comma') { return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; } if (node.value) { return node.value; } if (node.nodes && node.ranges > 0) { const args = utils.reduce(node.nodes); const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; } } if (node.nodes) { for (const child of node.nodes) { output += walk(child, node); } } return output; }; return walk(ast); }; module.exports = compile; node_modules/braces/index.js 0000664 00000010434 15114743311 0012131 0 ustar 00 'use strict'; const stringify = require('./lib/stringify'); const compile = require('./lib/compile'); const expand = require('./lib/expand'); const parse = require('./lib/parse'); /** * Expand the given pattern or create a regex-compatible string. * * ```js * const braces = require('braces'); * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] * ``` * @param {String} `str` * @param {Object} `options` * @return {String} * @api public */ const braces = (input, options = {}) => { let output = []; if (Array.isArray(input)) { for (const pattern of input) { const result = braces.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { output.push(result); } } } else { output = [].concat(braces.create(input, options)); } if (options && options.expand === true && options.nodupes === true) { output = [...new Set(output)]; } return output; }; /** * Parse the given `str` with the given `options`. * * ```js * // braces.parse(pattern, [, options]); * const ast = braces.parse('a/{b,c}/d'); * console.log(ast); * ``` * @param {String} pattern Brace pattern to parse * @param {Object} options * @return {Object} Returns an AST * @api public */ braces.parse = (input, options = {}) => parse(input, options); /** * Creates a braces string from an AST, or an AST node. * * ```js * const braces = require('braces'); * let ast = braces.parse('foo/{a,b}/bar'); * console.log(stringify(ast.nodes[2])); //=> '{a,b}' * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.stringify = (input, options = {}) => { if (typeof input === 'string') { return stringify(braces.parse(input, options), options); } return stringify(input, options); }; /** * Compiles a brace pattern into a regex-compatible, optimized string. * This method is called by the main [braces](#braces) function by default. * * ```js * const braces = require('braces'); * console.log(braces.compile('a/{b,c}/d')); * //=> ['a/(b|c)/d'] * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.compile = (input, options = {}) => { if (typeof input === 'string') { input = braces.parse(input, options); } return compile(input, options); }; /** * Expands a brace pattern into an array. This method is called by the * main [braces](#braces) function when `options.expand` is true. Before * using this method it's recommended that you read the [performance notes](#performance)) * and advantages of using [.compile](#compile) instead. * * ```js * const braces = require('braces'); * console.log(braces.expand('a/{b,c}/d')); * //=> ['a/b/d', 'a/c/d']; * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.expand = (input, options = {}) => { if (typeof input === 'string') { input = braces.parse(input, options); } let result = expand(input, options); // filter out empty strings if specified if (options.noempty === true) { result = result.filter(Boolean); } // filter out duplicates if specified if (options.nodupes === true) { result = [...new Set(result)]; } return result; }; /** * Processes a brace pattern and returns either an expanded array * (if `options.expand` is true), a highly optimized regex-compatible string. * This method is called by the main [braces](#braces) function. * * ```js * const braces = require('braces'); * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.create = (input, options = {}) => { if (input === '' || input.length < 3) { return [input]; } return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); }; /** * Expose "braces" */ module.exports = braces; node_modules/braces/README.md 0000664 00000052001 15114743311 0011737 0 ustar 00 # braces [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [](https://www.npmjs.com/package/braces) [](https://npmjs.org/package/braces) [](https://npmjs.org/package/braces) [](https://travis-ci.org/micromatch/braces) > Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save braces ``` ## v3.0.0 Released!! See the [changelog](CHANGELOG.md) for details. ## Why use braces? Brace patterns make globs more powerful by adding the ability to match specific ranges and sequences of characters. - **Accurate** - complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests) - **[fast and performant](#benchmarks)** - Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity. - **Organized code base** - The parser and compiler are easy to maintain and update when edge cases crop up. - **Well-tested** - Thousands of test assertions, and passes all of the Bash, minimatch, and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests (as of the date this was written). - **Safer** - You shouldn't have to worry about users defining aggressive or malicious brace patterns that can break your application. Braces takes measures to prevent malicious regex that can be used for DDoS attacks (see [catastrophic backtracking](https://www.regular-expressions.info/catastrophic.html)). - [Supports lists](#lists) - (aka "sets") `a/{b,c}/d` => `['a/b/d', 'a/c/d']` - [Supports sequences](#sequences) - (aka "ranges") `{01..03}` => `['01', '02', '03']` - [Supports steps](#steps) - (aka "increments") `{2..10..2}` => `['2', '4', '6', '8', '10']` - [Supports escaping](#escaping) - To prevent evaluation of special characters. ## Usage The main export is a function that takes one or more brace `patterns` and `options`. ```js const braces = require('braces'); // braces(patterns[, options]); console.log(braces(['{01..05}', '{a..e}'])); //=> ['(0[1-5])', '([a-e])'] console.log(braces(['{01..05}', '{a..e}'], { expand: true })); //=> ['01', '02', '03', '04', '05', 'a', 'b', 'c', 'd', 'e'] ``` ### Brace Expansion vs. Compilation By default, brace patterns are compiled into strings that are optimized for creating regular expressions and matching. **Compiled** ```js console.log(braces('a/{x,y,z}/b')); //=> ['a/(x|y|z)/b'] console.log(braces(['a/{01..20}/b', 'a/{1..5}/b'])); //=> [ 'a/(0[1-9]|1[0-9]|20)/b', 'a/([1-5])/b' ] ``` **Expanded** Enable brace expansion by setting the `expand` option to true, or by using [braces.expand()](#expand) (returns an array similar to what you'd expect from Bash, or `echo {1..5}`, or [minimatch](https://github.com/isaacs/minimatch)): ```js console.log(braces('a/{x,y,z}/b', { expand: true })); //=> ['a/x/b', 'a/y/b', 'a/z/b'] console.log(braces.expand('{01..10}')); //=> ['01','02','03','04','05','06','07','08','09','10'] ``` ### Lists Expand lists (like Bash "sets"): ```js console.log(braces('a/{foo,bar,baz}/*.js')); //=> ['a/(foo|bar|baz)/*.js'] console.log(braces.expand('a/{foo,bar,baz}/*.js')); //=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js'] ``` ### Sequences Expand ranges of characters (like Bash "sequences"): ```js console.log(braces.expand('{1..3}')); // ['1', '2', '3'] console.log(braces.expand('a/{1..3}/b')); // ['a/1/b', 'a/2/b', 'a/3/b'] console.log(braces('{a..c}', { expand: true })); // ['a', 'b', 'c'] console.log(braces('foo/{a..c}', { expand: true })); // ['foo/a', 'foo/b', 'foo/c'] // supports zero-padded ranges console.log(braces('a/{01..03}/b')); //=> ['a/(0[1-3])/b'] console.log(braces('a/{001..300}/b')); //=> ['a/(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)/b'] ``` See [fill-range](https://github.com/jonschlinkert/fill-range) for all available range-expansion options. ### Steppped ranges Steps, or increments, may be used with ranges: ```js console.log(braces.expand('{2..10..2}')); //=> ['2', '4', '6', '8', '10'] console.log(braces('{2..10..2}')); //=> ['(2|4|6|8|10)'] ``` When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion. ### Nesting Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved. **"Expanded" braces** ```js console.log(braces.expand('a{b,c,/{x,y}}/e')); //=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e'] console.log(braces.expand('a/{x,{1..5},y}/c')); //=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c'] ``` **"Optimized" braces** ```js console.log(braces('a{b,c,/{x,y}}/e')); //=> ['a(b|c|/(x|y))/e'] console.log(braces('a/{x,{1..5},y}/c')); //=> ['a/(x|([1-5])|y)/c'] ``` ### Escaping **Escaping braces** A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_: ```js console.log(braces.expand('a\\{d,c,b}e')); //=> ['a{d,c,b}e'] console.log(braces.expand('a{d,c,b\\}e')); //=> ['a{d,c,b}e'] ``` **Escaping commas** Commas inside braces may also be escaped: ```js console.log(braces.expand('a{b\\,c}d')); //=> ['a{b,c}d'] console.log(braces.expand('a{d\\,c,b}e')); //=> ['ad,ce', 'abe'] ``` **Single items** Following bash conventions, a brace pattern is also not expanded when it contains a single character: ```js console.log(braces.expand('a{b}c')); //=> ['a{b}c'] ``` ## Options ### options.maxLength **Type**: `Number` **Default**: `10,000` **Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera. ```js console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error ``` ### options.expand **Type**: `Boolean` **Default**: `undefined` **Description**: Generate an "expanded" brace pattern (alternatively you can use the `braces.expand()` method, which does the same thing). ```js console.log(braces('a/{b,c}/d', { expand: true })); //=> [ 'a/b/d', 'a/c/d' ] ``` ### options.nodupes **Type**: `Boolean` **Default**: `undefined` **Description**: Remove duplicates from the returned array. ### options.rangeLimit **Type**: `Number` **Default**: `1000` **Description**: To prevent malicious patterns from being passed by users, an error is thrown when `braces.expand()` is used or `options.expand` is true and the generated range will exceed the `rangeLimit`. You can customize `options.rangeLimit` or set it to `Inifinity` to disable this altogether. **Examples** ```js // pattern exceeds the "rangeLimit", so it's optimized automatically console.log(braces.expand('{1..1000}')); //=> ['([1-9]|[1-9][0-9]{1,2}|1000)'] // pattern does not exceed "rangeLimit", so it's NOT optimized console.log(braces.expand('{1..100}')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100'] ``` ### options.transform **Type**: `Function` **Default**: `undefined` **Description**: Customize range expansion. **Example: Transforming non-numeric values** ```js const alpha = braces.expand('x/{a..e}/y', { transform(value, index) { // When non-numeric values are passed, "value" is a character code. return 'foo/' + String.fromCharCode(value) + '-' + index; }, }); console.log(alpha); //=> [ 'x/foo/a-0/y', 'x/foo/b-1/y', 'x/foo/c-2/y', 'x/foo/d-3/y', 'x/foo/e-4/y' ] ``` **Example: Transforming numeric values** ```js const numeric = braces.expand('{1..5}', { transform(value) { // when numeric values are passed, "value" is a number return 'foo/' + value * 2; }, }); console.log(numeric); //=> [ 'foo/2', 'foo/4', 'foo/6', 'foo/8', 'foo/10' ] ``` ### options.quantifiers **Type**: `Boolean` **Default**: `undefined` **Description**: In regular expressions, quanitifiers can be used to specify how many times a token can be repeated. For example, `a{1,3}` will match the letter `a` one to three times. Unfortunately, regex quantifiers happen to share the same syntax as [Bash lists](#lists) The `quantifiers` option tells braces to detect when [regex quantifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#quantifiers) are defined in the given pattern, and not to try to expand them as lists. **Examples** ```js const braces = require('braces'); console.log(braces('a/b{1,3}/{x,y,z}')); //=> [ 'a/b(1|3)/(x|y|z)' ] console.log(braces('a/b{1,3}/{x,y,z}', { quantifiers: true })); //=> [ 'a/b{1,3}/(x|y|z)' ] console.log(braces('a/b{1,3}/{x,y,z}', { quantifiers: true, expand: true })); //=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ] ``` ### options.keepEscaping **Type**: `Boolean` **Default**: `undefined` **Description**: Do not strip backslashes that were used for escaping from the result. ## What is "brace expansion"? Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs). In addition to "expansion", braces are also used for matching. In other words: - [brace expansion](#brace-expansion) is for generating new lists - [brace matching](#brace-matching) is for filtering existing lists <details> <summary><strong>More about brace expansion</strong> (click to expand)</summary> There are two main types of brace expansion: 1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}` 2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges". Here are some example brace patterns to illustrate how they work: **Sets** ``` {a,b,c} => a b c {a,b,c}{1,2} => a1 a2 b1 b2 c1 c2 ``` **Sequences** ``` {1..9} => 1 2 3 4 5 6 7 8 9 {4..-4} => 4 3 2 1 0 -1 -2 -3 -4 {1..20..3} => 1 4 7 10 13 16 19 {a..j} => a b c d e f g h i j {j..a} => j i h g f e d c b a {a..z..3} => a d g j m p s v y ``` **Combination** Sets and sequences can be mixed together or used along with any other strings. ``` {a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3 foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar ``` The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases. ## Brace matching In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching. For example, the pattern `foo/{1..3}/bar` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar ``` But not: ``` baz/1/qux baz/2/qux baz/3/qux ``` Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar baz/1/qux baz/2/qux baz/3/qux ``` ## Brace matching pitfalls Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of. ### tldr **"brace bombs"** - brace expansion can eat up a huge amount of processing resources - as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially - users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!) For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section. ### The solution Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries. ### Geometric complexity At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`. For example, the following sets demonstrate quadratic (`O(n^2)`) complexity: ``` {1,2}{3,4} => (2X2) => 13 14 23 24 {1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246 ``` But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity: ``` {1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248 249 257 258 259 267 268 269 347 348 349 357 358 359 367 368 369 ``` Now, imagine how this complexity grows given that each element is a n-tuple: ``` {1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB) {1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB) ``` Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control. **More information** Interested in learning more about brace expansion? - [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion) - [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion) - [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) </details> ## Performance Braces is not only screaming fast, it's also more accurate the other brace expansion libraries. ### Better algorithms Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_. Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently. **The proof is in the numbers** Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively. | **Pattern** | **braces** | **[minimatch][]** | | --------------------------- | ------------------- | ---------------------------- | | `{1..9007199254740991}`[^1] | `298 B` (5ms 459μs) | N/A (freezes) | | `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) | | `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) | | `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) | | `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) | | `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) | | `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) | | `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) | | `{1..100000000}` | `33 B` (733μs) | N/A (freezes) | | `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) | | `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) | | `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) | | `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) | | `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) | | `{1..100}` | `22 B` (345μs) | `291 B` (196μs) | | `{1..10}` | `10 B` (533μs) | `20 B` (37μs) | | `{1..3}` | `7 B` (190μs) | `5 B` (27μs) | ### Faster algorithms When you need expansion, braces is still much faster. _(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_ | **Pattern** | **braces** | **[minimatch][]** | | --------------- | --------------------------- | ---------------------------- | | `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) | | `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) | | `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) | | `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) | | `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) | | `{1..100}` | `291 B` (424μs) | `291 B` (211μs) | | `{1..10}` | `20 B` (487μs) | `20 B` (72μs) | | `{1..3}` | `5 B` (166μs) | `5 B` (27μs) | If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js). ## Benchmarks ### Running benchmarks Install dev dependencies: ```bash npm i -d && npm benchmark ``` ### Latest results Braces is more accurate, without sacrificing performance. ```bash ● expand - range (expanded) braces x 53,167 ops/sec ±0.12% (102 runs sampled) minimatch x 11,378 ops/sec ±0.10% (102 runs sampled) ● expand - range (optimized for regex) braces x 373,442 ops/sec ±0.04% (100 runs sampled) minimatch x 3,262 ops/sec ±0.18% (100 runs sampled) ● expand - nested ranges (expanded) braces x 33,921 ops/sec ±0.09% (99 runs sampled) minimatch x 10,855 ops/sec ±0.28% (100 runs sampled) ● expand - nested ranges (optimized for regex) braces x 287,479 ops/sec ±0.52% (98 runs sampled) minimatch x 3,219 ops/sec ±0.28% (101 runs sampled) ● expand - set (expanded) braces x 238,243 ops/sec ±0.19% (97 runs sampled) minimatch x 538,268 ops/sec ±0.31% (96 runs sampled) ● expand - set (optimized for regex) braces x 321,844 ops/sec ±0.10% (97 runs sampled) minimatch x 140,600 ops/sec ±0.15% (100 runs sampled) ● expand - nested sets (expanded) braces x 165,371 ops/sec ±0.42% (96 runs sampled) minimatch x 337,720 ops/sec ±0.28% (100 runs sampled) ● expand - nested sets (optimized for regex) braces x 242,948 ops/sec ±0.12% (99 runs sampled) minimatch x 87,403 ops/sec ±0.79% (96 runs sampled) ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Contributors | **Commits** | **Contributor** | | ----------- | ------------------------------------------------------------- | | 197 | [jonschlinkert](https://github.com/jonschlinkert) | | 4 | [doowb](https://github.com/doowb) | | 1 | [es128](https://github.com/es128) | | 1 | [eush77](https://github.com/eush77) | | 1 | [hemanth](https://github.com/hemanth) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Author **Jon Schlinkert** - [GitHub Profile](https://github.com/jonschlinkert) - [Twitter Profile](https://twitter.com/jonschlinkert) - [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). --- _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ node_modules/restore-cursor/license 0000664 00000002135 15114743311 0013567 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/restore-cursor/package.json 0000664 00000001645 15114743311 0014515 0 ustar 00 { "name": "restore-cursor", "version": "4.0.0", "description": "Gracefully restore the CLI cursor on exit", "license": "MIT", "repository": "sindresorhus/restore-cursor", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "scripts": { "test": "xo && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "exit", "quit", "process", "graceful", "shutdown", "sigterm", "sigint", "terminate", "kill", "stop", "cli", "cursor", "ansi", "show", "term", "terminal", "console", "tty", "shell", "command-line" ], "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" }, "devDependencies": { "tsd": "^0.7.2", "xo": "^0.24.0" } } node_modules/restore-cursor/readme.md 0000664 00000001337 15114743311 0014004 0 ustar 00 # restore-cursor > Gracefully restore the CLI cursor on exit Prevent the cursor you've hidden interactively from remaining hidden if the process crashes. ## Install ``` $ npm install restore-cursor ``` ## Usage ```js import restoreCursor from 'restore-cursor'; restoreCursor(); ``` --- <div align="center"> <b> <a href="https://tidelift.com/subscription/pkg/npm-restore-cursor?utm_source=npm-restore-cursor&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> </b> <br> <sub> Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. </sub> </div> node_modules/restore-cursor/index.d.ts 0000664 00000000261 15114743311 0014121 0 ustar 00 /** Gracefully restore the CLI cursor on exit. @example ``` import restoreCursor from 'restore-cursor'; restoreCursor(); ``` */ export default function restoreCursor(): void; node_modules/restore-cursor/index.js 0000664 00000000407 15114743311 0013667 0 ustar 00 import process from 'node:process'; import onetime from 'onetime'; import signalExit from 'signal-exit'; const restoreCursor = onetime(() => { signalExit(() => { process.stderr.write('\u001B[?25h'); }, {alwaysLast: true}); }); export default restoreCursor; node_modules/@winches/prompts/license 0000664 00000002067 15114743311 0014041 0 ustar 00 MIT License Copyright (c) 2018 Terkel Gjervig Nielsen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/@winches/prompts/package.json 0000664 00000001704 15114743311 0014757 0 ustar 00 { "name": "@winches/prompts", "version": "0.0.7", "description": "Lightweight, beautiful and user-friendly prompts", "license": "MIT", "main": "index.js", "types": "index.d.ts", "author": "winches", "files": [ "lib", "index.js", "index.d.ts" ], "scripts": { "start": "node lib/index.js", "test": "tape test/*.js | tap-spec", "test-types": "tsc --noEmit test/type-declarations.ts" }, "keywords": [ "ui", "prompts", "cli", "prompt", "interface", "command-line", "input", "command", "stdin", "menu", "ask", "interact" ], "dependencies": { "kleur": "^4.0.1", "sisteransi": "^1.0.5" }, "devDependencies": { "@types/node": "^18.11.17", "tap-spec": "^5.0.0", "tape": "^4.13.3", "typescript": "^4.9.4" }, "engines": { "node": ">= 14" }, "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" } } node_modules/@winches/prompts/readme.md 0000775 00000067625 15114743311 0014271 0 ustar 00 <p align="center"> <img src="https://github.com/terkelg/prompts/raw/master/prompts.png" alt="Prompts" width="500" /> </p> <h1 align="center">❯ Prompts</h1> <p align="center"> <a href="https://npmjs.org/package/prompts"> <img src="https://img.shields.io/npm/v/prompts.svg" alt="version" /> </a> <a href="https://github.com/terkelg/prompts/actions/workflows/test.yml"> <img src="https://github.com/terkelg/prompts/actions/workflows/test.yml/badge.svg" alt="test" /> </a> <a href="https://npmjs.org/package/prompts"> <img src="https://img.shields.io/npm/dm/prompts.svg" alt="downloads" /> </a> <a href="https://licenses.dev/npm/prompts"> <img src="https://licenses.dev/b/npm/prompts" alt="licenses" /> </a> <!--- <a href="https://packagephobia.now.sh/result?p=prompts"> <img src="https://packagephobia.now.sh/badge?p=prompts" alt="install size" /> </a> ---> </p> <p align="center"> <b>Lightweight, beautiful and user-friendly interactive prompts</b><br /> <sub>>_ Easy to use CLI prompts to enquire users for information▌</sub> </p> <br /> * **Simple**: prompts has [no big dependencies](http://npm.anvaka.com/#/view/2d/prompts) nor is it broken into a [dozen](http://npm.anvaka.com/#/view/2d/inquirer) tiny modules that only work well together. * **User friendly**: prompt uses layout and colors to create beautiful cli interfaces. * **Promised**: uses promises and `async`/`await`. No callback hell. * **Flexible**: all prompts are independent and can be used on their own. * **Testable**: provides a way to submit answers programmatically. * **Unified**: consistent experience across all [prompts](#-types).  ## ❯ Install ``` $ npm install --save prompts ``` > This package supports Node 14 and above  ## ❯ Usage <img src="https://github.com/terkelg/prompts/raw/master/media/example.gif" alt="example prompt" width="499" height="103" /> ```js const prompts = require('prompts'); (async () => { const response = await prompts({ type: 'number', name: 'value', message: 'How old are you?', validate: value => value < 18 ? `Nightclub is 18+ only` : true }); console.log(response); // => { value: 24 } })(); ``` > See [`example.js`](https://github.com/terkelg/prompts/blob/master/example.js) for more options.  ## ❯ Examples ### Single Prompt Prompt with a single prompt object. Returns an object with the response. ```js const prompts = require('prompts'); (async () => { const response = await prompts({ type: 'text', name: 'meaning', message: 'What is the meaning of life?' }); console.log(response.meaning); })(); ``` ### Prompt Chain Prompt with a list of prompt objects. Returns an object with the responses. Make sure to give each prompt a unique `name` property to prevent overwriting values. ```js const prompts = require('prompts'); const questions = [ { type: 'text', name: 'username', message: 'What is your GitHub username?' }, { type: 'number', name: 'age', message: 'How old are you?' }, { type: 'text', name: 'about', message: 'Tell something about yourself', initial: 'Why should I?' } ]; (async () => { const response = await prompts(questions); // => response => { username, age, about } })(); ``` ### Dynamic Prompts Prompt properties can be functions too. Prompt Objects with `type` set to `falsy` values are skipped. ```js const prompts = require('prompts'); const questions = [ { type: 'text', name: 'dish', message: 'Do you like pizza?' }, { type: prev => prev == 'pizza' ? 'text' : null, name: 'topping', message: 'Name a topping' } ]; (async () => { const response = await prompts(questions); })(); ```  ## ❯ API ### prompts(prompts, options) Type: `Function`<br> Returns: `Object` Prompter function which takes your [prompt objects](#-prompt-objects) and returns an object with responses. #### prompts Type: `Array|Object`<br> Array of [prompt objects](#-prompt-objects). These are the questions the user will be prompted. You can see the list of supported [prompt types here](#-types). Prompts can be submitted (<kbd>return</kbd>, <kbd>enter</kbd>) or canceled (<kbd>esc</kbd>, <kbd>abort</kbd>, <kbd>ctrl</kbd>+<kbd>c</kbd>, <kbd>ctrl</kbd>+<kbd>d</kbd>). No property is being defined on the returned response object when a prompt is canceled. #### options.onSubmit Type: `Function`<br> Default: `() => {}` Callback that's invoked after each prompt submission. Its signature is `(prompt, answer, answers)` where `prompt` is the current prompt object, `answer` the user answer to the current question and `answers` the user answers so far. Async functions are supported. Return `true` to quit the prompt chain and return all collected responses so far, otherwise continue to iterate prompt objects. **Example:** ```js (async () => { const questions = [{ ... }]; const onSubmit = (prompt, answer) => console.log(`Thanks I got ${answer} from ${prompt.name}`); const response = await prompts(questions, { onSubmit }); })(); ``` #### options.onCancel Type: `Function`<br> Default: `() => {}` Callback that's invoked when the user cancels/exits the prompt. Its signature is `(prompt, answers)` where `prompt` is the current prompt object and `answers` the user answers so far. Async functions are supported. Return `true` to continue and prevent the prompt loop from aborting. On cancel responses collected so far are returned. **Example:** ```js (async () => { const questions = [{ ... }]; const onCancel = prompt => { console.log('Never stop prompting!'); return true; } const response = await prompts(questions, { onCancel }); })(); ``` ### override Type: `Function` Preanswer questions by passing an object with answers to `prompts.override`. Powerful when combined with arguments of process. **Example** ```js const prompts = require('prompts'); prompts.override(require('yargs').argv); (async () => { const response = await prompts([ { type: 'text', name: 'twitter', message: `What's your twitter handle?` }, { type: 'multiselect', name: 'color', message: 'Pick colors', choices: [ { title: 'Red', value: '#ff0000' }, { title: 'Green', value: '#00ff00' }, { title: 'Blue', value: '#0000ff' } ], } ]); console.log(response); })(); ``` ### inject(values) Type: `Function`<br> Programmatically inject responses. This enables you to prepare the responses ahead of time. If any injected value is found the prompt is immediately resolved with the injected value. This feature is intended for testing only. #### values Type: `Array` Array with values to inject. Resolved values are removed from the internal inject array. Each value can be an array of values in order to provide answers for a question asked multiple times. If a value is an instance of `Error` it will simulate the user cancelling/exiting the prompt. **Example:** ```js const prompts = require('prompts'); prompts.inject([ '@terkelg', ['#ff0000', '#0000ff'] ]); (async () => { const response = await prompts([ { type: 'text', name: 'twitter', message: `What's your twitter handle?` }, { type: 'multiselect', name: 'color', message: 'Pick colors', choices: [ { title: 'Red', value: '#ff0000' }, { title: 'Green', value: '#00ff00' }, { title: 'Blue', value: '#0000ff' } ], } ]); // => { twitter: 'terkelg', color: [ '#ff0000', '#0000ff' ] } })(); ```  ## ❯ Prompt Objects Prompts Objects are JavaScript objects that define the "questions" and the [type of prompt](#-types). Almost all prompt objects have the following properties: ```js { type: String | Function, name: String | Function, message: String | Function, initial: String | Function | Async Function format: Function | Async Function, onRender: Function onState: Function stdin: Readable stdout: Writeable } ``` Each property be of type `function` and will be invoked right before prompting the user. The function signature is `(prev, values, prompt)`, where `prev` is the value from the previous prompt, `values` is the response object with all values collected so far and `prompt` is the previous prompt object. **Function example:** ```js { type: prev => prev > 3 ? 'confirm' : null, name: 'confirm', message: (prev, values) => `Please confirm that you eat ${values.dish} times ${prev} a day?` } ``` The above prompt will be skipped if the value of the previous prompt is less than 3. ### type Type: `String|Function` Defines the type of prompt to display. See the list of [prompt types](#-types) for valid values. If `type` is a falsy value the prompter will skip that question. ```js { type: null, name: 'forgetme', message: `I'll never be shown anyway`, } ``` ### name Type: `String|Function` The response will be saved under this key/property in the returned response object. In case you have multiple prompts with the same name only the latest response will be stored. > Make sure to give prompts unique names if you don't want to overwrite previous values. ### message Type: `String|Function` The message to be displayed to the user. ### initial Type: `String|Function` Optional default prompt value. Async functions are supported too. ### format Type: `Function` Receive the user input and return the formatted value to be used inside the program. The value returned will be added to the response object. The function signature is `(val, values)`, where `val` is the value from the current prompt and `values` is the current response object in case you need to format based on previous responses. **Example:** ```js { type: 'number', name: 'price', message: 'Enter price', format: val => Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }).format(val); } ``` ### onRender Type: `Function` Callback for when the prompt is rendered. The function receives [kleur](https://github.com/lukeed/kleur) as its first argument and `this` refers to the current prompt. **Example:** ```js { type: 'number', message: 'This message will be overridden', onRender(kleur) { this.msg = kleur.cyan('Enter a number'); } } ``` ### onState Type: `Function` Callback for when the state of the current prompt changes. The function signature is `(state)` where `state` is an object with a snapshot of the current state. The state object has two properties `value` and `aborted`. E.g `{ value: 'This is ', aborted: false }` ### stdin and stdout Type: `Stream` By default, prompts uses `process.stdin` for receiving input and `process.stdout` for writing output. If you need to use different streams, for instance `process.stderr`, you can set these with the `stdin` and `stdout` properties.  ## ❯ Types * [text](#textmessage-initial-style) * [password](#passwordmessage-initial) * [invisible](#invisiblemessage-initial) * [number](#numbermessage-initial-max-min-style) * [confirm](#confirmmessage-initial) * [list](#listmessage-initial) * [toggle](#togglemessage-initial-active-inactive) * [select](#selectmessage-choices-initial-hint-warn) * [multiselect](#multiselectmessage-choices-initial-max-hint-warn) * [autocompleteMultiselect](#multiselectmessage-choices-initial-max-hint-warn) * [autocomplete](#autocompletemessage-choices-initial-suggest-limit-style) * [date](#datemessage-initial-warn) *** ### text(message, [initial], [style]) > Text prompt for free text input. Hit <kbd>tab</kbd> to autocomplete to `initial` value when provided. #### Example <img src="https://github.com/terkelg/prompts/raw/master/media/text.gif" alt="text prompt" width="499" height="103" /> ```js { type: 'text', name: 'value', message: `What's your twitter handle?` } ``` #### Options | Param | Type | Description | | ----- | :--: | ----------- | | message | `string` | Prompt message to display | | initial | `string` | Default string value | | style | `string` | Render style (`default`, `password`, `invisible`, `emoji`). Defaults to `default` | | format | `function` | Receive user input. The returned value will be added to the response object | | validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown | | onRender | `function` | On render callback. Keyword `this` refers to the current prompt | | onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | **↑ back to:** [Prompt types](#-types) *** ### password(message, [initial]) > Password prompt with masked input. This prompt is a similar to a prompt of type `'text'` with `style` set to `'password'`. #### Example <img src="https://github.com/terkelg/prompts/raw/master/media/password.gif" alt="password prompt" width="499" height="103" /> ```js { type: 'password', name: 'value', message: 'Tell me a secret' } ``` #### Options | Param | Type | Description | | ----- | :--: | ----------- | | message | `string` | Prompt message to display | | initial | `string` | Default string value | | format | `function` | Receive user input. The returned value will be added to the response object | | validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown | | onRender | `function` | On render callback. Keyword `this` refers to the current prompt | | onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | **↑ back to:** [Prompt types](#-types) *** ### invisible(message, [initial]) > Prompts user for invisible text input. This prompt is working like `sudo` where the input is invisible. This prompt is a similar to a prompt of type `'text'` with style set to `'invisible'`. #### Example <img src="https://github.com/terkelg/prompts/raw/master/media/invisible.gif" alt="invisible prompt" width="499" height="103" /> ```js { type: 'invisible', name: 'value', message: 'Enter password' } ``` #### Options | Param | Type | Description | | ----- | :--: | ----------- | | message | `string` | Prompt message to display | | initial | `string` | Default string value | | format | `function` | Receive user input. The returned value will be added to the response object | | validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown | | onRender | `function` | On render callback. Keyword `this` refers to the current prompt | | onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | **↑ back to:** [Prompt types](#-types) *** ### number(message, initial, [max], [min], [style]) > Prompts user for number input. You can type in numbers and use <kbd>up</kbd>/<kbd>down</kbd> to increase/decrease the value. Only numbers are allowed as input. Hit <kbd>tab</kbd> to autocomplete to `initial` value when provided. #### Example <img src="https://github.com/terkelg/prompts/raw/master/media/number.gif" alt="number prompt" width="499" height="103" /> ```js { type: 'number', name: 'value', message: 'How old are you?', initial: 0, style: 'default', min: 2, max: 10 } ``` #### Options | Param | Type | Description | | ----- | :--: | ----------- | | message | `string` | Prompt message to display | | initial | `number` | Default number value | | format | `function` | Receive user input. The returned value will be added to the response object | | validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown | | max | `number` | Max value. Defaults to `Infinity` | | min | `number` | Min value. Defaults to `-infinity` | | float | `boolean` | Allow floating point inputs. Defaults to `false` | | round | `number` | Round `float` values to x decimals. Defaults to `2` | | increment | `number` | Increment step when using <kbd>arrow</kbd> keys. Defaults to `1` | | style | `string` | Render style (`default`, `password`, `invisible`, `emoji`). Defaults to `default` | | onRender | `function` | On render callback. Keyword `this` refers to the current prompt | | onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | **↑ back to:** [Prompt types](#-types) *** ### confirm(message, [initial]) > Classic yes/no prompt. Hit <kbd>y</kbd> or <kbd>n</kbd> to confirm/reject. #### Example <img src="https://github.com/terkelg/prompts/raw/master/media/confirm.gif" alt="confirm prompt" width="499" height="103" /> ```js { type: 'confirm', name: 'value', message: 'Can you confirm?', initial: true } ``` #### Options | Param | Type | Description | | ----- | :--: | ----------- | | message | `string` | Prompt message to display | | initial | `boolean` | Default value. Default is `false` | | format | `function` | Receive user input. The returned value will be added to the response object | | onRender | `function` | On render callback. Keyword `this` refers to the current prompt | | onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | **↑ back to:** [Prompt types](#-types) *** ### list(message, [initial]) > List prompt that return an array. Similar to the `text` prompt, but the output is an `Array` containing the string separated by `separator`. ```js { type: 'list', name: 'value', message: 'Enter keywords', initial: '', separator: ',' } ``` <img src="https://github.com/terkelg/prompts/raw/master/media/list.gif" alt="list prompt" width="499" height="103" /> | Param | Type | Description | | ----- | :--: | ----------- | | message | `string` | Prompt message to display | | initial | `boolean` | Default value | | format | `function` | Receive user input. The returned value will be added to the response object | | separator | `string` | String separator. Will trim all white-spaces from start and end of string. Defaults to `','` | | onRender | `function` | On render callback. Keyword `this` refers to the current prompt | | onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | **↑ back to:** [Prompt types](#-types) *** ### toggle(message, [initial], [active], [inactive]) > Interactive toggle/switch prompt. Use tab or <kbd>arrow keys</kbd>/<kbd>tab</kbd>/<kbd>space</kbd> to switch between options. #### Example <img src="https://github.com/terkelg/prompts/raw/master/media/toggle.gif" alt="toggle prompt" width="499" height="103" /> ```js { type: 'toggle', name: 'value', message: 'Can you confirm?', initial: true, active: 'yes', inactive: 'no' } ``` #### Options | Param | Type | Description | | ----- | :--: | ----------- | | message | `string` | Prompt message to display | | initial | `boolean` | Default value. Defaults to `false` | | format | `function` | Receive user input. The returned value will be added to the response object | | active | `string` | Text for `active` state. Defaults to `'on'` | | inactive | `string` | Text for `inactive` state. Defaults to `'off'` | | onRender | `function` | On render callback. Keyword `this` refers to the current prompt | | onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | **↑ back to:** [Prompt types](#-types) *** ### select(message, choices, [initial], [hint], [warn]) > Interactive select prompt. Use <kbd>up</kbd>/<kbd>down</kbd> to navigate. Use <kbd>tab</kbd> to cycle the list. #### Example <img src="https://github.com/terkelg/prompts/raw/master/media/select.gif" alt="select prompt" width="499" height="130" /> ```js { type: 'select', name: 'value', message: 'Pick a color', choices: [ { title: 'Red', description: 'This option has a description', value: '#ff0000' }, { title: 'Green', value: '#00ff00', disabled: true }, { title: 'Blue', value: '#0000ff' } ], initial: 1 } ``` #### Options | Param | Type | Description | | ----- | :--: | ----------- | | message | `string` | Prompt message to display | | initial | `number` | Index of default value | | format | `function` | Receive user input. The returned value will be added to the response object | | hint | `string` | Hint to display to the user | | warn | `string` | Message to display when selecting a disabled option | | choices | `Array` | Array of strings or choices objects `[{ title, description, value, disabled }, ...]`. The choice's index in the array will be used as its value if it is not specified. | | onRender | `function` | On render callback. Keyword `this` refers to the current prompt | | onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | **↑ back to:** [Prompt types](#-types) *** ### multiselect(message, choices, [initial], [max], [hint], [warn]) ### autocompleteMultiselect(same) > Interactive multi-select prompt. > Autocomplete is a searchable multiselect prompt with the same options. Useful for long lists. Use <kbd>space</kbd> to toggle select/unselect and <kbd>up</kbd>/<kbd>down</kbd> to navigate. Use <kbd>tab</kbd> to cycle the list. You can also use <kbd>right</kbd> to select and <kbd>left</kbd> to deselect. By default this prompt returns an `array` containing the **values** of the selected items - not their display title. #### Example <img src="https://github.com/terkelg/prompts/raw/master/media/multiselect.gif" alt="multiselect prompt" width="499" height="130" /> ```js { type: 'multiselect', name: 'value', message: 'Pick colors', choices: [ { title: 'Red', value: '#ff0000' }, { title: 'Green', value: '#00ff00', disabled: true }, { title: 'Blue', value: '#0000ff', selected: true } ], max: 2, hint: '- Space to select. Return to submit' } ``` #### Options | Param | Type | Description | | ----- | :--: | ----------- | | message | `string` | Prompt message to display | | format | `function` | Receive user input. The returned value will be added to the response object | | instructions | `string` or `boolean` | Prompt instructions to display | | choices | `Array` | Array of strings or choices objects `[{ title, value, disabled }, ...]`. The choice's index in the array will be used as its value if it is not specified. | | optionsPerPage | `number` | Number of options displayed per page (default: 10) | | min | `number` | Min select - will display error | | max | `number` | Max select | | hint | `string` | Hint to display to the user | | warn | `string` | Message to display when selecting a disabled option | | onRender | `function` | On render callback. Keyword `this` refers to the current prompt | | onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | This is one of the few prompts that don't take a initial value. If you want to predefine selected values, give the choice object an `selected` property of `true`. **↑ back to:** [Prompt types](#-types) *** ### autocomplete(message, choices, [initial], [suggest], [limit], [style]) > Interactive auto complete prompt. The prompt will list options based on user input. Type to filter the list. Use <kbd>⇧</kbd>/<kbd>⇩</kbd> to navigate. Use <kbd>tab</kbd> to cycle the result. Use <kbd>Page Up</kbd>/<kbd>Page Down</kbd> (on Mac: <kbd>fn</kbd> + <kbd>⇧</kbd> / <kbd>⇩</kbd>) to change page. Hit <kbd>enter</kbd> to select the highlighted item below the prompt. The default suggests function is sorting based on the `title` property of the choices. You can overwrite how choices are being filtered by passing your own suggest function. #### Example <img src="https://github.com/terkelg/prompts/raw/master/media/autocomplete.gif" alt="auto complete prompt" width="499" height="163" /> ```js { type: 'autocomplete', name: 'value', message: 'Pick your favorite actor', choices: [ { title: 'Cage' }, { title: 'Clooney', value: 'silver-fox' }, { title: 'Gyllenhaal' }, { title: 'Gibson' }, { title: 'Grant' } ] } ``` #### Options | Param | Type | Description | | ----- | :--: | ----------- | | message | `string` | Prompt message to display | | format | `function` | Receive user input. The returned value will be added to the response object | | choices | `Array` | Array of auto-complete choices objects `[{ title, value }, ...]` | | suggest | `function` | Filter function. Defaults to sort by `title` property. `suggest` should always return a promise. Filters using `title` by default | | limit | `number` | Max number of results to show. Defaults to `10` | | style | `string` | Render style (`default`, `password`, `invisible`, `emoji`). Defaults to `'default'` | | initial | `string \| number` | Default initial value | | clearFirst | `boolean` | The first ESCAPE keypress will clear the input | | fallback | `string` | Fallback message when no match is found. Defaults to `initial` value if provided | | onRender | `function` | On render callback. Keyword `this` refers to the current prompt | | onState | `function` | On state change callback. Function signature is an `object` with three properties: `value`, `aborted` and `exited` | Example on what a `suggest` function might look like: ```js const suggestByTitle = (input, choices) => Promise.resolve(choices.filter(i => i.title.slice(0, input.length) === input)) ``` **↑ back to:** [Prompt types](#-types) *** ### date(message, [initial], [warn]) > Interactive date prompt. Use <kbd>left</kbd>/<kbd>right</kbd>/<kbd>tab</kbd> to navigate. Use <kbd>up</kbd>/<kbd>down</kbd> to change date. #### Example <img src="https://github.com/terkelg/prompts/raw/master/media/date.gif" alt="date prompt" width="499" height="103" /> ```js { type: 'date', name: 'value', message: 'Pick a date', initial: new Date(1997, 09, 12), validate: date => date > Date.now() ? 'Not in the future' : true } ``` #### Options | Param | Type | Description | | ----- | :--: | ----------- | | message | `string` | Prompt message to display | | initial | `date` | Default date | | locales | `object` | Use to define custom locales. See below for an example. | | mask | `string` | The format mask of the date. See below for more information.<br />Default: `YYYY-MM-DD HH:mm:ss` | | validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown | | onRender | `function` | On render callback. Keyword `this` refers to the current prompt | | onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` | Default locales: ```javascript { months: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ], monthsShort: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], weekdays: [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ], weekdaysShort: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ] } ``` >**Formatting**: See full list of formatting options in the [wiki](https://github.com/terkelg/prompts/wiki/Date-Time-Formatting)  **↑ back to:** [Prompt types](#-types) *** ## ❯ Credit Many of the prompts are based on the work of [derhuerst](https://github.com/derhuerst). ## ❯ License MIT © [Terkel Gjervig](https://terkel.com) node_modules/@winches/prompts/index.d.ts 0000664 00000010175 15114743311 0014374 0 ustar 00 /// <reference types="node" /> export = prompts; import { Kleur } from "kleur"; import { Readable, Writable } from "stream"; declare function prompts<T extends string = string>( questions: prompts.PromptObject<T> | Array<prompts.PromptObject<T>>, options?: prompts.Options, ): Promise<prompts.Answers<T>>; declare namespace prompts { // Circular reference from prompts const prompt: any; function inject(arr: readonly any[]): void; namespace inject { const prototype: {}; } function override(obj: { [key: string]: any }): void; namespace override { const prototype: {}; } namespace prompts { function autocomplete(args: PromptObject): any; function confirm(args: PromptObject): void; function date(args: PromptObject): any; function invisible(args: PromptObject): any; function list(args: PromptObject): any; function multiselect(args: PromptObject): any; function number(args: PromptObject): void; function password(args: PromptObject): any; function select(args: PromptObject): void; function text(args: PromptObject): void; function toggle(args: PromptObject): void; } // Based upon: https://github.com/terkelg/prompts/blob/d7d2c37a0009e3235b2e88a7d5cdbb114ac271b2/lib/elements/select.js#L29 interface Choice { title: string; value?: any; disabled?: boolean | undefined; selected?: boolean | undefined; description?: string | undefined; disabledMessage?: string | undefined; } interface Options { onSubmit?: ((prompt: PromptObject, answer: any, answers: any[]) => void) | undefined; onCancel?: ((prompt: PromptObject, answers: any) => void) | undefined; } interface PromptObject<T extends string = string> { type: PromptType | Falsy | PrevCaller<T, PromptType | Falsy>; name: ValueOrFunc<T>; message?: ValueOrFunc<string> | undefined; initial?: InitialReturnValue | PrevCaller<T, InitialReturnValue | Promise<InitialReturnValue>> | undefined; style?: string | PrevCaller<T, string | Falsy> | undefined; format?: PrevCaller<T, void> | undefined; validate?: PrevCaller<T, boolean | string | Promise<boolean | string>> | undefined; onState?: PrevCaller<T, void> | undefined; onRender?: ((kleur: Kleur) => void) | undefined; min?: number | PrevCaller<T, number | Falsy> | undefined; max?: number | PrevCaller<T, number | Falsy> | undefined; float?: boolean | PrevCaller<T, boolean | Falsy> | undefined; round?: number | PrevCaller<T, number | Falsy> | undefined; instructions?: string | boolean | undefined; increment?: number | PrevCaller<T, number | Falsy> | undefined; separator?: string | PrevCaller<T, string | Falsy> | undefined; active?: string | PrevCaller<T, string | Falsy> | undefined; inactive?: string | PrevCaller<T, string | Falsy> | undefined; choices?: Choice[] | PrevCaller<T, Choice[] | Falsy> | undefined; hint?: string | PrevCaller<T, string | Falsy> | undefined; warn?: string | PrevCaller<T, string | Falsy> | undefined; suggest?: ((input: any, choices: Choice[]) => Promise<any>) | undefined; limit?: number | PrevCaller<T, number | Falsy> | undefined; mask?: string | PrevCaller<T, string | Falsy> | undefined; stdout?: Writable | undefined; stdin?: Readable | undefined; } type Answers<T extends string> = { [id in T]: any }; type PrevCaller<T extends string, R = T> = ( prev: any, values: Answers<T>, prompt: PromptObject, ) => R; type Falsy = false | null | undefined; type PromptType = | "text" | "password" | "invisible" | "number" | "confirm" | "list" | "toggle" | "select" | "multiselect" | "autocomplete" | "date" | "autocompleteMultiselect"; type ValueOrFunc<T extends string> = T | PrevCaller<T>; type InitialReturnValue = string | number | boolean | Date; } node_modules/@winches/prompts/lib/dateparts/hours.js 0000664 00000001055 15114743311 0016723 0 ustar 00 'use strict'; const DatePart = require('./datepart'); class Hours extends DatePart { constructor(opts={}) { super(opts); } up() { this.date.setHours(this.date.getHours() + 1); } down() { this.date.setHours(this.date.getHours() - 1); } setTo(val) { this.date.setHours(parseInt(val.substr(-2))); } toString() { let hours = this.date.getHours(); if (/h/.test(this.token)) hours = (hours % 12) || 12; return this.token.length > 1 ? String(hours).padStart(2, '0') : hours; } } module.exports = Hours; node_modules/@winches/prompts/lib/dateparts/datepart.js 0000664 00000001251 15114743311 0017365 0 ustar 00 'use strict'; class DatePart { constructor({token, date, parts, locales}) { this.token = token; this.date = date || new Date(); this.parts = parts || [this]; this.locales = locales || {}; } up() {} down() {} next() { const currentIdx = this.parts.indexOf(this); return this.parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); } setTo(val) {} prev() { let parts = [].concat(this.parts).reverse(); const currentIdx = parts.indexOf(this); return parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); } toString() { return String(this.date); } } module.exports = DatePart; node_modules/@winches/prompts/lib/dateparts/minutes.js 0000664 00000000761 15114743311 0017252 0 ustar 00 'use strict'; const DatePart = require('./datepart'); class Minutes extends DatePart { constructor(opts={}) { super(opts); } up() { this.date.setMinutes(this.date.getMinutes() + 1); } down() { this.date.setMinutes(this.date.getMinutes() - 1); } setTo(val) { this.date.setMinutes(parseInt(val.substr(-2))); } toString() { let m = this.date.getMinutes(); return this.token.length > 1 ? String(m).padStart(2, '0') : m; } } module.exports = Minutes; node_modules/@winches/prompts/lib/dateparts/day.js 0000664 00000001536 15114743311 0016344 0 ustar 00 'use strict'; const DatePart = require('./datepart'); const pos = n => { n = n % 10; return n === 1 ? 'st' : n === 2 ? 'nd' : n === 3 ? 'rd' : 'th'; } class Day extends DatePart { constructor(opts={}) { super(opts); } up() { this.date.setDate(this.date.getDate() + 1); } down() { this.date.setDate(this.date.getDate() - 1); } setTo(val) { this.date.setDate(parseInt(val.substr(-2))); } toString() { let date = this.date.getDate(); let day = this.date.getDay(); return this.token === 'DD' ? String(date).padStart(2, '0') : this.token === 'Do' ? date + pos(date) : this.token === 'd' ? day + 1 : this.token === 'ddd' ? this.locales.weekdaysShort[day] : this.token === 'dddd' ? this.locales.weekdays[day] : date; } } module.exports = Day; node_modules/@winches/prompts/lib/dateparts/milliseconds.js 0000664 00000001114 15114743311 0020244 0 ustar 00 'use strict'; const DatePart = require('./datepart'); class Milliseconds extends DatePart { constructor(opts={}) { super(opts); } up() { this.date.setMilliseconds(this.date.getMilliseconds() + 1); } down() { this.date.setMilliseconds(this.date.getMilliseconds() - 1); } setTo(val) { this.date.setMilliseconds(parseInt(val.substr(-(this.token.length)))); } toString() { return String(this.date.getMilliseconds()).padStart(4, '0') .substr(0, this.token.length); } } module.exports = Milliseconds; node_modules/@winches/prompts/lib/dateparts/year.js 0000664 00000000775 15114743311 0016533 0 ustar 00 'use strict'; const DatePart = require('./datepart'); class Year extends DatePart { constructor(opts={}) { super(opts); } up() { this.date.setFullYear(this.date.getFullYear() + 1); } down() { this.date.setFullYear(this.date.getFullYear() - 1); } setTo(val) { this.date.setFullYear(val.substr(-4)); } toString() { let year = String(this.date.getFullYear()).padStart(4, '0'); return this.token.length === 2 ? year.substr(-2) : year; } } module.exports = Year; node_modules/@winches/prompts/lib/dateparts/month.js 0000664 00000001255 15114743311 0016712 0 ustar 00 'use strict'; const DatePart = require('./datepart'); class Month extends DatePart { constructor(opts={}) { super(opts); } up() { this.date.setMonth(this.date.getMonth() + 1); } down() { this.date.setMonth(this.date.getMonth() - 1); } setTo(val) { val = parseInt(val.substr(-2)) - 1; this.date.setMonth(val < 0 ? 0 : val); } toString() { let month = this.date.getMonth(); let tl = this.token.length; return tl === 2 ? String(month + 1).padStart(2, '0') : tl === 3 ? this.locales.monthsShort[month] : tl === 4 ? this.locales.months[month] : String(month + 1); } } module.exports = Month; node_modules/@winches/prompts/lib/dateparts/meridiem.js 0000664 00000000643 15114743311 0017360 0 ustar 00 'use strict'; const DatePart = require('./datepart'); class Meridiem extends DatePart { constructor(opts={}) { super(opts); } up() { this.date.setHours((this.date.getHours() + 12) % 24); } down() { this.up(); } toString() { let meridiem = this.date.getHours() > 12 ? 'pm' : 'am'; return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem; } } module.exports = Meridiem; node_modules/@winches/prompts/lib/dateparts/index.js 0000664 00000000505 15114743311 0016671 0 ustar 00 'use strict'; module.exports = { DatePart: require('./datepart'), Meridiem: require('./meridiem'), Day: require('./day'), Hours: require('./hours'), Milliseconds: require('./milliseconds'), Minutes: require('./minutes'), Month: require('./month'), Seconds: require('./seconds'), Year: require('./year'), } node_modules/@winches/prompts/lib/dateparts/seconds.js 0000664 00000000761 15114743311 0017224 0 ustar 00 'use strict'; const DatePart = require('./datepart'); class Seconds extends DatePart { constructor(opts={}) { super(opts); } up() { this.date.setSeconds(this.date.getSeconds() + 1); } down() { this.date.setSeconds(this.date.getSeconds() - 1); } setTo(val) { this.date.setSeconds(parseInt(val.substr(-2))); } toString() { let s = this.date.getSeconds(); return this.token.length > 1 ? String(s).padStart(2, '0') : s; } } module.exports = Seconds; node_modules/@winches/prompts/lib/prompts.js 0000664 00000021141 15114743311 0015276 0 ustar 00 'use strict'; const $ = exports; const el = require('./elements'); const noop = v => v; function toPrompt(type, args, opts={}) { return new Promise((res, rej) => { const p = new el[type](args); const onAbort = opts.onAbort || noop; const onSubmit = opts.onSubmit || noop; const onExit = opts.onExit || noop; p.on('state', args.onState || noop); p.on('submit', x => res(onSubmit(x))); p.on('exit', x => res(onExit(x))); p.on('abort', x => rej(onAbort(x))); }); } /** * Text prompt * @param {string} args.message Prompt message to display * @param {string} [args.initial] Default string value * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') * @param {function} [args.onState] On state change callback * @param {function} [args.validate] Function to validate user input * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.text = args => toPrompt('TextPrompt', args); /** * Password prompt with masked input * @param {string} args.message Prompt message to display * @param {string} [args.initial] Default string value * @param {function} [args.onState] On state change callback * @param {function} [args.validate] Function to validate user input * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.password = args => { args.style = 'password'; return $.text(args); }; /** * Prompt where input is invisible, like sudo * @param {string} args.message Prompt message to display * @param {string} [args.initial] Default string value * @param {function} [args.onState] On state change callback * @param {function} [args.validate] Function to validate user input * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.invisible = args => { args.style = 'invisible'; return $.text(args); }; /** * Number prompt * @param {string} args.message Prompt message to display * @param {number} args.initial Default number value * @param {function} [args.onState] On state change callback * @param {number} [args.max] Max value * @param {number} [args.min] Min value * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') * @param {Boolean} [opts.float=false] Parse input as floats * @param {Number} [opts.round=2] Round floats to x decimals * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys * @param {function} [args.validate] Function to validate user input * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.number = args => toPrompt('NumberPrompt', args); /** * Date prompt * @param {string} args.message Prompt message to display * @param {number} args.initial Default number value * @param {function} [args.onState] On state change callback * @param {number} [args.max] Max value * @param {number} [args.min] Min value * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') * @param {Boolean} [opts.float=false] Parse input as floats * @param {Number} [opts.round=2] Round floats to x decimals * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys * @param {function} [args.validate] Function to validate user input * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.date = args => toPrompt('DatePrompt', args); /** * Classic yes/no prompt * @param {string} args.message Prompt message to display * @param {boolean} [args.initial=false] Default value * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.confirm = args => toPrompt('ConfirmPrompt', args); /** * List prompt, split intput string by `seperator` * @param {string} args.message Prompt message to display * @param {string} [args.initial] Default string value * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') * @param {string} [args.separator] String separator * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input, in form of an `Array` */ $.list = args => { const sep = args.separator || ','; return toPrompt('TextPrompt', args, { onSubmit: str => str.split(sep).map(s => s.trim()) }); }; /** * Toggle/switch prompt * @param {string} args.message Prompt message to display * @param {boolean} [args.initial=false] Default value * @param {string} [args.active="on"] Text for `active` state * @param {string} [args.inactive="off"] Text for `inactive` state * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.toggle = args => toPrompt('TogglePrompt', args); /** * Interactive select prompt * @param {string} args.message Prompt message to display * @param {Array} args.choices Array of choices objects `[{ title, value }, ...]` * @param {number} [args.initial] Index of default value * @param {String} [args.hint] Hint to display * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.select = args => toPrompt('SelectPrompt', args); /** * Interactive multi-select / autocompleteMultiselect prompt * @param {string} args.message Prompt message to display * @param {Array} args.choices Array of choices objects `[{ title, value, [selected] }, ...]` * @param {number} [args.max] Max select * @param {string} [args.hint] Hint to display user * @param {Number} [args.cursor=0] Cursor start position * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.multiselect = args => { args.choices = [].concat(args.choices || []); const toSelected = items => items.filter(item => item.selected).map(item => item.value); return toPrompt('MultiselectPrompt', args, { onAbort: toSelected, onSubmit: toSelected }); }; $.autocompleteMultiselect = args => { args.choices = [].concat(args.choices || []); const toSelected = items => items.filter(item => item.selected).map(item => item.value); return toPrompt('AutocompleteMultiselectPrompt', args, { onAbort: toSelected, onSubmit: toSelected }); }; const byTitle = (input, choices) => Promise.resolve( choices.filter(item => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase()) ); /** * Interactive auto-complete prompt * @param {string} args.message Prompt message to display * @param {Array} args.choices Array of auto-complete choices objects `[{ title, value }, ...]` * @param {Function} [args.suggest] Function to filter results based on user input. Defaults to sort by `title` * @param {number} [args.limit=10] Max number of results to show * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') * @param {String} [args.initial] Index of the default value * @param {boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input * @param {String} [args.fallback] Fallback message - defaults to initial value * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.autocomplete = args => { args.suggest = args.suggest || byTitle; args.choices = [].concat(args.choices || []); return toPrompt('AutocompletePrompt', args); }; node_modules/@winches/prompts/lib/elements/autocompleteMultiselect.js 0000664 00000012734 15114743311 0022332 0 ustar 00 'use strict'; const color = require('kleur'); const { cursor } = require('sisteransi'); const MultiselectPrompt = require('./multiselect'); const { clear, style, figures } = require('../util'); /** * MultiselectPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Array} opts.choices Array of choice objects * @param {String} [opts.hint] Hint to display * @param {String} [opts.warn] Hint shown for disabled choices * @param {Number} [opts.max] Max choices * @param {Number} [opts.cursor=0] Cursor start position * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to */ class AutocompleteMultiselectPrompt extends MultiselectPrompt { constructor(opts={}) { opts.overrideRender = true; super(opts); this.inputValue = ''; this.clear = clear('', this.out.columns); this.filteredOptions = this.value; this.render(); } last() { this.cursor = this.filteredOptions.length - 1; this.render(); } next() { this.cursor = (this.cursor + 1) % this.filteredOptions.length; this.render(); } up() { if (this.cursor === 0) { this.cursor = this.filteredOptions.length - 1; } else { this.cursor--; } this.render(); } down() { if (this.cursor === this.filteredOptions.length - 1) { this.cursor = 0; } else { this.cursor++; } this.render(); } left() { this.filteredOptions[this.cursor].selected = false; this.render(); } right() { if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); this.filteredOptions[this.cursor].selected = true; this.render(); } delete() { if (this.inputValue.length) { this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1); this.updateFilteredOptions(); } } updateFilteredOptions() { const currentHighlight = this.filteredOptions[this.cursor]; this.filteredOptions = this.value .filter(v => { if (this.inputValue) { if (typeof v.title === 'string') { if (v.title.toLowerCase().includes(this.inputValue.toLowerCase())) { return true; } } if (typeof v.value === 'string') { if (v.value.toLowerCase().includes(this.inputValue.toLowerCase())) { return true; } } return false; } return true; }); const newHighlightIndex = this.filteredOptions.findIndex(v => v === currentHighlight) this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex; this.render(); } handleSpaceToggle() { const v = this.filteredOptions[this.cursor]; if (v.selected) { v.selected = false; this.render(); } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { return this.bell(); } else { v.selected = true; this.render(); } } handleInputChange(c) { this.inputValue = this.inputValue + c; this.updateFilteredOptions(); } _(c, key) { if (c === ' ') { this.handleSpaceToggle(); } else { this.handleInputChange(c); } } renderInstructions() { if (this.instructions === undefined || this.instructions) { if (typeof this.instructions === 'string') { return this.instructions; } return ` Instructions: ${figures.arrowUp}/${figures.arrowDown}: Highlight option ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection [a,b,c]/delete: Filter choices enter/return: Complete answer `; } return ''; } renderCurrentInput() { return `\n\nFiltered results for: ${this.inputValue ? this.inputValue : color.gray('Enter something to filter')}\n`; } renderOption(cursor, v, i, arrowIndicator) { const prefix = (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + arrowIndicator + ' '; let title; if (v.disabled) title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); else title = cursor === i ? color.cyan().underline(v.title) : v.title; return prefix + title; } renderDoneOrInstructions() { if (this.done) { return this.value .filter(e => e.selected) .map(v => v.title) .join(', '); } const output = [color.gray(this.hint), this.renderCurrentInput()]; if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) { output.push(color.yellow(this.warn)); } return output.join(' '); } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor.hide); super.render(); // print prompt let prompt = [ style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions() ].join(' '); if (this.showMinError) { prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); this.showMinError = false; } prompt += this.renderOptions(this.filteredOptions); // Add disabled output if (this.disabledList?.length) { prompt += `\n\n${color.gray( `${this.disabledList[0].disabledMessage || this.disabledMessage}: ${this.disabledList.map((v) => v.title).join(', ')}` )}`; } this.out.write(this.clear + prompt); this.clear = clear(prompt, this.out.columns); } } module.exports = AutocompleteMultiselectPrompt; node_modules/@winches/prompts/lib/elements/autocomplete.js 0000664 00000017114 15114743311 0020114 0 ustar 00 'use strict'; const color = require('kleur'); const Prompt = require('./prompt'); const { erase, cursor } = require('sisteransi'); const { style, clear, figures, wrap, entriesToDisplay } = require('../util'); const getVal = (arr, i) => arr[i] && (arr[i].value || arr[i].title || arr[i]); const getTitle = (arr, i) => arr[i] && (arr[i].title || arr[i].value || arr[i]); const getIndex = (arr, valOrTitle) => { const index = arr.findIndex(el => el.value === valOrTitle || el.title === valOrTitle); return index > -1 ? index : undefined; }; /** * TextPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Array} opts.choices Array of auto-complete choices objects * @param {Function} [opts.suggest] Filter function. Defaults to sort by title * @param {Number} [opts.limit=10] Max number of results to show * @param {Number} [opts.cursor=0] Cursor start position * @param {String} [opts.style='default'] Render style * @param {String} [opts.fallback] Fallback message - initial to default value * @param {String} [opts.initial] Index of the default value * @param {Boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to * @param {String} [opts.noMatches] The no matches found label */ class AutocompletePrompt extends Prompt { constructor(opts={}) { super(opts); this.msg = opts.message; this.suggest = opts.suggest; this.choices = opts.choices; this.initial = typeof opts.initial === 'number' ? opts.initial : getIndex(opts.choices, opts.initial); this.select = this.initial || opts.cursor || 0; this.i18n = { noMatches: opts.noMatches || 'no matches found' }; this.fallback = opts.fallback || this.initial; this.clearFirst = opts.clearFirst || false; this.suggestions = []; this.input = ''; this.limit = opts.limit || 10; this.cursor = 0; this.transform = style.render(opts.style); this.scale = this.transform.scale; this.render = this.render.bind(this); this.complete = this.complete.bind(this); this.clear = clear('', this.out.columns); this.complete(this.render); this.render(); } set fallback(fb) { this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb; } get fallback() { let choice; if (typeof this._fb === 'number') choice = this.choices[this._fb]; else if (typeof this._fb === 'string') choice = { title: this._fb }; return choice || this._fb || { title: this.i18n.noMatches }; } moveSelect(i) { this.select = i; if (this.suggestions.length > 0) this.value = getVal(this.suggestions, i); else this.value = this.fallback.value; this.fire(); } async complete(cb) { const p = (this.completing = this.suggest(this.input, this.choices)); const suggestions = await p; if (this.completing !== p) return; this.suggestions = suggestions .map((s, i, arr) => ({ title: getTitle(arr, i), value: getVal(arr, i), description: s.description })); this.completing = false; const l = Math.max(suggestions.length - 1, 0); this.moveSelect(Math.min(l, this.select)); cb && cb(); } reset() { this.input = ''; this.complete(() => { this.moveSelect(this.initial !== void 0 ? this.initial : 0); this.render(); }); this.render(); } exit() { if (this.clearFirst && this.input.length > 0) { this.reset(); } else { this.done = this.exited = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } } abort() { this.done = this.aborted = true; this.exited = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } submit() { this.done = true; this.aborted = this.exited = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } _(c, key) { let s1 = this.input.slice(0, this.cursor); let s2 = this.input.slice(this.cursor); this.input = `${s1}${c}${s2}`; this.cursor = s1.length+1; this.complete(this.render); this.render(); } delete() { if (this.cursor === 0) return this.bell(); let s1 = this.input.slice(0, this.cursor-1); let s2 = this.input.slice(this.cursor); this.input = `${s1}${s2}`; this.complete(this.render); this.cursor = this.cursor-1; this.render(); } deleteForward() { if(this.cursor*this.scale >= this.rendered.length) return this.bell(); let s1 = this.input.slice(0, this.cursor); let s2 = this.input.slice(this.cursor+1); this.input = `${s1}${s2}`; this.complete(this.render); this.render(); } first() { this.moveSelect(0); this.render(); } last() { this.moveSelect(this.suggestions.length - 1); this.render(); } up() { if (this.select === 0) { this.moveSelect(this.suggestions.length - 1); } else { this.moveSelect(this.select - 1); } this.render(); } down() { if (this.select === this.suggestions.length - 1) { this.moveSelect(0); } else { this.moveSelect(this.select + 1); } this.render(); } next() { if (this.select === this.suggestions.length - 1) { this.moveSelect(0); } else this.moveSelect(this.select + 1); this.render(); } nextPage() { this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1)); this.render(); } prevPage() { this.moveSelect(Math.max(this.select - this.limit, 0)); this.render(); } left() { if (this.cursor <= 0) return this.bell(); this.cursor = this.cursor-1; this.render(); } right() { if (this.cursor*this.scale >= this.rendered.length) return this.bell(); this.cursor = this.cursor+1; this.render(); } renderOption(v, hovered, isStart, isEnd) { let desc; let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : ' '; let title = hovered ? color.cyan().underline(v.title) : v.title; prefix = (hovered ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; if (v.description) { desc = ` - ${v.description}`; if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns }) } } return prefix + ' ' + title + color.gray(desc || ''); } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor.hide); else this.out.write(clear(this.outputText, this.out.columns)); super.render(); let { startIndex, endIndex } = entriesToDisplay(this.select, this.choices.length, this.limit); this.outputText = [ style.symbol(this.done, this.aborted, this.exited), color.bold(this.msg), style.delimiter(this.completing), this.done && this.suggestions[this.select] ? this.suggestions[this.select].title : this.rendered = this.transform.render(this.input) ].join(' '); if (!this.done) { const suggestions = this.suggestions .slice(startIndex, endIndex) .map((item, i) => this.renderOption(item, this.select === i + startIndex, i === 0 && startIndex > 0, i + startIndex === endIndex - 1 && endIndex < this.choices.length)) .join('\n'); this.outputText += `\n` + (suggestions || color.gray(this.fallback.title)); } this.out.write(erase.line + cursor.to(0) + this.outputText); } } module.exports = AutocompletePrompt; node_modules/@winches/prompts/lib/elements/confirm.js 0000664 00000004447 15114743311 0017055 0 ustar 00 const color = require('kleur'); const Prompt = require('./prompt'); const { style, clear } = require('../util'); const { erase, cursor } = require('sisteransi'); /** * ConfirmPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Boolean} [opts.initial] Default value (true/false) * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to * @param {String} [opts.yes] The "Yes" label * @param {String} [opts.yesOption] The "Yes" option when choosing between yes/no * @param {String} [opts.no] The "No" label * @param {String} [opts.noOption] The "No" option when choosing between yes/no */ class ConfirmPrompt extends Prompt { constructor(opts={}) { super(opts); this.msg = opts.message; this.value = opts.initial; this.initialValue = !!opts.initial; this.yesMsg = opts.yes || 'yes'; this.yesOption = opts.yesOption || '(Y/n)'; this.noMsg = opts.no || 'no'; this.noOption = opts.noOption || '(y/N)'; this.render(); } reset() { this.value = this.initialValue; this.fire(); this.render(); } exit() { this.abort(); } abort() { this.done = this.aborted = true; this.fire(); this.render(); this.out.write('\n'); this.close(); } submit() { this.value = this.value || false; this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } _(c, key) { if (c.toLowerCase() === 'y') { this.value = true; return this.submit(); } if (c.toLowerCase() === 'n') { this.value = false; return this.submit(); } return this.bell(); } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor.hide); else this.out.write(clear(this.outputText, this.out.columns)); super.render(); this.outputText = [ style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.done ? (this.value ? this.yesMsg : this.noMsg) : color.gray(this.initialValue ? this.yesOption : this.noOption) ].join(' '); this.out.write(erase.line + cursor.to(0) + this.outputText); } } module.exports = ConfirmPrompt; node_modules/@winches/prompts/lib/elements/prompt.js 0000664 00000003443 15114743311 0016734 0 ustar 00 'use strict'; const readline = require('readline'); const { action } = require('../util'); const EventEmitter = require('events'); const { beep, cursor } = require('sisteransi'); const color = require('kleur'); /** * Base prompt skeleton * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to */ class Prompt extends EventEmitter { constructor(opts={}) { super(); this.firstRender = true; this.in = opts.stdin || process.stdin; this.out = opts.stdout || process.stdout; this.onRender = (opts.onRender || (() => void 0)).bind(this); const rl = readline.createInterface({ input:this.in, escapeCodeTimeout:50 }); readline.emitKeypressEvents(this.in, rl); if (this.in.isTTY) this.in.setRawMode(true); const isSelect = [ 'SelectPrompt', 'MultiselectPrompt' ].indexOf(this.constructor.name) > -1; const keypress = (str, key) => { let a = action(key, isSelect); if (a === false) { this._ && this._(str, key); } else if (typeof this[a] === 'function') { this[a](key); } else { this.bell(); } }; this.close = () => { this.out.write(cursor.show); this.in.removeListener('keypress', keypress); if (this.in.isTTY) this.in.setRawMode(false); rl.close(); this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value); this.closed = true; }; this.in.on('keypress', keypress); } fire() { this.emit('state', { value: this.value, aborted: !!this.aborted, exited: !!this.exited }); } bell() { this.out.write(beep); } render() { this.onRender(color); if (this.firstRender) this.firstRender = false; } } module.exports = Prompt; node_modules/@winches/prompts/lib/elements/date.js 0000664 00000013054 15114743311 0016327 0 ustar 00 'use strict'; const color = require('kleur'); const Prompt = require('./prompt'); const { style, clear, figures } = require('../util'); const { erase, cursor } = require('sisteransi'); const { DatePart, Meridiem, Day, Hours, Milliseconds, Minutes, Month, Seconds, Year } = require('../dateparts'); const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g; const regexGroups = { 1: ({token}) => token.replace(/\\(.)/g, '$1'), 2: (opts) => new Day(opts), // Day // TODO 3: (opts) => new Month(opts), // Month 4: (opts) => new Year(opts), // Year 5: (opts) => new Meridiem(opts), // AM/PM // TODO (special) 6: (opts) => new Hours(opts), // Hours 7: (opts) => new Minutes(opts), // Minutes 8: (opts) => new Seconds(opts), // Seconds 9: (opts) => new Milliseconds(opts), // Fractional seconds } const dfltLocales = { months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','), monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',') } /** * DatePrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Number} [opts.initial] Index of default value * @param {String} [opts.mask] The format mask * @param {object} [opts.locales] The date locales * @param {String} [opts.error] The error message shown on invalid value * @param {Function} [opts.validate] Function to validate the submitted value * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to */ class DatePrompt extends Prompt { constructor(opts={}) { super(opts); this.msg = opts.message; this.cursor = 0; this.typed = ''; this.locales = Object.assign(dfltLocales, opts.locales); this._date = opts.initial || new Date(); this.errorMsg = opts.error || 'Please Enter A Valid Value'; this.validator = opts.validate || (() => true); this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss'; this.clear = clear('', this.out.columns); this.render(); } get value() { return this.date } get date() { return this._date; } set date(date) { if (date) this._date.setTime(date.getTime()); } set mask(mask) { let result; this.parts = []; while(result = regex.exec(mask)) { let match = result.shift(); let idx = result.findIndex(gr => gr != null); this.parts.push(idx in regexGroups ? regexGroups[idx]({ token: result[idx] || match, date: this.date, parts: this.parts, locales: this.locales }) : result[idx] || match); } let parts = this.parts.reduce((arr, i) => { if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string') arr[arr.length - 1] += i; else arr.push(i); return arr; }, []); this.parts.splice(0); this.parts.push(...parts); this.reset(); } moveCursor(n) { this.typed = ''; this.cursor = n; this.fire(); } reset() { this.moveCursor(this.parts.findIndex(p => p instanceof DatePart)); this.fire(); this.render(); } exit() { this.abort(); } abort() { this.done = this.aborted = true; this.error = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } async validate() { let valid = await this.validator(this.value); if (typeof valid === 'string') { this.errorMsg = valid; valid = false; } this.error = !valid; } async submit() { await this.validate(); if (this.error) { this.color = 'red'; this.fire(); this.render(); return; } this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } up() { this.typed = ''; this.parts[this.cursor].up(); this.render(); } down() { this.typed = ''; this.parts[this.cursor].down(); this.render(); } left() { let prev = this.parts[this.cursor].prev(); if (prev == null) return this.bell(); this.moveCursor(this.parts.indexOf(prev)); this.render(); } right() { let next = this.parts[this.cursor].next(); if (next == null) return this.bell(); this.moveCursor(this.parts.indexOf(next)); this.render(); } next() { let next = this.parts[this.cursor].next(); this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex((part) => part instanceof DatePart)); this.render(); } _(c) { if (/\d/.test(c)) { this.typed += c; this.parts[this.cursor].setTo(this.typed); this.render(); } } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor.hide); else this.out.write(clear(this.outputText, this.out.columns)); super.render(); // Print prompt this.outputText = [ style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p.toString()) : p), []) .join('') ].join(' '); // Print error if (this.error) { this.outputText += this.errorMsg.split('\n').reduce( (a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); } this.out.write(erase.line + cursor.to(0) + this.outputText); } } module.exports = DatePrompt; node_modules/@winches/prompts/lib/elements/number.js 0000664 00000013036 15114743311 0016702 0 ustar 00 const color = require('kleur'); const Prompt = require('./prompt'); const { cursor, erase } = require('sisteransi'); const { style, figures, clear, lines } = require('../util'); const isNumber = /[0-9]/; const isDef = any => any !== undefined; const round = (number, precision) => { let factor = Math.pow(10, precision); return Math.round(number * factor) / factor; } /** * NumberPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {String} [opts.style='default'] Render style * @param {Number} [opts.initial] Default value * @param {Number} [opts.max=+Infinity] Max value * @param {Number} [opts.min=-Infinity] Min value * @param {Boolean} [opts.float=false] Parse input as floats * @param {Number} [opts.round=2] Round floats to x decimals * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys * @param {Function} [opts.validate] Validate function * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to * @param {String} [opts.error] The invalid error label */ class NumberPrompt extends Prompt { constructor(opts={}) { super(opts); this.transform = style.render(opts.style); this.msg = opts.message; this.initial = isDef(opts.initial) ? opts.initial : ''; this.float = !!opts.float; this.round = opts.round || 2; this.inc = opts.increment || 1; this.min = isDef(opts.min) ? opts.min : -Infinity; this.max = isDef(opts.max) ? opts.max : Infinity; this.errorMsg = opts.error || `Please Enter A Valid Value`; this.validator = opts.validate || (() => true); this.color = `cyan`; this.value = ``; this.typed = ``; this.lastHit = 0; this.render(); } set value(v) { if (!v && v !== 0) { this.placeholder = true; this.rendered = color.gray(this.transform.render(`${this.initial}`)); this._value = ``; } else { this.placeholder = false; this.rendered = this.transform.render(`${round(v, this.round)}`); this._value = round(v, this.round); } this.fire(); } get value() { return this._value; } parse(x) { return this.float ? parseFloat(x) : parseInt(x); } valid(c) { return c === `-` || c === `.` && this.float || isNumber.test(c) } reset() { this.typed = ``; this.value = ``; this.fire(); this.render(); } exit() { this.abort(); } abort() { let x = this.value; this.value = x !== `` ? x : this.initial; this.done = this.aborted = true; this.error = false; this.fire(); this.render(); this.out.write(`\n`); this.close(); } async validate() { let valid = await this.validator(this.value); if (typeof valid === `string`) { this.errorMsg = valid; valid = false; } this.error = !valid; } async submit() { await this.validate(); if (this.error) { this.color = `red`; this.fire(); this.render(); return; } let x = this.value; this.value = x !== `` ? x : this.initial; this.done = true; this.aborted = false; this.error = false; this.fire(); this.render(); this.out.write(`\n`); this.close(); } up() { this.typed = ``; if(this.value === '') { this.value = this.min - this.inc; } if (this.value >= this.max) return this.bell(); this.value += this.inc; this.color = `cyan`; this.fire(); this.render(); } down() { this.typed = ``; if(this.value === '') { this.value = this.min + this.inc; } if (this.value <= this.min) return this.bell(); this.value -= this.inc; this.color = `cyan`; this.fire(); this.render(); } delete() { let val = this.value.toString(); if (val.length === 0) return this.bell(); this.value = this.parse((val = val.slice(0, -1))) || ``; if (this.value !== '' && this.value < this.min) { this.value = this.min; } this.color = `cyan`; this.fire(); this.render(); } next() { this.value = this.initial; this.fire(); this.render(); } _(c, key) { if (!this.valid(c)) return this.bell(); const now = Date.now(); if (now - this.lastHit > 1000) this.typed = ``; // 1s elapsed this.typed += c; this.lastHit = now; this.color = `cyan`; if (c === `.`) return this.fire(); this.value = Math.min(this.parse(this.typed), this.max); if (this.value > this.max) this.value = this.max; if (this.value < this.min) this.value = this.min; this.fire(); this.render(); } render() { if (this.closed) return; if (!this.firstRender) { if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); this.out.write(clear(this.outputText, this.out.columns)); } super.render(); this.outputError = ''; // Print prompt this.outputText = [ style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), !this.done || (!this.done && !this.placeholder) ? color[this.color]().underline(this.rendered) : this.rendered ].join(` `); // Print error if (this.error) { this.outputError += this.errorMsg.split(`\n`) .reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); } this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore); } } module.exports = NumberPrompt; node_modules/@winches/prompts/lib/elements/select.js 0000664 00000011337 15114743311 0016673 0 ustar 00 'use strict'; const color = require('kleur'); const Prompt = require('./prompt'); const { style, clear, figures, wrap, entriesToDisplay } = require('../util'); const { cursor } = require('sisteransi'); /** * SelectPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Array} opts.choices Array of choice objects * @param {String} [opts.hint] Hint to display * @param {Number} [opts.initial] Index of default value * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to * @param {Number} [opts.optionsPerPage=10] Max options to display at once */ class SelectPrompt extends Prompt { constructor(opts={}) { super(opts); this.msg = opts.message; this.hint = opts.hint || '- Use arrow-keys. Return to submit.'; this.warn = opts.warn || '- This option is disabled'; this.cursor = opts.initial || 0; this.choices = opts.choices.map((ch, idx) => { if (typeof ch === 'string') ch = {title: ch, value: idx}; return { title: ch && (ch.title || ch.value || ch), value: ch && (ch.value === undefined ? idx : ch.value), description: ch && ch.description, selected: ch && ch.selected, disabled: ch && ch.disabled }; }); this.optionsPerPage = opts.optionsPerPage || 10; this.value = (this.choices[this.cursor] || {}).value; this.clear = clear('', this.out.columns); this.render(); } moveCursor(n) { this.cursor = n; this.value = this.choices[n].value; this.fire(); } reset() { this.moveCursor(0); this.fire(); this.render(); } exit() { this.abort(); } abort() { this.done = this.aborted = true; this.fire(); this.render(); this.out.write('\n'); this.close(); } submit() { if (!this.selection.disabled) { this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } else this.bell(); } first() { this.moveCursor(0); this.render(); } last() { this.moveCursor(this.choices.length - 1); this.render(); } up() { if (this.cursor === 0) { this.moveCursor(this.choices.length - 1); } else { this.moveCursor(this.cursor - 1); } this.render(); } down() { if (this.cursor === this.choices.length - 1) { this.moveCursor(0); } else { this.moveCursor(this.cursor + 1); } this.render(); } next() { this.moveCursor((this.cursor + 1) % this.choices.length); this.render(); } _(c, key) { if (c === ' ') return this.submit(); } get selection() { return this.choices[this.cursor]; } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor.hide); else this.out.write(clear(this.outputText, this.out.columns)); super.render(); let { startIndex, endIndex } = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage); // Print prompt this.outputText = [ style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.done ? this.selection.title : this.selection.disabled ? color.yellow(this.warn) : color.gray(this.hint) ].join(' '); // Print choices if (!this.done) { this.outputText += '\n'; for (let i = startIndex; i < endIndex; i++) { let title, prefix, desc = '', v = this.choices[i]; // Determine whether to display "more choices" indicators if (i === startIndex && startIndex > 0) { prefix = figures.arrowUp; } else if (i === endIndex - 1 && endIndex < this.choices.length) { prefix = figures.arrowDown; } else { prefix = ' '; } if (v.disabled) { title = this.cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); prefix = (this.cursor === i ? color.bold().gray(figures.pointer) + ' ' : ' ') + prefix; } else { title = this.cursor === i ? color.cyan().underline(v.title) : v.title; prefix = (this.cursor === i ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; if (v.description && this.cursor === i) { desc = ` - ${v.description}`; if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns }); } } } this.outputText += `${prefix} ${title}${color.gray(desc)}\n`; } } this.out.write(this.outputText); } } module.exports = SelectPrompt; node_modules/@winches/prompts/lib/elements/multiselect.js 0000664 00000017216 15114743311 0017750 0 ustar 00 'use strict'; const color = require('kleur'); const {cursor} = require('sisteransi'); const {clear, entriesToDisplay, figures, style, wrap} = require('../util'); const Prompt = require('./prompt'); /** * MultiselectPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Array} opts.choices Array of choice objects * @param {String} [opts.hint] Hint to display * @param {String} [opts.warn] Hint shown for disabled choices * @param {Number} [opts.max] Max choices * @param {Number} [opts.cursor=0] Cursor start position * @param {Number} [opts.optionsPerPage=10] Max options to display at once * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to * @param {string} [opts.disabledMessage] The disabled message for choices */ class MultiselectPrompt extends Prompt { constructor(opts = {}) { super(opts); this.msg = opts.message; this.cursor = opts.cursor || 0; this.scrollIndex = opts.cursor || 0; this.hint = opts.hint || ''; this.warn = opts.warn || '- This option is disabled -'; this.minSelected = opts.min; this.showMinError = false; this.maxChoices = opts.max; this.instructions = opts.instructions; this.optionsPerPage = opts.optionsPerPage || 10; this.value = opts.choices.map((ch, idx) => { if (typeof ch === 'string') ch = {title: ch, value: idx}; return { description: ch && ch.description, disabled: ch && ch.disabled, selected: ch && ch.selected, title: ch && (ch.title || ch.value || ch), value: ch && (ch.value === undefined ? idx : ch.value) }; }).filter((v) => !v.disabled); this.clear = clear('', this.out.columns); if (!opts.overrideRender) { this.render(); } this.disabledList = opts.choices.filter((v) => v.disabled); this.disabledMessage = opts.disabledMessage || 'Already disabled'; } reset() { this.value.map((v) => !v.selected); this.cursor = 0; this.fire(); this.render(); } selected() { return this.value.filter((v) => v.selected); } exit() { this.abort(); } abort() { this.done = this.aborted = true; this.fire(); this.render(); this.out.write('\n'); this.close(); } submit() { const selected = this.value.filter((e) => e.selected); if (this.minSelected && selected.length < this.minSelected) { this.showMinError = true; this.render(); } else { this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } } first() { this.cursor = 0; this.render(); } last() { this.cursor = this.value.length - 1; this.render(); } next() { this.cursor = (this.cursor + 1) % this.value.length; this.render(); } up() { if (this.cursor === 0) { this.cursor = this.value.length - 1; } else { this.cursor--; } this.render(); } down() { if (this.cursor === this.value.length - 1) { this.cursor = 0; } else { this.cursor++; } this.render(); } left() { this.value[this.cursor].selected = false; this.render(); } right() { if (this.value.filter((e) => e.selected).length >= this.maxChoices) return this.bell(); this.value[this.cursor].selected = true; this.render(); } handleSpaceToggle() { const v = this.value[this.cursor]; if (v.selected) { v.selected = false; this.render(); } else if (v.disabled || this.value.filter((e) => e.selected).length >= this.maxChoices) { return this.bell(); } else { v.selected = true; this.render(); } } toggleAll() { if (this.maxChoices !== undefined || this.value[this.cursor].disabled) { return this.bell(); } const newSelected = !this.value[this.cursor].selected; this.value.filter((v) => !v.disabled).forEach((v) => (v.selected = newSelected)); this.render(); } _(c, key) { if (c === ' ') { this.handleSpaceToggle(); } else if (c === 'a') { this.toggleAll(); } else { return this.bell(); } } renderInstructions() { if (this.instructions === undefined || this.instructions) { if (typeof this.instructions === 'string') { return this.instructions; } return ( '\nInstructions:\n' + ` ${figures.arrowUp}/${figures.arrowDown}: Highlight option\n` + ` ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection\n` + (this.maxChoices === undefined ? ` a: Toggle all\n` : '') + ` enter/return: Complete answer` ); } return ''; } renderOption(cursor, v, i, arrowIndicator) { const prefix = (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + arrowIndicator + ' '; let title, desc; if (v.disabled) { title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); } else { title = cursor === i ? color.cyan().underline(v.title) : v.title; if (cursor === i && v.description) { desc = ` - ${v.description}`; if ( prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1 ) { desc = '\n' + wrap(v.description, {margin: prefix.length, width: this.out.columns}); } } } return prefix + title + color.gray(desc || ''); } // shared with autocompleteMultiselect paginateOptions(options) { if (options.length === 0) { return color.red('No matches for this query.'); } let {endIndex, startIndex} = entriesToDisplay(this.cursor, options.length, this.optionsPerPage); let prefix, styledOptions = []; for (let i = startIndex; i < endIndex; i++) { // disabled continue; if (options[i].disabled) { continue; } if (i === startIndex && startIndex > 0) { prefix = figures.arrowUp; } else if (i === endIndex - 1 && endIndex < options.length) { prefix = figures.arrowDown; } else { prefix = ' '; } styledOptions.push(this.renderOption(this.cursor, options[i], i, prefix)); } return '\n' + styledOptions.join('\n'); } // shared with autocomleteMultiselect renderOptions(options) { if (!this.done) { return this.paginateOptions(options); } return ''; } renderDoneOrInstructions() { if (this.done) { return this.value .filter((e) => e.selected) .map((v) => v.title) .join(', '); } const output = [color.gray(this.hint)]; if (this.value[this.cursor].disabled) { output.push(color.yellow(this.warn)); } return output.join(' '); } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor.hide); super.render(); // print prompt let prompt = [ style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions() ].join(' '); if (this.showMinError) { prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); this.showMinError = false; } prompt += this.renderOptions(this.value); // Add disabled output if (this.disabledList?.length) { prompt += `\n\n${color.gray( `${this.disabledList[0].disabledMessage || this.disabledMessage}: ${this.disabledList.map((v) => v.title).join(', ')}` )}`; } this.out.write(this.clear + prompt); this.clear = clear(prompt, this.out.columns); } } module.exports = MultiselectPrompt; node_modules/@winches/prompts/lib/elements/text.js 0000664 00000012335 15114743311 0016377 0 ustar 00 const color = require('kleur'); const Prompt = require('./prompt'); const { erase, cursor } = require('sisteransi'); const { style, clear, lines, figures } = require('../util'); /** * TextPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {String} [opts.style='default'] Render style * @param {String} [opts.initial] Default value * @param {Function} [opts.validate] Validate function * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to * @param {String} [opts.error] The invalid error label */ class TextPrompt extends Prompt { constructor(opts={}) { super(opts); this.transform = style.render(opts.style); this.scale = this.transform.scale; this.msg = opts.message; this.initial = opts.initial || ``; this.validator = opts.validate || (() => true); this.value = ``; this.errorMsg = opts.error || `Please Enter A Valid Value`; this.cursor = Number(!!this.initial); this.cursorOffset = 0; this.clear = clear(``, this.out.columns); this.render(); } set value(v) { if (!v && this.initial) { this.placeholder = true; this.rendered = color.gray(this.transform.render(this.initial)); } else { this.placeholder = false; this.rendered = this.transform.render(v); } this._value = v; this.fire(); } get value() { return this._value; } reset() { this.value = ``; this.cursor = Number(!!this.initial); this.cursorOffset = 0; this.fire(); this.render(); } exit() { this.abort(); } abort() { this.value = this.value || this.initial; this.done = this.aborted = true; this.error = false; this.red = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } async validate() { let valid = await this.validator(this.value); if (typeof valid === `string`) { this.errorMsg = valid; valid = false; } this.error = !valid; } async submit() { this.value = this.value || this.initial; this.cursorOffset = 0; this.cursor = this.rendered.length; await this.validate(); if (this.error) { this.red = true; this.fire(); this.render(); return; } this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } next() { if (!this.placeholder) return this.bell(); this.value = this.initial; this.cursor = this.rendered.length; this.fire(); this.render(); } moveCursor(n) { if (this.placeholder) return; this.cursor = this.cursor+n; this.cursorOffset += n; } _(c, key) { let s1 = this.value.slice(0, this.cursor); let s2 = this.value.slice(this.cursor); this.value = `${s1}${c}${s2}`; this.red = false; this.cursor = this.placeholder ? 0 : s1.length+1; this.render(); } delete() { if (this.isCursorAtStart()) return this.bell(); let s1 = this.value.slice(0, this.cursor-1); let s2 = this.value.slice(this.cursor); this.value = `${s1}${s2}`; this.red = false; if (this.isCursorAtStart()) { this.cursorOffset = 0 } else { this.cursorOffset++; this.moveCursor(-1); } this.render(); } deleteForward() { if(this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell(); let s1 = this.value.slice(0, this.cursor); let s2 = this.value.slice(this.cursor+1); this.value = `${s1}${s2}`; this.red = false; if (this.isCursorAtEnd()) { this.cursorOffset = 0; } else { this.cursorOffset++; } this.render(); } first() { this.cursor = 0; this.render(); } last() { this.cursor = this.value.length; this.render(); } left() { if (this.cursor <= 0 || this.placeholder) return this.bell(); this.moveCursor(-1); this.render(); } right() { if (this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell(); this.moveCursor(1); this.render(); } isCursorAtStart() { return this.cursor === 0 || (this.placeholder && this.cursor === 1); } isCursorAtEnd() { return this.cursor === this.rendered.length || (this.placeholder && this.cursor === this.rendered.length + 1) } render() { if (this.closed) return; if (!this.firstRender) { if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); this.out.write(clear(this.outputText, this.out.columns)); } super.render(); this.outputError = ''; this.outputText = [ style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.red ? color.red(this.rendered) : this.rendered ].join(` `); if (this.error) { this.outputError += this.errorMsg.split(`\n`) .reduce((a, l, i) => a + `\n${i ? ' ' : figures.pointerSmall} ${color.red().italic(l)}`, ``); } this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0)); } } module.exports = TextPrompt; node_modules/@winches/prompts/lib/elements/toggle.js 0000664 00000005040 15114743311 0016667 0 ustar 00 const color = require('kleur'); const Prompt = require('./prompt'); const { style, clear } = require('../util'); const { cursor, erase } = require('sisteransi'); /** * TogglePrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Boolean} [opts.initial=false] Default value * @param {String} [opts.active='no'] Active label * @param {String} [opts.inactive='off'] Inactive label * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to */ class TogglePrompt extends Prompt { constructor(opts={}) { super(opts); this.msg = opts.message; this.value = !!opts.initial; this.active = opts.active || 'on'; this.inactive = opts.inactive || 'off'; this.initialValue = this.value; this.render(); } reset() { this.value = this.initialValue; this.fire(); this.render(); } exit() { this.abort(); } abort() { this.done = this.aborted = true; this.fire(); this.render(); this.out.write('\n'); this.close(); } submit() { this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } deactivate() { if (this.value === false) return this.bell(); this.value = false; this.render(); } activate() { if (this.value === true) return this.bell(); this.value = true; this.render(); } delete() { this.deactivate(); } left() { this.deactivate(); } right() { this.activate(); } down() { this.deactivate(); } up() { this.activate(); } next() { this.value = !this.value; this.fire(); this.render(); } _(c, key) { if (c === ' ') { this.value = !this.value; } else if (c === '1') { this.value = true; } else if (c === '0') { this.value = false; } else return this.bell(); this.render(); } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor.hide); else this.out.write(clear(this.outputText, this.out.columns)); super.render(); this.outputText = [ style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.value ? this.inactive : color.cyan().underline(this.inactive), color.gray('/'), this.value ? color.cyan().underline(this.active) : this.active ].join(' '); this.out.write(erase.line + cursor.to(0) + this.outputText); } } module.exports = TogglePrompt; node_modules/@winches/prompts/lib/elements/index.js 0000664 00000000643 15114743311 0016521 0 ustar 00 'use strict'; module.exports = { TextPrompt: require('./text'), SelectPrompt: require('./select'), TogglePrompt: require('./toggle'), DatePrompt: require('./date'), NumberPrompt: require('./number'), MultiselectPrompt: require('./multiselect'), AutocompletePrompt: require('./autocomplete'), AutocompleteMultiselectPrompt: require('./autocompleteMultiselect'), ConfirmPrompt: require('./confirm') }; node_modules/@winches/prompts/lib/util/clear.js 0000664 00000000751 15114743311 0015641 0 ustar 00 'use strict'; const strip = require('./strip'); const { erase, cursor } = require('sisteransi'); const width = str => [...strip(str)].length; /** * @param {string} prompt * @param {number} perLine */ module.exports = function(prompt, perLine) { if (!perLine) return erase.line + cursor.to(0); let rows = 0; const lines = prompt.split(/\r?\n/); for (let line of lines) { rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine); } return erase.lines(rows); }; node_modules/@winches/prompts/lib/util/action.js 0000664 00000002352 15114743311 0016027 0 ustar 00 'use strict'; module.exports = (key, isSelect) => { if (key.meta && key.name !== 'escape') return; if (key.ctrl) { if (key.name === 'a') return 'first'; if (key.name === 'c') return 'abort'; if (key.name === 'd') return 'abort'; if (key.name === 'e') return 'last'; if (key.name === 'g') return 'reset'; } if (isSelect) { if (key.name === 'j') return 'down'; if (key.name === 'k') return 'up'; } if (key.name === 'return') return 'submit'; if (key.name === 'enter') return 'submit'; // ctrl + J if (key.name === 'backspace') return 'delete'; if (key.name === 'delete') return 'deleteForward'; if (key.name === 'abort') return 'abort'; if (key.name === 'escape') return 'exit'; if (key.name === 'tab') return 'next'; if (key.name === 'pagedown') return 'nextPage'; if (key.name === 'pageup') return 'prevPage'; // TODO create home() in prompt types (e.g. TextPrompt) if (key.name === 'home') return 'home'; // TODO create end() in prompt types (e.g. TextPrompt) if (key.name === 'end') return 'end'; if (key.name === 'up') return 'up'; if (key.name === 'down') return 'down'; if (key.name === 'right') return 'right'; if (key.name === 'left') return 'left'; return false; }; node_modules/@winches/prompts/lib/util/entriesToDisplay.js 0000664 00000001321 15114743311 0020047 0 ustar 00 'use strict'; /** * Determine what entries should be displayed on the screen, based on the * currently selected index and the maximum visible. Used in list-based * prompts like `select` and `multiselect`. * * @param {number} cursor the currently selected entry * @param {number} total the total entries available to display * @param {number} [maxVisible] the number of entries that can be displayed */ module.exports = (cursor, total, maxVisible) => { maxVisible = maxVisible || total; let startIndex = Math.min(total- maxVisible, cursor - Math.floor(maxVisible / 2)); if (startIndex < 0) startIndex = 0; let endIndex = Math.min(startIndex + maxVisible, total); return { startIndex, endIndex }; }; node_modules/@winches/prompts/lib/util/lines.js 0000664 00000000516 15114743311 0015664 0 ustar 00 'use strict'; const strip = require('./strip'); /** * @param {string} msg * @param {number} perLine */ module.exports = function (msg, perLine) { let lines = String(strip(msg) || '').split(/\r?\n/); if (!perLine) return lines.length; return lines.map(l => Math.ceil(l.length / perLine)) .reduce((a, b) => a + b); }; node_modules/@winches/prompts/lib/util/wrap.js 0000664 00000001432 15114743311 0015521 0 ustar 00 'use strict'; /** * @param {string} msg The message to wrap * @param {object} opts * @param {number|string} [opts.margin] Left margin * @param {number} opts.width Maximum characters per line including the margin */ module.exports = (msg, opts = {}) => { const tab = Number.isSafeInteger(parseInt(opts.margin)) ? new Array(parseInt(opts.margin)).fill(' ').join('') : (opts.margin || ''); const width = opts.width; return (msg || '').split(/\r?\n/g) .map(line => line .split(/\s+/g) .reduce((arr, w) => { if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width) arr[arr.length - 1] += ` ${w}`; else arr.push(`${tab}${w}`); return arr; }, [ tab ]) .join('\n')) .join('\n'); }; node_modules/@winches/prompts/lib/util/figures.js 0000664 00000001164 15114743311 0016216 0 ustar 00 'use strict'; const main = { arrowUp: '↑', arrowDown: '↓', arrowLeft: '←', arrowRight: '→', radioOn: '◉', radioOff: '◯', tick: '✔', cross: '✖', ellipsis: '…', pointerSmall: '›', line: '─', pointer: '❯' }; const win = { arrowUp: main.arrowUp, arrowDown: main.arrowDown, arrowLeft: main.arrowLeft, arrowRight: main.arrowRight, radioOn: '(*)', radioOff: '( )', tick: '√', cross: '×', ellipsis: '...', pointerSmall: '»', line: '─', pointer: '>' }; const figures = process.platform === 'win32' ? win : main; module.exports = figures; node_modules/@winches/prompts/lib/util/style.js 0000664 00000002126 15114743311 0015711 0 ustar 00 'use strict'; const c = require('kleur'); const figures = require('./figures'); // rendering user input. const styles = Object.freeze({ password: { scale: 1, render: input => '*'.repeat(input.length) }, emoji: { scale: 2, render: input => '😃'.repeat(input.length) }, invisible: { scale: 0, render: input => '' }, default: { scale: 1, render: input => `${input}` } }); const render = type => styles[type] || styles.default; // icon to signalize a prompt. const symbols = Object.freeze({ aborted: c.red(figures.cross), done: c.green(figures.tick), exited: c.yellow(figures.cross), default: c.cyan('?') }); const symbol = (done, aborted, exited) => aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default; // between the question and the user's input. const delimiter = completing => c.gray(completing ? figures.ellipsis : figures.pointerSmall); const item = (expandable, expanded) => c.gray(expandable ? (expanded ? figures.pointerSmall : '+') : figures.line); module.exports = { styles, render, symbols, symbol, delimiter, item }; node_modules/@winches/prompts/lib/util/index.js 0000664 00000000446 15114743311 0015663 0 ustar 00 'use strict'; module.exports = { action: require('./action'), clear: require('./clear'), style: require('./style'), strip: require('./strip'), figures: require('./figures'), lines: require('./lines'), wrap: require('./wrap'), entriesToDisplay: require('./entriesToDisplay') }; node_modules/@winches/prompts/lib/util/strip.js 0000664 00000000570 15114743311 0015713 0 ustar 00 'use strict'; module.exports = str => { const pattern = [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' ].join('|'); const RGX = new RegExp(pattern, 'g'); return typeof str === 'string' ? str.replace(RGX, '') : str; }; node_modules/@winches/prompts/lib/index.js 0000664 00000005756 15114743311 0014717 0 ustar 00 'use strict'; const prompts = require('./prompts'); const passOn = ['suggest', 'format', 'onState', 'validate', 'onRender', 'type']; const noop = () => {}; /** * Prompt for a series of questions * @param {Array|Object} questions Single question object or Array of question objects * @param {Function} [onSubmit] Callback function called on prompt submit * @param {Function} [onCancel] Callback function called on cancel/abort * @returns {Object} Object with values from user input */ async function prompt(questions=[], { onSubmit=noop, onCancel=noop }={}) { const answers = {}; const override = prompt._override || {}; questions = [].concat(questions); let answer, question, quit, name, type, lastPrompt; const getFormattedAnswer = async (question, answer, skipValidation = false) => { if (!skipValidation && question.validate && question.validate(answer) !== true) { return; } return question.format ? await question.format(answer, answers) : answer }; for (question of questions) { ({ name, type } = question); // evaluate type first and skip if type is a falsy value if (typeof type === 'function') { type = await type(answer, { ...answers }, question) question['type'] = type } if (!type) continue; // if property is a function, invoke it unless it's a special function for (let key in question) { if (passOn.includes(key)) continue; let value = question[key]; question[key] = typeof value === 'function' ? await value(answer, { ...answers }, lastPrompt) : value; } lastPrompt = question; if (typeof question.message !== 'string') { throw new Error('prompt message is required'); } // update vars in case they changed ({ name, type } = question); if (prompts[type] === void 0) { throw new Error(`prompt type (${type}) is not defined`); } if (override[question.name] !== undefined) { answer = await getFormattedAnswer(question, override[question.name]); if (answer !== undefined) { answers[name] = answer; continue; } } try { // Get the injected answer if there is one or prompt the user answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : await prompts[type](question); answers[name] = answer = await getFormattedAnswer(question, answer, true); quit = await onSubmit(question, answer, answers); } catch (err) { quit = !(await onCancel(question, answers)); } if (quit) return answers; } return answers; } function getInjectedAnswer(injected, deafultValue) { const answer = injected.shift(); if (answer instanceof Error) { throw answer; } return (answer === undefined) ? deafultValue : answer; } function inject(answers) { prompt._injected = (prompt._injected || []).concat(answers); } function override(answers) { prompt._override = Object.assign({}, answers); } module.exports = Object.assign(prompt, { prompt, prompts, inject, override }); node_modules/@winches/prompts/index.js 0000664 00000000054 15114743311 0014133 0 ustar 00 module.exports = require('./lib/index.js'); node_modules/path-exists/license 0000664 00000002135 15114743311 0013042 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/path-exists/package.json 0000664 00000001263 15114743311 0013764 0 ustar 00 { "name": "path-exists", "version": "5.0.0", "description": "Check if a path exists", "license": "MIT", "repository": "sindresorhus/path-exists", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "path", "exists", "exist", "file", "filepath", "fs", "filesystem", "file-system", "access", "stat" ], "devDependencies": { "ava": "^3.15.0", "tsd": "^0.17.0", "xo": "^0.44.0" } } node_modules/path-exists/readme.md 0000664 00000002744 15114743311 0013262 0 ustar 00 # path-exists > Check if a path exists NOTE: `fs.existsSync` has been un-deprecated in Node.js since 6.8.0. If you only need to check synchronously, this module is not needed. Never use this before handling a file though: > In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to `fs.exists()` and `fs.open()`. Just open the file and handle the error when it's not there. ## Install ``` $ npm install path-exists ``` ## Usage ```js // foo.js import {pathExists} from 'path-exists'; console.log(await pathExists('foo.js')); //=> true ``` ## API ### pathExists(path) Returns a `Promise<boolean>` of whether the path exists. ### pathExistsSync(path) Returns a `boolean` of whether the path exists. ## Related - [path-exists-cli](https://github.com/sindresorhus/path-exists-cli) - CLI for this module - [path-type](https://github.com/sindresorhus/path-type) - Check if a path exists and whether it's a file, directory, or symlink --- <div align="center"> <b> <a href="https://tidelift.com/subscription/pkg/npm-path-exists?utm_source=npm-path-exists&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> </b> <br> <sub> Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. </sub> </div> node_modules/path-exists/index.d.ts 0000664 00000000770 15114743311 0013401 0 ustar 00 /** Check if a path exists. @returns Whether the path exists. @example ``` // foo.ts import {pathExists} from 'path-exists'; console.log(await pathExists('foo.ts')); //=> true ``` */ export function pathExists(path: string): Promise<boolean>; /** Synchronously check if a path exists. @returns Whether the path exists. @example ``` // foo.ts import {pathExistsSync} from 'path-exists'; console.log(pathExistsSync('foo.ts')); //=> true ``` */ export function pathExistsSync(path: string): boolean; node_modules/path-exists/index.js 0000664 00000000452 15114743311 0013142 0 ustar 00 import fs, {promises as fsPromises} from 'node:fs'; export async function pathExists(path) { try { await fsPromises.access(path); return true; } catch { return false; } } export function pathExistsSync(path) { try { fs.accessSync(path); return true; } catch { return false; } } node_modules/reusify/reusify.js 0000664 00000000706 15114743311 0012740 0 ustar 00 'use strict' function reusify (Constructor) { var head = new Constructor() var tail = head function get () { var current = head if (current.next) { head = current.next } else { head = new Constructor() tail = head } current.next = null return current } function release (obj) { tail.next = obj tail = obj } return { get: get, release: release } } module.exports = reusify node_modules/reusify/package.json 0000664 00000002062 15114743311 0013177 0 ustar 00 { "name": "reusify", "version": "1.1.0", "description": "Reuse objects and functions with style", "main": "reusify.js", "types": "reusify.d.ts", "scripts": { "lint": "eslint", "test": "tape test.js", "test:coverage": "c8 --100 tape test.js", "test:typescript": "tsc" }, "pre-commit": [ "lint", "test", "test:typescript" ], "repository": { "type": "git", "url": "git+https://github.com/mcollina/reusify.git" }, "keywords": [ "reuse", "object", "performance", "function", "fast" ], "author": "Matteo Collina <hello@matteocollina.com>", "license": "MIT", "bugs": { "url": "https://github.com/mcollina/reusify/issues" }, "homepage": "https://github.com/mcollina/reusify#readme", "engines": { "node": ">=0.10.0", "iojs": ">=1.0.0" }, "devDependencies": { "@types/node": "^22.9.0", "eslint": "^9.13.0", "neostandard": "^0.12.0", "pre-commit": "^1.2.2", "tape": "^5.0.0", "c8": "^10.1.2", "typescript": "^5.2.2" }, "dependencies": { } } node_modules/reusify/benchmarks/createNoCodeFunction.js 0000664 00000001116 15114743311 0017424 0 ustar 00 'use strict' var fib = require('./fib') var max = 100000000 var start = Date.now() // create a funcion with the typical error // pattern, that delegates the heavy load // to something else function createNoCodeFunction () { /* eslint no-constant-condition: "off" */ var num = 100 ;(function () { if (null) { // do nothing } else { fib(num) } })() } for (var i = 0; i < max; i++) { createNoCodeFunction() } var time = Date.now() - start console.log('Total time', time) console.log('Total iterations', max) console.log('Iteration/s', max / time * 1000) node_modules/reusify/benchmarks/reuseNoCodeFunction.js 0000664 00000001311 15114743311 0017301 0 ustar 00 'use strict' var reusify = require('../') var fib = require('./fib') var instance = reusify(MyObject) var max = 100000000 var start = Date.now() function reuseNoCodeFunction () { var obj = instance.get() obj.num = 100 obj.func() obj.num = 0 instance.release(obj) } function MyObject () { this.next = null var that = this this.num = 0 this.func = function () { /* eslint no-constant-condition: "off" */ if (null) { // do nothing } else { fib(that.num) } } } for (var i = 0; i < max; i++) { reuseNoCodeFunction() } var time = Date.now() - start console.log('Total time', time) console.log('Total iterations', max) console.log('Iteration/s', max / time * 1000) node_modules/reusify/benchmarks/fib.js 0000664 00000000261 15114743311 0014123 0 ustar 00 'use strict' function fib (num) { var fib = [] fib[0] = 0 fib[1] = 1 for (var i = 2; i <= num; i++) { fib[i] = fib[i - 2] + fib[i - 1] } } module.exports = fib node_modules/reusify/reusify.d.ts 0000664 00000000324 15114743311 0013170 0 ustar 00 interface Node { next: Node | null; } interface Constructor<T> { new(): T; } declare function reusify<T extends Node>(constructor: Constructor<T>): { get(): T; release(node: T): void; }; export = reusify; node_modules/reusify/LICENSE 0000664 00000002077 15114743311 0011724 0 ustar 00 The MIT License (MIT) Copyright (c) 2015-2024 Matteo Collina Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/reusify/SECURITY.md 0000664 00000000707 15114743311 0012506 0 ustar 00 # Security Policy ## Supported Versions Use this section to tell people about which versions of your project are currently being supported with security updates. | Version | Supported | | ------- | ------------------ | | 1.x | :white_check_mark: | | < 1.0 | :x: | ## Reporting a Vulnerability Please report all vulnerabilities at [https://github.com/mcollina/fastq/security](https://github.com/mcollina/fastq/security). node_modules/reusify/test.js 0000664 00000002640 15114743311 0012230 0 ustar 00 'use strict' var test = require('tape') var reusify = require('./') test('reuse objects', function (t) { t.plan(6) function MyObject () { t.pass('constructor called') this.next = null } var instance = reusify(MyObject) var obj = instance.get() t.notEqual(obj, instance.get(), 'two instance created') t.notOk(obj.next, 'next must be null') instance.release(obj) // the internals keeps a hot copy ready for reuse // putting this one back in the queue instance.release(instance.get()) // comparing the old one with the one we got // never do this in real code, after release you // should never reuse that instance t.equal(obj, instance.get(), 'instance must be reused') }) test('reuse more than 2 objects', function (t) { function MyObject () { t.pass('constructor called') this.next = null } var instance = reusify(MyObject) var obj = instance.get() var obj2 = instance.get() var obj3 = instance.get() t.notOk(obj.next, 'next must be null') t.notOk(obj2.next, 'next must be null') t.notOk(obj3.next, 'next must be null') t.notEqual(obj, obj2) t.notEqual(obj, obj3) t.notEqual(obj3, obj2) instance.release(obj) instance.release(obj2) instance.release(obj3) // skip one instance.get() var obj4 = instance.get() var obj5 = instance.get() var obj6 = instance.get() t.equal(obj4, obj) t.equal(obj5, obj2) t.equal(obj6, obj3) t.end() }) node_modules/reusify/tsconfig.json 0000664 00000000234 15114743311 0013417 0 ustar 00 { "compilerOptions": { "target": "es6", "module": "commonjs", "noEmit": true, "strict": true }, "files": [ "./reusify.d.ts" ] } node_modules/reusify/eslint.config.js 0000664 00000000304 15114743311 0014006 0 ustar 00 'use strict' const base = require('neostandard')({}) module.exports = [ ...base, { name: 'old-standard', rules: { 'no-var': 'off', 'object-shorthand': 'off', } } ] node_modules/reusify/.github/dependabot.yml 0000664 00000000175 15114743311 0015104 0 ustar 00 version: 2 updates: - package-ecosystem: npm directory: "/" schedule: interval: daily open-pull-requests-limit: 10 node_modules/reusify/.github/workflows/ci.yml 0000664 00000003357 15114743311 0015434 0 ustar 00 name: ci on: [push, pull_request] jobs: legacy: runs-on: ubuntu-latest strategy: matrix: node-version: ['0.10', '0.12', 4.x, 6.x, 8.x, 10.x, 12.x, 13.x, 14.x, 15.x, 16.x] steps: - uses: actions/checkout@v4 with: persist-credentials: false - name: Use Node.js uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - name: Install run: | npm install --production && npm install tape - name: Run tests run: | npm run test test: runs-on: ubuntu-latest strategy: matrix: node-version: [18.x, 20.x, 22.x] steps: - uses: actions/checkout@v4 with: persist-credentials: false - name: Use Node.js uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - name: Install run: | npm install - name: Run tests run: | npm run test:coverage types: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: persist-credentials: false - name: Use Node.js uses: actions/setup-node@v4 with: node-version: 22 - name: Install run: | npm install - name: Run types tests run: | npm run test:typescript lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: persist-credentials: false - name: Use Node.js uses: actions/setup-node@v4 with: node-version: 22 - name: Install run: | npm install - name: Lint run: | npm run lint node_modules/reusify/README.md 0000664 00000006252 15114743311 0012175 0 ustar 00 # reusify [![npm version][npm-badge]][npm-url] Reuse your objects and functions for maximum speed. This technique will make any function run ~10% faster. You call your functions a lot, and it adds up quickly in hot code paths. ``` $ node benchmarks/createNoCodeFunction.js Total time 53133 Total iterations 100000000 Iteration/s 1882069.5236482036 $ node benchmarks/reuseNoCodeFunction.js Total time 50617 Total iterations 100000000 Iteration/s 1975620.838848608 ``` The above benchmark uses fibonacci to simulate a real high-cpu load. The actual numbers might differ for your use case, but the difference should not. The benchmark was taken using Node v6.10.0. This library was extracted from [fastparallel](http://npm.im/fastparallel). ## Example ```js var reusify = require('reusify') var fib = require('reusify/benchmarks/fib') var instance = reusify(MyObject) // get an object from the cache, // or creates a new one when cache is empty var obj = instance.get() // set the state obj.num = 100 obj.func() // reset the state. // if the state contains any external object // do not use delete operator (it is slow) // prefer set them to null obj.num = 0 // store an object in the cache instance.release(obj) function MyObject () { // you need to define this property // so V8 can compile MyObject into an // hidden class this.next = null this.num = 0 var that = this // this function is never reallocated, // so it can be optimized by V8 this.func = function () { if (null) { // do nothing } else { // calculates fibonacci fib(that.num) } } } ``` The above example was intended for synchronous code, let's see async: ```js var reusify = require('reusify') var instance = reusify(MyObject) for (var i = 0; i < 100; i++) { getData(i, console.log) } function getData (value, cb) { var obj = instance.get() obj.value = value obj.cb = cb obj.run() } function MyObject () { this.next = null this.value = null var that = this this.run = function () { asyncOperation(that.value, that.handle) } this.handle = function (err, result) { that.cb(err, result) that.value = null that.cb = null instance.release(that) } } ``` Also note how in the above examples, the code, that consumes an instance of `MyObject`, reset the state to initial condition, just before storing it in the cache. That's needed so that every subsequent request for an instance from the cache, could get a clean instance. ## Why It is faster because V8 doesn't have to collect all the functions you create. On a short-lived benchmark, it is as fast as creating the nested function, but on a longer time frame it creates less pressure on the garbage collector. ## Other examples If you want to see some complex example, checkout [middie](https://github.com/fastify/middie) and [steed](https://github.com/mcollina/steed). ## Acknowledgements Thanks to [Trevor Norris](https://github.com/trevnorris) for getting me down the rabbit hole of performance, and thanks to [Mathias Buss](http://github.com/mafintosh) for suggesting me to share this trick. ## License MIT [npm-badge]: https://badge.fury.io/js/reusify.svg [npm-url]: https://badge.fury.io/js/reusify node_modules/to-regex-range/package.json 0000664 00000003366 15114743311 0014345 0 ustar 00 { "name": "to-regex-range", "description": "Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions.", "version": "5.0.1", "homepage": "https://github.com/micromatch/to-regex-range", "author": "Jon Schlinkert (https://github.com/jonschlinkert)", "contributors": [ "Jon Schlinkert (http://twitter.com/jonschlinkert)", "Rouven Weßling (www.rouvenwessling.de)" ], "repository": "micromatch/to-regex-range", "bugs": { "url": "https://github.com/micromatch/to-regex-range/issues" }, "license": "MIT", "files": [ "index.js" ], "main": "index.js", "engines": { "node": ">=8.0" }, "scripts": { "test": "mocha" }, "dependencies": { "is-number": "^7.0.0" }, "devDependencies": { "fill-range": "^6.0.0", "gulp-format-md": "^2.0.0", "mocha": "^6.0.2", "text-table": "^0.2.0", "time-diff": "^0.3.1" }, "keywords": [ "bash", "date", "expand", "expansion", "expression", "glob", "match", "match date", "match number", "match numbers", "match year", "matches", "matching", "number", "numbers", "numerical", "range", "ranges", "regex", "regexp", "regular", "regular expression", "sequence" ], "verb": { "layout": "default", "toc": false, "tasks": [ "readme" ], "plugins": [ "gulp-format-md" ], "lint": { "reflinks": true }, "helpers": { "examples": { "displayName": "examples" } }, "related": { "list": [ "expand-range", "fill-range", "micromatch", "repeat-element", "repeat-string" ] } } } node_modules/to-regex-range/LICENSE 0000664 00000002103 15114743311 0013050 0 ustar 00 The MIT License (MIT) Copyright (c) 2015-present, Jon Schlinkert. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/to-regex-range/index.js 0000664 00000014521 15114743311 0013517 0 ustar 00 /*! * to-regex-range <https://github.com/micromatch/to-regex-range> * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. */ 'use strict'; const isNumber = require('is-number'); const toRegexRange = (min, max, options) => { if (isNumber(min) === false) { throw new TypeError('toRegexRange: expected the first argument to be a number'); } if (max === void 0 || min === max) { return String(min); } if (isNumber(max) === false) { throw new TypeError('toRegexRange: expected the second argument to be a number.'); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === 'boolean') { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; if (toRegexRange.cache.hasOwnProperty(cacheKey)) { return toRegexRange.cache[cacheKey].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + '|' + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives, opts); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { state.result = `(?:${state.result})`; } toRegexRange.cache[cacheKey] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; let onlyPositive = filterPatterns(pos, neg, '', false, options) || []; let intersected = filterPatterns(neg, pos, '-?', true, options) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join('|'); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; stops.sort(compare); return stops; } /** * Convert a range to a regex pattern * @param {Number} `start` * @param {Number} `stop` * @return {String} */ function rangeToPattern(start, stop, options) { if (start === stop) { return { pattern: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ''; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit, options); } else { count++; } } if (count) { pattern += options.shorthand === true ? '\\d' : '[0-9]'; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max = ranges[i]; let obj = rangeToPattern(String(start), String(max), options); let zeros = ''; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max + 1; continue; } if (tok.isPadded) { zeros = padZeros(max, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection, options) { let result = []; for (let ele of arr) { let { string } = ele; // only push if _both_ are negative... if (!intersection && !contains(comparison, 'string', string)) { result.push(prefix + string); } // or _both_ are positive if (intersection && contains(comparison, 'string', string)) { result.push(prefix + string); } } return result; } /** * Zip strings */ function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some(ele => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + '9'.repeat(len)); } function countZeros(integer, zeros) { return integer - (integer % Math.pow(10, zeros)); } function toQuantifier(digits) { let [start = 0, stop = ''] = digits; if (stop || start > 1) { return `{${start + (stop ? ',' + stop : '')}}`; } return ''; } function toCharacterClass(a, b, options) { return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff) { case 0: return ''; case 1: return relax ? '0?' : '0'; case 2: return relax ? '0{0,2}' : '00'; default: { return relax ? `0{0,${diff}}` : `0{${diff}}`; } } } /** * Cache */ toRegexRange.cache = {}; toRegexRange.clearCache = () => (toRegexRange.cache = {}); /** * Expose `toRegexRange` */ module.exports = toRegexRange; node_modules/to-regex-range/README.md 0000664 00000032421 15114743311 0013330 0 ustar 00 # to-regex-range [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [](https://www.npmjs.com/package/to-regex-range) [](https://npmjs.org/package/to-regex-range) [](https://npmjs.org/package/to-regex-range) [](https://travis-ci.org/micromatch/to-regex-range) > Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save to-regex-range ``` <details> <summary><strong>What does this do?</strong></summary> <br> This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers. **Example** ```js const toRegexRange = require('to-regex-range'); const regex = new RegExp(toRegexRange('15', '95')); ``` A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string). <br> </details> <details> <summary><strong>Why use this library?</strong></summary> <br> ### Convenience Creating regular expressions for matching numbers gets deceptively complicated pretty fast. For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc: * regex for matching `1` => `/1/` (easy enough) * regex for matching `1` through `5` => `/[1-5]/` (not bad...) * regex for matching `1` or `5` => `/(1|5)/` (still easy...) * regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...) * regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...) * regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...) * regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!) The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation. **Learn more** If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful. ### Heavily tested As of April 07, 2019, this library runs [>1m test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are correct. Tests run in ~280ms on my MacBook Pro, 2.5 GHz Intel Core i7. ### Optimized Generated regular expressions are optimized: * duplicate sequences and character classes are reduced using quantifiers * smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative * uses fragment caching to avoid processing the same exact string more than once <br> </details> ## Usage Add this library to your javascript application with the following line of code ```js const toRegexRange = require('to-regex-range'); ``` The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers). ```js const source = toRegexRange('15', '95'); //=> 1[5-9]|[2-8][0-9]|9[0-5] const regex = new RegExp(`^${source}$`); console.log(regex.test('14')); //=> false console.log(regex.test('50')); //=> true console.log(regex.test('94')); //=> true console.log(regex.test('96')); //=> false ``` ## Options ### options.capture **Type**: `boolean` **Deafault**: `undefined` Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges. ```js console.log(toRegexRange('-10', '10')); //=> -[1-9]|-?10|[0-9] console.log(toRegexRange('-10', '10', { capture: true })); //=> (-[1-9]|-?10|[0-9]) ``` ### options.shorthand **Type**: `boolean` **Deafault**: `undefined` Use the regex shorthand for `[0-9]`: ```js console.log(toRegexRange('0', '999999')); //=> [0-9]|[1-9][0-9]{1,5} console.log(toRegexRange('0', '999999', { shorthand: true })); //=> \d|[1-9]\d{1,5} ``` ### options.relaxZeros **Type**: `boolean` **Default**: `true` This option relaxes matching for leading zeros when when ranges are zero-padded. ```js const source = toRegexRange('-0010', '0010'); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> true console.log(regex.test('-010')); //=> true console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> true console.log(regex.test('010')); //=> true console.log(regex.test('0010')); //=> true ``` When `relaxZeros` is false, matching is strict: ```js const source = toRegexRange('-0010', '0010', { relaxZeros: false }); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> false console.log(regex.test('-010')); //=> false console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> false console.log(regex.test('010')); //=> false console.log(regex.test('0010')); //=> true ``` ## Examples | **Range** | **Result** | **Compile time** | | --- | --- | --- | | `toRegexRange(-10, 10)` | `-[1-9]\|-?10\|[0-9]` | _132μs_ | | `toRegexRange(-100, -10)` | `-1[0-9]\|-[2-9][0-9]\|-100` | _50μs_ | | `toRegexRange(-100, 100)` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _42μs_ | | `toRegexRange(001, 100)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|100` | _109μs_ | | `toRegexRange(001, 555)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _51μs_ | | `toRegexRange(0010, 1000)` | `0{0,2}1[0-9]\|0{0,2}[2-9][0-9]\|0?[1-9][0-9]{2}\|1000` | _31μs_ | | `toRegexRange(1, 50)` | `[1-9]\|[1-4][0-9]\|50` | _24μs_ | | `toRegexRange(1, 55)` | `[1-9]\|[1-4][0-9]\|5[0-5]` | _23μs_ | | `toRegexRange(1, 555)` | `[1-9]\|[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _30μs_ | | `toRegexRange(1, 5555)` | `[1-9]\|[1-9][0-9]{1,2}\|[1-4][0-9]{3}\|5[0-4][0-9]{2}\|55[0-4][0-9]\|555[0-5]` | _43μs_ | | `toRegexRange(111, 555)` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _38μs_ | | `toRegexRange(29, 51)` | `29\|[34][0-9]\|5[01]` | _24μs_ | | `toRegexRange(31, 877)` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _32μs_ | | `toRegexRange(5, 5)` | `5` | _8μs_ | | `toRegexRange(5, 6)` | `5\|6` | _11μs_ | | `toRegexRange(1, 2)` | `1\|2` | _6μs_ | | `toRegexRange(1, 5)` | `[1-5]` | _15μs_ | | `toRegexRange(1, 10)` | `[1-9]\|10` | _22μs_ | | `toRegexRange(1, 100)` | `[1-9]\|[1-9][0-9]\|100` | _25μs_ | | `toRegexRange(1, 1000)` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _31μs_ | | `toRegexRange(1, 10000)` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _34μs_ | | `toRegexRange(1, 100000)` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _36μs_ | | `toRegexRange(1, 1000000)` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _42μs_ | | `toRegexRange(1, 10000000)` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _42μs_ | ## Heads up! **Order of arguments** When the `min` is larger than the `max`, values will be flipped to create a valid range: ```js toRegexRange('51', '29'); ``` Is effectively flipped to: ```js toRegexRange('29', '51'); //=> 29|[3-4][0-9]|5[0-1] ``` **Steps / increments** This library does not support steps (increments). A pr to add support would be welcome. ## History ### v2.0.0 - 2017-04-21 **New features** Adds support for zero-padding! ### v1.0.0 **Optimizations** Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching. ## Attribution Inspired by the python library [range-regex](https://github.com/dimka665/range-regex). ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used by micromatch.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") * [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.") * [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 63 | [jonschlinkert](https://github.com/jonschlinkert) | | 3 | [doowb](https://github.com/doowb) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! <a href="https://www.patreon.com/jonschlinkert"> <img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" height="50"> </a> ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 07, 2019._ node_modules/is-unicode-supported/license 0000664 00000002135 15114743311 0014653 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/is-unicode-supported/package.json 0000664 00000001517 15114743311 0015577 0 ustar 00 { "name": "is-unicode-supported", "version": "2.1.0", "description": "Detect whether the terminal supports Unicode", "license": "MIT", "repository": "sindresorhus/is-unicode-supported", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "default": "./index.js" }, "sideEffects": false, "engines": { "node": ">=18" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "terminal", "unicode", "detect", "utf8", "console", "shell", "support", "supports", "supported", "check", "detection" ], "devDependencies": { "ava": "^6.1.3", "tsd": "^0.31.2", "xo": "^0.59.3" } } node_modules/is-unicode-supported/readme.md 0000664 00000002143 15114743311 0015064 0 ustar 00 # is-unicode-supported > Detect whether the terminal supports Unicode This can be useful to decide whether to use Unicode characters or fallback ASCII characters in command-line output. Note that the check is quite naive. It just assumes all non-Windows terminals support Unicode and hard-codes which Windows terminals that do support Unicode. However, I have been using this logic in some popular packages for years without problems. ## Install ```sh npm install is-unicode-supported ``` ## Usage ```js import isUnicodeSupported from 'is-unicode-supported'; isUnicodeSupported(); //=> true ``` ## API ### isUnicodeSupported() Returns a `boolean` for whether the terminal supports Unicode. ## Related - [is-interactive](https://github.com/sindresorhus/is-interactive) - Check if stdout or stderr is interactive - [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color - [figures](https://github.com/sindresorhus/figures) - Unicode symbols with Windows fallbacks - [log-symbols](https://github.com/sindresorhus/log-symbols) - Colored symbols for various log levels node_modules/is-unicode-supported/index.d.ts 0000664 00000000326 15114743311 0015207 0 ustar 00 /** Detect whether the terminal supports Unicode. @example ``` import isUnicodeSupported from 'is-unicode-supported'; isUnicodeSupported(); //=> true ``` */ export default function isUnicodeSupported(): boolean; node_modules/is-unicode-supported/index.js 0000664 00000001221 15114743311 0014746 0 ustar 00 import process from 'node:process'; export default function isUnicodeSupported() { const {env} = process; const {TERM, TERM_PROGRAM} = env; if (process.platform !== 'win32') { return TERM !== 'linux'; // Linux console (kernel) } return Boolean(env.WT_SESSION) // Windows Terminal || Boolean(env.TERMINUS_SUBLIME) // Terminus (<0.2.27) || env.ConEmuTask === '{cmd::Cmder}' // ConEmu and cmder || TERM_PROGRAM === 'Terminus-Sublime' || TERM_PROGRAM === 'vscode' || TERM === 'xterm-256color' || TERM === 'alacritty' || TERM === 'rxvt-unicode' || TERM === 'rxvt-unicode-256color' || env.TERMINAL_EMULATOR === 'JetBrains-JediTerm'; } node_modules/color-convert/package.json 0000664 00000001473 15114743311 0014312 0 ustar 00 { "name": "color-convert", "description": "Plain color conversion functions", "version": "2.0.1", "author": "Heather Arthur <fayearthur@gmail.com>", "license": "MIT", "repository": "Qix-/color-convert", "scripts": { "pretest": "xo", "test": "node test/basic.js" }, "engines": { "node": ">=7.0.0" }, "keywords": [ "color", "colour", "convert", "converter", "conversion", "rgb", "hsl", "hsv", "hwb", "cmyk", "ansi", "ansi16" ], "files": [ "index.js", "conversions.js", "route.js" ], "xo": { "rules": { "default-case": 0, "no-inline-comments": 0, "operator-linebreak": 0 } }, "devDependencies": { "chalk": "^2.4.2", "xo": "^0.24.0" }, "dependencies": { "color-name": "~1.1.4" } } node_modules/color-convert/LICENSE 0000664 00000002077 15114743311 0013032 0 ustar 00 Copyright (c) 2011-2016 Heather Arthur <fayearthur@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/color-convert/route.js 0000664 00000004321 15114743311 0013513 0 ustar 00 const conversions = require('./conversions'); /* This function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 const models = Object.keys(conversions); for (let len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { const graph = buildGraph(); const queue = [fromModel]; // Unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { const current = queue.pop(); const adjacents = Object.keys(conversions[current]); for (let len = adjacents.length, i = 0; i < len; i++) { const adjacent = adjacents[i]; const node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { const path = [graph[toModel].parent, toModel]; let fn = conversions[graph[toModel].parent][toModel]; let cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } module.exports = function (fromModel) { const graph = deriveBFS(fromModel); const conversion = {}; const models = Object.keys(graph); for (let len = models.length, i = 0; i < len; i++) { const toModel = models[i]; const node = graph[toModel]; if (node.parent === null) { // No possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; node_modules/color-convert/conversions.js 0000664 00000041220 15114743311 0014724 0 ustar 00 /* MIT license */ /* eslint-disable no-mixed-operators */ const cssKeywords = require('color-name'); // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) const reverseKeywords = {}; for (const key of Object.keys(cssKeywords)) { reverseKeywords[cssKeywords[key]] = key; } const convert = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; module.exports = convert; // Hide .channels and .labels properties for (const model of Object.keys(convert)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } const {channels, labels} = convert[model]; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', {value: channels}); Object.defineProperty(convert[model], 'labels', {value: labels}); } convert.rgb.hsl = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; let h; let s; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } const l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { let rdif; let gdif; let bdif; let h; let s; const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const v = Math.max(r, g, b); const diff = v - Math.min(r, g, b); const diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = 0; s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert.rgb.hwb = function (rgb) { const r = rgb[0]; const g = rgb[1]; let b = rgb[2]; const h = convert.rgb.hsl(rgb)[0]; const w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const k = Math.min(1 - r, 1 - g, 1 - b); const c = (1 - r - k) / (1 - k) || 0; const m = (1 - g - k) / (1 - k) || 0; const y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; function comparativeDistance(x, y) { /* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance */ return ( ((x[0] - y[0]) ** 2) + ((x[1] - y[1]) ** 2) + ((x[2] - y[2]) ** 2) ); } convert.rgb.keyword = function (rgb) { const reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } let currentClosestDistance = Infinity; let currentClosestKeyword; for (const keyword of Object.keys(cssKeywords)) { const value = cssKeywords[keyword]; // Compute comparative distance const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return cssKeywords[keyword]; }; convert.rgb.xyz = function (rgb) { let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; // Assume sRGB r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { const xyz = convert.rgb.xyz(rgb); let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { const h = hsl[0] / 360; const s = hsl[1] / 100; const l = hsl[2] / 100; let t2; let t3; let val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } const t1 = 2 * l - t2; const rgb = [0, 0, 0]; for (let i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { const h = hsl[0]; let s = hsl[1] / 100; let l = hsl[2] / 100; let smin = s; const lmin = Math.max(l, 0.01); l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; const v = (l + s) / 2; const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { const h = hsv[0] / 60; const s = hsv[1] / 100; let v = hsv[2] / 100; const hi = Math.floor(h) % 6; const f = h - Math.floor(h); const p = 255 * v * (1 - s); const q = 255 * v * (1 - (s * f)); const t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { const h = hsv[0]; const s = hsv[1] / 100; const v = hsv[2] / 100; const vmin = Math.max(v, 0.01); let sl; let l; l = (2 - s) * v; const lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { const h = hwb[0] / 360; let wh = hwb[1] / 100; let bl = hwb[2] / 100; const ratio = wh + bl; let f; // Wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } const i = Math.floor(6 * h); const v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } const n = wh + f * (v - wh); // Linear interpolation let r; let g; let b; /* eslint-disable max-statements-per-line,no-multi-spaces */ switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } /* eslint-enable max-statements-per-line,no-multi-spaces */ return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { const c = cmyk[0] / 100; const m = cmyk[1] / 100; const y = cmyk[2] / 100; const k = cmyk[3] / 100; const r = 1 - Math.min(1, c * (1 - k) + k); const g = 1 - Math.min(1, m * (1 - k) + k); const b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { const x = xyz[0] / 100; const y = xyz[1] / 100; const z = xyz[2] / 100; let r; let g; let b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // Assume sRGB r = r > 0.0031308 ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let x; let y; let z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; const y2 = y ** 3; const x2 = x ** 3; const z2 = z ** 3; y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let h; const hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } const c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { const l = lch[0]; const c = lch[1]; const h = lch[2]; const hr = h / 360 * 2 * Math.PI; const a = c * Math.cos(hr); const b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args, saturation = null) { const [r, g, b] = args; let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } let ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // Optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { const r = args[0]; const g = args[1]; const b = args[2]; // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } const ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { let color = args % 10; // Handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } const mult = (~~(args > 50) + 1) * 0.5; const r = ((color & 1) * mult) * 255; const g = (((color >> 1) & 1) * mult) * 255; const b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // Handle greyscale if (args >= 232) { const c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; let rem; const r = Math.floor(args / 36) / 5 * 255; const g = Math.floor((rem = args % 36) / 6) / 5 * 255; const b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } let colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(char => { return char + char; }).join(''); } const integer = parseInt(colorString, 16); const r = (integer >> 16) & 0xFF; const g = (integer >> 8) & 0xFF; const b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const max = Math.max(Math.max(r, g), b); const min = Math.min(Math.min(r, g), b); const chroma = (max - min); let grayscale; let hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { const s = hsl[1] / 100; const l = hsl[2] / 100; const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); let f = 0; if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { const s = hsv[1] / 100; const v = hsv[2] / 100; const c = s * v; let f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { const h = hcg[0] / 360; const c = hcg[1] / 100; const g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } const pure = [0, 0, 0]; const hi = (h % 1) * 6; const v = hi % 1; const w = 1 - v; let mg = 0; /* eslint-disable max-statements-per-line */ switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } /* eslint-enable max-statements-per-line */ mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert.hcg.hsv = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); let f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const l = g * (1.0 - c) + 0.5 * c; let s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { const w = hwb[1] / 100; const b = hwb[2] / 100; const v = 1 - b; const c = v - w; let g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = function (args) { return [0, 0, args[0]]; }; convert.gray.hsv = convert.gray.hsl; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { const val = Math.round(gray[0] / 100 * 255) & 0xFF; const integer = (val << 16) + (val << 8) + val; const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { const val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; node_modules/color-convert/index.js 0000664 00000003254 15114743311 0013470 0 ustar 00 const conversions = require('./conversions'); const route = require('./route'); const convert = {}; const models = Object.keys(conversions); function wrapRaw(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } return fn(args); }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } const result = fn(args); // We're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (let len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(fromModel => { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); const routes = route(fromModel); const routeModels = Object.keys(routes); routeModels.forEach(toModel => { const fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); module.exports = convert; node_modules/color-convert/CHANGELOG.md 0000664 00000002611 15114743311 0013630 0 ustar 00 # 1.0.0 - 2016-01-07 - Removed: unused speed test - Added: Automatic routing between previously unsupported conversions ([#27](https://github.com/Qix-/color-convert/pull/27)) - Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions ([#27](https://github.com/Qix-/color-convert/pull/27)) - Removed: `convert()` class ([#27](https://github.com/Qix-/color-convert/pull/27)) - Changed: all functions to lookup dictionary ([#27](https://github.com/Qix-/color-convert/pull/27)) - Changed: `ansi` to `ansi256` ([#27](https://github.com/Qix-/color-convert/pull/27)) - Fixed: argument grouping for functions requiring only one argument ([#27](https://github.com/Qix-/color-convert/pull/27)) # 0.6.0 - 2015-07-23 - Added: methods to handle [ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors: - rgb2ansi16 - rgb2ansi - hsl2ansi16 - hsl2ansi - hsv2ansi16 - hsv2ansi - hwb2ansi16 - hwb2ansi - cmyk2ansi16 - cmyk2ansi - keyword2ansi16 - keyword2ansi - ansi162rgb - ansi162hsl - ansi162hsv - ansi162hwb - ansi162cmyk - ansi162keyword - ansi2rgb - ansi2hsl - ansi2hsv - ansi2hwb - ansi2cmyk - ansi2keyword ([#18](https://github.com/harthur/color-convert/pull/18)) # 0.5.3 - 2015-06-02 - Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]` ([#15](https://github.com/harthur/color-convert/issues/15)) --- Check out commit logs for older releases node_modules/color-convert/README.md 0000664 00000005445 15114743311 0013306 0 ustar 00 # color-convert [](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). node_modules/gradient-string/package.json 0000664 00000003101 15114743311 0014605 0 ustar 00 { "name": "gradient-string", "description": "Beautiful color gradients in terminal output", "version": "2.0.2", "author": "Boris K", "license": "MIT", "main": "index.js", "scripts": { "built-in": "node examples/built-in.js", "coverage": "c8 report --reporter=text-lcov > coverage.lcov", "demo": "node examples/demo.js", "fix": "xo --fix", "lint": "xo", "test": "cross-env FORCE_COLOR=1 c8 ava", "prepare": "husky install" }, "dependencies": { "chalk": "^4.1.2", "tinygradient": "^1.1.5" }, "devDependencies": { "ava": "^3.15.0", "c8": "^7.11.2", "cross-env": "^7.0.3", "esm": "^3.2.25", "xo": "^0.48.0", "husky": "^7.0.4" }, "files": [ "index.js" ], "engines": { "node": ">=10" }, "repository": "bokub/gradient-string", "homepage": "https://github.com/bokub/gradient-string", "bugs": "https://github.com/bokub/gradient-string/issues", "keywords": [ "cli", "color", "colors", "colour", "command-line", "console", "formatting", "gradient", "gradients", "log", "logging", "shell", "string", "style", "styles", "terminal" ], "ava": { "require": [ "esm" ] }, "xo": { "rules": { "comma-dangle": "off", "node/prefer-global/buffer": "off", "operator-linebreak": "off", "padding-line-between-statements": "off", "unicorn/prefer-module": "off", "unicorn/prefer-regexp-test": "off", "unicorn/prefer-spread": "off", "unicorn/prevent-abbreviations": "off" } } } node_modules/gradient-string/LICENSE 0000664 00000002050 15114743311 0013326 0 ustar 00 MIT License Copyright (c) 2017 Boris K Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/gradient-string/index.js 0000664 00000006530 15114743311 0013775 0 ustar 00 'use strict'; const chalk = require('chalk'); const tinygradient = require('tinygradient'); const forbiddenChars = /\s/g; function InitGradient(...args) { const grad = tinygradient.apply(this, args); const ret = (str, opts) => applyGradient(str ? str.toString() : '', grad, opts); ret.multiline = (str, opts) => multilineGradient(str ? str.toString() : '', grad, opts); return ret; } const getColors = (gradient, options, count) => options.interpolation.toLowerCase() === 'hsv' ? gradient.hsv(count, options.hsvSpin.toLowerCase()) : gradient.rgb(count); function applyGradient(str, gradient, opts) { const options = validateOptions(opts); const colorsCount = Math.max(str.replace(forbiddenChars, '').length, gradient.stops.length); const colors = getColors(gradient, options, colorsCount); let result = ''; for (const s of str) { result += s.match(forbiddenChars) ? s : chalk.hex(colors.shift().toHex())(s); } return result; } function multilineGradient(str, gradient, opts) { const options = validateOptions(opts); const lines = str.split('\n'); const maxLength = Math.max.apply(null, lines.map(l => l.length).concat([gradient.stops.length])); const colors = getColors(gradient, options, maxLength); const results = []; for (const line of lines) { const lineColors = colors.slice(0); let lineResult = ''; for (const l of line) { lineResult += chalk.hex(lineColors.shift().toHex())(l); } results.push(lineResult); } return results.join('\n'); } function validateOptions(opts) { const options = {interpolation: 'rgb', hsvSpin: 'short', ...opts}; if (opts !== undefined && typeof opts !== 'object') { throw new TypeError(`Expected \`options\` to be an \`object\`, got \`${typeof opts}\``); } if (typeof options.interpolation !== 'string') { throw new TypeError(`Expected \`options.interpolation\` to be a \`string\`, got \`${typeof options.interpolation}\``); } if (options.interpolation.toLowerCase() === 'hsv' && typeof options.hsvSpin !== 'string') { throw new TypeError(`Expected \`options.hsvSpin\` to be a \`string\`, got \`${typeof options.hsvSpin}\``); } return options; } const aliases = { atlas: {colors: ['#feac5e', '#c779d0', '#4bc0c8'], options: {}}, cristal: {colors: ['#bdfff3', '#4ac29a'], options: {}}, teen: {colors: ['#77a1d3', '#79cbca', '#e684ae'], options: {}}, mind: {colors: ['#473b7b', '#3584a7', '#30d2be'], options: {}}, morning: {colors: ['#ff5f6d', '#ffc371'], options: {interpolation: 'hsv'}}, vice: {colors: ['#5ee7df', '#b490ca'], options: {interpolation: 'hsv'}}, passion: {colors: ['#f43b47', '#453a94'], options: {}}, fruit: {colors: ['#ff4e50', '#f9d423'], options: {}}, instagram: {colors: ['#833ab4', '#fd1d1d', '#fcb045'], options: {}}, retro: {colors: ['#3f51b1', '#5a55ae', '#7b5fac', '#8f6aae', '#a86aa4', '#cc6b8e', '#f18271', '#f3a469', '#f7c978'], options: {}}, summer: {colors: ['#fdbb2d', '#22c1c3'], options: {}}, rainbow: {colors: ['#ff0000', '#ff0100'], options: {interpolation: 'hsv', hsvSpin: 'long'}}, pastel: {colors: ['#74ebd5', '#74ecd5'], options: {interpolation: 'hsv', hsvSpin: 'long'}} }; module.exports = InitGradient; for (const a in aliases) { // eslint-disable-line guard-for-in module.exports[a] = str => new InitGradient(aliases[a].colors)(str, aliases[a].options); module.exports[a].multiline = str => new InitGradient(aliases[a].colors).multiline(str, aliases[a].options); } node_modules/gradient-string/node_modules/chalk/license 0000664 00000002125 15114743311 0017430 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/gradient-string/node_modules/chalk/package.json 0000664 00000002255 15114743311 0020355 0 ustar 00 { "name": "chalk", "version": "4.1.2", "description": "Terminal string styling done right", "license": "MIT", "repository": "chalk/chalk", "funding": "https://github.com/chalk/chalk?sponsor=1", "main": "source", "engines": { "node": ">=10" }, "scripts": { "test": "xo && nyc ava && tsd", "bench": "matcha benchmark.js" }, "files": [ "source", "index.d.ts" ], "keywords": [ "color", "colour", "colors", "terminal", "console", "cli", "string", "str", "ansi", "style", "styles", "tty", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" }, "devDependencies": { "ava": "^2.4.0", "coveralls": "^3.0.7", "execa": "^4.0.0", "import-fresh": "^3.1.0", "matcha": "^0.7.0", "nyc": "^15.0.0", "resolve-from": "^5.0.0", "tsd": "^0.7.4", "xo": "^0.28.2" }, "xo": { "rules": { "unicorn/prefer-string-slice": "off", "unicorn/prefer-includes": "off", "@typescript-eslint/member-ordering": "off", "no-redeclare": "off", "unicorn/string-content": "off", "unicorn/better-regex": "off" } } } node_modules/gradient-string/node_modules/chalk/readme.md 0000664 00000032065 15114743311 0017650 0 ustar 00 <h1 align="center"> <br> <br> <img width="320" src="media/logo.svg" alt="Chalk"> <br> <br> <br> </h1> > Terminal string styling done right [](https://travis-ci.org/chalk/chalk) [](https://coveralls.io/github/chalk/chalk?branch=master) [](https://www.npmjs.com/package/chalk?activeTab=dependents) [](https://www.npmjs.com/package/chalk) [](https://www.youtube.com/watch?v=9auOCbH5Ns4) [](https://github.com/xojs/xo)  [](https://repl.it/github/chalk/chalk) <img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900"> <br> --- <div align="center"> <p> <p> <sup> Sindre Sorhus' open source work is supported by the community on <a href="https://github.com/sponsors/sindresorhus">GitHub Sponsors</a> and <a href="https://stakes.social/0x44d871aebF0126Bf646753E2C976Aa7e68A66c15">Dev</a> </sup> </p> <sup>Special thanks to:</sup> <br> <br> <a href="https://standardresume.co/tech"> <img src="https://sindresorhus.com/assets/thanks/standard-resume-logo.svg" width="160"/> </a> <br> <br> <a href="https://retool.com/?utm_campaign=sindresorhus"> <img src="https://sindresorhus.com/assets/thanks/retool-logo.svg" width="230"/> </a> <br> <br> <a href="https://doppler.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=chalk&utm_source=github"> <div> <img src="https://dashboard.doppler.com/imgs/logo-long.svg" width="240" alt="Doppler"> </div> <b>All your environment variables, in one place</b> <div> <span>Stop struggling with scattered API keys, hacking together home-brewed tools,</span> <br> <span>and avoiding access controls. Keep your team and servers in sync with Doppler.</span> </div> </a> <br> <a href="https://uibakery.io/?utm_source=chalk&utm_medium=sponsor&utm_campaign=github"> <div> <img src="https://sindresorhus.com/assets/thanks/uibakery-logo.jpg" width="270" alt="UI Bakery"> </div> </a> </p> </div> --- <br> ## Highlights - Expressive API - Highly performant - Ability to nest styles - [256/Truecolor color support](#256-and-truecolor-color-support) - Auto-detects color support - Doesn't extend `String.prototype` - Clean and focused - Actively maintained - [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020 ## Install ```console $ npm install chalk ``` ## Usage ```js const chalk = require('chalk'); console.log(chalk.blue('Hello world!')); ``` Chalk comes with an easy to use composable API where you just chain and nest the styles you want. ```js const chalk = require('chalk'); const log = console.log; // Combine styled and normal strings log(chalk.blue('Hello') + ' World' + chalk.red('!')); // Compose multiple styles using the chainable API log(chalk.blue.bgRed.bold('Hello world!')); // Pass in multiple arguments log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); // Nest styles log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); // Nest styles of the same type even (color, underline, background) log(chalk.green( 'I am a green line ' + chalk.blue.underline.bold('with a blue substring') + ' that becomes green again!' )); // ES2015 template literal log(` CPU: ${chalk.red('90%')} RAM: ${chalk.green('40%')} DISK: ${chalk.yellow('70%')} `); // ES2015 tagged template literal log(chalk` CPU: {red ${cpu.totalPercent}%} RAM: {green ${ram.used / ram.total * 100}%} DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} `); // Use RGB colors in terminal emulators that support it. log(chalk.keyword('orange')('Yay for orange colored text!')); log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); log(chalk.hex('#DEADED').bold('Bold gray!')); ``` Easily define your own themes: ```js const chalk = require('chalk'); const error = chalk.bold.red; const warning = chalk.keyword('orange'); console.log(error('Error!')); console.log(warning('Warning!')); ``` Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): ```js const name = 'Sindre'; console.log(chalk.green('Hello %s'), name); //=> 'Hello Sindre' ``` ## API ### chalk.`<style>[.<style>...](string, [string...])` Example: `chalk.red.bold.underline('Hello', 'world');` Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. Multiple arguments will be separated by space. ### chalk.level Specifies the level of color support. Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers. If you need to change this in a reusable module, create a new instance: ```js const ctx = new chalk.Instance({level: 0}); ``` | Level | Description | | :---: | :--- | | `0` | All colors disabled | | `1` | Basic color support (16 colors) | | `2` | 256 color support | | `3` | Truecolor support (16 million colors) | ### chalk.supportsColor Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience. Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. ### chalk.stderr and chalk.stderr.supportsColor `chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience. ## Styles ### Modifiers - `reset` - Resets the current color chain. - `bold` - Make text bold. - `dim` - Emitting only a small amount of light. - `italic` - Make text italic. *(Not widely supported)* - `underline` - Make text underline. *(Not widely supported)* - `inverse`- Inverse background and foreground colors. - `hidden` - Prints the text, but makes it invisible. - `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)* - `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic. ### Colors - `black` - `red` - `green` - `yellow` - `blue` - `magenta` - `cyan` - `white` - `blackBright` (alias: `gray`, `grey`) - `redBright` - `greenBright` - `yellowBright` - `blueBright` - `magentaBright` - `cyanBright` - `whiteBright` ### Background colors - `bgBlack` - `bgRed` - `bgGreen` - `bgYellow` - `bgBlue` - `bgMagenta` - `bgCyan` - `bgWhite` - `bgBlackBright` (alias: `bgGray`, `bgGrey`) - `bgRedBright` - `bgGreenBright` - `bgYellowBright` - `bgBlueBright` - `bgMagentaBright` - `bgCyanBright` - `bgWhiteBright` ## Tagged template literal Chalk can be used as a [tagged template literal](https://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals). ```js const chalk = require('chalk'); const miles = 18; const calculateFeet = miles => miles * 5280; console.log(chalk` There are {bold 5280 feet} in a mile. In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}. `); ``` Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`). Template styles are chained exactly like normal Chalk styles. The following three statements are equivalent: ```js console.log(chalk.bold.rgb(10, 100, 200)('Hello!')); console.log(chalk.bold.rgb(10, 100, 200)`Hello!`); console.log(chalk`{bold.rgb(10,100,200) Hello!}`); ``` Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters. All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped. ## 256 and Truecolor color support Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps. Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red). Examples: - `chalk.hex('#DEADED').underline('Hello, world!')` - `chalk.keyword('orange')('Some orange text')` - `chalk.rgb(15, 100, 204).inverse('Hello!')` Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors). - `chalk.bgHex('#DEADED').underline('Hello, world!')` - `chalk.bgKeyword('orange')('Some orange text')` - `chalk.bgRgb(15, 100, 204).inverse('Hello!')` The following color models can be used: - [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')` - [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')` - [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')` - [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')` - [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')` - [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')` - [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')` - [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')` ## Windows If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`. ## Origin story [colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative. ## chalk for enterprise Available as part of the Tidelift Subscription. The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) ## Related - [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module - [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal - [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color - [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes - [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream - [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes - [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes - [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes - [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes - [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models - [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal - [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings - [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings - [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) node_modules/gradient-string/node_modules/chalk/source/util.js 0000664 00000002013 15114743311 0020672 0 ustar 00 'use strict'; const stringReplaceAll = (string, substring, replacer) => { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; module.exports = { stringReplaceAll, stringEncaseCRLFWithFirstIndex }; node_modules/gradient-string/node_modules/chalk/source/templates.js 0000664 00000006447 15114743311 0021732 0 ustar 00 'use strict'; const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES = new Map([ ['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007'] ]); function unescape(c) { const u = c[0] === 'u'; const bracket = c[1] === '{'; if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { return String.fromCharCode(parseInt(c.slice(1), 16)); } if (u && bracket) { return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); } return ESCAPES.get(c) || c; } function parseArguments(name, arguments_) { const results = []; const chunks = arguments_.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { const number = Number(chunk); if (!Number.isNaN(number)) { results.push(number); } else if ((matches = chunk.match(STRING_REGEX))) { results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); } else { throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); } } return results; } function parseStyle(style) { STYLE_REGEX.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const [styleName, styles] of Object.entries(enabled)) { if (!Array.isArray(styles)) { continue; } if (!(styleName in current)) { throw new Error(`Unknown Chalk style: ${styleName}`); } current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; } return current; } module.exports = (chalk, temporary) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { if (escapeCharacter) { chunk.push(unescape(escapeCharacter)); } else if (style) { const string = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); styles.push({inverse, styles: parseStyle(style)}); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(character); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; throw new Error(errMessage); } return chunks.join(''); }; node_modules/gradient-string/node_modules/chalk/source/index.js 0000664 00000013673 15114743311 0021042 0 ustar 00 'use strict'; const ansiStyles = require('ansi-styles'); const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color'); const { stringReplaceAll, stringEncaseCRLFWithFirstIndex } = require('./util'); const {isArray} = Array; // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = [ 'ansi', 'ansi', 'ansi256', 'ansi16m' ]; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; class ChalkClass { constructor(options) { // eslint-disable-next-line no-constructor-return return chalkFactory(options); } } const chalkFactory = options => { const chalk = {}; applyOptions(chalk, options); chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = () => { throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); }; chalk.template.Instance = ChalkClass; return chalk.template; }; function Chalk(options) { return chalkFactory(options); } for (const [styleName, style] of Object.entries(ansiStyles)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); Object.defineProperty(this, styleName, {value: builder}); return builder; } }; } styles.visible = { get() { const builder = createBuilder(this, this._styler, true); Object.defineProperty(this, 'visible', {value: builder}); return builder; } }; const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } for (const model of usedModels) { const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } const proto = Object.defineProperties(() => {}, { ...styles, level: { enumerable: true, get() { return this._generator.level; }, set(level) { this._generator.level = level; } } }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent }; }; const createBuilder = (self, _styler, _isEmpty) => { const builder = (...arguments_) => { if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` return applyStyle(builder, chalkTag(builder, ...arguments_)); } // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); }; // We alter the prototype because we must return a function, but there is // no way to create a function with a different prototype Object.setPrototypeOf(builder, proto); builder._generator = self; builder._styler = _styler; builder._isEmpty = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self._isEmpty ? '' : string; } let styler = self._styler; if (styler === undefined) { return string; } const {openAll, closeAll} = styler; if (string.indexOf('\u001B') !== -1) { while (styler !== undefined) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. string = stringReplaceAll(string, styler.close, styler.open); styler = styler.parent; } } // We can move both next actions out of loop, because remaining actions in loop won't have // any/visible effect on parts we add here. Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; let template; const chalkTag = (chalk, ...strings) => { const [firstString] = strings; if (!isArray(firstString) || !isArray(firstString.raw)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return strings.join(' '); } const arguments_ = strings.slice(1); const parts = [firstString.raw[0]]; for (let i = 1; i < firstString.length; i++) { parts.push( String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]) ); } if (template === undefined) { template = require('./templates'); } return template(chalk, parts.join('')); }; Object.defineProperties(Chalk.prototype, styles); const chalk = Chalk(); // eslint-disable-line new-cap chalk.supportsColor = stdoutColor; chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap chalk.stderr.supportsColor = stderrColor; module.exports = chalk; node_modules/gradient-string/node_modules/chalk/index.d.ts 0000664 00000021303 15114743311 0017763 0 ustar 00 /** Basic foreground colors. [More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) */ declare type ForegroundColor = | 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray' | 'grey' | 'blackBright' | 'redBright' | 'greenBright' | 'yellowBright' | 'blueBright' | 'magentaBright' | 'cyanBright' | 'whiteBright'; /** Basic background colors. [More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) */ declare type BackgroundColor = | 'bgBlack' | 'bgRed' | 'bgGreen' | 'bgYellow' | 'bgBlue' | 'bgMagenta' | 'bgCyan' | 'bgWhite' | 'bgGray' | 'bgGrey' | 'bgBlackBright' | 'bgRedBright' | 'bgGreenBright' | 'bgYellowBright' | 'bgBlueBright' | 'bgMagentaBright' | 'bgCyanBright' | 'bgWhiteBright'; /** Basic colors. [More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) */ declare type Color = ForegroundColor | BackgroundColor; declare type Modifiers = | 'reset' | 'bold' | 'dim' | 'italic' | 'underline' | 'inverse' | 'hidden' | 'strikethrough' | 'visible'; declare namespace chalk { /** Levels: - `0` - All colors disabled. - `1` - Basic 16 colors support. - `2` - ANSI 256 colors support. - `3` - Truecolor 16 million colors support. */ type Level = 0 | 1 | 2 | 3; interface Options { /** Specify the color support for Chalk. By default, color support is automatically detected based on the environment. Levels: - `0` - All colors disabled. - `1` - Basic 16 colors support. - `2` - ANSI 256 colors support. - `3` - Truecolor 16 million colors support. */ level?: Level; } /** Return a new Chalk instance. */ type Instance = new (options?: Options) => Chalk; /** Detect whether the terminal supports color. */ interface ColorSupport { /** The color level used by Chalk. */ level: Level; /** Return whether Chalk supports basic 16 colors. */ hasBasic: boolean; /** Return whether Chalk supports ANSI 256 colors. */ has256: boolean; /** Return whether Chalk supports Truecolor 16 million colors. */ has16m: boolean; } interface ChalkFunction { /** Use a template string. @remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341)) @example ``` import chalk = require('chalk'); log(chalk` CPU: {red ${cpu.totalPercent}%} RAM: {green ${ram.used / ram.total * 100}%} DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} `); ``` @example ``` import chalk = require('chalk'); log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`) ``` */ (text: TemplateStringsArray, ...placeholders: unknown[]): string; (...text: unknown[]): string; } interface Chalk extends ChalkFunction { /** Return a new Chalk instance. */ Instance: Instance; /** The color support for Chalk. By default, color support is automatically detected based on the environment. Levels: - `0` - All colors disabled. - `1` - Basic 16 colors support. - `2` - ANSI 256 colors support. - `3` - Truecolor 16 million colors support. */ level: Level; /** Use HEX value to set text color. @param color - Hexadecimal value representing the desired color. @example ``` import chalk = require('chalk'); chalk.hex('#DEADED'); ``` */ hex(color: string): Chalk; /** Use keyword color value to set text color. @param color - Keyword value representing the desired color. @example ``` import chalk = require('chalk'); chalk.keyword('orange'); ``` */ keyword(color: string): Chalk; /** Use RGB values to set text color. */ rgb(red: number, green: number, blue: number): Chalk; /** Use HSL values to set text color. */ hsl(hue: number, saturation: number, lightness: number): Chalk; /** Use HSV values to set text color. */ hsv(hue: number, saturation: number, value: number): Chalk; /** Use HWB values to set text color. */ hwb(hue: number, whiteness: number, blackness: number): Chalk; /** Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color. 30 <= code && code < 38 || 90 <= code && code < 98 For example, 31 for red, 91 for redBright. */ ansi(code: number): Chalk; /** Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. */ ansi256(index: number): Chalk; /** Use HEX value to set background color. @param color - Hexadecimal value representing the desired color. @example ``` import chalk = require('chalk'); chalk.bgHex('#DEADED'); ``` */ bgHex(color: string): Chalk; /** Use keyword color value to set background color. @param color - Keyword value representing the desired color. @example ``` import chalk = require('chalk'); chalk.bgKeyword('orange'); ``` */ bgKeyword(color: string): Chalk; /** Use RGB values to set background color. */ bgRgb(red: number, green: number, blue: number): Chalk; /** Use HSL values to set background color. */ bgHsl(hue: number, saturation: number, lightness: number): Chalk; /** Use HSV values to set background color. */ bgHsv(hue: number, saturation: number, value: number): Chalk; /** Use HWB values to set background color. */ bgHwb(hue: number, whiteness: number, blackness: number): Chalk; /** Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color. 30 <= code && code < 38 || 90 <= code && code < 98 For example, 31 for red, 91 for redBright. Use the foreground code, not the background code (for example, not 41, nor 101). */ bgAnsi(code: number): Chalk; /** Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color. */ bgAnsi256(index: number): Chalk; /** Modifier: Resets the current color chain. */ readonly reset: Chalk; /** Modifier: Make text bold. */ readonly bold: Chalk; /** Modifier: Emitting only a small amount of light. */ readonly dim: Chalk; /** Modifier: Make text italic. (Not widely supported) */ readonly italic: Chalk; /** Modifier: Make text underline. (Not widely supported) */ readonly underline: Chalk; /** Modifier: Inverse background and foreground colors. */ readonly inverse: Chalk; /** Modifier: Prints the text, but makes it invisible. */ readonly hidden: Chalk; /** Modifier: Puts a horizontal line through the center of the text. (Not widely supported) */ readonly strikethrough: Chalk; /** Modifier: Prints the text only when Chalk has a color support level > 0. Can be useful for things that are purely cosmetic. */ readonly visible: Chalk; readonly black: Chalk; readonly red: Chalk; readonly green: Chalk; readonly yellow: Chalk; readonly blue: Chalk; readonly magenta: Chalk; readonly cyan: Chalk; readonly white: Chalk; /* Alias for `blackBright`. */ readonly gray: Chalk; /* Alias for `blackBright`. */ readonly grey: Chalk; readonly blackBright: Chalk; readonly redBright: Chalk; readonly greenBright: Chalk; readonly yellowBright: Chalk; readonly blueBright: Chalk; readonly magentaBright: Chalk; readonly cyanBright: Chalk; readonly whiteBright: Chalk; readonly bgBlack: Chalk; readonly bgRed: Chalk; readonly bgGreen: Chalk; readonly bgYellow: Chalk; readonly bgBlue: Chalk; readonly bgMagenta: Chalk; readonly bgCyan: Chalk; readonly bgWhite: Chalk; /* Alias for `bgBlackBright`. */ readonly bgGray: Chalk; /* Alias for `bgBlackBright`. */ readonly bgGrey: Chalk; readonly bgBlackBright: Chalk; readonly bgRedBright: Chalk; readonly bgGreenBright: Chalk; readonly bgYellowBright: Chalk; readonly bgBlueBright: Chalk; readonly bgMagentaBright: Chalk; readonly bgCyanBright: Chalk; readonly bgWhiteBright: Chalk; } } /** Main Chalk object that allows to chain styles together. Call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. */ declare const chalk: chalk.Chalk & chalk.ChalkFunction & { supportsColor: chalk.ColorSupport | false; Level: chalk.Level; Color: Color; ForegroundColor: ForegroundColor; BackgroundColor: BackgroundColor; Modifiers: Modifiers; stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false}; }; export = chalk; node_modules/gradient-string/README.md 0000664 00000012535 15114743311 0013611 0 ustar 00 # gradient-string [![Build Status][build-src]][build-href] [![Version][version-src]][version-href] [![Codecov][codecov-src]][codecov-href] [![Downloads][downloads-src]][downloads-href] [![XO code style][xo-src]][xo-href] [![Mentioned in Awesome Node.js][awesome-src]][awesome-href] > Beautiful color gradients in terminal output [](http://bit.ly/gradient-string-large) ## Install ``` $ npm i gradient-string ``` ## Usage ```javascript const gradient = require('gradient-string'); console.log(gradient('cyan', 'pink')('Hello world!')); ``` ### Initialize a gradient ```javascript // Using varargs let coolGradient = gradient('red', 'green', 'blue'); // Using array let coolGradient = gradient(['#FF0000', '#00FF00', '#0000FF']); ``` The colors are parsed with TinyColor, [multiple formats are accepted](https://github.com/bgrins/TinyColor/blob/master/README.md#accepted-string-input). ```javascript let coolGradient = gradient([ tinycolor('#FFBB65'), // tinycolor object {r: 0, g: 255, b: 0}, // RGB object {h: 240, s: 1, v: 1, a: 1}, // HSVa object 'rgb(120, 120, 0)', // RGB CSS string 'gold' // named color ]); ``` ### Use a gradient ```javascript let coolString = coolGradient('This is a fancy string!'); console.log(coolString); ``` ## Built-in gradients ### Usage ```javascript const gradient = require('gradient-string'); // Use the rainbow gradient console.log(gradient.rainbow('I love gradient-strings!')) ``` ### Available built-in gradients [](http://bit.ly/2ufX07r) ## Multi line gradients In some cases, you may want to apply the same horizontal gradient on each line of a long text (or a piece of ASCII art). You can use the `multiline()` method of a gradient to ensure that the colors are vertically aligned. ```javascript const gradient = require('gradient-string'); // Use the same gradient on every line let duck = gradient('orange', 'yellow').multiline([ " __", "<(o )___", " ( ._> /", " `---'", ].join('\n')); console.log(duck); // Works with aliases gradient.atlas.multiline('Multi line\nstring'); // Works with advanced options gradient('cyan', 'pink').multiline('Multi line\nstring', {interpolation: 'hsv'}); ``` ## Advanced gradients There are also more advanced options for gradient customization, such as custom color stops, or choice of color interpolation ### Custom color stops By default, the gradient color stops are distributed equidistantly. You can specify the position of each color stop (between `0` and `1`), using the following syntax: ```javascript let coolGradient = gradient([ {color: '#d8e0de', pos: 0}, {color: '#255B53', pos: 0.8}, {color: '#000000', pos: 1} ]); ``` ### Color interpolation When using a gradient, you can actually add a second parameter to choose how the colors will be generated. Here is the full gradient API: #### myGradient(text, [options]) ##### text Type: `string`<br> String you want to color. ##### options Type: `Object`<br> ###### interpolation Type: `string`<br> The gradient can be generated using RGB or HSV interpolation. HSV usually produces brighter colors. `interpolation` can be set to `rgb` for RGB interpolation, or`hsv` for HSV interpolation.<br> Defaults to `rgb`. Case insentitive ###### hsvSpin Type: `string`<br> Used only in the case of HSV interpolation.<br> Because hue can be considered as a circle, there are two ways to go from a color to another color.<br> `hsvSpin` can be either `short` or `long`, depending on if you want to take the shortest or the longest way between two colors.<br> Defaults to `short`. Case insensitive #### Example ##### Code ```javascript const redToGreen = gradient('red', 'green'); const str = '■'.repeat(48); // Standard RGB gradient console.log(redToGreen(str)); // Short HSV gradient: red -> yellow -> green console.log(redToGreen(str, {interpolation: 'hsv'})); // Long HSV gradient: red -> magenta -> blue -> cyan -> green console.log(redToGreen(str, {interpolation: 'hsv', hsvSpin: 'long'})); ``` ##### Result  ## Typescript Typescript definitions of gradient-string are available on [DefinitelyTyped](https://www.npmjs.com/package/@types/gradient-string) ```sh npm i @types/gradient-string ``` ## Dependencies - [tinygradient](https://github.com/mistic100/tinygradient) - Generate gradients - [chalk](https://github.com/chalk/chalk) - Output colored text to terminal ## License MIT © [Boris K](https://github.com/bokub) [build-src]: https://flat.badgen.net/github/checks/bokub/gradient-string?label=tests [version-src]: https://runkit.io/bokub/npm-version/branches/master/gradient-string?style=flat [codecov-src]: https://flat.badgen.net/codecov/c/github/bokub/gradient-string [downloads-src]: https://flat.badgen.net/npm/dm/gradient-string?color=FF9800 [xo-src]: https://flat.badgen.net/badge/code%20style/XO/5ed9c7 [awesome-src]: https://awesome.re/mentioned-badge-flat.svg [build-href]: https://github.com/bokub/gradient-string/actions/workflows/run.yml [version-href]: https://www.npmjs.com/package/gradient-string [codecov-href]: https://codecov.io/gh/bokub/gradient-string [downloads-href]: https://www.npmjs.com/package/gradient-string [xo-href]: https://github.com/sindresorhus/xo [awesome-href]: https://github.com/sindresorhus/awesome-nodejs node_modules/sisteransi/license 0000664 00000002067 15114743311 0012761 0 ustar 00 MIT License Copyright (c) 2018 Terkel Gjervig Nielsen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/sisteransi/package.json 0000775 00000001223 15114743311 0013676 0 ustar 00 { "name": "sisteransi", "version": "1.0.5", "description": "ANSI escape codes for some terminal swag", "main": "src/index.js", "license": "MIT", "author": { "name": "Terkel Gjervig", "email": "terkel@terkel.com", "url": "https://terkel.com" }, "scripts": { "test": "tape test/*.js | tap-spec" }, "repository": { "type": "git", "url": "https://github.com/terkelg/sisteransi" }, "files": [ "src" ], "types": "./src/sisteransi.d.ts", "keywords": [ "ansi", "escape codes", "escape", "terminal", "style" ], "devDependencies": { "tap-spec": "^5.0.0", "tape": "^4.13.2" } } node_modules/sisteransi/readme.md 0000775 00000005033 15114743311 0013172 0 ustar 00 # sister ANSI [](https://www.npmjs.com/package/sisteransi) [](https://travis-ci.org/terkelg/sisteransi) [](https://www.npmjs.com/package/sisteransi) > Ansi escape codes faster than you can say "[Bam bam](https://www.youtube.com/watch?v=OcaPu9JPenU)". ## Installation ``` npm install sisteransi ``` ## Usage ```js const ansi = require('sisteransi'); // or const { cursor } = require('sisteransi'); const p = str => process.stdout.write(str); // move cursor to 2, 1 p(ansi.cursor.to(2, 1)); // to up, one down p(ansi.cursor.up(2)+ansi.cursor.down(1)); ``` ## API ### cursor #### to(x, y) Set the absolute position of the cursor. `x0` `y0` is the top left of the screen. #### move(x, y) Set the position of the cursor relative to its current position. #### up(count = 1) Move cursor up a specific amount of rows. Default is `1`. #### down(count = 1) Move cursor down a specific amount of rows. Default is `1`. #### forward(count = 1) Move cursor forward a specific amount of rows. Default is `1`. #### backward(count = 1) Move cursor backward a specific amount of rows. Default is `1`. #### nextLine(count = 1) Move cursor to the next line a specific amount of lines. Default is `1`. #### prevLine(count = 1) Move cursor to the previous a specific amount of lines. Default is `1`. #### left Move cursor to the left side. #### hide Hide cursor. #### show Show cursor. #### save Save cursor position. #### restore Restore cursor position. ### scroll #### up(count = 1) Scroll display up a specific amount of lines. Default to `1`. #### down(count = 1) Scroll display down a specific amount of lines. Default to `1`. ### erase #### screen Erase the screen and move the cursor the top left position. #### up(count = 1) Erase the screen from the current line up to the top of the screen. Default to `1`. #### down(count = 2) Erase the screen from the current line down to the bottom of the screen. Default to `1`. #### line Erase the entire current line. #### lineEnd Erase from the current cursor position to the end of the current line. #### lineStart Erase from the current cursor position to the start of the current line. #### lines(count) Erase from the current cursor position up the specified amount of rows. ## Credit This is a fork of [ansi-escapes](https://github.com/sindresorhus/ansi-escapes). ## License MIT © [Terkel Gjervig](https://terkel.com) node_modules/sisteransi/src/sisteransi.d.ts 0000664 00000002121 15114743311 0015150 0 ustar 00 export const beep: string; export const clear: string; export namespace cursor { export const left: string; export const hide: string; export const show: string; export const save: string; export const restore: string; export function to(x: number, y?: number): string; export function move(x: number, y: number): string; export function up(count?: number): string; export function down(count?: number): string; export function forward(count?: number): string; export function backward(count?: number): string; export function nextLine(count?: number): string; export function prevLine(count?: number): string; } export namespace scroll { export function up(count?: number): string; export function down(count?: number): string; } export namespace erase { export const screen: string; export const line: string; export const lineEnd: string; export const lineStart: string; export function up(count?: number): string; export function down(count?: number): string; export function lines(count: number): string; } node_modules/sisteransi/src/index.js 0000664 00000002521 15114743311 0013643 0 ustar 00 'use strict'; const ESC = '\x1B'; const CSI = `${ESC}[`; const beep = '\u0007'; const cursor = { to(x, y) { if (!y) return `${CSI}${x + 1}G`; return `${CSI}${y + 1};${x + 1}H`; }, move(x, y) { let ret = ''; if (x < 0) ret += `${CSI}${-x}D`; else if (x > 0) ret += `${CSI}${x}C`; if (y < 0) ret += `${CSI}${-y}A`; else if (y > 0) ret += `${CSI}${y}B`; return ret; }, up: (count = 1) => `${CSI}${count}A`, down: (count = 1) => `${CSI}${count}B`, forward: (count = 1) => `${CSI}${count}C`, backward: (count = 1) => `${CSI}${count}D`, nextLine: (count = 1) => `${CSI}E`.repeat(count), prevLine: (count = 1) => `${CSI}F`.repeat(count), left: `${CSI}G`, hide: `${CSI}?25l`, show: `${CSI}?25h`, save: `${ESC}7`, restore: `${ESC}8` } const scroll = { up: (count = 1) => `${CSI}S`.repeat(count), down: (count = 1) => `${CSI}T`.repeat(count) } const erase = { screen: `${CSI}2J`, up: (count = 1) => `${CSI}1J`.repeat(count), down: (count = 1) => `${CSI}J`.repeat(count), line: `${CSI}2K`, lineEnd: `${CSI}K`, lineStart: `${CSI}1K`, lines(count) { let clear = ''; for (let i = 0; i < count; i++) clear += this.line + (i < count - 1 ? cursor.up() : ''); if (count) clear += cursor.left; return clear; } } module.exports = { cursor, scroll, erase, beep }; node_modules/mimic-fn/license 0000664 00000002125 15114743311 0012267 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/mimic-fn/package.json 0000664 00000001201 15114743311 0013202 0 ustar 00 { "name": "mimic-fn", "version": "2.1.0", "description": "Make a function mimic another one", "license": "MIT", "repository": "sindresorhus/mimic-fn", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=6" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "function", "mimic", "imitate", "rename", "copy", "inherit", "properties", "name", "func", "fn", "set", "infer", "change" ], "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.1", "xo": "^0.24.0" } } node_modules/mimic-fn/readme.md 0000664 00000002254 15114743311 0012504 0 ustar 00 # mimic-fn [](https://travis-ci.org/sindresorhus/mimic-fn) > Make a function mimic another one Useful when you wrap a function in another function and like to preserve the original name and other properties. ## Install ``` $ npm install mimic-fn ``` ## Usage ```js const mimicFn = require('mimic-fn'); function foo() {} foo.unicorn = '🦄'; function wrapper() { return foo(); } console.log(wrapper.name); //=> 'wrapper' mimicFn(wrapper, foo); console.log(wrapper.name); //=> 'foo' console.log(wrapper.unicorn); //=> '🦄' ``` ## API It will copy over the properties `name`, `length`, `displayName`, and any custom properties you may have set. ### mimicFn(to, from) Modifies the `to` function and returns it. #### to Type: `Function` Mimicking function. #### from Type: `Function` Function to mimic. ## Related - [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function - [keep-func-props](https://github.com/ehmicky/keep-func-props) - Wrap a function without changing its name, length and other properties ## License MIT © [Sindre Sorhus](https://sindresorhus.com) node_modules/mimic-fn/index.d.ts 0000664 00000002273 15114743311 0012627 0 ustar 00 declare const mimicFn: { /** Make a function mimic another one. It will copy over the properties `name`, `length`, `displayName`, and any custom properties you may have set. @param to - Mimicking function. @param from - Function to mimic. @returns The modified `to` function. @example ``` import mimicFn = require('mimic-fn'); function foo() {} foo.unicorn = '🦄'; function wrapper() { return foo(); } console.log(wrapper.name); //=> 'wrapper' mimicFn(wrapper, foo); console.log(wrapper.name); //=> 'foo' console.log(wrapper.unicorn); //=> '🦄' ``` */ < ArgumentsType extends unknown[], ReturnType, FunctionType extends (...arguments: ArgumentsType) => ReturnType >( to: (...arguments: ArgumentsType) => ReturnType, from: FunctionType ): FunctionType; // TODO: Remove this for the next major release, refactor the whole definition to: // declare function mimicFn< // ArgumentsType extends unknown[], // ReturnType, // FunctionType extends (...arguments: ArgumentsType) => ReturnType // >( // to: (...arguments: ArgumentsType) => ReturnType, // from: FunctionType // ): FunctionType; // export = mimicFn; default: typeof mimicFn; }; export = mimicFn; node_modules/mimic-fn/index.js 0000664 00000000454 15114743311 0012372 0 ustar 00 'use strict'; const mimicFn = (to, from) => { for (const prop of Reflect.ownKeys(from)) { Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); } return to; }; module.exports = mimicFn; // TODO: Remove this for the next major release module.exports.default = mimicFn; node_modules/cli-cursor/license 0000664 00000002135 15114743311 0012653 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/cli-cursor/package.json 0000664 00000001527 15114743311 0013600 0 ustar 00 { "name": "cli-cursor", "version": "4.0.0", "description": "Toggle the CLI cursor", "license": "MIT", "repository": "sindresorhus/cli-cursor", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "cli", "cursor", "ansi", "toggle", "display", "show", "hide", "term", "terminal", "console", "tty", "shell", "command-line" ], "dependencies": { "restore-cursor": "^4.0.0" }, "devDependencies": { "@types/node": "^16.7.1", "ava": "^3.15.0", "tsd": "^0.17.0", "xo": "^0.44.0" } } node_modules/cli-cursor/readme.md 0000664 00000001741 15114743311 0013067 0 ustar 00 # cli-cursor > Toggle the CLI cursor The cursor is [gracefully restored](https://github.com/sindresorhus/restore-cursor) if the process exits. ## Install ``` $ npm install cli-cursor ``` ## Usage ```js import cliCursor from 'cli-cursor'; cliCursor.hide(); const unicornsAreAwesome = true; cliCursor.toggle(unicornsAreAwesome); ``` ## API ### .show(stream?) ### .hide(stream?) ### .toggle(force?, stream?) #### force Useful for showing or hiding the cursor based on a boolean. #### stream Type: `stream.Writable`\ Default: `process.stderr` --- <div align="center"> <b> <a href="https://tidelift.com/subscription/pkg/npm-cli-cursor?utm_source=npm-cli-cursor&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> </b> <br> <sub> Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. </sub> </div> node_modules/cli-cursor/index.d.ts 0000664 00000001427 15114743311 0013212 0 ustar 00 declare const cliCursor: { /** Show cursor. @param stream - Default: `process.stderr`. @example ``` import cliCursor from 'cli-cursor'; cliCursor.show(); ``` */ show(stream?: NodeJS.WritableStream): void; /** Hide cursor. @param stream - Default: `process.stderr`. @example ``` import cliCursor from 'cli-cursor'; cliCursor.hide(); ``` */ hide(stream?: NodeJS.WritableStream): void; /** Toggle cursor visibility. @param force - Is useful to show or hide the cursor based on a boolean. @param stream - Default: `process.stderr`. @example ``` import cliCursor from 'cli-cursor'; const unicornsAreAwesome = true; cliCursor.toggle(unicornsAreAwesome); ``` */ toggle(force?: boolean, stream?: NodeJS.WritableStream): void; }; export default cliCursor; node_modules/cli-cursor/index.js 0000664 00000001266 15114743311 0012757 0 ustar 00 import process from 'node:process'; import restoreCursor from 'restore-cursor'; let isHidden = false; const cliCursor = {}; cliCursor.show = (writableStream = process.stderr) => { if (!writableStream.isTTY) { return; } isHidden = false; writableStream.write('\u001B[?25h'); }; cliCursor.hide = (writableStream = process.stderr) => { if (!writableStream.isTTY) { return; } restoreCursor(); isHidden = true; writableStream.write('\u001B[?25l'); }; cliCursor.toggle = (force, writableStream) => { if (force !== undefined) { isHidden = force; } if (isHidden) { cliCursor.show(writableStream); } else { cliCursor.hide(writableStream); } }; export default cliCursor; node_modules/log-symbols/license 0000664 00000002135 15114743311 0013040 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/log-symbols/package.json 0000664 00000001777 15114743311 0013774 0 ustar 00 { "name": "log-symbols", "version": "6.0.0", "description": "Colored symbols for various log levels. Example: `✔︎ Success`", "license": "MIT", "repository": "sindresorhus/log-symbols", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "node": "./index.js", "default": "./browser.js" }, "engines": { "node": ">=18" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts", "browser.js" ], "keywords": [ "unicode", "cli", "cmd", "command-line", "characters", "symbol", "symbols", "figure", "figures", "fallback", "windows", "log", "logging", "terminal", "stdout" ], "dependencies": { "chalk": "^5.3.0", "is-unicode-supported": "^1.3.0" }, "devDependencies": { "ava": "^5.3.1", "strip-ansi": "^7.1.0", "tsd": "^0.29.0", "xo": "^0.56.0" } } node_modules/log-symbols/readme.md 0000664 00000001702 15114743311 0013251 0 ustar 00 # log-symbols <img src="screenshot.png" width="226" height="192" align="right"> > Colored symbols for various log levels Includes fallbacks for Windows CMD which only supports a [limited character set](https://en.wikipedia.org/wiki/Code_page_437). ## Install ```sh npm install log-symbols ``` ## Usage ```js import logSymbols from 'log-symbols'; console.log(logSymbols.success, 'Finished successfully!'); // Terminals with Unicode support: ✔ Finished successfully! // Terminals without Unicode support: √ Finished successfully! ``` ## API ### logSymbols #### info #### success #### warning #### error ## Related - [figures](https://github.com/sindresorhus/figures) - Unicode symbols with Windows CMD fallbacks - [py-log-symbols](https://github.com/ManrajGrover/py-log-symbols) - Python port - [log-symbols](https://github.com/palash25/log-symbols) - Ruby port - [guumaster/logsymbols](https://github.com/guumaster/logsymbols) - Golang port node_modules/log-symbols/index.d.ts 0000664 00000001111 15114743311 0013365 0 ustar 00 /** Colored symbols for various log levels. Includes fallbacks for Windows CMD which only supports a [limited character set](https://en.wikipedia.org/wiki/Code_page_437). @example ``` import logSymbols from 'log-symbols'; console.log(logSymbols.success, 'Finished successfully!'); // Terminals with Unicode support: ✔ Finished successfully! // Terminals without Unicode support: √ Finished successfully! ``` */ declare const logSymbols: { readonly info: string; readonly success: string; readonly warning: string; readonly error: string; }; export default logSymbols; node_modules/log-symbols/index.js 0000664 00000000663 15114743311 0013144 0 ustar 00 import chalk from 'chalk'; import isUnicodeSupported from 'is-unicode-supported'; const main = { info: chalk.blue('ℹ'), success: chalk.green('✔'), warning: chalk.yellow('⚠'), error: chalk.red('✖'), }; const fallback = { info: chalk.blue('i'), success: chalk.green('√'), warning: chalk.yellow('‼'), error: chalk.red('×'), }; const logSymbols = isUnicodeSupported() ? main : fallback; export default logSymbols; node_modules/log-symbols/browser.js 0000664 00000000174 15114743311 0013515 0 ustar 00 const logSymbols = { info: 'ℹ️', success: '✅', warning: '⚠️', error: '❌️', }; export default logSymbols; node_modules/log-symbols/node_modules/is-unicode-supported/license 0000664 00000002135 15114743311 0021577 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/log-symbols/node_modules/is-unicode-supported/package.json 0000664 00000001413 15114743311 0022516 0 ustar 00 { "name": "is-unicode-supported", "version": "1.3.0", "description": "Detect whether the terminal supports Unicode", "license": "MIT", "repository": "sindresorhus/is-unicode-supported", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": ">=12" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "terminal", "unicode", "detect", "utf8", "console", "shell", "support", "supports", "supported", "check", "detection" ], "devDependencies": { "ava": "^4.0.1", "tsd": "^0.19.1", "xo": "^0.47.0" } } node_modules/log-symbols/node_modules/is-unicode-supported/readme.md 0000664 00000002143 15114743311 0022010 0 ustar 00 # is-unicode-supported > Detect whether the terminal supports Unicode This can be useful to decide whether to use Unicode characters or fallback ASCII characters in command-line output. Note that the check is quite naive. It just assumes all non-Windows terminals support Unicode and hard-codes which Windows terminals that do support Unicode. However, I have been using this logic in some popular packages for years without problems. ## Install ```sh npm install is-unicode-supported ``` ## Usage ```js import isUnicodeSupported from 'is-unicode-supported'; isUnicodeSupported(); //=> true ``` ## API ### isUnicodeSupported() Returns a `boolean` for whether the terminal supports Unicode. ## Related - [is-interactive](https://github.com/sindresorhus/is-interactive) - Check if stdout or stderr is interactive - [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color - [figures](https://github.com/sindresorhus/figures) - Unicode symbols with Windows fallbacks - [log-symbols](https://github.com/sindresorhus/log-symbols) - Colored symbols for various log levels node_modules/log-symbols/node_modules/is-unicode-supported/index.d.ts 0000664 00000000326 15114743311 0022133 0 ustar 00 /** Detect whether the terminal supports Unicode. @example ``` import isUnicodeSupported from 'is-unicode-supported'; isUnicodeSupported(); //=> true ``` */ export default function isUnicodeSupported(): boolean; node_modules/log-symbols/node_modules/is-unicode-supported/index.js 0000664 00000001213 15114743311 0021673 0 ustar 00 import process from 'node:process'; export default function isUnicodeSupported() { if (process.platform !== 'win32') { return process.env.TERM !== 'linux'; // Linux console (kernel) } return Boolean(process.env.CI) || Boolean(process.env.WT_SESSION) // Windows Terminal || Boolean(process.env.TERMINUS_SUBLIME) // Terminus (<0.2.27) || process.env.ConEmuTask === '{cmd::Cmder}' // ConEmu and cmder || process.env.TERM_PROGRAM === 'Terminus-Sublime' || process.env.TERM_PROGRAM === 'vscode' || process.env.TERM === 'xterm-256color' || process.env.TERM === 'alacritty' || process.env.TERMINAL_EMULATOR === 'JetBrains-JediTerm'; } node_modules/p-limit/license 0000664 00000002135 15114743311 0012144 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/p-limit/package.json 0000664 00000001752 15114743311 0013071 0 ustar 00 { "name": "p-limit", "version": "4.0.0", "description": "Run multiple promise-returning & async functions with limited concurrency", "license": "MIT", "repository": "sindresorhus/p-limit", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "promise", "limit", "limited", "concurrency", "throttle", "throat", "rate", "batch", "ratelimit", "task", "queue", "async", "await", "promises", "bluebird" ], "dependencies": { "yocto-queue": "^1.0.0" }, "devDependencies": { "ava": "^3.15.0", "delay": "^5.0.0", "in-range": "^3.0.0", "random-int": "^3.0.0", "time-span": "^5.0.0", "tsd": "^0.17.0", "xo": "^0.44.0" } } node_modules/p-limit/readme.md 0000664 00000005265 15114743311 0012365 0 ustar 00 # p-limit > Run multiple promise-returning & async functions with limited concurrency ## Install ``` $ npm install p-limit ``` ## Usage ```js import pLimit from 'p-limit'; const limit = pLimit(1); const input = [ limit(() => fetchSomething('foo')), limit(() => fetchSomething('bar')), limit(() => doSomething()) ]; // Only one promise is run at once const result = await Promise.all(input); console.log(result); ``` ## API ### pLimit(concurrency) Returns a `limit` function. #### concurrency Type: `number`\ Minimum: `1`\ Default: `Infinity` Concurrency limit. ### limit(fn, ...args) Returns the promise returned by calling `fn(...args)`. #### fn Type: `Function` Promise-returning/async function. #### args Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. ### limit.activeCount The number of promises that are currently running. ### limit.pendingCount The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). ### limit.clearQueue() Discard pending promises that are waiting to run. This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. Note: This does not cancel promises that are already running. ## FAQ ### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. ## Related - [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control - [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions - [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions - [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency - [More…](https://github.com/sindresorhus/promise-fun) --- <div align="center"> <b> <a href="https://tidelift.com/subscription/pkg/npm-p-limit?utm_source=npm-p-limit&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> </b> <br> <sub> Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. </sub> </div> node_modules/p-limit/index.d.ts 0000664 00000002622 15114743311 0012501 0 ustar 00 /* eslint-disable @typescript-eslint/member-ordering */ export interface LimitFunction { /** The number of promises that are currently running. */ readonly activeCount: number; /** The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). */ readonly pendingCount: number; /** Discard pending promises that are waiting to run. This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. Note: This does not cancel promises that are already running. */ clearQueue: () => void; /** @param fn - Promise-returning/async function. @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. @returns The promise returned by calling `fn(...arguments)`. */ <Arguments extends unknown[], ReturnType>( fn: (...arguments: Arguments) => PromiseLike<ReturnType> | ReturnType, ...arguments: Arguments ): Promise<ReturnType>; } /** Run multiple promise-returning & async functions with limited concurrency. @param concurrency - Concurrency limit. Minimum: `1`. @returns A `limit` function. */ export default function pLimit(concurrency: number): LimitFunction; node_modules/p-limit/index.js 0000664 00000002736 15114743311 0012253 0 ustar 00 import Queue from 'yocto-queue'; export default function pLimit(concurrency) { if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) { throw new TypeError('Expected `concurrency` to be a number from 1 and up'); } const queue = new Queue(); let activeCount = 0; const next = () => { activeCount--; if (queue.size > 0) { queue.dequeue()(); } }; const run = async (fn, resolve, args) => { activeCount++; const result = (async () => fn(...args))(); resolve(result); try { await result; } catch {} next(); }; const enqueue = (fn, resolve, args) => { queue.enqueue(run.bind(undefined, fn, resolve, args)); (async () => { // This function needs to wait until the next microtask before comparing // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously // when the run function is dequeued and called. The comparison in the if-statement // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. await Promise.resolve(); if (activeCount < concurrency && queue.size > 0) { queue.dequeue()(); } })(); }; const generator = (fn, ...args) => new Promise(resolve => { enqueue(fn, resolve, args); }); Object.defineProperties(generator, { activeCount: { get: () => activeCount, }, pendingCount: { get: () => queue.size, }, clearQueue: { value: () => { queue.clear(); }, }, }); return generator; } node_modules/get-east-asian-width/license 0000664 00000002135 15114743311 0014510 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/get-east-asian-width/package.json 0000664 00000002363 15114743311 0015434 0 ustar 00 { "name": "get-east-asian-width", "version": "1.3.0", "description": "Determine the East Asian Width of a Unicode character", "license": "MIT", "repository": "sindresorhus/get-east-asian-width", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "default": "./index.js" }, "sideEffects": false, "engines": { "node": ">=18" }, "scripts": { "test": "xo && ava && tsc index.d.ts", "build": "node scripts/build.js", "prepublish": "npm run build" }, "files": [ "index.js", "index.d.ts", "lookup.js" ], "keywords": [ "unicode", "east-asian-width", "eastasianwidth", "character", "string", "width", "text", "layout", "alignment", "fullwidth", "halfwidth", "ambiguous", "narrow", "wide", "neutral", "typography", "japanese", "chinese", "korean", "codepoint", "text-processing", "i18n", "l10n" ], "devDependencies": { "ava": "^5.3.1", "indent-string": "^5.0.0", "outdent": "^0.8.0", "simplify-ranges": "^0.1.0", "typescript": "^5.2.2", "xo": "^0.56.0" }, "xo": { "ignores": [ "lookup.js" ] } } node_modules/get-east-asian-width/readme.md 0000664 00000003513 15114743311 0014723 0 ustar 00 # get-east-asian-width > Determine the [East Asian Width](https://unicode.org/reports/tr11/) of a Unicode character > East Asian Width categorizes Unicode characters based on their occupied space in East Asian typography, which helps in text layout and alignment, particularly in languages like Japanese, Chinese, and Korean. Unlike other similar packages, this package uses the latest Unicode data (which changes each year). ## Install ```sh npm install get-east-asian-width ``` ## Usage ```js import {eastAsianWidth, eastAsianWidthType} from 'get-east-asian-width'; const codePoint = '字'.codePointAt(0); console.log(eastAsianWidth(codePoint)); //=> 2 console.log(eastAsianWidthType(codePoint)); //=> 'wide' ``` ## `eastAsianWidth(codePoint: number, options?: object): 1 | 2` Returns the width as a number for the given code point. ### options Type: `object` #### ambiguousAsWide Type: `boolean`\ Default: `false` Whether to treat an `'ambiguous'` character as wide. ```js import {eastAsianWidth} from 'get-east-asian-width'; const codePoint = '⛣'.codePointAt(0); console.log(eastAsianWidth(codePoint)); //=> 1 console.log(eastAsianWidth(codePoint, {ambiguousAsWide: true})); //=> 2 ``` > Ambiguous characters behave like wide or narrow characters depending on the context (language tag, script identification, associated font, source of data, or explicit markup; all can provide the context). **If the context cannot be established reliably, they should be treated as narrow characters by default.** > - http://www.unicode.org/reports/tr11/ ## `eastAsianWidthType(codePoint: number): 'fullwidth' | 'halfwidth' | 'wide' | 'narrow' | 'neutral' | 'ambiguous'` Returns the type of “East Asian Width” for the given code point. ## Related - [string-width](https://github.com/sindresorhus/string-width) - Get the visual width of a string node_modules/get-east-asian-width/index.d.ts 0000664 00000003006 15114743311 0015042 0 ustar 00 export type WidthType = 'fullwidth' | 'halfwidth' | 'wide' | 'narrow' | 'neutral' | 'ambiguous'; export type Options = { /** Whether to treat an `'ambiguous'` character as wide. @default true @example ``` import {eastAsianWidth} from 'get-east-asian-width'; const codePoint = '⛣'.codePointAt(0); console.log(eastAsianWidth(codePoint)); //=> 1 console.log(eastAsianWidth(codePoint, {ambiguousAsWide: true})); //=> 2 ``` > Ambiguous characters behave like wide or narrow characters depending on the context (language tag, script identification, associated font, source of data, or explicit markup; all can provide the context). __If the context cannot be established reliably, they should be treated as narrow characters by default.__ > - http://www.unicode.org/reports/tr11/ */ readonly ambiguousAsWide?: boolean; }; /** Returns the width as a number for the given code point. @param codePoint - A Unicode code point. @example ``` import {eastAsianWidth} from 'get-east-asian-width'; const codePoint = '字'.codePointAt(0); console.log(eastAsianWidth(codePoint)); //=> 2 ``` */ export function eastAsianWidth(codePoint: number, options?: Options): 1 | 2; /** Returns the type of “East Asian Width” for the given code point. @param codePoint - A Unicode code point. @example ``` import {eastAsianWidthType} from 'get-east-asian-width'; const codePoint = '字'.codePointAt(0); console.log(eastAsianWidthType(codePoint)); //=> 'wide' ``` */ export function eastAsianWidthType(codePoint: number): WidthType; node_modules/get-east-asian-width/index.js 0000664 00000001456 15114743311 0014615 0 ustar 00 import {getCategory, isAmbiguous, isFullWidth, isWide} from './lookup.js'; function validate(codePoint) { if (!Number.isSafeInteger(codePoint)) { throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`); } } export function eastAsianWidthType(codePoint) { validate(codePoint); return getCategory(codePoint); } export function eastAsianWidth(codePoint, {ambiguousAsWide = false} = {}) { validate(codePoint); if ( isFullWidth(codePoint) || isWide(codePoint) || (ambiguousAsWide && isAmbiguous(codePoint)) ) { return 2; } return 1; } // For Prettier. This doesn't count "ambiguous" characters or check for valid input. // https://github.com/sindresorhus/get-east-asian-width/pull/6 export const _isNarrowWidth = codePoint => !(isFullWidth(codePoint) || isWide(codePoint)); node_modules/get-east-asian-width/lookup.js 0000664 00000021571 15114743311 0015017 0 ustar 00 // Generated code. function isAmbiguous(x) { return x === 0xA1 || x === 0xA4 || x === 0xA7 || x === 0xA8 || x === 0xAA || x === 0xAD || x === 0xAE || x >= 0xB0 && x <= 0xB4 || x >= 0xB6 && x <= 0xBA || x >= 0xBC && x <= 0xBF || x === 0xC6 || x === 0xD0 || x === 0xD7 || x === 0xD8 || x >= 0xDE && x <= 0xE1 || x === 0xE6 || x >= 0xE8 && x <= 0xEA || x === 0xEC || x === 0xED || x === 0xF0 || x === 0xF2 || x === 0xF3 || x >= 0xF7 && x <= 0xFA || x === 0xFC || x === 0xFE || x === 0x101 || x === 0x111 || x === 0x113 || x === 0x11B || x === 0x126 || x === 0x127 || x === 0x12B || x >= 0x131 && x <= 0x133 || x === 0x138 || x >= 0x13F && x <= 0x142 || x === 0x144 || x >= 0x148 && x <= 0x14B || x === 0x14D || x === 0x152 || x === 0x153 || x === 0x166 || x === 0x167 || x === 0x16B || x === 0x1CE || x === 0x1D0 || x === 0x1D2 || x === 0x1D4 || x === 0x1D6 || x === 0x1D8 || x === 0x1DA || x === 0x1DC || x === 0x251 || x === 0x261 || x === 0x2C4 || x === 0x2C7 || x >= 0x2C9 && x <= 0x2CB || x === 0x2CD || x === 0x2D0 || x >= 0x2D8 && x <= 0x2DB || x === 0x2DD || x === 0x2DF || x >= 0x300 && x <= 0x36F || x >= 0x391 && x <= 0x3A1 || x >= 0x3A3 && x <= 0x3A9 || x >= 0x3B1 && x <= 0x3C1 || x >= 0x3C3 && x <= 0x3C9 || x === 0x401 || x >= 0x410 && x <= 0x44F || x === 0x451 || x === 0x2010 || x >= 0x2013 && x <= 0x2016 || x === 0x2018 || x === 0x2019 || x === 0x201C || x === 0x201D || x >= 0x2020 && x <= 0x2022 || x >= 0x2024 && x <= 0x2027 || x === 0x2030 || x === 0x2032 || x === 0x2033 || x === 0x2035 || x === 0x203B || x === 0x203E || x === 0x2074 || x === 0x207F || x >= 0x2081 && x <= 0x2084 || x === 0x20AC || x === 0x2103 || x === 0x2105 || x === 0x2109 || x === 0x2113 || x === 0x2116 || x === 0x2121 || x === 0x2122 || x === 0x2126 || x === 0x212B || x === 0x2153 || x === 0x2154 || x >= 0x215B && x <= 0x215E || x >= 0x2160 && x <= 0x216B || x >= 0x2170 && x <= 0x2179 || x === 0x2189 || x >= 0x2190 && x <= 0x2199 || x === 0x21B8 || x === 0x21B9 || x === 0x21D2 || x === 0x21D4 || x === 0x21E7 || x === 0x2200 || x === 0x2202 || x === 0x2203 || x === 0x2207 || x === 0x2208 || x === 0x220B || x === 0x220F || x === 0x2211 || x === 0x2215 || x === 0x221A || x >= 0x221D && x <= 0x2220 || x === 0x2223 || x === 0x2225 || x >= 0x2227 && x <= 0x222C || x === 0x222E || x >= 0x2234 && x <= 0x2237 || x === 0x223C || x === 0x223D || x === 0x2248 || x === 0x224C || x === 0x2252 || x === 0x2260 || x === 0x2261 || x >= 0x2264 && x <= 0x2267 || x === 0x226A || x === 0x226B || x === 0x226E || x === 0x226F || x === 0x2282 || x === 0x2283 || x === 0x2286 || x === 0x2287 || x === 0x2295 || x === 0x2299 || x === 0x22A5 || x === 0x22BF || x === 0x2312 || x >= 0x2460 && x <= 0x24E9 || x >= 0x24EB && x <= 0x254B || x >= 0x2550 && x <= 0x2573 || x >= 0x2580 && x <= 0x258F || x >= 0x2592 && x <= 0x2595 || x === 0x25A0 || x === 0x25A1 || x >= 0x25A3 && x <= 0x25A9 || x === 0x25B2 || x === 0x25B3 || x === 0x25B6 || x === 0x25B7 || x === 0x25BC || x === 0x25BD || x === 0x25C0 || x === 0x25C1 || x >= 0x25C6 && x <= 0x25C8 || x === 0x25CB || x >= 0x25CE && x <= 0x25D1 || x >= 0x25E2 && x <= 0x25E5 || x === 0x25EF || x === 0x2605 || x === 0x2606 || x === 0x2609 || x === 0x260E || x === 0x260F || x === 0x261C || x === 0x261E || x === 0x2640 || x === 0x2642 || x === 0x2660 || x === 0x2661 || x >= 0x2663 && x <= 0x2665 || x >= 0x2667 && x <= 0x266A || x === 0x266C || x === 0x266D || x === 0x266F || x === 0x269E || x === 0x269F || x === 0x26BF || x >= 0x26C6 && x <= 0x26CD || x >= 0x26CF && x <= 0x26D3 || x >= 0x26D5 && x <= 0x26E1 || x === 0x26E3 || x === 0x26E8 || x === 0x26E9 || x >= 0x26EB && x <= 0x26F1 || x === 0x26F4 || x >= 0x26F6 && x <= 0x26F9 || x === 0x26FB || x === 0x26FC || x === 0x26FE || x === 0x26FF || x === 0x273D || x >= 0x2776 && x <= 0x277F || x >= 0x2B56 && x <= 0x2B59 || x >= 0x3248 && x <= 0x324F || x >= 0xE000 && x <= 0xF8FF || x >= 0xFE00 && x <= 0xFE0F || x === 0xFFFD || x >= 0x1F100 && x <= 0x1F10A || x >= 0x1F110 && x <= 0x1F12D || x >= 0x1F130 && x <= 0x1F169 || x >= 0x1F170 && x <= 0x1F18D || x === 0x1F18F || x === 0x1F190 || x >= 0x1F19B && x <= 0x1F1AC || x >= 0xE0100 && x <= 0xE01EF || x >= 0xF0000 && x <= 0xFFFFD || x >= 0x100000 && x <= 0x10FFFD; } function isFullWidth(x) { return x === 0x3000 || x >= 0xFF01 && x <= 0xFF60 || x >= 0xFFE0 && x <= 0xFFE6; } function isWide(x) { return x >= 0x1100 && x <= 0x115F || x === 0x231A || x === 0x231B || x === 0x2329 || x === 0x232A || x >= 0x23E9 && x <= 0x23EC || x === 0x23F0 || x === 0x23F3 || x === 0x25FD || x === 0x25FE || x === 0x2614 || x === 0x2615 || x >= 0x2630 && x <= 0x2637 || x >= 0x2648 && x <= 0x2653 || x === 0x267F || x >= 0x268A && x <= 0x268F || x === 0x2693 || x === 0x26A1 || x === 0x26AA || x === 0x26AB || x === 0x26BD || x === 0x26BE || x === 0x26C4 || x === 0x26C5 || x === 0x26CE || x === 0x26D4 || x === 0x26EA || x === 0x26F2 || x === 0x26F3 || x === 0x26F5 || x === 0x26FA || x === 0x26FD || x === 0x2705 || x === 0x270A || x === 0x270B || x === 0x2728 || x === 0x274C || x === 0x274E || x >= 0x2753 && x <= 0x2755 || x === 0x2757 || x >= 0x2795 && x <= 0x2797 || x === 0x27B0 || x === 0x27BF || x === 0x2B1B || x === 0x2B1C || x === 0x2B50 || x === 0x2B55 || x >= 0x2E80 && x <= 0x2E99 || x >= 0x2E9B && x <= 0x2EF3 || x >= 0x2F00 && x <= 0x2FD5 || x >= 0x2FF0 && x <= 0x2FFF || x >= 0x3001 && x <= 0x303E || x >= 0x3041 && x <= 0x3096 || x >= 0x3099 && x <= 0x30FF || x >= 0x3105 && x <= 0x312F || x >= 0x3131 && x <= 0x318E || x >= 0x3190 && x <= 0x31E5 || x >= 0x31EF && x <= 0x321E || x >= 0x3220 && x <= 0x3247 || x >= 0x3250 && x <= 0xA48C || x >= 0xA490 && x <= 0xA4C6 || x >= 0xA960 && x <= 0xA97C || x >= 0xAC00 && x <= 0xD7A3 || x >= 0xF900 && x <= 0xFAFF || x >= 0xFE10 && x <= 0xFE19 || x >= 0xFE30 && x <= 0xFE52 || x >= 0xFE54 && x <= 0xFE66 || x >= 0xFE68 && x <= 0xFE6B || x >= 0x16FE0 && x <= 0x16FE4 || x === 0x16FF0 || x === 0x16FF1 || x >= 0x17000 && x <= 0x187F7 || x >= 0x18800 && x <= 0x18CD5 || x >= 0x18CFF && x <= 0x18D08 || x >= 0x1AFF0 && x <= 0x1AFF3 || x >= 0x1AFF5 && x <= 0x1AFFB || x === 0x1AFFD || x === 0x1AFFE || x >= 0x1B000 && x <= 0x1B122 || x === 0x1B132 || x >= 0x1B150 && x <= 0x1B152 || x === 0x1B155 || x >= 0x1B164 && x <= 0x1B167 || x >= 0x1B170 && x <= 0x1B2FB || x >= 0x1D300 && x <= 0x1D356 || x >= 0x1D360 && x <= 0x1D376 || x === 0x1F004 || x === 0x1F0CF || x === 0x1F18E || x >= 0x1F191 && x <= 0x1F19A || x >= 0x1F200 && x <= 0x1F202 || x >= 0x1F210 && x <= 0x1F23B || x >= 0x1F240 && x <= 0x1F248 || x === 0x1F250 || x === 0x1F251 || x >= 0x1F260 && x <= 0x1F265 || x >= 0x1F300 && x <= 0x1F320 || x >= 0x1F32D && x <= 0x1F335 || x >= 0x1F337 && x <= 0x1F37C || x >= 0x1F37E && x <= 0x1F393 || x >= 0x1F3A0 && x <= 0x1F3CA || x >= 0x1F3CF && x <= 0x1F3D3 || x >= 0x1F3E0 && x <= 0x1F3F0 || x === 0x1F3F4 || x >= 0x1F3F8 && x <= 0x1F43E || x === 0x1F440 || x >= 0x1F442 && x <= 0x1F4FC || x >= 0x1F4FF && x <= 0x1F53D || x >= 0x1F54B && x <= 0x1F54E || x >= 0x1F550 && x <= 0x1F567 || x === 0x1F57A || x === 0x1F595 || x === 0x1F596 || x === 0x1F5A4 || x >= 0x1F5FB && x <= 0x1F64F || x >= 0x1F680 && x <= 0x1F6C5 || x === 0x1F6CC || x >= 0x1F6D0 && x <= 0x1F6D2 || x >= 0x1F6D5 && x <= 0x1F6D7 || x >= 0x1F6DC && x <= 0x1F6DF || x === 0x1F6EB || x === 0x1F6EC || x >= 0x1F6F4 && x <= 0x1F6FC || x >= 0x1F7E0 && x <= 0x1F7EB || x === 0x1F7F0 || x >= 0x1F90C && x <= 0x1F93A || x >= 0x1F93C && x <= 0x1F945 || x >= 0x1F947 && x <= 0x1F9FF || x >= 0x1FA70 && x <= 0x1FA7C || x >= 0x1FA80 && x <= 0x1FA89 || x >= 0x1FA8F && x <= 0x1FAC6 || x >= 0x1FACE && x <= 0x1FADC || x >= 0x1FADF && x <= 0x1FAE9 || x >= 0x1FAF0 && x <= 0x1FAF8 || x >= 0x20000 && x <= 0x2FFFD || x >= 0x30000 && x <= 0x3FFFD; } function getCategory(x) { if (isAmbiguous(x)) return 'ambiguous'; if (isFullWidth(x)) return 'fullwidth'; if ( x === 0x20A9 || x >= 0xFF61 && x <= 0xFFBE || x >= 0xFFC2 && x <= 0xFFC7 || x >= 0xFFCA && x <= 0xFFCF || x >= 0xFFD2 && x <= 0xFFD7 || x >= 0xFFDA && x <= 0xFFDC || x >= 0xFFE8 && x <= 0xFFEE ) { return 'halfwidth'; } if ( x >= 0x20 && x <= 0x7E || x === 0xA2 || x === 0xA3 || x === 0xA5 || x === 0xA6 || x === 0xAC || x === 0xAF || x >= 0x27E6 && x <= 0x27ED || x === 0x2985 || x === 0x2986 ) { return 'narrow'; } if (isWide(x)) return 'wide'; return 'neutral'; } export {isAmbiguous, isFullWidth, isWide, getCategory}; node_modules/heroui-cli/license 0000664 00000002050 15114743311 0012625 0 ustar 00 MIT License Copyright (c) 2024 Next UI Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/heroui-cli/package.json 0000664 00000006024 15114743311 0013553 0 ustar 00 { "name": "heroui-cli", "private": false, "type": "module", "license": "MIT", "version": "1.2.3", "homepage": "https://github.com/heroui-inc/heroui-cli#readme", "description": "A CLI tool that unlocks seamless HeroUI integration (Previously NextUI CLI)", "keywords": [ "UI", "CLI", "Tool", "NextUI", "Template", "Integration", "Add Component", "HeroUI" ], "author": { "name": "HeroUI", "email": "support@heroui.com", "url": "https://github.com/heroui-inc" }, "repository": { "type": "git", "url": "https://github.com/heroui-inc/heroui-cli.git" }, "bugs": { "url": "https://github.com/heroui-inc/heroui-cli/issues" }, "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" }, "files": [ "dist" ], "bin": { "heroui": "./dist/index.js" }, "main": "./dist/index.js", "module": "./dist/index.js", "types": "./dist/index.d.ts", "scripts": { "dev": "tsup --watch", "link:cli": "pnpm link --global", "link:remove": "pnpm uninstall --global heroui-cli", "build": "tsup", "update:components": "tsx src/scripts/update/update-components.ts", "sync:docs": "tsx src/scripts/sync/sync.ts", "clean:cache": "tsx src/scripts/cache/clean.ts", "lint": "eslint . --max-warnings=0", "lint:fix": "eslint . --max-warnings=0 --fix", "check:prettier": "prettier --check .", "check:types": "tsc --noEmit", "changelog": "npx conventional-changelog -p angular -i CHANGELOG.md -s --commit-path .", "release": "bumpp --execute='pnpm run changelog' --all", "prepare": "husky install", "prebuild": "pnpm run update:components", "prepublishOnly": "pnpm run build" }, "dependencies": { "@clack/prompts": "0.7.0", "@winches/prompts": "0.0.7", "async-retry": "1.3.3", "chalk": "5.3.0", "commander": "11.0.0", "compare-versions": "6.1.1", "fast-glob": "3.3.2", "find-up": "7.0.0", "gradient-string": "2.0.2", "ora": "8.0.1", "pathe": "1.1.2", "tar": "6.2.1" }, "devDependencies": { "@commitlint/cli": "17.7.1", "@commitlint/config-conventional": "17.7.0", "@types/gradient-string": "1.1.3", "@types/node": "20.11.30", "@typescript-eslint/eslint-plugin": "6.7.2", "@typescript-eslint/parser": "6.7.2", "bumpp": "9.4.0", "clean-package": "2.2.0", "commitlint-plugin-function-rules": "2.0.2", "conventional-changelog-cli": "4.1.0", "eslint": "8.50.0", "eslint-config-prettier": "9.0.0", "eslint-import-resolver-typescript": "3.6.1", "eslint-plugin-import": "2.28.1", "eslint-plugin-prettier": "5.0.0", "eslint-plugin-sort-destructure-keys": "1.5.0", "eslint-plugin-sort-keys-fix": "1.1.2", "eslint-plugin-unicorn": "52.0.0", "eslint-plugin-unused-imports": "3.0.0", "husky": "8.0.3", "lint-staged": "14.0.1", "prettier": "3.3.2", "tsup": "7.2.0", "tsx": "4.7.1", "typescript": "5.2.2" }, "engines": { "pnpm": ">=9.x" }, "packageManager": "pnpm@9.6.0" } node_modules/heroui-cli/dist/index.d.ts 0000664 00000000014 15114743311 0014122 0 ustar 00 export { } node_modules/heroui-cli/dist/.heroui-cli-cache/data.json 0000664 00000002015 15114743311 0017207 0 ustar 00 { "@heroui/react": { "version": "2.7.8", "date": "2025-05-29T10:19:26.611Z", "expiredDate": 1748515766611, "expiredFormatDate": "Thu May 29 2025 12:49:26 GMT+0200 (Central European Summer Time)", "formatDate": "Thu May 29 2025 12:19:26 GMT+0200 (Central European Summer Time)" }, "npm view @heroui/react dist-tags --json": { "execResult": "{\n \"canary\": \"0.0.0-canary-20250526221703\",\n \"latest\": \"2.7.8\",\n \"beta\": \"2.8.0-beta.6\"\n}", "date": "2025-05-29T10:19:27.995Z", "expiredDate": 1748515767995, "expiredFormatDate": "Thu May 29 2025 12:49:27 GMT+0200 (Central European Summer Time)", "formatDate": "Thu May 29 2025 12:19:27 GMT+0200 (Central European Summer Time)" }, "heroui-cli": { "version": "1.2.3", "date": "2025-05-29T10:19:29.385Z", "expiredDate": 1748515769385, "expiredFormatDate": "Thu May 29 2025 12:49:29 GMT+0200 (Central European Summer Time)", "formatDate": "Thu May 29 2025 12:19:29 GMT+0200 (Central European Summer Time)" } } node_modules/heroui-cli/dist/components.json 0000664 00000062310 15114743311 0015310 0 ustar 00 { "betaComponents": [], "betaVersion": "2.8.0-beta.6", "components": [ { "name": "accordion", "package": "@heroui/accordion", "version": "2.2.16", "docs": "https://heroui.com/docs/components/accordion", "description": "Collapse display a list of high-level options that can expand/collapse to reveal more information.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "alert", "package": "@heroui/alert", "version": "2.2.19", "docs": "https://heroui.com/docs/components/alert", "description": "Alerts are temporary notifications that provide concise feedback about an action or event.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "autocomplete", "package": "@heroui/autocomplete", "version": "2.3.20", "docs": "https://heroui.com/docs/components/autocomplete", "description": "An autocomplete combines a text input with a listbox, allowing users to filter a list of options to items matching a query.", "status": "stable", "style": "", "peerDependencies": { "@heroui/system": ">=2.4.7", "@heroui/theme": ">=2.4.6", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "tailwindcss": ">=3.4.0" } }, { "name": "avatar", "package": "@heroui/avatar", "version": "2.2.15", "docs": "https://heroui.com/docs/components/avatar", "description": "The Avatar component is used to represent a user, and displays the profile picture, initials or fallback icon.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "badge", "package": "@heroui/badge", "version": "2.2.12", "docs": "https://heroui.com/docs/components/badge", "description": "Badges are used as a small numerical value or status descriptor for UI elements.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "breadcrumbs", "package": "@heroui/breadcrumbs", "version": "2.2.15", "docs": "https://heroui.com/docs/components/breadcrumbs", "description": "Breadcrumbs display a hierarchy of links to the current page or resource in an application.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "button", "package": "@heroui/button", "version": "2.2.19", "docs": "https://heroui.com/docs/components/button", "description": "Buttons allow users to perform actions and choose with a single tap.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "calendar", "package": "@heroui/calendar", "version": "2.2.19", "docs": "https://heroui.com/docs/components/calendar", "description": "A calendar displays one or more date grids and allows users to select a single date.", "status": "stable", "style": "", "peerDependencies": { "@heroui/system": ">=2.4.7", "@heroui/theme": ">=2.4.6", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "tailwindcss": ">=3.4.0" } }, { "name": "card", "package": "@heroui/card", "version": "2.2.18", "docs": "https://heroui.com/docs/components/card", "description": "Card is a container for text, photos, and actions in the context of a single subject.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "checkbox", "package": "@heroui/checkbox", "version": "2.3.18", "docs": "https://heroui.com/docs/components/checkbox", "description": "Checkboxes allow users to select multiple items from a list of individual items, or to mark one individual item as selected.", "status": "updated", "style": "", "peerDependencies": { "@heroui/system": ">=2.4.7", "@heroui/theme": ">=2.4.3", "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "tailwindcss": ">=3.4.0" } }, { "name": "chip", "package": "@heroui/chip", "version": "2.2.15", "docs": "https://heroui.com/docs/components/chip", "description": "Chips help people enter information, make selections, filter content, or trigger actions.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "code", "package": "@heroui/code", "version": "2.2.14", "docs": "https://heroui.com/docs/components/code", "description": "Code is a component used to display inline code.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "tailwindcss": ">=3.4.0" } }, { "name": "date-input", "package": "@heroui/date-input", "version": "2.3.18", "docs": "https://heroui.com/docs/components/date-input", "description": "A date input allows users to enter and edit date and time values using a keyboard.", "status": "stable", "style": "", "peerDependencies": { "@heroui/system": ">=2.4.10", "@heroui/theme": ">=2.4.9", "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "tailwindcss": ">=3.4.0" } }, { "name": "date-picker", "package": "@heroui/date-picker", "version": "2.3.19", "docs": "https://heroui.com/docs/components/date-picker", "description": "A date picker combines a DateInput and a Calendar popover to allow users to enter or select a date and time value.", "status": "stable", "style": "", "peerDependencies": { "@heroui/system": ">=2.4.10", "@heroui/theme": ">=2.4.9", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "tailwindcss": ">=3.4.0" } }, { "name": "divider", "package": "@heroui/divider", "version": "2.2.13", "docs": "https://heroui.com/docs/components/divider", "description": ". A separator is a visual divider between two groups of content", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "tailwindcss": ">=3.4.0" } }, { "name": "drawer", "package": "@heroui/drawer", "version": "2.2.16", "docs": "https://heroui.com/docs/components/drawer", "description": "Used to render a content that slides in from the side of the screen.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "dropdown", "package": "@heroui/dropdown", "version": "2.3.19", "docs": "https://heroui.com/docs/components/dropdown", "description": "A dropdown displays a list of actions or options that a user can choose.", "status": "stable", "style": "", "peerDependencies": { "@heroui/system": ">=2.4.7", "@heroui/theme": ">=2.4.6", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "tailwindcss": ">=3.4.0" } }, { "name": "form", "package": "@heroui/form", "version": "2.1.18", "docs": "https://heroui.com/docs/components/form", "description": "A form is a group of inputs that allows users submit data to a server and supports field validation errors.", "status": "stable", "style": "", "peerDependencies": { "@heroui/system": ">=2.4.7", "@heroui/theme": ">=2.4.6", "react": ">=18", "react-dom": ">=18", "tailwindcss": ">=3.4.0" } }, { "name": "image", "package": "@heroui/image", "version": "2.2.12", "docs": "https://heroui.com/docs/components/image", "description": "A simple image component", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "input", "package": "@heroui/input", "version": "2.4.19", "docs": "https://heroui.com/docs/components/input", "description": "The input component is designed for capturing user input within a text field.", "status": "updated", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.12", "@heroui/system": ">=2.4.10", "tailwindcss": ">=3.4.0" } }, { "name": "input-otp", "package": "@heroui/input-otp", "version": "2.1.18", "docs": "https://heroui.com/docs/components/input-otp", "description": "", "status": "updated", "style": "", "peerDependencies": { "react": ">=18", "react-dom": ">=18", "@heroui/theme": ">=2.4.13", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "kbd", "package": "@heroui/kbd", "version": "2.2.15", "docs": "https://heroui.com/docs/components/kbd", "description": "The keyboard key components indicates which key or set of keys used to execute a specificv action", "status": "updated", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "tailwindcss": ">=3.4.0" } }, { "name": "link", "package": "@heroui/link", "version": "2.2.16", "docs": "https://heroui.com/docs/components/link", "description": "Links allow users to click their way from page to page. This component is styled to resemble a hyperlink and semantically renders an <a>", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "listbox", "package": "@heroui/listbox", "version": "2.3.18", "docs": "https://heroui.com/docs/components/listbox", "description": "A listbox displays a list of options and allows a user to select one or more of them.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "menu", "package": "@heroui/menu", "version": "2.2.18", "docs": "https://heroui.com/docs/components/menu", "description": "A menu displays a list of options and allows a user to select one or more of them.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "modal", "package": "@heroui/modal", "version": "2.2.16", "docs": "https://heroui.com/docs/components/modal", "description": "Displays a dialog with a custom content that requires attention or provides additional information.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "navbar", "package": "@heroui/navbar", "version": "2.2.17", "docs": "https://heroui.com/docs/components/navbar", "description": "A responsive navigation header positioned on top side of your page that includes support for branding, links, navigation, collapse and more.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "number-input", "package": "@heroui/number-input", "version": "2.0.9", "docs": "https://heroui.com/docs/components/number-input", "description": "The numeric input component is designed for users to enter a number, and increase or decrease the value using stepper buttons", "status": "new", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/system": ">=2.4.10", "@heroui/theme": ">=2.4.9", "tailwindcss": ">=3.4.0" } }, { "name": "pagination", "package": "@heroui/pagination", "version": "2.2.17", "docs": "https://heroui.com/docs/components/pagination", "description": "The Pagination component allows you to display active page and navigate between multiple pages.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "popover", "package": "@heroui/popover", "version": "2.3.19", "docs": "https://heroui.com/docs/components/popover", "description": "A popover is an overlay element positioned relative to a trigger.", "status": "stable", "style": "", "peerDependencies": { "@heroui/system": ">=2.4.7", "@heroui/theme": ">=2.4.6", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "tailwindcss": ">=3.4.0" } }, { "name": "progress", "package": "@heroui/progress", "version": "2.2.15", "docs": "https://heroui.com/docs/components/progress", "description": "Progress bars show either determinate or indeterminate progress of an operation over time.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "radio", "package": "@heroui/radio", "version": "2.3.18", "docs": "https://heroui.com/docs/components/radio", "description": "Radios allow users to select a single option from a list of mutually exclusive options.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.3", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "ripple", "package": "@heroui/ripple", "version": "2.2.14", "docs": "https://heroui.com/docs/components/ripple", "description": "A simple implementation to display a ripple animation when the source component is clicked", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "scroll-shadow", "package": "@heroui/scroll-shadow", "version": "2.3.13", "docs": "https://heroui.com/docs/components/scroll-shadow", "description": "A component that applies top and bottom shadows when content overflows on scroll.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "select", "package": "@heroui/select", "version": "2.4.19", "docs": "https://heroui.com/docs/components/select", "description": "A select displays a collapsible list of options and allows a user to select one of them.", "status": "stable", "style": "", "peerDependencies": { "@heroui/system": ">=2.4.10", "@heroui/theme": ">=2.4.12", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "tailwindcss": ">=3.4.0" } }, { "name": "skeleton", "package": "@heroui/skeleton", "version": "2.2.12", "docs": "https://heroui.com/docs/components/skeleton", "description": "Skeleton is used to display the loading state of some component.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "slider", "package": "@heroui/slider", "version": "2.4.16", "docs": "https://heroui.com/docs/components/slider", "description": "A slider allows a user to select one or more values within a range.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "snippet", "package": "@heroui/snippet", "version": "2.2.20", "docs": "https://heroui.com/docs/components/snippet", "description": "Display a snippet of copyable code for the command line.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "spacer", "package": "@heroui/spacer", "version": "2.2.14", "docs": "https://heroui.com/docs/components/spacer", "description": "A flexible spacer component designed to create consistent spacing and maintain alignment in your layout.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "tailwindcss": ">=3.4.0" } }, { "name": "spinner", "package": "@heroui/spinner", "version": "2.2.16", "docs": "https://heroui.com/docs/components/spinner", "description": "Loaders express an unspecified wait time or display the length of a process.", "status": "updated", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "tailwindcss": ">=3.4.0" } }, { "name": "switch", "package": "@heroui/switch", "version": "2.2.17", "docs": "https://heroui.com/docs/components/switch", "description": "A switch is similar to a checkbox, but represents on/off values as opposed to selection.", "status": "stable", "style": "toggle", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.3", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "table", "package": "@heroui/table", "version": "2.2.18", "docs": "https://heroui.com/docs/components/table", "description": "Tables are used to display tabular data using rows and columns. ", "status": "updated", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "tabs", "package": "@heroui/tabs", "version": "2.2.16", "docs": "https://heroui.com/docs/components/tabs", "description": "Tabs organize content into multiple sections and allow users to navigate between them.", "status": "updated", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "toast", "package": "@heroui/toast", "version": "2.0.9", "docs": "https://heroui.com/docs/components/toast", "description": "Toast are temporary notifications that provide concise feedback about an action or event", "status": "new", "style": "", "peerDependencies": { "@heroui/system": ">=2.4.10", "@heroui/theme": ">=2.4.12", "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "tailwindcss": ">=3.4.0" } }, { "name": "tooltip", "package": "@heroui/tooltip", "version": "2.2.16", "docs": "https://heroui.com/docs/components/tooltip", "description": "A React Component for rendering dynamically positioned Tooltips", "status": "stable", "style": "popover", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "framer-motion": ">=11.5.6 || >=12.0.0-alpha.1", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } }, { "name": "user", "package": "@heroui/user", "version": "2.2.15", "docs": "https://heroui.com/docs/components/user", "description": "Flexible User Profile Component.", "status": "stable", "style": "", "peerDependencies": { "react": ">=18 || >=19.0.0-rc.0", "react-dom": ">=18 || >=19.0.0-rc.0", "@heroui/theme": ">=2.4.6", "@heroui/system": ">=2.4.7", "tailwindcss": ">=3.4.0" } } ], "version": "2.7.8" } node_modules/heroui-cli/dist/index.js.map 0000664 00000717734 15114743311 0014472 0 ustar 00 {"version":3,"sources":["../src/index.ts","../src/helpers/actions/add/heroui-chat/add-hero-chat-codebase.ts","../src/helpers/detect.ts","../src/constants/path.ts","../src/prompts/index.ts","../src/helpers/logger.ts","../src/helpers/exec.ts","../src/helpers/utils.ts","../src/helpers/output-info.ts","../src/constants/box.ts","../src/scripts/cache/cache.ts","../src/scripts/helpers.ts","../src/scripts/path.ts","../src/helpers/beta.ts","../src/constants/required.ts","../src/helpers/package.ts","../src/constants/store.ts","../src/constants/component.ts","../src/prompts/clack.ts","../src/helpers/actions/add/heroui-chat/get-base-storage-url.ts","../src/helpers/fetch.ts","../src/helpers/actions/add/heroui-chat/get-codebase-files.ts","../src/helpers/actions/add/heroui-chat/get-related-imports.ts","../src/helpers/match.ts","../src/helpers/actions/add/heroui-chat/write-files.ts","../src/helpers/math-diff.ts","../package.json","../src/actions/add-action.ts","../src/helpers/check.ts","../src/helpers/actions/add/get-peer-pakcage-version.ts","../src/helpers/upgrade.ts","../src/helpers/condition-value.ts","../src/helpers/actions/upgrade/get-libs-data.ts","../src/helpers/debug.ts","../src/helpers/actions/upgrade/catch-pnpm-exec.ts","../src/helpers/fix.ts","../src/constants/templates.ts","../src/actions/doctor-action.ts","../src/actions/env-action.ts","../src/actions/init-action.ts","../src/helpers/actions/init/change-npmrc.ts","../src/helpers/init.ts","../src/actions/list-action.ts","../src/actions/remove-action.ts","../src/helpers/remove.ts","../src/actions/upgrade-action.ts","../src/helpers/setup.ts"],"names":["chalk","Command","fs","join","p","resolve","findUp","path","fileURLToPath","ROOT","resolver","COMPONENTS_PATH","prompts","_gradientString","defaultColors","gradientString","logPrefix","Logger","args","item","content","options","type","lines","i","defaultPromptOptions","getAutocompleteMultiselect","message","choices","getSelect","getMultiselect","AGENTS","LOCKS","detect","cwd","agent","lockPath","execSync","compareVersions","fg","boxRound","existsSync","mkdirSync","readFileSync","unlinkSync","writeFileSync","exec","retry","InternalCompareVersions","validate","ora","oraPromise","version1","version2","updateComponents","autoUpdateComponents","components","currentVersion","betaVersion","latestVersion","getStore","latestBetaVersion","getComponents","error","oraExecCmd","cmd","text","spinner","result","stdout","getLatestVersion","packageName","store","getPackageVersion","getUnpkgUrl","version","url","betaComponents","downloadFile","getStoreSync","filterMissingComponents","component","c","componentsJson","log","data","bail","isGithubAction","PROD_DIR","PROD","CACHE_DIR","CACHE_PATH","cacheTTL","noCache","initCache","_noCache","getCacheData","cacheData","packageData","now","expiredDate","ttl","n","isExpired","pkgData","pkgVersion","getCacheExecData","key","execMessage","getBetaVersionData","getPrefixComponent","getBetaVersion","componentName","getBetaComponents","getPackageInfo","packagePath","transformVersion","pkg","devDependencies","dependencies","allDependencies","allDependenciesKeys","currentComponents","versionMode","getVersionAndMode","isAllComponents","HERO_UI","transformComponentsToPackage","transformPackageDetail","docs","description","detailPackageInfo","HEROUI_CLI","FRAMER_MOTION","TAILWINDCSS","THEME_UI","SYSTEM_UI","HEROUI_PREFIX","DOCS_INSTALLED","DOCS_TAILWINDCSS_SETUP","DOCS_PNPM_SETUP","DOCS_PROVIDER_SETUP","tailwindRequired","isTypescript","individualTailwindRequired","isPnpm","walkDeps","walkDepComponents","outputComponents","acc","appRequired","pnpmRequired","heroUIComponent","componentPath","pnpmDir","file","getHerouiComponentsData","heroUIComponents","heroUIComponentsKeys","heroUIcomponentsPackages","heroUIComponentsKeysSet","heroUIComponentsMap","heroUIComponentsPackageMap","initStoreComponentsData","beta","orderHeroUIComponentKeys","colorHeroUIComponentKeys","getConditionComponentData","colorMatchRegex","rounded","space","padStart","padEnd","versionRegex","newVersionRegex","commandName","warnError","componentKeyLengthMap","str","newVersion","value","strip","generateComponentOutputVersion","transformComponentsOutput","outputData","fillAnsiLength","boxHeader","boxHeaderSec","boxHeaderTrd","PasCalCase","boxFooter","outputInfo","outputBox","align","borderStyle","center","color","padding","title","mergedRounded","contentArr","transformArr","isPadding","paddingLength","mergedPadding","maxLength","cur","clearColorTitle","titleLength","titleHeaderLength","spaceLen","boxHeaderContent","spaceFir","spaceSec","padFir","padSec","boxContent","transformCur","spaceLength","pad","endLen","versionModeRegex","getCommandDescAndLog","desc","s","findFiles","glob","transformOption","omit","obj","keys","getColorVersion","transformPeerVersion","isMajorUpdate","isMinorUpdate","isPatchUpdate","currentVersionArr","latestVersionArr","getPackageManagerInfo","packageManager","isLatest","r","range","a","b","length","stripStr","fillSpace","execCache","commonExecOptions","reject","cache","logCmd","output","readdirSync","statSync","_spinner","cancel","confirm","isCancel","multiselect","select","cancelClack","textClack","opts","selectClack","taskClack","failText","successText","task","confirmClack","getDirectoryClack","dir","ignore","getBaseStorageUrl","httpMatch","baseUrl","userId","chatId","sandboxId","chatTitle","basename","Readable","pipeline","tar","fetchTarStream","res","downloadTemplate","root","fetchRequest","fetchInfo","throwError","rest","response","getCodeBaseFiles","getMatchImport","importRegexAll","matchAll","matchImport","itemImport","importRegex","match","removeQuote","getMatchArray","target","mixinReg","replaceMatchArray","_replaceValue","replaceValue","v","_value","targetArray","contentIndex","moduleIndex","insertIndex","getRelatedImports","fileContent","imports","fetchAllRelatedFiles","params","entries","filePath","fetchRelatedImports","relatedImports","relatedPath","targetFile","suffix","fileName","writeFilesWithMkdir","directory","httpRegex","APP_FILE","isAddingHeroChatCodebase","targets","addHeroChatCodebase","baseStorageUrl","chatTitleFile","codeFiles","appFile","pkgContent","relatedFiles","relatedFile","pkgContentJson","missingDependencies","isAddMissingDependencies","currentPkgManager","installCmd","matchTextScore","pattern","score","textLength","patternLength","j","findMostMatchText","list","maxScore","printMostMatchText","mathOption","package_default","getPeerPackageVersion","peerPackageName","isMinVersion","filerTargetPackages","min","getConditionVersion","getLibsData","allLibs","dependency","lib","conditionVersion","DEFAULT_SPACE","MISSING","upgrade","all","isHeroUIAll","upgradeOptionList","missingDepSet","allOutputData","getAllOutputData","libsData","transformUpgradeOptionList","upgradePeerList","upgradeOption","getPackagePeerDep","missingDepList","getPackageUpgradeData","outputList","peerDepList","index","arr","outputDependencies","outputUpgradeCount","getUpgradeVersion","peer","optionMaxLenMap","compareLength","peerDependencies","peerPackage","peerVersion","formatPeerVersion","outputDefault","outputPeerDepInfo","filterPeerDepList","colorVersion","heroUIPeerDepList","heroUIThemePeerDepList","allOutputList","allPeerDepList","missingDep","count","stripLatestVersion","writeUpgradeVersion","upgradePackageList","upgradePackage","combineProblemRecord","errorInfo","tailwindName","info","checkRequiredContentInstalled","dependenciesKeys","checkPeerDependenciesConfig","packageNames","peerDependenciesList","hasFramerMotion","hasTailwind","minTailwindVersion","checkPeerDependencies","hasAllComponents","hasSystemUI","hasThemeUI","betaSystemUI","betaThemeUI","config","peerData","findPeerDepIndex","peerDep","findPeerDepVersion","checkTailwind","tailwindPath","logWarning","tailwindContent","contentMatch","pluginsMatch","isDarkModeCorrect","darkMode","isContentCorrect","isPluginsCorrect","plugins","individualContent","isHaveAllContent","checkApp","appPath","appContent","isAppCorrect","checkPnpm","npmrcPath","isPnpmCorrect","checkIllegalComponents","loggerError","illegalList","matchComponent","illegalComponents","matchComponents","illegalComponent","catchPnpmExec","execFn","debugExecAddAction","debugAddedPkg","packageJson","compData","debugRemovedPkg","fixProvider","format","write","wrapWithHeroUIProvider","returnRegex","_","p1","fixTailwind","errorInfoList","errorType","transformErrorInfo","darkModeIndex","darkModeContent","fixPnpm","runInstall","logger","APP_REPO","PAGES_REPO","VITE_REPO","REMIX_REPO","LARAVEL_REPO","APP_DIR","PAGES_DIR","VITE_DIR","REMIX_DIR","LARAVEL_DIR","APP_NAME","PAGES_NAME","VITE_NAME","REMIX_NAME","LARAVEL_NAME","tailwindTemplate","addAction","addApp","prettier","filteredComponents","currentComponent","currentComponentsKeys","filterCurrentComponents","runCmd","mergedComponents","_missingDependencies","template","isCorrectProvider","isCorrectPnpm","doctorAction","_enableCheckApp","_enableCheckPnpm","_enableCheckTailwind","enableCheckApp","enableCheckPnpm","enableCheckTailwind","tailwindPaths","problemRecord","isCorrectInstalled","_isCorrectInstalled","d","isCorrectTailwind","isCorrect","problem","envAction","renameSync","DEFAULT_NPMRC_CONTENT","changeNpmrc","npmrcFile","checkInitOptions","templatesMap","initAction","_projectName","_package","_template","projectName","getTableInfo","run","generateTemplate","renameTemplate","originName","listAction","remote","removeDependencies","remove","removeTailwind","insIncludeAll","removeAction","removeDepList","setupPnpm","betaCompareVersions","autoChangeTag","compareResult","upgradeAction","transformComponents","mergedVersion","herouiData","isUpToDate","ignoreList","isExecute","install","commandList","heroui","command","isArgs","matchCommand","helpInfoArr","debug","targetsArgs","heroUIComponentsBeta","cliLatestVersion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';\n\nimport chalk from 'chalk';\nimport {Command} from 'commander';\n\nimport {isAddingHeroChatCodebase} from '@helpers/actions/add/heroui-chat/add-hero-chat-codebase';\nimport {Logger, gradientString} from '@helpers/logger';\nimport {findMostMatchText} from '@helpers/math-diff';\nimport {outputBox} from '@helpers/output-info';\nimport {getCommandDescAndLog} from '@helpers/utils';\n\nimport pkg from '../package.json';\n\nimport {addAction} from './actions/add-action';\nimport {doctorAction} from './actions/doctor-action';\nimport {envAction} from './actions/env-action';\nimport {initAction, templatesMap} from './actions/init-action';\nimport {listAction} from './actions/list-action';\nimport {removeAction} from './actions/remove-action';\nimport {upgradeAction} from './actions/upgrade-action';\nimport {initStoreComponentsData} from './constants/component';\nimport {getStore, store} from './constants/store';\nimport {getCacheExecData, initCache} from './scripts/cache/cache';\nimport {compareVersions, getComponents} from './scripts/helpers';\n\nconst commandList: CommandName[] = ['add', 'env', 'init', 'list', 'upgrade', 'doctor', 'remove'];\n\nconst heroui = new Command();\n\nheroui\n .name('heroui')\n .usage('[command]')\n .description(getCommandDescAndLog(`\\nHeroUI CLI v${pkg.version}\\n`, ''))\n .version(pkg.version, '-v, --version', 'Output the current version')\n .helpOption('-h, --help', 'Display help for command')\n .allowUnknownOption()\n .option(\n '--no-cache',\n 'Disable cache, by default data will be cached for 30m after the first request'\n )\n .option('-d, --debug', 'Debug mode will not install dependencies')\n .action(async (_, command) => {\n let isArgs = false;\n\n if (command) {\n const args = command.args?.[0];\n\n if (args && !commandList.includes(args as CommandName)) {\n isArgs = true;\n\n const matchCommand = findMostMatchText(commandList, args);\n\n if (matchCommand) {\n Logger.error(\n `Unknown command '${args}', Did you mean '${chalk.underline(matchCommand)}'?`\n );\n } else {\n Logger.error(`Unknown command '${args}'`);\n }\n }\n }\n\n if (!isArgs) {\n const helpInfo = (await getCacheExecData('heroui --help')) as string;\n\n let helpInfoArr = helpInfo.split('\\n');\n\n helpInfoArr = helpInfoArr.filter((info) => info && !info.includes('HeroUI CLI v'));\n // Add command name color\n helpInfoArr = helpInfoArr.map((info) => {\n const command = info.match(/(\\w+)\\s\\[/)?.[1];\n\n if (command) {\n return info.replace(command, chalk.cyan(command));\n }\n\n return info;\n });\n\n Logger.log(helpInfoArr.join('\\n'));\n }\n process.exit(0);\n });\n\nheroui\n .command('init')\n .description('Initializes a new project')\n .argument('[projectName]', 'Name of the project to initialize')\n .option(\n '-t --template [string]',\n `Specify a template for the new project, e.g. ${Object.keys(templatesMap).join(', ')}`\n )\n .option('-p --package [string]', 'The package manager to use for the new project', 'npm')\n .action(initAction);\n\nheroui\n .command('add')\n .description('1. Adds components to your project\\n2. Adds HeroUI Chat codebase to your project')\n .argument('[targets...]', 'Names of components, HeroUI Chat codebase url to add')\n .option('-a --all [boolean]', 'Add all components', false)\n .option('-p --packagePath [string]', 'Specify the path to the package.json file')\n .option('-tw --tailwindPath [string]', 'Specify the path to the tailwind.config.js file')\n .option('-app --appPath [string]', 'Specify the path to the App.tsx file')\n .option('--prettier [boolean]', 'Apply Prettier formatting to the added content')\n .option('--addApp [boolean]', 'Include App.tsx file content that requires a provider', false)\n .option('-b --beta [boolean]', 'Add beta components', false)\n .option('-d --directory [string]', 'Add HeroUI Chat codebase to a specific directory')\n .action(addAction);\n\nheroui\n .command('upgrade')\n .description('Upgrades project components to the latest versions')\n .argument('[components...]', 'Names of components to upgrade')\n .option('-p --packagePath [string]', 'Specify the path to the package.json file')\n .option('-a --all [boolean]', 'Upgrade all components', false)\n .option('-w --write [boolean]', 'Write the upgrade version to package.json file', false)\n .option('-b --beta [boolean]', 'Upgrade beta components', false)\n .action(upgradeAction);\n\nheroui\n .command('remove')\n .description('Removes components from the project')\n .argument('[components...]', 'Names of components to remove')\n .option('-p --packagePath [string]', 'Specify the path to the package.json file')\n .option('-a --all [boolean]', 'Remove all components', false)\n .option('-tw --tailwindPath [string]', 'Specify the path to the tailwind.config.js file')\n .option('--prettier [boolean]', 'Apply Prettier formatting to the added content')\n .action(removeAction);\n\nheroui\n .command('list')\n .description('Lists all components, showing status, descriptions, and versions')\n .option('-p --packagePath [string]', 'Specify the path to the package.json file')\n .option('-r --remote', 'List all components available remotely')\n .action(listAction);\nheroui\n .command('env')\n .description('Displays debugging information for the local environment')\n .option('-p --packagePath [string]', 'Specify the path to the package.json file')\n .action(envAction);\n\nheroui\n .command('doctor')\n .description('Checks for issues in the project')\n .option('-p --packagePath [string]', 'Specify the path to the package.json file')\n .option('-tw --tailwindPath [string]', 'Specify the path to the tailwind.config.js file')\n .option('-app --appPath [string]', 'Specify the path to the App.tsx file')\n .option('-ca --checkApp [boolean]', 'Check the App.tsx file', false)\n .option('-ct --checkTailwind [boolean]', 'Check the tailwind.config.js file', true)\n .option('-cp --checkPnpm [boolean]', 'Check for Pnpm', true)\n .action(doctorAction);\n\nheroui.hook('preAction', async (command) => {\n const commandName = command.args?.[0];\n const options = (command as SAFE_ANY).rawArgs.slice(2);\n const noCache = options.includes('--no-cache');\n const debug = options.includes('--debug') || options.includes('-d');\n const targetsArgs = command.args?.slice(1);\n\n if (isAddingHeroChatCodebase(targetsArgs) || !commandName) {\n // HeroUI chat action don't need to init\n return;\n }\n\n // Init cache\n initCache(noCache);\n // Init debug\n store.debug = debug;\n store.beta = options.includes('-b') || options.includes('--beta');\n\n if (commandName && commandList.includes(commandName as CommandName)) {\n // Before run the command init the components.json\n const heroUIComponents = (await getComponents()).components;\n const heroUIComponentsBeta = (await getComponents()).betaComponents;\n\n initStoreComponentsData({beta: false, heroUIComponents: heroUIComponents});\n store.beta && initStoreComponentsData({beta: true, heroUIComponents: heroUIComponentsBeta});\n }\n\n const [cliLatestVersion] = await Promise.all([getStore('cliLatestVersion')]);\n\n // Init latest version\n store.cliLatestVersion = cliLatestVersion;\n\n // Add HeroUI CLI version check preAction\n const currentVersion = pkg.version;\n\n if (compareVersions(currentVersion, cliLatestVersion) === -1) {\n outputBox({\n center: true,\n color: 'yellow',\n padding: 1,\n text: `${chalk.gray(\n `Available upgrade: v${currentVersion} -> ${chalk.greenBright(\n `v${cliLatestVersion}`\n )}\\nRun \\`${chalk.cyan(\n 'npm install -g heroui-cli@latest'\n )}\\` to upgrade\\nChangelog: ${chalk.underline(\n 'https://github.com/heroui-inc/heroui-cli/releases'\n )}`\n )}`,\n title: gradientString('HeroUI CLI')\n });\n Logger.newLine();\n }\n});\n\nheroui.parseAsync(process.argv).catch(async (reason) => {\n Logger.newLine();\n Logger.error('Unexpected error. Please report it as a bug:');\n Logger.log(reason);\n Logger.newLine();\n process.exit(1);\n});\n","import fs from 'node:fs';\nimport {join} from 'node:path';\n\nimport * as p from '@clack/prompts';\nimport chalk from 'chalk';\nimport {resolve} from 'pathe';\n\nimport {detect} from '@helpers/detect';\nimport {exec} from '@helpers/exec';\nimport {Logger} from '@helpers/logger';\nimport {getPackageInfo} from '@helpers/package';\nimport {confirmClack, getDirectoryClack} from 'src/prompts/clack';\n\nimport {getBaseStorageUrl} from './get-base-storage-url';\nimport {getCodeBaseFiles} from './get-codebase-files';\nimport {fetchAllRelatedFiles} from './get-related-imports';\nimport {writeFilesWithMkdir} from './write-files';\n\nexport interface AddActionOptions {\n all?: boolean;\n prettier?: boolean;\n packagePath?: string;\n tailwindPath?: string;\n appPath?: string;\n addApp?: boolean;\n beta?: boolean;\n directory: string;\n}\n\nconst httpRegex = /^https?:\\/\\//;\nconst APP_FILE = 'App.tsx';\n\nexport function isAddingHeroChatCodebase(targets: string[]) {\n return targets.some((target) => httpRegex.test(target));\n}\n\nexport async function addHeroChatCodebase(targets: string[], options: AddActionOptions) {\n p.intro(chalk.cyan('Starting to add HeroUI Chat codebase'));\n\n const directory = resolve(process.cwd(), options.directory ?? (await getDirectoryClack()));\n const {baseStorageUrl, chatTitle, userId} = await getBaseStorageUrl(targets[0]!);\n const chatTitleFile = chatTitle ? `${chatTitle}.tsx` : undefined;\n\n const ifExists = fs.existsSync(directory);\n\n if (!ifExists) {\n Logger.error(`Directory ${directory} does not exist`);\n process.exit(1);\n }\n\n /** ======================== Add files ======================== */\n\n const codeFiles = await getCodeBaseFiles(baseStorageUrl, userId);\n const appFile = codeFiles.find((file) => file.name.includes(APP_FILE));\n const pkgContent = codeFiles.find((file) => file.name.includes('package.json'))?.content;\n\n if (appFile) {\n const relatedFiles = await fetchAllRelatedFiles({\n content: appFile.content,\n entries: codeFiles,\n filePath: 'src/App.tsx'\n });\n\n for (const relatedFile of relatedFiles) {\n if (relatedFile.fileName.includes(APP_FILE)) {\n writeFilesWithMkdir(directory, `${chatTitleFile || APP_FILE}`, relatedFile.fileContent);\n continue;\n }\n\n writeFilesWithMkdir(\n directory,\n `${relatedFile.filePath.replace('src/', '')}`,\n relatedFile.fileContent\n );\n }\n }\n\n /** ======================== Check if the project missing dependencies ======================== */\n if (pkgContent) {\n const pkgContentJson = JSON.parse(pkgContent);\n const {allDependenciesKeys} = getPackageInfo(join(process.cwd(), 'package.json'));\n const missingDependencies = Object.keys(pkgContentJson.dependencies).filter(\n (key) => !allDependenciesKeys.has(key)\n );\n\n if (missingDependencies.length > 0) {\n p.log.warn(\n `The project is missing the following dependencies to run the codebase: ${missingDependencies.join(', ')}`\n );\n\n const isAddMissingDependencies = await confirmClack({\n message: 'Do you want to add the missing dependencies?'\n });\n\n const currentPkgManager = await detect();\n const runCmd = currentPkgManager === 'npm' ? 'install' : 'add';\n const installCmd = `${currentPkgManager} ${runCmd} ${missingDependencies.map((target) => `${target}@${pkgContentJson.dependencies[target]}`).join(' ')}`;\n\n if (isAddMissingDependencies) {\n try {\n await exec(installCmd);\n } catch {\n p.log.error(\n `Failed to install dependencies. Please add ${missingDependencies.join(' ')} manually.`\n );\n }\n } else {\n p.note(`Run \\`${installCmd}\\` to start!`, 'Next steps');\n }\n }\n }\n\n p.outro(chalk.green('✅ HeroUI Chat codebase added successfully!'));\n}\n\n/** ======================== For the future init project ======================== */\n// else {\n// for (let file of filesToAdd) {\n// const filePath = `${url}/${file}`;\n// const response = await fetchRequest(filePath);\n\n// let fileContent = await response.text();\n\n// if (chatTitleFile) {\n// // Update App.tsx to chatTitle\n// if (file.includes(APP_FILE)) {\n// file = file.replace(APP_FILE, chatTitleFile);\n// }\n// // Update main.tsx import\n// if (file.includes('main.tsx')) {\n// fileContent = fileContent.replace(/from '.\\/App\\.tsx'/, `from './${chatTitleFile}'`);\n// fileContent = fileContent.replace(/from '.\\/App'/, `from './${chatTitle}'`);\n// }\n// }\n\n// writeFilesWithMkdir(directory, file, fileContent);\n// }\n// }\n\n/** ======================== Add templates ======================== */\n// for (const [file, value] of Object.entries(templates)) {\n// writeFilesWithMkdir(directory, file, value.content);\n// }\n\n// const isInstall = await confirmClack({\n// message: 'Do you want to install the dependencies?'\n// });\n\n// if (isInstall) {\n// const packageManager = await detect();\n// const installCmd =\n// packageManager === 'pnpm' ? 'pnpm install --shamefully-hoist' : `${packageManager} install`;\n\n// try {\n// await exec(`cd ${directory} && ${installCmd} && npm run dev`);\n// } catch {\n// p.log.error(`Failed to install dependencies. Please run \"${installCmd}\" manually.`);\n// }\n// } else {\n// p.note(`Cd to ${directory}\\nRun \\`pnpm install\\` to start!`, 'Next steps');\n// }\n","import type {SAFE_ANY} from './type';\n\nimport {findUp} from 'find-up';\nimport path from 'pathe';\n\nimport {ROOT} from 'src/constants/path';\nimport {getSelect} from 'src/prompts';\n\ntype TupleToUnion<T extends readonly SAFE_ANY[]> = T[number];\n\nexport const AGENTS = ['npm', 'bun', 'pnpm', 'yarn'] as const;\n\nexport type Agent = TupleToUnion<typeof AGENTS>;\n\nexport const agents = AGENTS;\n\n// the order here matters, more specific one comes first\nexport const LOCKS: Record<string, Agent> = {\n 'bun.lockb': 'bun',\n 'npm-shrinkwrap.json': 'npm',\n 'package-lock.json': 'npm',\n 'pnpm-lock.yaml': 'pnpm',\n 'yarn.lock': 'yarn'\n};\n\nexport async function detect(cwd = ROOT) {\n let agent: Agent;\n const lockPath = await findUp(Object.keys(LOCKS), {cwd});\n\n // detect based on lock\n if (lockPath) {\n agent = LOCKS[path.basename(lockPath)]!;\n } else {\n agent = await getSelect(\n 'No agent found, please choose one',\n AGENTS.map((agent) => ({\n title: agent,\n value: agent\n }))\n );\n }\n\n return agent;\n}\n","import {fileURLToPath} from 'node:url';\n\nimport {resolve} from 'pathe';\n\nexport const ROOT = process.cwd();\nexport const resolver = (path: string) => resolve(ROOT, path);\n\nexport const COMPONENTS_PATH = resolve(fileURLToPath(import.meta.url), '../components.json');\n","import prompts from '@winches/prompts';\nimport chalk from 'chalk';\n\nimport {Logger} from '@helpers/logger';\n\nconst defaultPromptOptions: prompts.Options = {\n onCancel: () => {\n Logger.log(`${chalk.red('✖')} Operation cancelled`);\n process.exit(0);\n }\n};\n\nexport async function getText(message: string, initial?: string) {\n const result = await prompts(\n {\n message,\n name: 'value',\n type: 'text',\n ...(initial ? {initial} : {})\n },\n defaultPromptOptions\n );\n\n return result.value;\n}\n\nexport async function getAutocomplete(message: string, choices?: prompts.Choice[]) {\n const result = await prompts(\n {\n message,\n name: 'value',\n type: 'autocomplete',\n ...(choices ? {choices} : {})\n },\n defaultPromptOptions\n );\n\n return result.value;\n}\n\nexport async function getAutocompleteMultiselect(message: string, choices?: prompts.Choice[]) {\n const result = await prompts(\n {\n hint: '- Space to select. Return to submit',\n message,\n min: 1,\n name: 'value',\n type: 'autocompleteMultiselect',\n ...(choices ? {choices} : {})\n },\n defaultPromptOptions\n );\n\n return result.value;\n}\n\nexport async function getSelect(message: string, choices: prompts.Choice[]) {\n const result = await prompts(\n {\n message,\n name: 'value',\n type: 'select',\n ...(choices ? {choices} : {})\n },\n defaultPromptOptions\n );\n\n return result.value;\n}\n\nexport async function getMultiselect(message: string, choices?: prompts.Choice[]) {\n const result = await prompts(\n {\n hint: '- Space to select. Return to submit',\n message,\n min: 1,\n name: 'value',\n type: 'multiselect',\n ...(choices ? {choices} : {})\n },\n defaultPromptOptions\n );\n\n return result.value;\n}\n","/* eslint-disable no-console */\n\nimport type {SAFE_ANY} from './type';\n\nimport chalk from 'chalk';\nimport {default as _gradientString} from 'gradient-string';\n\nexport const defaultColors = ['#F54180', '#338EF7'] as const;\n\nexport const gradientString = _gradientString(...defaultColors);\n\nconst logPrefix = gradientString('HeroUI CLI:');\n\nexport type PrefixLogType = Extract<\n keyof typeof Logger,\n 'error' | 'gradient' | 'info' | 'log' | 'warn' | 'success'\n>;\nexport class Logger {\n constructor() {}\n\n static log(...args: Parameters<typeof console.log>) {\n console.log(...args);\n }\n\n static info(...args: Parameters<typeof console.info>) {\n console.info(...args.map((item) => chalk.blue(item)));\n }\n\n static success(...args: Parameters<typeof console.info>) {\n console.info(...args.map((item) => chalk.green(item)));\n }\n\n static warn(...args: Parameters<typeof console.warn>) {\n console.warn(...args.map((item) => chalk.yellow(item)));\n }\n\n static error(...args: Parameters<typeof console.error>) {\n console.error(...args.map((item) => chalk.red(item)));\n }\n\n static grey(...args: Parameters<typeof console.log>) {\n console.log(...args.map((item) => chalk.gray(item)));\n }\n\n static gradient(content: string | number | boolean, options?: {colors?: tinycolor.ColorInput[]}) {\n this.log(_gradientString(...(options?.colors ?? defaultColors))(String(content)));\n }\n\n static prefix(type: PrefixLogType, ...args: SAFE_ANY) {\n return this[type](logPrefix, ...args);\n }\n\n static newLine(lines?: number) {\n if (!lines) lines = 1;\n\n for (let i = 0; i < lines; i++) this.log();\n }\n}\n","import type {AppendKeyValue} from './type';\n\nimport {type CommonExecOptions, execSync} from 'node:child_process';\n\nimport {Logger} from './logger';\nimport {omit} from './utils';\n\nconst execCache = new Map<string, string>();\n\n/**\n * Execute a command and return the output\n *\n * Recommend use `getCacheExecData` instead if you want to cache the output\n */\nexport async function exec(\n cmd: string,\n commonExecOptions?: AppendKeyValue<CommonExecOptions, 'logCmd', boolean> & {\n cache?: boolean;\n }\n) {\n return new Promise((resolve, reject) => {\n try {\n const {cache = true, logCmd = true} = commonExecOptions || {};\n\n if (execCache.has(cmd) && cache) {\n resolve(execCache.get(cmd));\n }\n\n if (logCmd) {\n Logger.newLine();\n Logger.log(`${cmd}`);\n }\n\n const stdout = execSync(cmd, {\n stdio: 'inherit',\n ...(commonExecOptions ? omit(commonExecOptions, ['logCmd']) : {})\n });\n\n if (stdout) {\n const output = stdout.toString();\n\n resolve(output);\n execCache.set(cmd, output);\n }\n resolve('');\n } catch (error) {\n reject(error);\n }\n });\n}\n","import type {Agent} from './detect';\nimport type {PascalCase, SAFE_ANY} from './type';\n\nimport chalk from 'chalk';\nimport {compareVersions} from 'compare-versions';\nimport fg, {type Options} from 'fast-glob';\n\nimport {ROOT} from 'src/constants/path';\n\nimport {Logger} from './logger';\nimport {colorMatchRegex} from './output-info';\n\nexport const versionModeRegex = /([\\^~])/;\n\nexport function getCommandDescAndLog(log: string, desc: string) {\n Logger.gradient(log);\n\n return desc;\n}\n\n/**\n * Convert a string to PascalCase.\n * @example 'test-test' => 'TestTest'\n * @param str\n */\nexport function PasCalCase<T extends string>(str: T) {\n return str\n .split('-')\n .map((s) => s.charAt(0).toUpperCase() + s.slice(1))\n .join('') as PascalCase<T>;\n}\n\n/**\n * Find files by glob pattern.\n * @param glob\n * @param options\n */\nexport const findFiles = (glob: string, options?: Options) => {\n const file = fg.sync(glob, {\n absolute: true,\n cwd: ROOT,\n deep: 5,\n ignore: ['node_modules/**', 'dist/**', 'build/**', 'coverage/**', 'public/**', 'out/**'],\n onlyFiles: true,\n ...options\n });\n\n return file;\n};\n\nexport function transformOption(options: boolean | 'false') {\n if (options === 'false') return false;\n\n return !!options;\n}\n\nexport function omit(obj: Record<string, SAFE_ANY>, keys: string[]) {\n return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key)));\n}\n\nexport function getUpgradeType({\n major,\n minor,\n patch\n}: {\n major: boolean;\n minor: boolean;\n patch: boolean;\n}) {\n if (major) return 'major';\n if (minor) return 'minor';\n if (patch) return 'patch';\n\n return 'minor';\n}\n\nexport function getColorVersion(currentVersion: string, latestVersion: string) {\n currentVersion = transformPeerVersion(currentVersion);\n latestVersion = transformPeerVersion(latestVersion);\n\n if (isMajorUpdate(currentVersion, latestVersion)) {\n return isMajorUpdate(currentVersion, latestVersion);\n } else if (isMinorUpdate(currentVersion, latestVersion)) {\n return isMinorUpdate(currentVersion, latestVersion);\n } else if (isPatchUpdate(currentVersion, latestVersion)) {\n return isPatchUpdate(currentVersion, latestVersion);\n }\n\n return latestVersion;\n}\n\nexport function isMajorUpdate(currentVersion: string, latestVersion: string) {\n const currentVersionArr = currentVersion.split('.');\n const latestVersionArr = latestVersion.split('.');\n\n if (currentVersionArr[0] !== latestVersionArr[0]) {\n return chalk.redBright(latestVersionArr.join('.'));\n }\n\n return '';\n}\n\nexport function isMinorUpdate(currentVersion: string, latestVersion: string) {\n const currentVersionArr = currentVersion.split('.');\n const latestVersionArr = latestVersion.split('.');\n\n if (currentVersionArr[1] !== latestVersionArr[1]) {\n return `${chalk.white(latestVersionArr[0])}${chalk.white('.')}${chalk.cyanBright(\n latestVersionArr.slice(1).join('.')\n )}`;\n }\n\n return '';\n}\n\nexport function isPatchUpdate(currentVersion: string, latestVersion: string) {\n const currentVersionArr = currentVersion.split('.');\n const latestVersionArr = latestVersion.split('.');\n\n if (currentVersionArr[2] !== latestVersionArr[2]) {\n return `${chalk.white(latestVersionArr.slice(0, 2).join('.'))}${chalk.white(\n '.'\n )}${chalk.greenBright(latestVersionArr.slice(2).join('.'))}`;\n }\n\n return '';\n}\n\nexport function getVersionAndMode(allDependencies: Record<string, SAFE_ANY>, packageName: string) {\n const currentVersion = allDependencies[packageName].replace(versionModeRegex, '');\n const versionMode = allDependencies[packageName].match(versionModeRegex)?.[1] || '';\n\n return {\n currentVersion,\n versionMode\n };\n}\n\nexport function getPackageManagerInfo<T extends Agent = Agent>(packageManager: T) {\n const packageManagerInfo = {\n bun: {\n install: 'add',\n remove: 'remove',\n run: 'run'\n },\n npm: {\n install: 'install',\n remove: 'uninstall',\n run: 'run'\n },\n pnpm: {\n install: 'add',\n remove: 'remove',\n run: 'run'\n },\n yarn: {\n install: 'add',\n remove: 'remove',\n run: 'run'\n }\n } as const;\n\n return packageManagerInfo[packageManager] as (typeof packageManagerInfo)[T];\n}\n\n/**\n * @example transformPeerVersion('>=1.0.0') // '1.0.0'\n * @example transformPeerVersion(\">=11.5.6 || >=12.0.0-alpha.1\") // 11.5.6\n * @param version\n */\nexport function transformPeerVersion(version: string, isLatest = false) {\n const ranges = version.split('||').map((r) => r.trim());\n const result = ranges\n .map((range) => {\n return range.replace(/^[<=>^~]+\\s*/, '').trim();\n })\n .sort((a, b) => {\n if (isLatest) {\n return compareVersions(b, a);\n }\n\n return compareVersions(a, b);\n });\n\n return result[0]!;\n}\n\nexport function fillAnsiLength(str: string, length: number) {\n const stripStr = str.replace(colorMatchRegex, '');\n const fillSpace = length - stripStr.length > 0 ? ' '.repeat(length - stripStr.length) : '';\n\n return `${str}${fillSpace}`;\n}\n\nexport function strip(str: string) {\n return str.replace(colorMatchRegex, '');\n}\n","import type {ChalkColor, CommandName} from './type';\n\nimport chalk from 'chalk';\n\nimport {boxRound} from 'src/constants/box';\nimport {\n type HeroUIComponent,\n type HeroUIComponents,\n colorHeroUIComponentKeys,\n orderHeroUIComponentKeys\n} from 'src/constants/component';\n\nimport {Logger} from './logger';\nimport {PasCalCase, fillAnsiLength, strip} from './utils';\n\n// eslint-disable-next-line no-control-regex\nexport const colorMatchRegex = /\\u001b\\[[\\d;]+m/g;\n\nconst rounded = boxRound.round;\nconst space = ' ';\nconst padStart = `${rounded.vertical}${space}`;\nconst padEnd = `${space}${rounded.vertical}${space}`;\nconst versionRegex = /([\\W\\w]+)\\snew:/;\nconst newVersionRegex = /new:\\s([\\W\\w]+)/;\n\n/**\n * Output the components information e.g. status, description, version, etc.\n * @param components\n * @param commandName\n * @param warnError\n */\nexport function outputComponents({\n commandName,\n components,\n message = 'Current installed components:\\n',\n warnError = true\n}: {\n components: HeroUIComponents;\n commandName?: CommandName;\n warnError?: boolean;\n message?: string;\n}) {\n if (!components.length) {\n if (warnError) {\n Logger.prefix('warn', 'No components found');\n }\n\n return;\n }\n\n const componentKeyLengthMap: Record<keyof HeroUIComponent | 'originVersion', number> = {\n description: 0,\n docs: 0,\n name: 0,\n originVersion: 0,\n package: 0,\n peerDependencies: 0,\n status: 0,\n style: 0,\n version: 0\n };\n\n for (const component of components) {\n for (const key in component) {\n const str = String(component[key]);\n\n if (key === 'version') {\n const newVersion = str.match(newVersionRegex)?.[1];\n const currentVersion = str.match(versionRegex)?.[1];\n\n const value = strip(generateComponentOutputVersion(currentVersion!, newVersion!));\n\n // Align the length of the version\n componentKeyLengthMap[key] = Math.max(\n componentKeyLengthMap[key],\n Math.max(value.length, 'version'.length)\n );\n // Record origin version length\n componentKeyLengthMap.originVersion = Math.max(\n componentKeyLengthMap.originVersion,\n currentVersion!.length\n );\n\n continue;\n }\n\n componentKeyLengthMap[key] = Math.max(componentKeyLengthMap[key], str.length);\n }\n }\n\n let transformComponentsOutput = components.reduce((acc, component) => {\n let outputData = padStart;\n\n for (const key of orderHeroUIComponentKeys) {\n let value = fillAnsiLength(component[key], componentKeyLengthMap[key]);\n\n /** ======================== Replace version to new version ======================== */\n if (commandName !== 'list' && key === 'version') {\n // Filter list command cause it will list all the latest components\n const currentVersion = value.match(versionRegex)?.[1]?.trim();\n const newVersion = value.match(newVersionRegex)?.[1]?.trim();\n\n if (currentVersion === newVersion) {\n value = value.replace(/\\snew:\\s[\\W\\w]+(\\s+)?/, '');\n value = fillAnsiLength(\n `${fillAnsiLength(value, componentKeyLengthMap.originVersion)} 🚀latest`,\n componentKeyLengthMap[key]\n );\n value = value.replace('latest', chalk.magentaBright.underline('latest'));\n } else if (newVersion) {\n value = fillAnsiLength(\n generateComponentOutputVersion(\n fillAnsiLength(currentVersion!, componentKeyLengthMap.originVersion),\n newVersion\n ),\n componentKeyLengthMap[key]\n );\n }\n }\n\n /** ======================== Change the color according to different status ======================== */\n if (component.status === 'stable' && colorHeroUIComponentKeys.includes(key)) {\n value = chalk.greenBright(value);\n } else if (component.status === 'new') {\n value = chalk.magentaBright(value);\n } else if (component.status === 'updated') {\n value = chalk.blueBright(value);\n }\n\n outputData += value + padEnd;\n }\n\n outputData;\n\n acc.push(outputData);\n\n return acc;\n }, [] as string[]);\n\n /** ======================== Generate box header ======================== */\n let boxHeader = rounded.topLeft + padStart.replace(/.*/g, rounded.horizontal).slice(1);\n let boxHeaderSec = padStart;\n let boxHeaderTrd = rounded.vertical + padStart.replace(/.*/g, rounded.horizontal).slice(1);\n\n for (const key of orderHeroUIComponentKeys) {\n boxHeader += `${rounded.horizontal.padEnd(componentKeyLengthMap[key] + 7, rounded.horizontal)}`;\n boxHeaderSec += chalk.redBright(PasCalCase(key).padEnd(componentKeyLengthMap[key])) + padEnd;\n boxHeaderTrd += `${rounded.horizontal.padEnd(\n componentKeyLengthMap[key] + 7,\n rounded.horizontal\n )}`;\n }\n\n boxHeader = boxHeader.slice(0, -2) + rounded.topRight;\n boxHeaderTrd = boxHeaderTrd.slice(0, -2) + rounded.vertical;\n\n /** ======================== Generate box footer ======================== */\n let boxFooter = rounded.bottomLeft + padStart.replace(/.*/g, rounded.horizontal).slice(1);\n\n for (const key of orderHeroUIComponentKeys) {\n boxFooter += `${rounded.horizontal.padEnd(componentKeyLengthMap[key] + 7, rounded.horizontal)}`;\n }\n\n boxFooter = boxFooter.slice(0, -2) + rounded.bottomRight;\n\n transformComponentsOutput = [\n boxHeader,\n boxHeaderSec,\n boxHeaderTrd,\n ...transformComponentsOutput,\n boxFooter\n ];\n\n Logger.info(message);\n\n Logger.log(transformComponentsOutput.join('\\n'));\n}\n\n/**\n * Output the environment information e.g. OS, CPU, Node version, etc.\n */\nexport function outputInfo() {\n Logger.newLine();\n Logger.log(chalk.redBright('Environment Info:'));\n Logger.log(chalk.blueBright(' System:'));\n Logger.log(chalk.blueBright(' OS:'), process.platform);\n Logger.log(chalk.blueBright(' CPU:'), process.arch);\n Logger.log(chalk.greenBright(' Binaries:'));\n Logger.log(chalk.greenBright(' Node:'), process.version);\n Logger.newLine();\n}\n\n/**\n * Output a box with the content\n * @param text\n * @param center\n * @param log\n * @param color\n * @param title\n * @param borderStyle\n * @param padding\n * @param align\n */\nexport function outputBox({\n align = 'center',\n borderStyle = 'round',\n center = false,\n color,\n log = true,\n padding = 0,\n text,\n title\n}: {\n text: string;\n center?: boolean;\n log?: boolean;\n color?: ChalkColor;\n title?: string;\n borderStyle?: keyof typeof boxRound;\n padding?: number;\n align?: 'left' | 'center' | 'right';\n}) {\n const rounded = boxRound[borderStyle];\n const mergedRounded = color\n ? Object.fromEntries(Object.entries(rounded).map(([key, value]) => [key, chalk[color](value)]))\n : rounded;\n const contentArr = text.split('\\n');\n const transformArr = contentArr.map((c) => c.replace(colorMatchRegex, ''));\n\n const isPadding = padding > 0;\n const paddingLength = padding;\n\n const mergedPadding = center || isPadding;\n\n let maxLength = transformArr.reduce((acc, cur) => (cur.length > acc ? cur.length : acc), 0);\n\n // Update the padding maxLength\n // paddingLength * 2 because one vertical line == 4 spaces\n maxLength = isPadding ? maxLength + paddingLength * 4 : maxLength;\n\n const clearColorTitle = title ? title.replace(colorMatchRegex, '') : '';\n const titleLength = title ? clearColorTitle.length : 0;\n let titleHeaderLength = maxLength - titleLength;\n const spaceLen = 2;\n\n while (titleLength + spaceLen + paddingLength >= maxLength) {\n // Need to adjust the maxLength\n maxLength += Math.floor(titleLength / 2);\n }\n // Update the titleHeaderLength\n titleHeaderLength = maxLength - titleLength;\n\n const boxHeaderContent = (() => {\n if (title) {\n if (align === 'center') {\n const spaceFir = Math.floor(titleHeaderLength / 2) - 1;\n const spaceSec = Math.ceil(titleHeaderLength / 2) - 1;\n\n const padFir = spaceFir > 0 ? mergedRounded.horizontal.repeat(spaceFir) : '';\n const padSec = spaceSec > 0 ? mergedRounded.horizontal.repeat(spaceSec) : '';\n\n return `${padFir} ${title} ${padSec}`;\n } else if (align === 'left') {\n return ` ${title} ${mergedRounded.horizontal.repeat(titleHeaderLength - 2)}`;\n } else {\n return `${mergedRounded.horizontal.repeat(titleHeaderLength - 2)} ${title} `;\n }\n }\n\n return mergedRounded.horizontal.repeat(maxLength);\n })();\n\n const boxHeader = mergedRounded.topLeft + boxHeaderContent + mergedRounded.topRight;\n const boxFooter =\n mergedRounded.bottomLeft +\n mergedRounded.horizontal.repeat(maxLength) +\n mergedRounded.bottomRight;\n\n let boxContent = contentArr.reduce((acc, cur) => {\n const transformCur = cur.replace(colorMatchRegex, '');\n const spaceLength = maxLength - transformCur.length;\n\n const pad = ' '.repeat(spaceLength);\n\n const spaceFir = Math.floor(spaceLength / 2);\n const spaceSec = Math.ceil(spaceLength / 2);\n\n const padFir = spaceFir > 0 ? ' '.repeat(spaceFir) : '';\n const padSec = spaceSec > 0 ? ' '.repeat(spaceSec) : '';\n\n // Over 2 cause one vertical line == 2 spaces\n // paddingLength = Math.floor(Math.max(paddingLength, spaceFir, spaceSec) / 2);\n\n if (center) {\n acc.push(\n `${mergedRounded.vertical}${spaceLength ? `${padFir}${cur}${padSec}` : cur}${\n mergedRounded.vertical\n }`\n );\n } else if (padding) {\n const endLen = spaceLength - paddingLength * 2;\n\n acc.push(\n `${mergedRounded.vertical}${' '.repeat(paddingLength * 2)}${cur}${' '.repeat(endLen)}${\n mergedRounded.vertical\n }`\n );\n } else {\n acc.push(\n `${mergedRounded.vertical}${spaceLength > 0 ? `${cur}${pad}` : cur}${\n mergedRounded.vertical\n }`\n );\n }\n\n return acc;\n }, [] as string[]);\n\n // Generate the padding\n if (mergedPadding) {\n for (let i = 0; i < paddingLength; i++) {\n boxContent.unshift(\n `${mergedRounded.vertical}${' '.repeat(maxLength)}${mergedRounded.vertical}`\n );\n boxContent.push(`${mergedRounded.vertical}${' '.repeat(maxLength)}${mergedRounded.vertical}`);\n }\n }\n\n boxContent = [boxHeader, ...boxContent, boxFooter];\n\n log && Logger.log(boxContent.join('\\n'));\n\n return boxContent.join('\\n');\n}\n\nfunction generateComponentOutputVersion(currentVersion: string, newVersion: string) {\n return `${chalk.white(`${currentVersion} ->`)} ${chalk.yellowBright(`${newVersion} (new)`)}`;\n}\n\nexport function outputDeprecatedInfo() {\n outputBox({\n color: 'yellow',\n padding: 1,\n text: `NextUI has rebranded to HeroUI! These packages are deprecated and won’t receive updates.\nHeroUI offers the same great features with ongoing improvements.\n\n→ ${chalk.bold('Switch to [HeroUI](https://heroui.com) for the latest updates.')}\n→ ${chalk.bold('Migration guide:')} [NextUI to HeroUI](https://heroui.com/docs/nextui-to-heroui)\n→ ${chalk.bold('New NPM package:')} \"@heroui/react\"\n\nThanks for your support — see you at HeroUI!`,\n title: chalk.yellow(`❗️ Notice: NextUI is now ${chalk.bold('HeroUI')} ❗️`)\n });\n}\n","export const boxRound = {\n bold: {\n bottomLeft: '┗',\n bottomRight: '┛',\n horizontal: '━',\n topLeft: '┏',\n topRight: '┓',\n vertical: '┃'\n },\n classic: {\n bottomLeft: '+',\n bottomRight: '+',\n horizontal: '-',\n topLeft: '+',\n topRight: '+',\n vertical: '|'\n },\n double: {\n bottomLeft: '╚',\n bottomRight: '╝',\n horizontal: '═',\n topLeft: '╔',\n topRight: '╗',\n vertical: '║'\n },\n doubleSingle: {\n bottomLeft: '╘',\n bottomRight: '╛',\n horizontal: '═',\n topLeft: '╒',\n topRight: '╕',\n vertical: '│'\n },\n round: {\n bottomLeft: '╰',\n bottomRight: '╯',\n horizontal: '─',\n topLeft: '╭',\n topRight: '╮',\n vertical: '│'\n },\n single: {\n bottomLeft: '└',\n bottomRight: '┘',\n horizontal: '─',\n topLeft: '┌',\n topRight: '┐',\n vertical: '│'\n },\n singleDouble: {\n bottomLeft: '╙',\n bottomRight: '╜',\n horizontal: '─',\n topLeft: '╓',\n topRight: '╖',\n vertical: '║'\n }\n};\n","import type {SAFE_ANY} from '@helpers/type';\n\nimport {existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync} from 'node:fs';\n\nimport {oraExecCmd} from '../helpers';\nimport {CACHE_DIR, CACHE_PATH} from '../path';\n\nconst cacheTTL = 30 * 60_000; // 30min\nlet noCache = false;\n\nexport interface CacheData {\n [packageName: string]: {\n version: string;\n date: Date;\n formatDate: string;\n expiredDate: number;\n expiredFormatDate: string;\n execResult: SAFE_ANY;\n };\n}\n\nexport function initCache(_noCache = noCache) {\n noCache = !!_noCache;\n\n const isExistCache = existsSync(CACHE_DIR);\n\n if (isExistCache) return;\n\n mkdirSync(CACHE_DIR, {recursive: true});\n writeFileSync(CACHE_PATH, JSON.stringify({}), 'utf8');\n}\n\nexport function getCacheData(): CacheData {\n const data = readFileSync(CACHE_PATH, 'utf8');\n\n return JSON.parse(data);\n}\n\n/**\n * Used to cache unknown npm package expired time 30m\n * @packageName string\n */\nexport function cacheData(\n packageName: string,\n packageData: {\n version?: string;\n execResult?: SAFE_ANY;\n },\n cacheData?: CacheData\n) {\n initCache();\n\n const data = cacheData ?? getCacheData();\n const now = new Date();\n const expiredDate = +now + cacheTTL;\n\n data[packageName] = {\n ...(packageData as SAFE_ANY),\n date: now,\n expiredDate,\n expiredFormatDate: new Date(expiredDate).toString(),\n formatDate: now.toString()\n };\n\n writeFileSync(CACHE_PATH, JSON.stringify(data, undefined, 2), 'utf-8');\n}\n\nexport function removeCache() {\n unlinkSync(CACHE_DIR);\n}\n\nfunction now() {\n return +new Date();\n}\n\nfunction ttl(n: number) {\n return now() - n;\n}\n\nexport function isExpired(packageName: string, cacheData?: CacheData) {\n // If noCache then always return true\n if (noCache) return true;\n\n const data = cacheData ?? getCacheData();\n const pkgData = data[packageName];\n\n if (!pkgData?.expiredDate) return true;\n\n return ttl(pkgData.expiredDate) > 0;\n}\n\nexport async function getPackageVersion(packageName: string) {\n const data = getCacheData();\n const isExpiredPkg = isExpired(packageName, data);\n\n // If expired or don't exist then init data\n if (isExpiredPkg) {\n const version = await oraExecCmd(\n `npm view ${packageName} version`,\n `Fetching ${packageName} latest version`\n );\n\n const pkgVersion = {version};\n\n cacheData(packageName, pkgVersion, data);\n\n return pkgVersion;\n }\n\n return data[packageName]!;\n}\n\nexport async function getCacheExecData<T extends SAFE_ANY>(\n key: string,\n execMessage?: string\n): Promise<T> {\n const data = getCacheData();\n const isExpiredPkg = isExpired(key, data);\n\n // If expired or don't exist then init data\n if (isExpiredPkg) {\n const execResult = await oraExecCmd(key, execMessage);\n\n const result = {execResult};\n\n cacheData(key, result, data);\n\n return result.execResult;\n }\n\n return data[key]!.execResult;\n}\n","import type {SAFE_ANY} from '@helpers/type';\n\nimport {exec} from 'node:child_process';\nimport {existsSync, readFileSync, writeFileSync} from 'node:fs';\n\nimport retry from 'async-retry';\nimport chalk from 'chalk';\nimport {compareVersions as InternalCompareVersions, validate} from 'compare-versions';\nimport ora, {oraPromise} from 'ora';\n\nimport {Logger} from '@helpers/logger';\nimport {COMPONENTS_PATH} from 'src/constants/path';\nimport {getStore, getStoreSync, store} from 'src/constants/store';\n\nimport {getPackageVersion} from './cache/cache';\n\nexport type Dependencies = Record<string, string>;\n\nexport type Components = {\n name: string;\n package: string;\n version: string;\n docs: string;\n description: string;\n status: string;\n style: string;\n peerDependencies: Dependencies;\n}[];\n\nexport type ComponentsJson = {\n version: string;\n components: Components;\n betaComponents: Components;\n betaVersion: string;\n};\n\n/**\n * Compare two versions\n * @example compareVersions('1.0.0', '1.0.1') // -1\n * compareVersions('1.0.1', '1.0.0') // 1\n * compareVersions('1.0.0', '1.0.0') // 0\n * @param version1\n * @param version2\n */\nexport function compareVersions(version1 = '', version2 = '') {\n if (!validate(version1)) {\n // e.g. Current version is https://pkg.pr.new/@heroui/dropdown@4656 then just upgrade to latest version\n return -1;\n }\n try {\n return InternalCompareVersions(version1, version2);\n } catch {\n // Can't not support ('18 || 19.0.0-rc.0' received) temporary solution\n return 0;\n }\n}\n\nexport async function updateComponents() {\n if (!existsSync(COMPONENTS_PATH)) {\n // First time download the latest date from net\n await autoUpdateComponents();\n\n return;\n }\n\n const components = JSON.parse(readFileSync(COMPONENTS_PATH, 'utf-8')) as ComponentsJson;\n const currentVersion = components.version;\n const betaVersion = components.betaVersion;\n const latestVersion = await getStore('latestVersion');\n const latestBetaVersion = await getStore('betaVersion');\n\n if (\n compareVersions(currentVersion, latestVersion) === -1 ||\n (betaVersion && compareVersions(betaVersion, latestBetaVersion) === -1)\n ) {\n // After the first time, check the version and update\n await autoUpdateComponents(latestVersion, latestBetaVersion);\n }\n}\n\nexport async function getComponents() {\n let components: ComponentsJson = {} as ComponentsJson;\n\n await updateComponents();\n\n try {\n components = JSON.parse(readFileSync(COMPONENTS_PATH, 'utf-8')) as ComponentsJson;\n } catch (error) {\n new Error(`Get components.json error: ${error}`);\n }\n\n return components;\n}\n\nexport async function oraExecCmd(cmd: string, text?: string): Promise<SAFE_ANY> {\n text = text ?? `Executing ${cmd}`;\n\n const spinner = ora({\n // Open ctrl + c cancel\n discardStdin: false,\n spinner: {\n frames: [\n `⠋ ${chalk.gray(`${text}.`)}`,\n `⠙ ${chalk.gray(`${text}..`)}`,\n `⠹ ${chalk.gray(`${text}...`)}`,\n `⠸ ${chalk.gray(`${text}.`)}`,\n `⠼ ${chalk.gray(`${text}..`)}`,\n `⠴ ${chalk.gray(`${text}...`)}`,\n `⠦ ${chalk.gray(`${text}.`)}`,\n `⠧ ${chalk.gray(`${text}..`)}`,\n `⠇ ${chalk.gray(`${text}...`)}`,\n `⠏ ${chalk.gray(`${text}.`)}`\n ],\n interval: 150\n }\n });\n\n spinner.start();\n\n const result = await new Promise((resolve) => {\n exec(cmd, (error, stdout) => {\n if (error) {\n Logger.error(`Exec cmd ${cmd} error`);\n process.exit(1);\n }\n resolve(stdout.trim());\n });\n });\n\n spinner.stop();\n\n return result;\n}\n\nexport async function getLatestVersion(packageName: string): Promise<string> {\n if (store.heroUIComponentsPackageMap[packageName]) {\n return store.heroUIComponentsPackageMap[packageName]!.version;\n }\n\n const result = await getPackageVersion(packageName);\n\n return result.version;\n}\n\nconst getUnpkgUrl = (version: string) =>\n `https://unpkg.com/@heroui/react@${version}/dist/components.json`;\n\nexport async function autoUpdateComponents(latestVersion?: string, betaVersion?: string) {\n [latestVersion, betaVersion] = await Promise.all([\n latestVersion || getStore('latestVersion'),\n betaVersion || getStore('betaVersion')\n ]);\n\n const url = getUnpkgUrl(latestVersion);\n\n const [components, betaComponents] = await Promise.all([\n downloadFile(url),\n getStoreSync('beta') && betaVersion\n ? downloadFile(getUnpkgUrl(betaVersion), false)\n : Promise.resolve([])\n ]);\n\n const filterMissingComponents = betaComponents.filter(\n (component) => !components.find((c) => c.name === component.name)\n );\n\n // Add missing beta components to components\n components.push(...filterMissingComponents);\n\n const componentsJson: ComponentsJson = {\n betaComponents,\n betaVersion,\n components,\n version: latestVersion\n };\n\n writeFileSync(COMPONENTS_PATH, JSON.stringify(componentsJson, null, 2), 'utf-8');\n\n return componentsJson;\n}\n\nexport async function downloadFile(url: string, log = true): Promise<Components> {\n let data;\n\n await oraPromise(\n retry(\n async (bail) => {\n try {\n const result = await fetch(url, {\n body: null,\n headers: {\n 'Content-Type': 'application/json',\n accept:\n 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'\n },\n method: 'GET',\n mode: 'cors'\n });\n\n data = JSON.parse(await result.text());\n } catch (error) {\n bail(error);\n }\n },\n {\n retries: 3\n }\n ),\n {\n failText(error) {\n log && Logger.prefix('error', `Update components data error: ${error}`);\n process.exit(1);\n },\n ...(log ? {successText: chalk.greenBright('Components data updated successfully!\\n')} : {}),\n text: 'Fetching components data...'\n }\n );\n\n return data;\n}\n\nexport const isGithubAction = process.env['CI'] === 'true';\n","import {existsSync} from 'node:fs';\nimport {fileURLToPath} from 'node:url';\n\nimport {join, resolve} from 'pathe';\n\nexport const ROOT = resolve(fileURLToPath(import.meta.url), '../..');\n\nexport const resolver = (path: string) => resolve(ROOT, path);\n\nconst PROD_DIR = resolve(fileURLToPath(import.meta.url), '..');\nconst PROD = existsSync(join(PROD_DIR, 'components.json'));\n\nexport const CACHE_DIR = PROD\n ? resolve(`${PROD_DIR}/.heroui-cli-cache`)\n : resolve(join(ROOT, '..'), 'node_modules/.heroui-cli-cache');\nexport const CACHE_PATH = resolve(`${CACHE_DIR}/data.json`);\n","import {store} from 'src/constants/store';\nimport {getCacheExecData} from 'src/scripts/cache/cache';\n\nimport {Logger} from './logger';\n\nexport async function getBetaVersionData(component: string) {\n const data = await getCacheExecData<string>(\n `npm view ${component} dist-tags --json`,\n `Fetching ${component} tags`\n );\n\n return data;\n}\n\nexport function getPrefixComponent(component: string) {\n return `@heroui/${component.replace('@heroui/', '')}`;\n}\n\nexport async function getBetaVersion(componentName: string) {\n if (store.betaHeroUIComponentsPackageMap[componentName]) {\n return store.betaHeroUIComponentsPackageMap[componentName]!.version;\n }\n\n const data = await getBetaVersionData(componentName);\n\n try {\n return JSON.parse(data).beta;\n } catch (error) {\n Logger.error(`Get beta version error: ${error}`);\n process.exit(1);\n }\n}\n\n/**\n * @example Input: [\"drawer\"]\n *\n * Return:\n * [\"@heroui/drawer@beta\"]\n */\nexport async function getBetaComponents(components: string[]) {\n const componentsVersionList = await Promise.all(\n components.map(getPrefixComponent).map(async (c) => {\n const version = await getBetaVersion(c);\n\n return `${getPrefixComponent(c)}@${version}`;\n })\n );\n\n return componentsVersionList;\n}\n","import {existsSync} from 'node:fs';\n\nimport fg from 'fast-glob';\nimport {join} from 'pathe';\n\nimport {getPackageInfo} from '@helpers/package';\n\nimport {type HeroUIComponent, type HeroUIComponents} from './component';\nimport {resolver} from './path';\n\nexport const HEROUI_CLI = 'heroui-cli';\n\nexport const FRAMER_MOTION = 'framer-motion';\nexport const TAILWINDCSS = 'tailwindcss';\nexport const HERO_UI = '@heroui/react';\nexport const THEME_UI = '@heroui/theme';\nexport const SYSTEM_UI = '@heroui/system';\nexport const ALL_COMPONENTS_REQUIRED = [HERO_UI, FRAMER_MOTION] as const;\nexport const HEROUI_PREFIX = '@heroui';\n\nexport const DOCS_INSTALLED = 'https://heroui.com/docs/guide/installation#global-installation';\nexport const DOCS_TAILWINDCSS_SETUP =\n 'https://heroui.com/docs/guide/installation#tailwind-css-setup';\nexport const DOCS_APP_SETUP = 'https://heroui.com/docs/guide/installation#provider-setup';\nexport const DOCS_PNPM_SETUP = 'https://heroui.com/docs/guide/installation#setup-pnpm-optional';\nexport const DOCS_PROVIDER_SETUP = 'https://heroui.com/docs/guide/installation#provider-setup';\n\n// Record the required content of tailwind.config file\nexport const tailwindRequired = {\n checkPluginsRegex: /heroui(([\\W\\w]+)?)/,\n content: './node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}',\n darkMode: 'darkMode: \"class\"',\n importContent: (isTypescript = false) => {\n if (isTypescript) {\n return `import {heroui} from '@heroui/theme';`;\n }\n\n return `const {heroui} = require('@heroui/theme');`;\n },\n plugins: 'heroui()'\n} as const;\n\nexport const individualTailwindRequired = {\n content: (currentComponents: HeroUIComponents, isPnpm: boolean) => {\n currentComponents.forEach((component) => {\n const walkDeps = walkDepComponents(component, isPnpm) as HeroUIComponents;\n\n currentComponents.push(...walkDeps);\n });\n\n const outputComponents = [\n ...new Set(\n currentComponents.map((component) => {\n return component.style || component.name;\n })\n )\n ];\n\n if (outputComponents.length === 1) {\n return `./node_modules/@heroui/theme/dist/components/${outputComponents[0]}.js`;\n }\n const requiredContent = outputComponents\n .reduce((acc, component) => {\n return (acc += `${component}|`);\n }, '')\n .replace(/\\|$/, '');\n\n return `./node_modules/@heroui/theme/dist/components/(${requiredContent}).js`;\n },\n plugins: 'heroui()'\n} as const;\n\nexport const appRequired = {\n import: 'HeroUIProvider'\n} as const;\n\nexport const pnpmRequired = {\n content: 'public-hoist-pattern[]=*@heroui/*'\n} as const;\n\nexport function walkDepComponents(heroUIComponent: HeroUIComponent, isPnpm: boolean) {\n const component = heroUIComponent.name;\n let componentPath = resolver(`node_modules/@heroui/${component}`);\n const components = [heroUIComponent];\n\n if (!existsSync(componentPath) && isPnpm) {\n const pnpmDir = resolver('node_modules/.pnpm');\n\n const file = fg.sync(`**/@heroui/${component}`, {\n absolute: true,\n cwd: pnpmDir,\n onlyDirectories: true\n })[0];\n\n if (file) {\n componentPath = file;\n } else {\n return components;\n }\n }\n\n const {currentComponents} = getPackageInfo(join(componentPath, 'package.json'));\n\n if (currentComponents.length) {\n for (const component of currentComponents) {\n const result = walkDepComponents(component, isPnpm);\n\n components.push(...result);\n }\n }\n\n return components;\n}\n","import type {UpgradeOption} from './actions/upgrade/upgrade-types';\n\nimport {readFileSync} from 'node:fs';\n\nimport {type HeroUIComponents} from 'src/constants/component';\nimport {HERO_UI} from 'src/constants/required';\nimport {store} from 'src/constants/store';\nimport {getCacheExecData} from 'src/scripts/cache/cache';\nimport {getLatestVersion} from 'src/scripts/helpers';\n\nimport {Logger} from './logger';\nimport {colorMatchRegex} from './output-info';\nimport {getVersionAndMode} from './utils';\n\n/**\n * Get the package information\n * @param packagePath string\n * @param transformVersion boolean\n */\nexport function getPackageInfo(packagePath: string, transformVersion = true) {\n let pkg;\n\n try {\n pkg = JSON.parse(readFileSync(packagePath, 'utf-8'));\n } catch (error) {\n Logger.prefix('error', `Error reading package.json file: ${packagePath} \\nError: ${error}`);\n }\n\n const devDependencies = pkg.devDependencies || {};\n const dependencies = pkg.dependencies || {};\n const allDependencies = {...devDependencies, ...dependencies};\n const allDependenciesKeys = new Set(Object.keys(allDependencies));\n\n const currentComponents = (store.heroUIComponents as unknown as HeroUIComponents)\n .map((component) => {\n let version = component.version;\n let versionMode = component.versionMode;\n\n if (allDependenciesKeys.has(component.package)) {\n const data = getVersionAndMode(allDependencies, component.package);\n\n version = transformVersion ? `${data.currentVersion} new: ${version}` : data.currentVersion;\n versionMode = data.versionMode;\n }\n\n return {\n ...component,\n version,\n versionMode\n };\n })\n .filter((component) => allDependenciesKeys.has(component.package)) as HeroUIComponents;\n const isAllComponents = allDependenciesKeys.has(HERO_UI);\n\n return {\n allDependencies,\n allDependenciesKeys,\n currentComponents,\n dependencies,\n devDependencies,\n isAllComponents,\n packageJson: pkg\n };\n}\n\nexport function transformComponentsToPackage(components: string[]) {\n return components.map((component) => {\n const herouiComponent = store.heroUIComponentsMap[component];\n const packageName = herouiComponent?.package;\n\n return packageName ? packageName : component;\n });\n}\n\n/**\n * Get the package detail information\n * @param components need package name\n * @param allDependencies\n * @returns\n */\nexport async function transformPackageDetail(\n components: string[],\n allDependencies: Record<string, string>,\n transformVersion = true\n): Promise<HeroUIComponents> {\n const result: HeroUIComponents = [];\n\n for (const component of components) {\n let {currentVersion} = getVersionAndMode(allDependencies, component);\n const {versionMode} = getVersionAndMode(allDependencies, component);\n const docs = (\n ((await getCacheExecData(`npm show ${component} homepage`)) || '') as string\n ).replace(/\\n/, '');\n const description = (\n ((await getCacheExecData(`npm show ${component} description`)) || '') as string\n ).replace(/\\n/, '');\n const latestVersion =\n store.heroUIComponentsPackageMap[component]?.version || (await getLatestVersion(component));\n\n currentVersion = transformVersion ? `${currentVersion} new: ${latestVersion}` : currentVersion;\n\n const detailPackageInfo: HeroUIComponents[0] = {\n description: description || '',\n docs: docs || '',\n name: component,\n package: component,\n peerDependencies: {},\n status: 'stable',\n style: '',\n version: currentVersion,\n versionMode: versionMode\n };\n\n result.push(detailPackageInfo);\n }\n\n return result;\n}\n\n/**\n * Get the complete version\n * @example getCompleteVersion({latestVersion: '1.0.0', versionMode: '^'}) --> '^1.0.0'\n */\nexport function getCompleteVersion(upgradeOption: UpgradeOption) {\n return `${upgradeOption.versionMode || ''}${upgradeOption.latestVersion.replace(\n colorMatchRegex,\n ''\n )}`;\n}\n","import type {ExtractStoreData, SAFE_ANY} from '@helpers/type';\n\nimport {getBetaVersion} from '@helpers/beta';\nimport {type Components, getLatestVersion} from 'src/scripts/helpers';\n\nimport {HEROUI_CLI, HERO_UI} from './required';\n\nexport type HeroUIComponentsMap = Record<string, Components[0]>;\n\nexport type Store = {\n debug: boolean;\n beta: boolean;\n cliLatestVersion: string;\n latestVersion: string;\n betaVersion: string;\n\n // HeroUI\n heroUIComponents: Components;\n heroUIComponentsKeys: string[];\n heroUIcomponentsPackages: string[];\n heroUIComponentsKeysSet: Set<string>;\n heroUIComponentsMap: HeroUIComponentsMap;\n heroUIComponentsPackageMap: HeroUIComponentsMap;\n\n // Beta HeroUI\n betaHeroUIComponents: Components;\n betaHeroUIIComponentsKeys: string[];\n betaHeroUIcomponentsPackages: string[];\n betaHeroUIComponentsKeysSet: Set<string>;\n betaHeroUIComponentsMap: HeroUIComponentsMap;\n betaHeroUIComponentsPackageMap: HeroUIComponentsMap;\n};\n\n/* eslint-disable sort-keys-fix/sort-keys-fix, sort-keys */\nexport const store = {\n debug: false,\n beta: false,\n cliLatestVersion: '',\n latestVersion: '',\n betaVersion: '',\n\n betaHeroUIComponents: [],\n betaHeroUIIComponentsKeys: [],\n betaHeroUIComponentsKeysSet: new Set(),\n betaHeroUIComponentsMap: {},\n betaHeroUIComponentsPackageMap: {},\n betaHeroUIcomponentsPackages: [],\n\n heroUIComponents: [],\n heroUIComponentsKeys: [],\n heroUIComponentsKeysSet: new Set(),\n heroUIComponentsMap: {},\n heroUIComponentsPackageMap: {},\n heroUIcomponentsPackages: []\n} as Store;\n/* eslint-enable sort-keys-fix/sort-keys-fix, sort-keys */\n\nexport type StoreKeys = keyof Store;\n\nexport async function getStore<T extends StoreKeys = StoreKeys>(\n key: T\n): Promise<ExtractStoreData<T>> {\n let data = store[key];\n\n if (!data) {\n if (key === 'latestVersion') {\n data = (await getLatestVersion(HERO_UI)) as SAFE_ANY;\n\n store[key] = data;\n } else if (key === 'cliLatestVersion') {\n data = (await getLatestVersion(HEROUI_CLI)) as SAFE_ANY;\n\n store[key] = data;\n } else if (key === 'betaVersion') {\n data = (await getBetaVersion(HERO_UI)) as SAFE_ANY;\n\n store[key] = data;\n }\n }\n\n return data as unknown as Promise<ExtractStoreData<T>>;\n}\n\nexport function getStoreSync<T extends StoreKeys = StoreKeys>(key: T) {\n return store[key] as unknown as ExtractStoreData<T>;\n}\n","import type {Components} from 'src/scripts/helpers';\n\nimport {store} from './store';\n\nexport function getHerouiComponentsData(heroUIComponents: Components) {\n const heroUIComponentsKeys = heroUIComponents.map((component) => component.name);\n const heroUIcomponentsPackages = heroUIComponents.map((component) => component.package);\n\n const heroUIComponentsKeysSet = new Set(heroUIComponentsKeys);\n\n const heroUIComponentsMap = heroUIComponents.reduce((acc, component) => {\n acc[component.name] = component;\n\n return acc;\n }, {} as HeroUIComponentsMap);\n const heroUIComponentsPackageMap = heroUIComponents.reduce((acc, component) => {\n acc[component.package] = component;\n\n return acc;\n }, {} as HeroUIComponentsMap);\n\n return {\n heroUIComponentsKeys,\n heroUIComponentsKeysSet,\n heroUIComponentsMap,\n heroUIComponentsPackageMap,\n heroUIcomponentsPackages\n };\n}\n\nexport function initStoreComponentsData({\n beta,\n heroUIComponents\n}: {\n beta: boolean;\n heroUIComponents: Components;\n}) {\n const {\n heroUIComponentsKeys,\n heroUIComponentsKeysSet,\n heroUIComponentsMap,\n heroUIComponentsPackageMap,\n heroUIcomponentsPackages\n } = getHerouiComponentsData(heroUIComponents);\n\n if (beta) {\n store.betaHeroUIComponents = heroUIComponents;\n store.betaHeroUIIComponentsKeys = heroUIComponentsKeys;\n store.betaHeroUIComponentsKeysSet = heroUIComponentsKeysSet;\n store.betaHeroUIComponentsMap = heroUIComponentsMap;\n store.betaHeroUIComponentsPackageMap = heroUIComponentsPackageMap;\n store.betaHeroUIcomponentsPackages = heroUIcomponentsPackages;\n } else {\n store.heroUIComponents = heroUIComponents;\n store.heroUIComponentsKeys = heroUIComponentsKeys;\n store.heroUIComponentsKeysSet = heroUIComponentsKeysSet;\n store.heroUIComponentsMap = heroUIComponentsMap;\n store.heroUIComponentsPackageMap = heroUIComponentsPackageMap;\n store.heroUIcomponentsPackages = heroUIcomponentsPackages;\n }\n}\n\nexport type HeroUIComponentsMap = Record<string, (typeof store.heroUIComponents)[number]>;\n\nexport const orderHeroUIComponentKeys = ['package', 'version', 'status', 'docs'] as const;\n\nexport const colorHeroUIComponentKeys = ['package', 'version', 'status'];\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport type HeroUIComponentStatus = 'stable' | 'updated' | 'new' | (string & {});\n\nexport type HeroUIComponent = (typeof store.heroUIComponents)[0];\n\nexport type HeroUIComponents = (Omit<HeroUIComponent, 'status'> & {\n status: HeroUIComponentStatus;\n versionMode: string;\n})[];\n\n/**\n * Get the component data\n * isBeta --> betaHeroUIComponents\n * isStable --> heroUIComponents\n */\nexport function getConditionComponentData() {\n if (store.beta) {\n return {\n components: store.betaHeroUIComponents,\n componentsKeys: store.betaHeroUIIComponentsKeys,\n componentsKeysSet: store.betaHeroUIComponentsKeysSet,\n componentsMap: store.betaHeroUIComponentsMap,\n componentsPackageMap: store.betaHeroUIComponentsPackageMap,\n componentsPackages: store.betaHeroUIcomponentsPackages\n };\n }\n\n return {\n components: store.heroUIComponents,\n componentsKeys: store.heroUIComponentsKeys,\n componentsKeysSet: store.heroUIComponentsKeysSet,\n componentsMap: store.heroUIComponentsMap,\n componentsPackageMap: store.heroUIComponentsPackageMap,\n componentsPackages: store.heroUIcomponentsPackages\n };\n}\n","import type {SAFE_ANY} from '@helpers/type';\n\nimport {readdirSync, statSync} from 'node:fs';\n\nimport {\n type ConfirmOptions,\n spinner as _spinner,\n cancel,\n confirm,\n isCancel,\n multiselect,\n select,\n text\n} from '@clack/prompts';\nimport chalk from 'chalk';\nimport {join} from 'pathe';\n\nexport const cancelClack = (value: SAFE_ANY) => {\n if (isCancel(value)) {\n cancel(`${chalk.red('✖')} Operation cancelled`);\n process.exit(0);\n }\n};\n\nexport const textClack: typeof text = async (opts) => {\n const result = (await text(opts)) as string;\n\n cancelClack(result);\n\n return result;\n};\n\nexport const selectClack: typeof select = async (opts) => {\n const result = await select(opts);\n\n cancelClack(result);\n\n return result;\n};\n\nexport const multiselectClack: typeof multiselect = async (opts) => {\n const result = await multiselect(opts);\n\n cancelClack(result);\n\n return result;\n};\n\nexport const spinner = _spinner();\n\nexport interface TaskClackOptions<T> {\n text: string;\n task: PromiseLike<T> | T;\n successText?: string;\n failText?: string;\n}\n\nexport const taskClack = async <T>(opts: TaskClackOptions<T>) => {\n const {failText, successText, task, text} = opts;\n\n let result: string | null = null;\n\n try {\n spinner.start(text);\n result = await (task instanceof Promise ? task : Promise.resolve(task));\n spinner.stop(successText);\n } catch (error) {\n cancel(failText ?? result ?? 'Task failed');\n process.exit(0);\n }\n\n return result;\n};\n\nexport const confirmClack = async (opts: ConfirmOptions) => {\n const result = await confirm(opts);\n\n cancelClack(result);\n\n return result;\n};\n\nexport const getDirectoryClack = async () => {\n const currentDirectories = readdirSync(process.cwd()).filter((dir) =>\n statSync(join(process.cwd(), dir)).isDirectory()\n );\n const options = currentDirectories\n .map((dir) => ({\n label: dir,\n value: dir\n }))\n .filter(\n (dir) =>\n !['node_modules', 'dist', 'build', 'output', /^\\./].some((ignore) => {\n if (typeof ignore === 'string') {\n return dir.value.includes(ignore);\n }\n\n return ignore.test(dir.value);\n })\n );\n const result = options.length\n ? await selectClack({\n message: 'Please select the directory to add the codebase',\n options\n })\n : 'src';\n\n return result as string;\n};\n","/**\n * Get the base storage url from the given url\n */\nexport async function getBaseStorageUrl(url: string) {\n const httpMatch = url.match(/^https?:\\/\\//)?.[0] ?? '';\n const [baseUrl, userId, chatId, sandboxId, chatTitle] = url.replace(httpMatch, '').split('/');\n\n const baseStorageUrl = `${httpMatch}${baseUrl}/sandbox/files/${chatId}?sandboxId=${sandboxId}`;\n\n return {\n baseStorageUrl,\n chatTitle,\n sandboxId,\n userId: userId ?? ''\n };\n}\n","import {basename} from 'node:path';\nimport {Readable} from 'node:stream';\nimport {pipeline} from 'node:stream/promises';\n\nimport retry from 'async-retry';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport tar from 'tar';\n\n/**\n * Fetch the tar stream from the specified URL.\n * @param url\n */\nasync function fetchTarStream(url: string) {\n const res = await fetch(url);\n\n if (!res.body) {\n throw new Error(`Failed to download: ${url}`);\n }\n\n return Readable.fromWeb(res.body);\n}\n\n/**\n * Download the template from the specified URL and extract it to the specified directory.\n * @param root\n * @param url\n */\nexport async function downloadTemplate(root: string, url: string) {\n await retry(\n async (bail) => {\n try {\n await pipeline(\n await fetchTarStream(url),\n tar.x({\n cwd: root\n })\n );\n } catch (error) {\n bail(new Error(`Failed to download ${url} Error: ${error}`));\n }\n },\n {\n retries: 3\n }\n );\n}\n\nexport async function fetchRequest(\n url: string,\n options?: RequestInit & {fetchInfo?: string; throwError?: boolean}\n): Promise<Response> {\n const {fetchInfo, throwError = true, ...rest} = options ?? {};\n const text = `Fetching ${fetchInfo ?? basename(url)}`;\n const spinner = ora({\n discardStdin: false,\n spinner: {\n frames: [\n `⠋ ${chalk.gray(`${text}.`)}`,\n `⠙ ${chalk.gray(`${text}..`)}`,\n `⠹ ${chalk.gray(`${text}...`)}`,\n `⠸ ${chalk.gray(`${text}.`)}`,\n `⠼ ${chalk.gray(`${text}..`)}`,\n `⠴ ${chalk.gray(`${text}...`)}`,\n `⠦ ${chalk.gray(`${text}.`)}`,\n `⠧ ${chalk.gray(`${text}..`)}`,\n `⠇ ${chalk.gray(`${text}...`)}`,\n `⠏ ${chalk.gray(`${text}.`)}`\n ],\n interval: 150\n }\n });\n\n spinner.start();\n\n try {\n return await retry(\n async () => {\n const response = await fetch(url, {\n ...rest,\n headers: {\n Accept: 'application/json',\n ...rest?.headers\n }\n });\n\n if (!response.ok && throwError) {\n throw new Error(`Request failed with status ${response.status}`);\n }\n\n return response;\n },\n {\n retries: 2\n }\n );\n } catch (error) {\n if (error instanceof Error && error.message.includes('fetch failed')) {\n throw new Error('Connection failed. Please check your network connection.');\n }\n\n throw error;\n } finally {\n spinner.stop();\n }\n}\n","import type {SAFE_ANY} from '@helpers/type';\n\nimport {fetchRequest} from '@helpers/fetch';\n\nexport const CODEBASE_FILES = [\n 'index.html',\n 'package.json',\n 'postcss.config.js',\n 'src/App.tsx',\n 'src/index.css',\n 'src/main.tsx',\n 'tailwind.config.js',\n 'tsconfig.json',\n 'vite.config.ts'\n];\n\nexport interface CodeBaseFile {\n name: string;\n type: 'file' | 'directory';\n isSymlink: boolean;\n content: string;\n}\n\nexport async function getCodeBaseFiles(url: string, userId: string): Promise<CodeBaseFile[]> {\n const response = await fetchRequest(url, {\n fetchInfo: 'codebase files',\n headers: {userId}\n });\n\n const data = await response.json();\n\n return ((data as SAFE_ANY).entries ?? {}) as CodeBaseFile[];\n}\n","import type {CodeBaseFile} from './get-codebase-files';\n\nimport {basename} from 'node:path';\n\nimport {Logger} from '@helpers/logger';\nimport {getMatchImport} from '@helpers/match';\n\nexport function getRelatedImports(fileContent: string) {\n const matchImport = getMatchImport(fileContent);\n const result = matchImport\n .map((imports) => imports.find((target) => target.includes('./')))\n .filter(Boolean);\n\n return result as string[];\n}\n\nexport interface FetchAllRelatedFilesParams {\n content: string;\n entries: CodeBaseFile[];\n filePath: string;\n}\n\nexport async function fetchAllRelatedFiles(params: FetchAllRelatedFilesParams) {\n const {content: fileContent, entries, filePath} = params;\n const result: {filePath: string; fileContent: string; fileName: string}[] = [];\n\n async function fetchRelatedImports(fileContent: string) {\n const relatedImports = getRelatedImports(fileContent);\n\n if (relatedImports.length === 0) return;\n\n // Add related imports\n await Promise.all(\n relatedImports.map(async (relatedPath) => {\n const targetFile = entries?.find((file) => {\n return basename(file.name).includes(basename(relatedPath));\n });\n const suffix = targetFile?.name.split('.').pop();\n const fileName = `${relatedPath.split('/').pop()}`;\n const filePath = `src/${relatedPath.replace(/.*?\\//, '')}${suffix ? `.${suffix}` : ''}`;\n\n if (result.some((file) => file.fileName === fileName)) return;\n\n const fileContent = targetFile?.content ?? '';\n\n result.push({\n fileContent,\n fileName,\n filePath\n });\n\n await fetchRelatedImports(fileContent);\n })\n );\n }\n\n try {\n await fetchRelatedImports(fileContent);\n\n result.push({\n fileContent,\n fileName: filePath.split('/').pop()!,\n filePath\n });\n } catch (error) {\n Logger.error(error);\n process.exit(1);\n }\n\n return result;\n}\n","/**\n * Get the content of the key in the target string.\n * @example getMatchImport('import {test} from \"source\"') => [['test', 'source']]\n * @param str\n */\nexport function getMatchImport(str: string) {\n const importRegexAll = /import {?\\s*([\\W\\w]+?)\\s*}? from [\"'](.+)[\"']/g;\n\n const matchAll = str.match(importRegexAll) ?? [];\n const result: string[][] = [];\n\n for (const item of matchAll) {\n result.push(matchImport(item));\n }\n\n return result.length ? result : [];\n\n function matchImport(itemImport: string) {\n const importRegex = /import {?\\s*([\\W\\w]+?)\\s*}? from [\"'](.+)[\"']/;\n const match = itemImport.match(importRegex) ?? [];\n\n return [match[1] ?? '', match[2] ?? ''];\n }\n}\n\nfunction removeQuote(str: string) {\n return str.replace(/^[\"'`](.*)[\"'`]$/, '$1');\n}\n\n/**\n * Get the array content of the key in the target string.\n * @example getMatchArray('key', 'key: [a, b, c]') => ['a', 'b', 'c']\n * @param key\n * @param target\n */\nexport function getMatchArray(key: string, target: string) {\n const mixinReg = new RegExp(`\\\\s*${key}:\\\\s\\\\[([\\\\w\\\\W]*?)\\\\]\\\\s*`);\n\n if (mixinReg.test(target))\n return (\n target\n .match(mixinReg)?.[1]\n ?.split(/,\\s/g)\n .map((i) => removeQuote(i.trim()))\n .filter(Boolean) ?? []\n );\n\n return [];\n}\n\n/**\n * Replace the array content of the key in the target string.\n * @example replaceMatchArray('key', 'key: [a, b, c]', ['d', 'e', 'f']) => 'key: [d, e, f]'\n * @param key\n * @param target\n * @param value\n */\nexport function replaceMatchArray(\n key: string,\n target: string,\n value: string[],\n _replaceValue?: string\n) {\n const mixinReg = new RegExp(`\\\\s*${key}:\\\\s\\\\[([\\\\w\\\\W]*?)\\\\]\\\\s*`);\n const replaceValue = _replaceValue ?? value.map((v) => JSON.stringify(v)).join(', ');\n\n if (mixinReg.test(target)) {\n const _value = key === 'content' ? `\\n ${key}: [${replaceValue}]` : `\\n ${key}: [${value}]`;\n\n return target.replace(mixinReg, _value);\n }\n\n // If the key does not exist, add the key and value to the end of the target\n const targetArray = target.split('\\n');\n const contentIndex = targetArray.findIndex((item) => item.includes('content:'));\n const moduleIndex = targetArray.findIndex((item) => item.includes('module.exports ='));\n const insertIndex = contentIndex !== -1 ? contentIndex - 1 : moduleIndex !== -1 ? moduleIndex : 0;\n\n key === 'content'\n ? targetArray.splice(insertIndex + 1, 0, ` ${key}: [${replaceValue}],`)\n : targetArray.splice(insertIndex + 1, 0, ` ${key}: [${value.map((v) => removeQuote(v))}],`);\n\n return targetArray.join('\\n');\n}\n","import fs from 'node:fs';\n\nexport function writeFilesWithMkdir(directory: string, file: string, content: string) {\n if (file.includes('/')) {\n const path = file.split('/').slice(0, -1).join('/');\n\n fs.mkdirSync(`${directory}/${path}`, {recursive: true});\n fs.writeFileSync(`${directory}/${file}`, content, 'utf8');\n } else {\n fs.writeFileSync(`${directory}/${file}`, content, 'utf8');\n }\n}\n","import {Logger} from './logger';\n\nfunction matchTextScore(text: string, pattern: string) {\n let score = 0;\n const textLength = text.length;\n const patternLength = pattern.length;\n let i = 0;\n let j = 0;\n\n while (i < textLength && j < patternLength) {\n if (text[i] === pattern[j]) {\n score++;\n j++;\n }\n\n i++;\n }\n\n return score;\n}\n\nexport function findMostMatchText(list: string[], pattern: string) {\n let maxScore = 0;\n let result = '';\n\n for (const text of list) {\n const score = matchTextScore(text, pattern);\n\n if (score > maxScore) {\n maxScore = score;\n result = text;\n }\n }\n\n return result !== '' ? result : null;\n}\n\nexport function printMostMatchText(list: string[], pattern: string) {\n const mathOption = findMostMatchText(list, pattern);\n\n if (mathOption) {\n Logger.error(`Unknown option '${pattern}', Did you mean '${mathOption}'?`);\n } else {\n Logger.error(`Unknown option '${pattern}'`);\n }\n process.exit(1);\n}\n","{\n \"name\": \"heroui-cli\",\n \"private\": false,\n \"type\": \"module\",\n \"license\": \"MIT\",\n \"version\": \"1.2.3\",\n \"homepage\": \"https://github.com/heroui-inc/heroui-cli#readme\",\n \"description\": \"A CLI tool that unlocks seamless HeroUI integration (Previously NextUI CLI)\",\n \"keywords\": [\n \"UI\",\n \"CLI\",\n \"Tool\",\n \"NextUI\",\n \"Template\",\n \"Integration\",\n \"Add Component\",\n \"HeroUI\"\n ],\n \"author\": {\n \"name\": \"HeroUI\",\n \"email\": \"support@heroui.com\",\n \"url\": \"https://github.com/heroui-inc\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/heroui-inc/heroui-cli.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/heroui-inc/heroui-cli/issues\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n },\n \"files\": [\n \"dist\"\n ],\n \"bin\": {\n \"heroui\": \"./dist/index.js\"\n },\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"dev\": \"tsup --watch\",\n \"link:cli\": \"pnpm link --global\",\n \"link:remove\": \"pnpm uninstall --global heroui-cli\",\n \"build\": \"tsup\",\n \"update:components\": \"tsx src/scripts/update/update-components.ts\",\n \"sync:docs\": \"tsx src/scripts/sync/sync.ts\",\n \"clean:cache\": \"tsx src/scripts/cache/clean.ts\",\n \"lint\": \"eslint . --max-warnings=0\",\n \"lint:fix\": \"eslint . --max-warnings=0 --fix\",\n \"check:prettier\": \"prettier --check .\",\n \"check:types\": \"tsc --noEmit\",\n \"changelog\": \"npx conventional-changelog -p angular -i CHANGELOG.md -s --commit-path .\",\n \"release\": \"bumpp --execute='pnpm run changelog' --all\",\n \"prepare\": \"husky install\",\n \"prebuild\": \"pnpm run update:components\",\n \"prepublishOnly\": \"pnpm run build\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"0.7.0\",\n \"@winches/prompts\": \"0.0.7\",\n \"async-retry\": \"1.3.3\",\n \"chalk\": \"5.3.0\",\n \"commander\": \"11.0.0\",\n \"compare-versions\": \"6.1.1\",\n \"fast-glob\": \"3.3.2\",\n \"find-up\": \"7.0.0\",\n \"gradient-string\": \"2.0.2\",\n \"ora\": \"8.0.1\",\n \"pathe\": \"1.1.2\",\n \"tar\": \"6.2.1\"\n },\n \"devDependencies\": {\n \"@commitlint/cli\": \"17.7.1\",\n \"@commitlint/config-conventional\": \"17.7.0\",\n \"@types/gradient-string\": \"1.1.3\",\n \"@types/node\": \"20.11.30\",\n \"@typescript-eslint/eslint-plugin\": \"6.7.2\",\n \"@typescript-eslint/parser\": \"6.7.2\",\n \"bumpp\": \"9.4.0\",\n \"clean-package\": \"2.2.0\",\n \"commitlint-plugin-function-rules\": \"2.0.2\",\n \"conventional-changelog-cli\": \"4.1.0\",\n \"eslint\": \"8.50.0\",\n \"eslint-config-prettier\": \"9.0.0\",\n \"eslint-import-resolver-typescript\": \"3.6.1\",\n \"eslint-plugin-import\": \"2.28.1\",\n \"eslint-plugin-prettier\": \"5.0.0\",\n \"eslint-plugin-sort-destructure-keys\": \"1.5.0\",\n \"eslint-plugin-sort-keys-fix\": \"1.1.2\",\n \"eslint-plugin-unicorn\": \"52.0.0\",\n \"eslint-plugin-unused-imports\": \"3.0.0\",\n \"husky\": \"8.0.3\",\n \"lint-staged\": \"14.0.1\",\n \"prettier\": \"3.3.2\",\n \"tsup\": \"7.2.0\",\n \"tsx\": \"4.7.1\",\n \"typescript\": \"5.2.2\"\n },\n \"engines\": {\n \"pnpm\": \">=9.x\"\n },\n \"packageManager\": \"pnpm@9.6.0\"\n}\n","/* eslint-disable no-var */\nimport type {SAFE_ANY} from '@helpers/type';\n\nimport {existsSync, writeFileSync} from 'node:fs';\n\nimport chalk from 'chalk';\n\nimport {\n type AddActionOptions,\n addHeroChatCodebase,\n isAddingHeroChatCodebase\n} from '@helpers/actions/add/heroui-chat/add-hero-chat-codebase';\nimport {getBetaComponents} from '@helpers/beta';\nimport {\n checkApp,\n checkIllegalComponents,\n checkPnpm,\n checkRequiredContentInstalled,\n checkTailwind\n} from '@helpers/check';\nimport {debugAddedPkg, debugExecAddAction, debugRemovedPkg} from '@helpers/debug';\nimport {detect} from '@helpers/detect';\nimport {fixPnpm, fixProvider, fixTailwind} from '@helpers/fix';\nimport {Logger} from '@helpers/logger';\nimport {getPackageInfo} from '@helpers/package';\nimport {findFiles, strip} from '@helpers/utils';\nimport {resolver} from 'src/constants/path';\nimport {\n DOCS_PROVIDER_SETUP,\n HERO_UI,\n individualTailwindRequired,\n pnpmRequired\n} from 'src/constants/required';\nimport {getStoreSync, store} from 'src/constants/store';\nimport {tailwindTemplate} from 'src/constants/templates';\nimport {getAutocompleteMultiselect} from 'src/prompts';\n\nexport async function addAction(targets: string[], options: AddActionOptions) {\n if (isAddingHeroChatCodebase(targets)) {\n // Add HeroUI Chat codebase\n await addHeroChatCodebase(targets, options);\n process.exit(0);\n }\n\n const {\n addApp = false,\n all = false,\n appPath,\n beta = false,\n packagePath = resolver('package.json'),\n tailwindPath = findFiles('**/tailwind.config.(j|t)s')[0]\n } = options;\n\n var {allDependencies, allDependenciesKeys, currentComponents} = getPackageInfo(packagePath);\n const prettier = options.prettier ?? allDependenciesKeys.has('prettier');\n\n const isHeroUIAll = !!allDependencies[HERO_UI];\n\n if (!targets.length && !all) {\n const filteredComponents = store.heroUIComponents.filter(\n (component) =>\n !currentComponents.some((currentComponent) => currentComponent.name === component.name)\n );\n\n if (!filteredComponents.length) {\n Logger.success('✅ All components have been added');\n process.exit(0);\n }\n\n targets = await getAutocompleteMultiselect(\n 'Which components would you like to add?',\n filteredComponents.map((component) => {\n return {\n description: component.description,\n title: component.name,\n value: component.name\n };\n })\n );\n } else if (all) {\n targets = [HERO_UI];\n }\n\n /** ======================== Add judge whether illegal component exist ======================== */\n if (!all && !checkIllegalComponents(targets, true)) {\n return;\n }\n\n // Check whether have added the HeroUI components\n var {allDependenciesKeys, currentComponents} = getPackageInfo(packagePath);\n\n const currentComponentsKeys = currentComponents.map((c) => c.name);\n const filterCurrentComponents = targets.filter(\n (c) => currentComponentsKeys.includes(c) || (isHeroUIAll && c === HERO_UI)\n );\n\n if (filterCurrentComponents.length && !getStoreSync('debug')) {\n Logger.prefix(\n 'error',\n `❌ You have already added the following components: ${filterCurrentComponents\n .map((c) => chalk.underline(c))\n .join(', ')}`\n );\n\n return;\n }\n\n // Check whether the App.tsx file exists\n if (addApp && !appPath) {\n Logger.prefix(\n 'error',\n \"❌ App.(j|t)sx file not found. Please specify the appPath if the default search path does not locate your file. 'add --appPath=yourAppPath'\"\n );\n\n return;\n }\n\n const currentPkgManager = await detect();\n const runCmd = currentPkgManager === 'npm' ? 'install' : 'add';\n\n /** ======================== Step 1 Add dependencies required ======================== */\n if (all) {\n let [, ...missingDependencies] = await checkRequiredContentInstalled(\n 'all',\n allDependenciesKeys,\n {allDependencies, beta, packageNames: [HERO_UI], peerDependencies: true}\n );\n\n missingDependencies = missingDependencies.map((c) => strip(c));\n\n if (missingDependencies.length) {\n Logger.info(\n `Adding required dependencies: ${[...missingDependencies]\n .map((c) => chalk.underline(c))\n .join(', ')}`\n );\n\n await debugExecAddAction(\n `${currentPkgManager} ${runCmd} ${[...missingDependencies].join(' ')}`,\n missingDependencies\n );\n }\n } else {\n const mergedComponents = beta\n ? await getBetaComponents(targets)\n : targets.map((c) => store.heroUIComponentsMap[c]!.package);\n const [, ..._missingDependencies] = await checkRequiredContentInstalled(\n 'partial',\n allDependenciesKeys,\n {\n allDependencies,\n beta,\n packageNames: mergedComponents,\n peerDependencies: true\n }\n );\n const missingDependencies = [..._missingDependencies, ...mergedComponents].map((c) => strip(c));\n\n Logger.info(\n `Adding required dependencies: ${[...missingDependencies]\n .map((c) => chalk.underline(c))\n .join(', ')}`\n );\n\n await debugExecAddAction(\n `${currentPkgManager} ${runCmd} ${[...missingDependencies].join(' ')}`,\n missingDependencies\n );\n }\n\n if (getStoreSync('debug')) {\n // Temporarily add the components to the package.json file\n debugAddedPkg(targets, packagePath);\n }\n\n // After install the required dependencies, get the latest package information\n var {allDependenciesKeys, currentComponents} = getPackageInfo(packagePath);\n\n /** ======================== Step 2 Tailwind CSS Setup ======================== */\n const type: SAFE_ANY = all ? 'all' : 'partial';\n\n const isPnpm = currentPkgManager === 'pnpm';\n\n if (!tailwindPath) {\n const individualContent = individualTailwindRequired.content(currentComponents, isPnpm);\n const template = tailwindTemplate(type, individualContent);\n const tailwindPath = resolver('tailwind.config.js');\n\n writeFileSync(tailwindPath, template, 'utf-8');\n\n Logger.newLine();\n Logger.info(`Tailwind CSS configuration file created at: ${tailwindPath}`);\n } else {\n const [, ...errorInfoList] = checkTailwind(\n type,\n tailwindPath,\n currentComponents,\n isPnpm,\n undefined,\n true\n );\n\n fixTailwind(type, {errorInfoList, format: prettier, tailwindPath});\n\n Logger.newLine();\n Logger.log(`Tailwind CSS settings have been updated in: ${tailwindPath}`);\n }\n\n /** ======================== Step 3 Provider Need Manually Open ======================== */\n if (addApp && appPath && existsSync(appPath)) {\n const [isCorrectProvider] = checkApp(type, appPath);\n\n if (!isCorrectProvider) {\n fixProvider(appPath, {format: prettier});\n\n Logger.newLine();\n Logger.info(`HeroUIProvider successfully added to the App file at: ${appPath}`);\n Logger.warn(\n \"Please check the placement of HeroUIProvider in the App file to ensure it's correctly integrated.'\"\n );\n }\n }\n\n /** ======================== Step 4 Setup Pnpm ======================== */\n if (currentPkgManager === 'pnpm') {\n const npmrcPath = resolver('.npmrc');\n\n if (!existsSync(npmrcPath)) {\n writeFileSync(resolver('.npmrc'), pnpmRequired.content, 'utf-8');\n } else {\n const [isCorrectPnpm] = checkPnpm(npmrcPath);\n\n if (!isCorrectPnpm) {\n fixPnpm(npmrcPath);\n }\n }\n }\n\n // Finish adding the HeroUI components\n Logger.newLine();\n Logger.success('✅ Components added successfully');\n\n // Check whether the user has installed the All HeroUI components\n if ((allDependenciesKeys.has(HERO_UI) || all) && currentComponents.length) {\n // Check whether have added redundant dependencies\n Logger.newLine();\n Logger.log(\n `${chalk.yellow('Attention')} Individual components from HeroUI do not require the \\`@heroui/react\\` package. For optimized bundle sizes, consider using individual components.`\n );\n Logger.log('The redundant dependencies are:');\n [...new Set(currentComponents)].forEach((component) => {\n Logger.log(`- ${component.package}`);\n });\n }\n\n // Warn the user to check the HeroUIProvider whether in the correct place\n Logger.newLine();\n Logger.grey(\n `Please check the ${chalk.bold(\n 'HeroUIProvider'\n )} whether in the correct place (ignore if added)\\nSee more info here: ${DOCS_PROVIDER_SETUP}`\n );\n\n if (getStoreSync('debug')) {\n // Temporarily remove the added components from the package.json file\n debugRemovedPkg(targets, packagePath);\n }\n process.exit(0);\n}\n","import type {PartialKey, RequiredKey, SAFE_ANY} from './type';\nimport type {ProblemRecord} from 'src/actions/doctor-action';\n\nimport {readFileSync} from 'node:fs';\n\nimport chalk from 'chalk';\n\nimport {type HeroUIComponents} from 'src/constants/component';\nimport {\n DOCS_INSTALLED,\n DOCS_TAILWINDCSS_SETUP,\n FRAMER_MOTION,\n HERO_UI,\n SYSTEM_UI,\n TAILWINDCSS,\n THEME_UI,\n appRequired,\n individualTailwindRequired,\n pnpmRequired,\n tailwindRequired\n} from 'src/constants/required';\nimport {store} from 'src/constants/store';\nimport {compareVersions} from 'src/scripts/helpers';\n\nimport {getPeerPackageVersion} from './actions/add/get-peer-pakcage-version';\nimport {getBetaVersionData} from './beta';\nimport {Logger} from './logger';\nimport {getMatchArray, getMatchImport} from './match';\nimport {findMostMatchText} from './math-diff';\nimport {getPackagePeerDep} from './upgrade';\nimport {strip} from './utils';\n\nexport type CheckType = 'all' | 'partial';\nexport type CombineType = 'missingDependencies' | 'incorrectTailwind' | 'incorrectApp';\n\ntype DefaultCombineOptions = {\n errorInfo: string[];\n missingDependencies: string[];\n tailwindName: string;\n};\n\ntype CombineOptions<T extends CombineType> = T extends 'missingDependencies'\n ? RequiredKey<Partial<DefaultCombineOptions>, 'missingDependencies'>\n : T extends 'incorrectTailwind'\n ? RequiredKey<Partial<DefaultCombineOptions>, 'errorInfo' | 'tailwindName'>\n : T extends 'incorrectApp'\n ? RequiredKey<Partial<DefaultCombineOptions>, 'errorInfo'>\n : DefaultCombineOptions;\n\ntype CheckResult<T extends SAFE_ANY[] = SAFE_ANY[]> = [boolean, ...T];\n\nexport function combineProblemRecord<T extends CombineType = CombineType>(\n type: T,\n options: CombineOptions<T>\n): ProblemRecord {\n const {errorInfo, missingDependencies, tailwindName} = options as DefaultCombineOptions;\n\n if (type === 'missingDependencies') {\n return {\n level: 'error',\n name: 'missingDependencies',\n outputFn: () => {\n Logger.log('You have not installed the required dependencies');\n Logger.newLine();\n Logger.log('The required dependencies are:');\n missingDependencies.forEach((dependency) => {\n Logger.log(`- ${dependency}`);\n });\n Logger.newLine();\n Logger.log(`See more info here: ${chalk.underline(DOCS_INSTALLED)}`);\n }\n };\n } else if (type === 'incorrectTailwind') {\n return {\n level: 'error',\n name: 'incorrectTailwind',\n outputFn: () => {\n Logger.log(`Your ${tailwindName} is incorrect`);\n Logger.newLine();\n Logger.log('The missing part is:');\n errorInfo.forEach((info) => {\n Logger.log(`- need to add ${info}`);\n });\n Logger.newLine();\n Logger.log(`See more info here: ${chalk.underline(`${DOCS_TAILWINDCSS_SETUP}-1`)}`);\n }\n };\n } else {\n return {\n level: 'error',\n name: 'incorrectApp',\n outputFn: () => {\n Logger.log('Your App.tsx is incorrect');\n Logger.newLine();\n Logger.log('The missing part is:');\n errorInfo.forEach((info) => {\n Logger.log(`- need to add ${info}`);\n });\n Logger.newLine();\n Logger.log(`See more info here: ${chalk.underline(DOCS_INSTALLED)}`);\n }\n };\n }\n}\n\ninterface CheckPeerDependenciesConfig {\n peerDependencies?: boolean;\n allDependencies?: Record<string, SAFE_ANY>;\n packageNames?: string[];\n beta?: boolean;\n}\n\n/**\n * Check if the required content is installed\n * @example return result and missing required [false, '@heroui/react', 'framer-motion']\n * @param type\n * @param dependenciesKeys\n * @param checkPeerDependenciesConfig\n * @returns\n */\nexport async function checkRequiredContentInstalled<\n T extends CheckPeerDependenciesConfig = CheckPeerDependenciesConfig\n>(\n type: CheckType,\n dependenciesKeys: Set<string>,\n checkPeerDependenciesConfig?: T extends {peerDependencies: infer P}\n ? P extends true\n ? PartialKey<Required<CheckPeerDependenciesConfig>, 'beta'>\n : T\n : T\n): Promise<CheckResult> {\n const result = [] as unknown as CheckResult;\n const {allDependencies, beta, packageNames, peerDependencies} = (checkPeerDependenciesConfig ??\n {}) as Required<CheckPeerDependenciesConfig>;\n const peerDependenciesList: string[] = [];\n const hasFramerMotion = dependenciesKeys.has(FRAMER_MOTION);\n const hasTailwind = dependenciesKeys.has(TAILWINDCSS);\n const minTailwindVersion = `${TAILWINDCSS}@${getPeerPackageVersion(TAILWINDCSS)}`;\n\n if (peerDependencies) {\n const peerDepList = await checkPeerDependencies({allDependencies, packageNames});\n\n peerDependenciesList.push(...peerDepList);\n }\n\n if (type === 'all') {\n const hasAllComponents = dependenciesKeys.has(HERO_UI);\n\n if (hasAllComponents && hasFramerMotion && hasTailwind && !peerDependenciesList.length) {\n return [true];\n }\n !hasAllComponents && result.push(beta ? `${HERO_UI}@${store.betaVersion}` : HERO_UI);\n !hasFramerMotion && result.push(FRAMER_MOTION);\n !hasTailwind && result.push(minTailwindVersion);\n } else if (type === 'partial') {\n const hasSystemUI = dependenciesKeys.has(SYSTEM_UI);\n const hasThemeUI = dependenciesKeys.has(THEME_UI);\n\n if (\n hasFramerMotion &&\n hasSystemUI &&\n hasThemeUI &&\n hasTailwind &&\n !peerDependenciesList.length\n ) {\n return [true];\n }\n const betaSystemUI = await getBetaVersionData(SYSTEM_UI);\n const betaThemeUI = await getBetaVersionData(THEME_UI);\n\n !hasFramerMotion && result.push(FRAMER_MOTION);\n !hasSystemUI && result.push(beta ? `${SYSTEM_UI}@${betaSystemUI}` : SYSTEM_UI);\n !hasThemeUI && result.push(beta ? `${THEME_UI}@${betaThemeUI}` : THEME_UI);\n !hasTailwind && result.push(minTailwindVersion);\n }\n\n return [false, ...result, ...(peerDependencies ? peerDependenciesList : [])];\n}\n\nexport async function checkPeerDependencies(\n config: Required<Pick<CheckPeerDependenciesConfig, 'allDependencies' | 'packageNames'>>\n) {\n const {allDependencies, packageNames} = config;\n const peerDepList: string[] = [];\n\n for (const packageName of packageNames) {\n const result = await getPackagePeerDep(packageName, allDependencies, new Set());\n\n for (const peerData of result) {\n if (!peerData.isLatest) {\n // If there are not the latest version, add the peerDependencies to the list\n const findPeerDepIndex = peerDepList.findIndex((peerDep) =>\n peerDep.includes(peerData.package)\n );\n const findPeerDep = strip(peerDepList[findPeerDepIndex] || '');\n const findPeerDepVersion = findPeerDep?.match(/@([\\d.]+)/)?.[1];\n\n // If the peerDependencies is not the latest version, remove the old version and add the latest version\n if (\n findPeerDepVersion &&\n compareVersions(findPeerDepVersion, strip(peerData.latestVersion)) <= 0\n ) {\n peerDepList.splice(findPeerDepIndex, 1);\n }\n peerDepList.push(`${peerData.package}@${peerData.latestVersion}`);\n }\n }\n }\n\n return peerDepList;\n}\n\n/**\n * Check if the tailwind.config file is correct\n * @param type\n * @param tailwindPath\n * @param currentComponents\n * @returns\n */\nexport function checkTailwind(\n type: 'all',\n tailwindPath: string,\n currentComponents?: HeroUIComponents,\n isPnpm?: boolean,\n content?: string,\n logWarning?: boolean\n): CheckResult;\nexport function checkTailwind(\n type: 'partial',\n tailwindPath: string,\n currentComponents: HeroUIComponents,\n isPnpm: boolean,\n content?: string,\n logWarning?: boolean\n): CheckResult;\nexport function checkTailwind(\n type: CheckType,\n tailwindPath: string,\n currentComponents?: HeroUIComponents,\n isPnpm?: boolean,\n content?: string,\n logWarning?: boolean\n): CheckResult {\n if (type === 'partial' && !currentComponents!.length) {\n return [true];\n }\n\n const result = [] as unknown as CheckResult;\n\n const tailwindContent = content ?? readFileSync(tailwindPath, 'utf-8');\n\n const contentMatch = getMatchArray('content', tailwindContent);\n const pluginsMatch = getMatchArray('plugins', tailwindContent);\n\n if (type === 'all') {\n // Check if the required content is added Detail: https://heroui.com/docs/guide/installation#global-installation\n const darkMatch = getMatchArray('darkMode', tailwindContent);\n // Some tailwind.config.js use darkMode: 'class' not darkMode: ['class']\n const isDarkModeCorrect =\n darkMatch.some((darkMode) => darkMode.includes('class')) ||\n /darkMode:\\s*[\"'`]class/.test(tailwindContent);\n const isContentCorrect = contentMatch.some(\n (content) => content.includes(tailwindRequired.content.replace('{js,ts,jsx,tsx}', '')) // Remove the suffix of the content for a better match\n );\n const isPluginsCorrect = pluginsMatch.some((plugins) =>\n tailwindRequired.checkPluginsRegex.test(plugins)\n );\n\n if (isDarkModeCorrect && isContentCorrect && isPluginsCorrect) {\n return [true];\n }\n !isDarkModeCorrect && result.push(tailwindRequired.darkMode);\n !isContentCorrect && result.push(tailwindRequired.content);\n !isPluginsCorrect && result.push(tailwindRequired.plugins);\n } else if (type === 'partial') {\n const individualContent = individualTailwindRequired.content(currentComponents!, isPnpm!);\n\n let isHaveAllContent = false;\n const isContentCorrect = contentMatch.some((content) => {\n // Add tailwindRequired.content check to the contentMatch, cause it is all include in the individualContent\n if (content.includes(tailwindRequired.content.replace('{js,ts,jsx,tsx}', ''))) {\n isHaveAllContent = true;\n\n return true;\n }\n\n return content.includes(individualContent);\n });\n\n if (logWarning && isHaveAllContent) {\n Logger.log(\n `\\n${chalk.yellow('Attention')} Individual components from HeroUI do not require the \"${chalk.bold(\n tailwindRequired.content\n )}\" in the tailwind config\\nFor optimized bundle sizes, consider using \"${chalk.bold(\n individualContent\n )}\" instead`\n );\n }\n\n const isPluginsCorrect = pluginsMatch.some((plugins) =>\n tailwindRequired.checkPluginsRegex.test(plugins)\n );\n\n if (isContentCorrect && isPluginsCorrect) {\n return [true];\n }\n !isContentCorrect && result.push(individualContent);\n !isPluginsCorrect && result.push(tailwindRequired.plugins);\n }\n\n return [false, ...result];\n}\n\nexport function checkApp(type: CheckType, appPath: string): CheckResult {\n const result = [] as unknown as CheckResult;\n\n if (type === 'all' || type === 'partial') {\n const appContent = readFileSync(appPath, 'utf-8');\n\n const importArray = getMatchImport(appContent);\n const isAppCorrect = importArray.some(([key]) => key!.includes(appRequired.import));\n\n if (isAppCorrect) {\n return [true];\n }\n\n !isAppCorrect && result.push(appRequired.import);\n }\n\n return [false, ...result];\n}\n\nexport function checkPnpm(npmrcPath: string): CheckResult {\n const result = [] as unknown as CheckResult;\n\n let content: string;\n\n if (npmrcPath) {\n try {\n content = readFileSync(npmrcPath, 'utf-8');\n const isPnpmCorrect = content.includes(pnpmRequired.content);\n\n if (isPnpmCorrect) {\n return [true];\n }\n\n !isPnpmCorrect && result.push(pnpmRequired.content);\n } catch (error) {\n result.push(`Error reading .npmrc file: ${npmrcPath} \\nError: ${error}`);\n }\n\n return [false, ...result];\n }\n\n return [false, ...result];\n}\n\nexport async function checkIllegalComponents<T extends boolean = false>(\n components: string[] = [],\n loggerError = true\n): Promise<T extends false ? boolean : string[]> {\n const illegalList: [string, null | string][] = [];\n\n for (const component of components) {\n if (!store.heroUIComponentsKeysSet.has(component)) {\n const matchComponent = findMostMatchText(store.heroUIComponentsKeys, component);\n\n illegalList.push([component, matchComponent]);\n }\n }\n\n if (illegalList.length) {\n const [illegalComponents, matchComponents] = illegalList.reduce(\n (acc, [illegalComponent, matchComponent]) => {\n return [\n acc[0] + chalk.underline(illegalComponent) + ', ',\n acc[1] + (matchComponent ? chalk.underline(matchComponent) + ', ' : '')\n ];\n },\n ['', '']\n );\n\n loggerError &&\n Logger.prefix(\n 'error',\n `Illegal components: ${illegalComponents.replace(/, $/, '')}${\n matchComponents\n ? `\\n${''.padEnd(12)}It may be a typo, did you mean ${matchComponents.replace(\n /, $/,\n ''\n )}?`\n : ''\n }`\n );\n\n return false as T extends false ? boolean : string[];\n }\n\n return true as T extends false ? boolean : string[];\n}\n","import {transformPeerVersion} from '@helpers/utils';\nimport {getConditionComponentData} from 'src/constants/component';\nimport {compareVersions} from 'src/scripts/helpers';\n\n/**\n * Find the peer package version\n * @param peerPackageName\n * @param isMinVersion default is true\n * @example\n * components: [\n * {\n * peerDependencies: {\n * 'react': '18.0.0'\n * }\n * },\n * {\n * peerDependencies: {\n * 'react': '18.2.0'\n * }\n * }\n * ]\n *\n * getPeerPackageVersion('react') --> 18.0.0\n * getPeerPackageVersion('react', false) --> 18.2.0\n */\nexport function getPeerPackageVersion(peerPackageName: string, isMinVersion = true) {\n const components = getConditionComponentData().components;\n const filerTargetPackages = components.filter(\n (component) => component.peerDependencies[peerPackageName]\n );\n let version = '';\n\n if (isMinVersion) {\n const versionList = filerTargetPackages.map(\n (component) => component.peerDependencies[peerPackageName]\n );\n const minVersion = versionList.reduce((min, version) => {\n return compareVersions(min, version) > 0 ? version : min;\n });\n\n version = minVersion || '';\n } else {\n version = filerTargetPackages[0]?.version || '';\n }\n\n return transformPeerVersion(version);\n}\n","import type {\n ExtractUpgrade,\n MissingDepSetType,\n Upgrade,\n UpgradeOption\n} from './actions/upgrade/upgrade-types';\nimport type {SAFE_ANY} from './type';\n\nimport chalk from 'chalk';\n\nimport {HERO_UI, THEME_UI} from 'src/constants/required';\nimport {getCacheExecData} from 'src/scripts/cache/cache';\nimport {type Dependencies, compareVersions, getLatestVersion} from 'src/scripts/helpers';\n\nimport {getLibsData} from './actions/upgrade/get-libs-data';\nimport {getConditionVersion} from './condition-value';\nimport {Logger} from './logger';\nimport {colorMatchRegex, outputBox} from './output-info';\nimport {\n fillAnsiLength,\n getColorVersion,\n getVersionAndMode,\n isMajorUpdate,\n isMinorUpdate,\n strip,\n transformPeerVersion,\n versionModeRegex\n} from './utils';\n\nconst DEFAULT_SPACE = ''.padEnd(7);\n\nconst MISSING = 'Missing';\n\nexport async function upgrade<T extends Upgrade = Upgrade>(options: ExtractUpgrade<T>) {\n const {all, allDependencies, isHeroUIAll, upgradeOptionList} = options as Required<Upgrade>;\n let result: UpgradeOption[] = [];\n const missingDepSet = new Set<MissingDepSetType>();\n\n const allOutputData = await getAllOutputData(all, isHeroUIAll, allDependencies, missingDepSet);\n const libsData = await getLibsData(allDependencies);\n\n const transformUpgradeOptionList = upgradeOptionList.map((c) => ({\n ...c,\n latestVersion: getColorVersion(c.version, c.latestVersion)\n }));\n\n const upgradePeerList = await Promise.all(\n upgradeOptionList.map((upgradeOption) =>\n getPackagePeerDep(\n upgradeOption.package,\n allDependencies,\n missingDepSet,\n upgradeOption.peerDependencies\n )\n )\n );\n\n const missingDepList = await getPackageUpgradeData([...missingDepSet]);\n\n const outputList = [...transformUpgradeOptionList, ...allOutputData.allOutputList];\n const peerDepList = [\n ...libsData,\n ...upgradePeerList.flat(),\n ...allOutputData.allPeerDepList,\n ...missingDepList\n ].filter(\n (upgradeOption, index, arr) =>\n index === arr.findIndex((c) => c.package === upgradeOption.package) &&\n !outputList.some((c) => c.package === upgradeOption.package)\n );\n\n // Output dependencies box\n outputDependencies(outputList, peerDepList);\n\n result = [...outputList, ...peerDepList].filter(\n (upgradeOption, index, arr) =>\n !upgradeOption.isLatest && index === arr.findIndex((c) => c.package === upgradeOption.package)\n );\n\n // Output upgrade count\n outputUpgradeCount(result);\n\n return result;\n}\n\n/**\n * Get upgrade version\n * @param upgradeOptionList\n * @param peer Use for peerDependencies change the latest to fulfillment\n */\nexport function getUpgradeVersion(upgradeOptionList: UpgradeOption[], peer = false) {\n if (!upgradeOptionList.length) {\n return '';\n }\n\n const output: string[] = [];\n\n const optionMaxLenMap = {\n latestVersion: 0,\n package: 0,\n version: 0\n };\n\n for (const upgradeOption of upgradeOptionList) {\n for (const key in upgradeOption) {\n if (!Object.prototype.hasOwnProperty.call(upgradeOption, key) || !upgradeOption[key]) {\n continue;\n }\n\n if (key === 'version') {\n // Remove the duplicate character '^'\n upgradeOption[key] = upgradeOption[key].replace(versionModeRegex, '');\n }\n\n const compareLength =\n key === 'version'\n ? upgradeOption[key].replace(colorMatchRegex, '').length\n : upgradeOption[key].length;\n\n optionMaxLenMap[key] = Math.max(optionMaxLenMap[key], compareLength);\n }\n }\n\n for (const upgradeOption of upgradeOptionList) {\n if (upgradeOption.isLatest) {\n if (peer) {\n // If it is peerDependencies, then skip output the latest version\n continue;\n }\n\n output.push(\n ` ${chalk.white(\n `${`${upgradeOption.package}@${upgradeOption.versionMode || ''}${\n upgradeOption.latestVersion\n }`.padEnd(optionMaxLenMap.package + DEFAULT_SPACE.length + DEFAULT_SPACE.length)}`\n )}${DEFAULT_SPACE}${chalk.greenBright('latest').padStart(optionMaxLenMap.version)}${DEFAULT_SPACE}`\n );\n continue;\n }\n output.push(\n ` ${chalk.white(\n `${upgradeOption.package.padEnd(\n optionMaxLenMap.package + DEFAULT_SPACE.length\n )}${DEFAULT_SPACE}${fillAnsiLength(\n `${upgradeOption.versionMode || ''}${upgradeOption.version}`,\n optionMaxLenMap.version\n )} -> ${upgradeOption.versionMode || ''}${upgradeOption.latestVersion}`\n )}${DEFAULT_SPACE}`\n );\n }\n\n return output.join('\\n');\n}\n\nexport async function getPackagePeerDep(\n packageName: string,\n allDependencies: Dependencies,\n missingDepList: Set<MissingDepSetType>,\n peerDependencies?: Dependencies\n): Promise<UpgradeOption[]> {\n peerDependencies =\n peerDependencies ||\n JSON.parse(\n (await getCacheExecData(`npm show ${packageName} peerDependencies --json`)) as SAFE_ANY\n ) ||\n {};\n\n if (!peerDependencies || !Object.keys(peerDependencies).length) {\n return [];\n }\n\n const upgradeOptionList: UpgradeOption[] = [];\n\n for (const [peerPackage, peerVersion] of Object.entries(peerDependencies)) {\n if (upgradeOptionList.some((c) => c.package === peerPackage)) {\n // Avoid duplicate\n continue;\n }\n\n const currentVersion = allDependencies[peerPackage];\n let formatPeerVersion = transformPeerVersion(peerVersion);\n\n if (!currentVersion) {\n missingDepList.add({name: peerPackage, version: formatPeerVersion});\n continue;\n }\n const {versionMode} = getVersionAndMode(allDependencies, peerPackage);\n const isLatest = compareVersions(currentVersion, formatPeerVersion) >= 0;\n\n if (isLatest) {\n formatPeerVersion = transformPeerVersion(currentVersion);\n } else {\n // If the current version is not the latest version, then get the latest version in upgrade command\n formatPeerVersion = await getLatestVersion(peerPackage);\n }\n\n upgradeOptionList.push({\n isLatest,\n latestVersion: isLatest\n ? formatPeerVersion\n : getColorVersion(currentVersion, formatPeerVersion),\n package: peerPackage,\n version: currentVersion,\n versionMode\n });\n }\n\n return upgradeOptionList;\n}\n\nfunction outputDependencies(outputList: UpgradeOption[], peerDepList: UpgradeOption[]) {\n const componentName = outputList.length === 1 ? 'Component' : 'Components';\n const outputDefault = {\n components: {color: 'blue', text: '', title: chalk.blue(componentName)},\n peerDependencies: {color: 'yellow', text: '', title: chalk.yellow('PeerDependencies')}\n } as const;\n\n const outputInfo = getUpgradeVersion(outputList);\n const outputPeerDepInfo = getUpgradeVersion(peerDepList, true);\n const filterPeerDepList = peerDepList.filter((c) => !c.isLatest);\n\n outputInfo.length && outputBox({...outputDefault.components, text: outputInfo});\n Logger.newLine();\n filterPeerDepList.length &&\n Logger.log(\n chalk.gray(\n `Required min version: ${filterPeerDepList\n .map((c) => {\n return `${c.package}>=${c.latestVersion.replace(colorMatchRegex, '')}`;\n })\n .join(', ')}`\n )\n );\n outputPeerDepInfo.length &&\n outputBox({...outputDefault.peerDependencies, text: outputPeerDepInfo});\n}\n\n/**\n * Get all output data\n * @example\n * getAllOutputData(true, allDependencies, missingDepSet) --> {allOutputList: [], allPeerDepList: []}\n */\nexport async function getAllOutputData(\n all: boolean,\n isHeroUIAll: boolean,\n allDependencies: Record<string, SAFE_ANY>,\n missingDepSet: Set<MissingDepSetType>\n) {\n if (!all || !isHeroUIAll) {\n return {\n allOutputList: [],\n allPeerDepList: []\n };\n }\n\n const latestVersion = await getConditionVersion(HERO_UI);\n\n const {currentVersion, versionMode} = getVersionAndMode(allDependencies, HERO_UI);\n const colorVersion = getColorVersion(currentVersion, latestVersion);\n const isLatest = compareVersions(currentVersion, latestVersion) >= 0;\n\n const heroUIPeerDepList = await getPackagePeerDep(HERO_UI, allDependencies, missingDepSet);\n const heroUIThemePeerDepList = await getPackagePeerDep(THEME_UI, allDependencies, missingDepSet);\n\n const allOutputList = [\n {\n isLatest,\n latestVersion: colorVersion,\n package: HERO_UI,\n version: currentVersion,\n versionMode\n }\n ];\n const allPeerDepList = [...heroUIPeerDepList, ...heroUIThemePeerDepList];\n const allOutputData = {\n allOutputList,\n allPeerDepList\n };\n\n return allOutputData;\n}\n\nexport async function getPackageUpgradeData(missingDepList: MissingDepSetType[]) {\n const result: UpgradeOption[] = [];\n\n for (const missingDep of missingDepList) {\n const allOutputList = {\n isLatest: false,\n latestVersion: missingDep.version,\n package: missingDep.name,\n version: chalk.red(MISSING),\n versionMode: ''\n };\n\n result.push(allOutputList);\n }\n\n return result;\n}\n\nfunction outputUpgradeCount(outputList: UpgradeOption[]) {\n const count = {\n major: 0,\n minor: 0,\n patch: 0\n };\n\n for (const component of outputList) {\n if (component.version === MISSING) {\n count.major++;\n continue;\n }\n const stripLatestVersion = strip(component.latestVersion);\n\n if (isMajorUpdate(component.version, stripLatestVersion)) {\n count.major++;\n } else if (isMinorUpdate(component.version, stripLatestVersion)) {\n count.minor++;\n } else {\n count.patch++;\n }\n }\n\n const outputInfo = Object.entries(count)\n .reduce((acc, [key, value]) => {\n if (!value) {\n return acc;\n }\n\n return `${acc}${chalk.yellowBright(value)} ${key}, `;\n }, '')\n .replace(/, $/, '');\n\n if (outputInfo) {\n Logger.log(outputInfo);\n Logger.newLine();\n }\n\n return count;\n}\n\nexport function writeUpgradeVersion({\n dependencies,\n devDependencies,\n upgradePackageList\n}: {\n dependencies: Dependencies;\n devDependencies: Dependencies;\n upgradePackageList: UpgradeOption[];\n}) {\n for (const upgradePackage of upgradePackageList) {\n const latestVersion = strip(upgradePackage.latestVersion);\n\n if (devDependencies[upgradePackage.package]) {\n devDependencies[upgradePackage.package] = latestVersion;\n continue;\n }\n dependencies[upgradePackage.package] = latestVersion;\n }\n}\n","import {store} from 'src/constants/store';\nimport {getLatestVersion} from 'src/scripts/helpers';\n\nimport {getBetaVersion} from './beta';\n\nexport async function getConditionVersion(packageName: string) {\n const conditionVersion = store.beta\n ? await getBetaVersion(packageName)\n : await getLatestVersion(packageName);\n\n return conditionVersion;\n}\n","import type {UpgradeOption} from './upgrade-types';\nimport type {SAFE_ANY} from '@helpers/type';\n\nimport {getConditionVersion} from '@helpers/condition-value';\nimport {getColorVersion, getVersionAndMode} from '@helpers/utils';\nimport {HEROUI_PREFIX} from 'src/constants/required';\nimport {store} from 'src/constants/store';\nimport {compareVersions} from 'src/scripts/helpers';\n\nexport async function getLibsData(\n allDependencies: Record<string, SAFE_ANY>\n): Promise<UpgradeOption[]> {\n const allDependenciesKeys = Object.keys(allDependencies);\n\n const allLibs = allDependenciesKeys.filter((dependency) => {\n return (\n !store.heroUIcomponentsPackages.includes(dependency) && dependency.startsWith(HEROUI_PREFIX)\n );\n });\n\n if (!allLibs.length) {\n return [];\n }\n\n const libsData: UpgradeOption[] = await Promise.all(\n allLibs.map(async (lib) => {\n const {currentVersion, versionMode} = getVersionAndMode(allDependencies, lib);\n const conditionVersion = await getConditionVersion(lib);\n const isLatest = compareVersions(currentVersion, conditionVersion) >= 0;\n\n return {\n isLatest,\n latestVersion: getColorVersion(\n currentVersion,\n isLatest ? currentVersion : conditionVersion\n ),\n package: lib,\n version: currentVersion,\n versionMode\n };\n })\n );\n\n return libsData;\n}\n","import {writeFileSync} from 'node:fs';\n\nimport {getStoreSync, store} from 'src/constants/store';\n\nimport {catchPnpmExec} from './actions/upgrade/catch-pnpm-exec';\nimport {exec} from './exec';\nimport {Logger} from './logger';\nimport {getPackageInfo} from './package';\n\nexport async function debugExecAddAction(cmd: string, components: string[] = []) {\n if (getStoreSync('debug')) {\n for (const component of components) {\n Logger.warn(`Debug: ${component}`);\n }\n } else {\n await catchPnpmExec(() => exec(cmd));\n }\n}\n\nexport function debugAddedPkg(components: string[], packagePath: string) {\n if (!components.length || !getStoreSync('debug')) return;\n\n const {dependencies, packageJson} = getPackageInfo(packagePath);\n\n for (const component of components) {\n const compData = store.heroUIComponentsMap[component];\n\n if (!compData) continue;\n\n dependencies[compData.package] = `${compData.package}@${compData.version}`;\n }\n writeFileSync(\n packagePath,\n JSON.stringify(\n {\n ...packageJson,\n dependencies\n },\n null,\n 2\n ),\n 'utf-8'\n );\n}\n\nexport function debugRemovedPkg(components: string[], packagePath: string) {\n if (!components.length || !getStoreSync('debug')) return;\n\n const {dependencies, packageJson} = getPackageInfo(packagePath);\n\n for (const component of components) {\n const compData = store.heroUIComponentsMap[component];\n\n if (!compData) continue;\n delete dependencies[compData.package];\n }\n writeFileSync(\n packagePath,\n JSON.stringify(\n {\n ...packageJson,\n dependencies\n },\n null,\n 2\n ),\n 'utf-8'\n );\n}\n","import chalk from 'chalk';\n\nimport {exec} from '@helpers/exec';\nimport {selectClack} from 'src/prompts/clack';\n\nexport async function catchPnpmExec(execFn: () => Promise<unknown>) {\n try {\n await execFn();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error) {\n const reRunPnpm = await selectClack({\n message: `${chalk.red('Error: ')}a unexpected error occurred, run \"pnpm install\" maybe can fix it or report it as a bug`,\n options: [\n {label: 'Re-run pnpm install', value: 're-run-pnpm-install'},\n {label: 'Exit', value: 'exit'}\n ]\n });\n\n if (reRunPnpm === 'exit') {\n process.exit(1);\n }\n\n await exec('pnpm install --force');\n await execFn();\n }\n }\n}\n","import type {CheckType} from './check';\n\nimport {execSync} from 'node:child_process';\nimport {existsSync, readFileSync, writeFileSync} from 'node:fs';\n\nimport {pnpmRequired, tailwindRequired} from 'src/constants/required';\nimport {getStoreSync} from 'src/constants/store';\n\nimport {Logger} from './logger';\nimport {getMatchArray, replaceMatchArray} from './match';\n\ninterface FixTailwind {\n errorInfoList: string[];\n tailwindPath: string;\n write?: boolean;\n format?: boolean;\n}\n\ninterface FixProvider {\n write?: boolean;\n format?: boolean;\n}\n\nexport function fixProvider(appPath: string, options: FixProvider) {\n const {format = false, write = true} = options;\n let appContent = readFileSync(appPath, 'utf-8');\n\n appContent = `import {HeroUIProvider} from \"@heroui/react\";\\n${appContent}`;\n\n appContent = wrapWithHeroUIProvider(appContent);\n\n write && writeFileSync(appPath, appContent, 'utf-8');\n format && execSync(`npx prettier --write ${appPath}`, {stdio: 'ignore'});\n}\n\nfunction wrapWithHeroUIProvider(content: string) {\n const returnRegex = /return\\s*\\(([\\S\\s]*?)\\);/g;\n const wrappedCode = content.replace(returnRegex, (_, p1) => {\n return `return (\n <HeroUIProvider>\n ${p1.trim()}\n </HeroUIProvider>\n );`;\n });\n\n return wrappedCode;\n}\n\nexport function fixTailwind(type: CheckType, options: FixTailwind) {\n const {errorInfoList, format = false, tailwindPath, write = true} = options;\n\n if (!errorInfoList.length) {\n return;\n }\n\n let tailwindContent = readFileSync(tailwindPath, 'utf-8');\n let contentMatch = getMatchArray('content', tailwindContent);\n const pluginsMatch = getMatchArray('plugins', tailwindContent);\n\n for (const errorInfo of errorInfoList) {\n const [errorType, info] = transformErrorInfo(errorInfo);\n\n if (errorType === 'content') {\n // Check if all the required content is added then skip\n const allPublic = contentMatch.includes(tailwindRequired.content);\n\n if (allPublic) continue;\n\n contentMatch = contentMatch.filter((content) => !content.includes('@heroui/theme/dist/'));\n contentMatch.push(info);\n tailwindContent = replaceMatchArray(\n 'content',\n tailwindContent,\n contentMatch,\n contentMatch\n .map((v, index, arr) => {\n // Add 4 spaces before the content\n if (index === 0) {\n if (arr.length === 1) {\n return `\\n ${JSON.stringify(v)}\\n`;\n }\n\n return `\\n ${JSON.stringify(v)}`;\n }\n if (arr.length - 1 === index) {\n return ` ${JSON.stringify(v)}\\n `;\n }\n\n return ` ${JSON.stringify(v)}`;\n })\n .join(',\\n')\n );\n } else if (errorType === 'plugins') {\n pluginsMatch.push(info);\n tailwindContent = replaceMatchArray('plugins', tailwindContent, pluginsMatch);\n\n // Add import content\n const importContent = tailwindRequired.importContent(tailwindPath.endsWith('.ts'));\n\n tailwindContent = `${importContent}\\n${tailwindContent}`;\n }\n\n if (type === 'all' && errorType === 'darkMode') {\n // Add darkMode under the plugins content in tailwindContent\n const darkModeIndex = tailwindContent.indexOf('plugins') - 1;\n const darkModeContent = tailwindRequired.darkMode;\n\n tailwindContent = `${tailwindContent.slice(\n 0,\n darkModeIndex\n )} ${darkModeContent},\\n${tailwindContent.slice(darkModeIndex)}`;\n }\n }\n\n write && writeFileSync(tailwindPath, tailwindContent, 'utf-8');\n\n if (format) {\n try {\n execSync(`npx prettier --write ${tailwindPath}`, {stdio: 'ignore'});\n } catch (error) {\n Logger.warn(`Prettier failed to format ${tailwindPath}`);\n }\n }\n}\n\nfunction transformErrorInfo(errorInfo: string): [keyof typeof tailwindRequired, string] {\n if (tailwindRequired.darkMode.includes(errorInfo)) {\n return ['darkMode', errorInfo];\n } else if (tailwindRequired.plugins.includes(errorInfo)) {\n return ['plugins', errorInfo];\n } else {\n return ['content', errorInfo];\n }\n}\n\nexport function fixPnpm(\n npmrcPath: string,\n write = true,\n runInstall = true,\n logger: (({message, runInstall}) => void) | undefined = undefined\n) {\n if (!existsSync(npmrcPath)) {\n write && writeFileSync(npmrcPath, pnpmRequired.content, 'utf-8');\n } else {\n let content = readFileSync(npmrcPath, 'utf-8');\n\n content = `${pnpmRequired.content}\\n${content}`;\n\n write && writeFileSync(npmrcPath, content, 'utf-8');\n }\n\n if (!logger) {\n Logger.newLine();\n Logger.log(`Added the required content in file: ${npmrcPath}`);\n\n if (runInstall && !getStoreSync('debug')) {\n Logger.newLine();\n Logger.log('Pnpm restructure will be run now');\n execSync('pnpm install', {stdio: 'inherit'});\n }\n\n return;\n }\n\n // Custom logger\n logger({message: `Added the required content in file: ${npmrcPath}`, runInstall});\n}\n","import type {CheckType} from '@helpers/check';\n\nexport const APP_REPO = 'https://codeload.github.com/heroui-inc/next-app-template/tar.gz/main';\nexport const PAGES_REPO = 'https://codeload.github.com/heroui-inc/next-pages-template/tar.gz/main';\nexport const VITE_REPO = 'https://codeload.github.com/heroui-inc/vite-template/tar.gz/main';\nexport const REMIX_REPO = 'https://codeload.github.com/heroui-inc/remix-template/tar.gz/main';\nexport const LARAVEL_REPO =\n 'https://github.com/heroui-inc/laravel-template/archive/refs/heads/master.zip';\n\nexport const APP_DIR = 'next-app-template-main';\nexport const PAGES_DIR = 'next-pages-template-main';\nexport const VITE_DIR = 'vite-template-main';\nexport const REMIX_DIR = 'remix-template-main';\nexport const LARAVEL_DIR = 'laravel-template-main';\n\nexport const APP_NAME = 'next-app-template';\nexport const PAGES_NAME = 'next-pages-template';\nexport const VITE_NAME = 'vite-template';\nexport const REMIX_NAME = 'remix-template';\nexport const LARAVEL_NAME = 'laravel-template';\nexport const DEFAULT_PROJECT_NAME = 'heroui-app';\n\nexport function tailwindTemplate(type: 'all', content?: string): string;\nexport function tailwindTemplate(type: 'partial', content: string): string;\nexport function tailwindTemplate(type: CheckType, content?: string) {\n if (type === 'all') {\n return `// tailwind.config.js\nconst {heroui} = require(\"@heroui/react\");\n\n/** @type {import('tailwindcss').Config} */\nmodule.exports = {\n content: [\n \"./node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}\",\n ],\n theme: {\n extend: {},\n },\n darkMode: \"class\",\n plugins: [heroui()],\n};`;\n } else {\n return `// tailwind.config.js\nconst {heroui} = require(\"@heroui/theme\");\n\n/** @type {import('tailwindcss').Config} */\nmodule.exports = {\n content: [\n ${JSON.stringify(content)},\n ],\n theme: {\n extend: {},\n },\n darkMode: \"class\",\n plugins: [heroui()],\n};`;\n }\n}\n","import chalk from 'chalk';\nimport {basename} from 'pathe';\n\nimport {\n checkApp,\n checkPnpm,\n checkRequiredContentInstalled,\n checkTailwind,\n combineProblemRecord\n} from '@helpers/check';\nimport {detect} from '@helpers/detect';\nimport {Logger, type PrefixLogType} from '@helpers/logger';\nimport {getPackageInfo} from '@helpers/package';\nimport {findFiles, strip, transformOption} from '@helpers/utils';\nimport {resolver} from 'src/constants/path';\nimport {DOCS_PNPM_SETUP, DOCS_TAILWINDCSS_SETUP, HERO_UI} from 'src/constants/required';\n\ninterface DoctorActionOptions {\n packagePath?: string;\n tailwindPath?: string;\n appPath?: string;\n checkApp?: boolean | 'false';\n checkTailwind?: boolean | 'false';\n checkPnpm?: boolean | 'false';\n}\n\nexport interface ProblemRecord {\n name: string;\n level: Extract<PrefixLogType, 'error' | 'warn'>;\n outputFn: () => void;\n}\n\nexport async function doctorAction(options: DoctorActionOptions) {\n const {\n appPath = findFiles('**/App.(j|t)sx')[0],\n checkApp: _enableCheckApp = false,\n checkPnpm: _enableCheckPnpm = true,\n checkTailwind: _enableCheckTailwind = true,\n packagePath = resolver('package.json'),\n tailwindPath = findFiles('**/tailwind.config.(j|t)s')\n } = options;\n const enableCheckApp = transformOption(_enableCheckApp);\n const enableCheckPnpm = transformOption(_enableCheckPnpm);\n const enableCheckTailwind = transformOption(_enableCheckTailwind);\n const tailwindPaths = [tailwindPath].flat();\n\n const {allDependencies, allDependenciesKeys, currentComponents, isAllComponents} =\n getPackageInfo(packagePath);\n\n /** ======================== Output when there is no components installed ======================== */\n if (!currentComponents.length && !isAllComponents) {\n Logger.prefix(\n 'error',\n `❌ No ${chalk.underline(\n 'HeroUI components'\n )} found in your project. Please consult the installation guide at: https://heroui.com/docs/guide/installation#global-installation`\n );\n\n return;\n }\n\n /** ======================== Problem record ======================== */\n const problemRecord: ProblemRecord[] = [];\n\n /** ======================== Check whether installed redundant dependencies ======================== */\n if (isAllComponents && currentComponents.length) {\n problemRecord.push({\n level: 'warn',\n name: 'redundantDependencies',\n outputFn: () => {\n Logger.log(\n 'You have installed some unnecessary dependencies. Consider removing them for optimal performance.'\n );\n Logger.newLine();\n Logger.log('The following dependencies are redundant:');\n currentComponents.forEach((component) => {\n Logger.log(`- ${component.package}`);\n });\n }\n });\n }\n // If there is no tailwind.config file\n if (enableCheckTailwind && !tailwindPaths.length) {\n problemRecord.push({\n level: 'error',\n name: 'missingTailwind',\n outputFn: () => {\n Logger.log(\n 'Missing tailwind.config.(j|t)s file. To set up, visit: ' +\n chalk.underline(DOCS_TAILWINDCSS_SETUP)\n );\n }\n });\n }\n // If there is no App.tsx\n if (enableCheckApp && !appPath) {\n problemRecord.push({\n level: 'error',\n name: 'missingApp',\n outputFn: () => {\n Logger.log(\n 'App.(j|t)sx file not found. Please specify the path using: doctor --appPath=[yourAppPath]'\n );\n }\n });\n }\n\n /** ======================== Check if the allComponents required dependencies installed ======================== */\n if (isAllComponents) {\n // Check if framer-motion allComponents is installed\n let [isCorrectInstalled, ...missingDependencies] = await checkRequiredContentInstalled(\n 'all',\n allDependenciesKeys,\n {allDependencies, packageNames: [HERO_UI], peerDependencies: true}\n );\n\n // Check if other allComponents are installed\n if (currentComponents.length) {\n const [_isCorrectInstalled, ..._missingDependencies] = await checkRequiredContentInstalled(\n 'partial',\n allDependenciesKeys,\n {\n allDependencies,\n packageNames: currentComponents.map((c) => c.package),\n peerDependencies: true\n }\n );\n\n isCorrectInstalled = _isCorrectInstalled || isCorrectInstalled;\n // Combine missing dependencies\n missingDependencies = [..._missingDependencies, ...missingDependencies].filter(\n (c, index, arr) => {\n c = strip(c).replace(/@[\\d.]+/g, '');\n\n return arr.findIndex((d) => strip(d).replace(/@[\\d.]+/g, '') === c) === index;\n }\n );\n }\n\n if (!isCorrectInstalled) {\n problemRecord.push(combineProblemRecord('missingDependencies', {missingDependencies}));\n }\n\n // Check whether tailwind.config file is correct\n if (enableCheckTailwind) {\n for (const tailwindPath of tailwindPaths) {\n const [isCorrectTailwind, ...errorInfo] = checkTailwind('all', tailwindPath);\n\n if (!isCorrectTailwind) {\n const tailwindName = basename(tailwindPath);\n\n problemRecord.push(combineProblemRecord('incorrectTailwind', {errorInfo, tailwindName}));\n }\n }\n }\n\n // Check whether the App.tsx is correct\n if (enableCheckApp && appPath) {\n const [isAppCorrect, ...errorInfo] = checkApp('all', appPath);\n\n if (!isAppCorrect) {\n problemRecord.push(combineProblemRecord('incorrectApp', {errorInfo}));\n }\n }\n } else if (currentComponents.length) {\n // Individual components check\n const [isCorrectInstalled, ...missingDependencies] = await checkRequiredContentInstalled(\n 'partial',\n allDependenciesKeys,\n {\n allDependencies,\n packageNames: currentComponents.map((c) => c.package),\n peerDependencies: true\n }\n );\n\n if (!isCorrectInstalled) {\n problemRecord.push(combineProblemRecord('missingDependencies', {missingDependencies}));\n }\n\n // Check whether tailwind.config file is correct\n if (enableCheckTailwind) {\n const isPnpm = (await detect()) === 'pnpm';\n\n for (const tailwindPath of tailwindPaths) {\n const [isCorrectTailwind, ...errorInfo] = checkTailwind(\n 'partial',\n tailwindPath,\n currentComponents,\n isPnpm,\n undefined,\n true\n );\n\n if (!isCorrectTailwind) {\n const tailwindName = basename(tailwindPath);\n\n problemRecord.push(combineProblemRecord('incorrectTailwind', {errorInfo, tailwindName}));\n }\n }\n }\n\n // Check whether the App.tsx is correct\n if (enableCheckApp && appPath) {\n const [isAppCorrect, ...errorInfo] = checkApp('partial', appPath);\n\n if (!isAppCorrect) {\n problemRecord.push(combineProblemRecord('incorrectApp', {errorInfo}));\n }\n }\n }\n\n /** ======================== Check whether Pnpm setup is correct ======================== */\n if (enableCheckPnpm) {\n const currentPkgManager = await detect();\n\n if (currentPkgManager === 'pnpm') {\n const npmrcPath = resolver('.npmrc');\n\n const [isCorrect, ...errorInfo] = checkPnpm(npmrcPath);\n\n if (!isCorrect) {\n problemRecord.push({\n level: 'error',\n name: 'incorrectPnpm',\n outputFn: () => {\n Logger.log(\n 'The pnpm setup is incorrect \\nPlease update your configuration according to the guidelines provided at: ' +\n chalk.underline(DOCS_PNPM_SETUP)\n );\n Logger.newLine();\n Logger.log('Required changes:');\n errorInfo.forEach((info) => {\n Logger.log(`- Add ${info}`);\n });\n }\n });\n }\n }\n }\n\n /** ======================== Return when there is no problem ======================== */\n if (!problemRecord.length) {\n Logger.newLine();\n Logger.success('✅ Your project has no detected issues.');\n\n return;\n }\n\n /** ======================== Output the problem record ======================== */\n Logger.prefix(\n 'error',\n `❌ Your project has ${chalk.underline(problemRecord.length)} issue${\n problemRecord.length === 1 ? '' : 's'\n } that require attention`\n );\n Logger.newLine();\n\n for (let index = 0; index < problemRecord.length; index++) {\n const problem = problemRecord[index] as ProblemRecord;\n\n Logger[problem.level](`❗️Issue ${index + 1}: ${chalk.bold(problem.name)}`);\n Logger.newLine();\n problem.outputFn();\n Logger.newLine();\n }\n\n process.exit(0);\n}\n","import {outputComponents, outputInfo} from '@helpers/output-info';\nimport {getPackageInfo} from '@helpers/package';\nimport {resolver} from 'src/constants/path';\n\ninterface EnvActionOptions {\n packagePath?: string;\n}\n\nexport async function envAction(options: EnvActionOptions) {\n const {packagePath = resolver('package.json')} = options;\n\n const {currentComponents} = getPackageInfo(packagePath);\n\n /** ======================== Output the current components ======================== */\n outputComponents({components: currentComponents});\n\n /** ======================== Output the system environment info ======================== */\n outputInfo();\n\n process.exit(0);\n}\n","import type {Agent} from '@helpers/detect';\nimport type {GetUnionLastValue} from '@helpers/type';\n\nimport {existsSync, renameSync} from 'node:fs';\n\nimport * as p from '@clack/prompts';\nimport chalk from 'chalk';\nimport {join} from 'pathe';\n\nimport {changeNpmrc} from '@helpers/actions/init/change-npmrc';\nimport {downloadTemplate} from '@helpers/fetch';\nimport {fixPnpm} from '@helpers/fix';\nimport {checkInitOptions} from '@helpers/init';\nimport {getPackageManagerInfo} from '@helpers/utils';\nimport {selectClack, taskClack, textClack} from 'src/prompts/clack';\nimport {resolver} from 'src/scripts/path';\n\nimport {ROOT} from '../../src/constants/path';\nimport {\n APP_DIR,\n APP_NAME,\n APP_REPO,\n LARAVEL_DIR,\n LARAVEL_NAME,\n LARAVEL_REPO,\n PAGES_DIR,\n PAGES_NAME,\n PAGES_REPO,\n REMIX_DIR,\n REMIX_NAME,\n REMIX_REPO,\n VITE_DIR,\n VITE_NAME,\n VITE_REPO\n} from '../../src/constants/templates';\n\nexport interface InitActionOptions {\n template?: 'app' | 'pages' | 'vite' | 'remix' | 'laravel';\n package?: Agent;\n}\n\nexport const templatesMap: Record<Required<InitActionOptions>['template'], string> = {\n app: APP_NAME,\n laravel: LARAVEL_NAME,\n pages: PAGES_NAME,\n remix: REMIX_NAME,\n vite: VITE_NAME\n};\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ndeclare let _exhaustiveCheck: never;\n\nexport async function initAction(_projectName: string, options: InitActionOptions) {\n const {package: _package = 'npm', template: _template} = options;\n\n /** ======================== Check invalid options ======================== */\n checkInitOptions(_template, _package);\n\n /** ======================== Welcome title ======================== */\n p.intro(chalk.cyanBright('Create a new project'));\n\n /** ======================== Get the init info ======================== */\n const {packageName, projectName, template} = await getTableInfo(\n _package,\n _projectName,\n _template\n );\n const {run} = getPackageManagerInfo(packageName);\n\n /** ======================== Generate template ======================== */\n // Detect if the project name already exists\n if (existsSync(resolver(`${ROOT}/${projectName}`))) {\n p.cancel(`The project name ${chalk.redBright(projectName)} already exists`);\n process.exit(1);\n }\n\n if (template === 'app') {\n await generateTemplate(APP_REPO);\n renameTemplate(APP_DIR, projectName);\n } else if (template === 'pages') {\n await generateTemplate(PAGES_REPO);\n renameTemplate(PAGES_DIR, projectName);\n } else if (template === 'vite') {\n await generateTemplate(VITE_REPO);\n renameTemplate(VITE_DIR, projectName);\n } else if (template === 'remix') {\n await generateTemplate(REMIX_REPO);\n renameTemplate(REMIX_DIR, projectName);\n } else if (template === 'laravel') {\n await generateTemplate(LARAVEL_REPO);\n renameTemplate(LARAVEL_DIR, projectName);\n } else {\n // If add new template and not update this template, it will be exhaustive check error\n _exhaustiveCheck = template;\n }\n\n const npmrcFile = resolver(`${ROOT}/${projectName}/.npmrc`);\n\n /** ======================== Change default npmrc content ======================== */\n changeNpmrc(npmrcFile);\n\n /** ======================== Pnpm setup (optional) ======================== */\n if (packageName === 'pnpm') {\n fixPnpm(npmrcFile, true, false, ({message}) => {\n p.log.message(message);\n });\n }\n\n /** ======================== Add guide ======================== */\n p.note(\n `cd ${chalk.cyanBright(projectName)}\\n${chalk.cyanBright(packageName)} install`,\n 'Next steps'\n );\n\n p.outro(`🚀 Get started with ${chalk.cyanBright(`${packageName} ${run} dev`)}`);\n\n process.exit(0);\n}\n\n/** ======================== Helper function ======================== */\nasync function generateTemplate(url: string) {\n await taskClack({\n failText: 'Template creation failed',\n successText: 'Template created successfully!',\n task: downloadTemplate(ROOT, url),\n text: 'Creating template...'\n });\n}\n\nfunction renameTemplate(originName: string, projectName: string) {\n try {\n renameSync(join(ROOT, originName), join(ROOT, projectName));\n } catch (error) {\n if (error) {\n p.cancel(`rename Error: ${error}`);\n process.exit(0);\n }\n }\n}\n\nexport type GenerateOptions<T, Last = GetUnionLastValue<T>> = [T] extends [never]\n ? []\n : [\n ...GenerateOptions<Exclude<T, Last>>,\n {\n label: string;\n value: Last;\n hint: string;\n }\n ];\n\nasync function getTableInfo(packageName?: string, projectName?: string, template?: string) {\n const options: GenerateOptions<Exclude<InitActionOptions['template'], undefined>> = [\n {\n hint: 'A Next.js 15 with app directory template pre-configured with HeroUI (v2) and Tailwind CSS.',\n label: 'App',\n value: 'app'\n },\n {\n hint: 'A Next.js 15 with pages directory template pre-configured with HeroUI (v2) and Tailwind CSS.',\n label: 'Pages',\n value: 'pages'\n },\n {\n hint: 'A Vite template pre-configured with HeroUI (v2) and Tailwind CSS.',\n label: 'Vite',\n value: 'vite'\n },\n {\n hint: 'A Remix template pre-configured with HeroUI (v2) and Tailwind CSS.',\n label: 'Remix',\n value: 'remix'\n },\n {\n hint: 'A Laravel template pre-configured with HeroUI (v2) and Tailwind CSS.',\n label: 'Laravel',\n value: 'laravel'\n }\n ];\n\n template = (await selectClack({\n initialValue: template,\n message: 'Select a template (Enter to select)',\n options\n })) as string;\n\n projectName = (await textClack({\n initialValue: projectName ?? templatesMap[template],\n message: 'New project name (Enter to skip with default name)',\n placeholder: projectName ?? templatesMap[template]\n })) as string;\n\n packageName = (await selectClack({\n initialValue: packageName,\n message: 'Select a package manager (Enter to select)',\n options: [\n {\n label: chalk.gray('npm'),\n value: 'npm'\n },\n {\n label: chalk.gray('yarn'),\n value: 'yarn'\n },\n {\n label: chalk.gray('pnpm'),\n value: 'pnpm'\n },\n {\n label: chalk.gray('bun'),\n value: 'bun'\n }\n ]\n })) as Agent;\n\n return {\n packageName: packageName as Agent,\n projectName,\n template: template as Exclude<InitActionOptions['template'], undefined>\n };\n}\n","import {writeFileSync} from 'node:fs';\n\nconst DEFAULT_NPMRC_CONTENT = `package-lock=true`;\n\n/**\n * Change the npmrc file to the default content\n * Currently it is using `package-lock=false` which won't generate the lockfile\n */\nexport function changeNpmrc(npmrcFile: string) {\n writeFileSync(npmrcFile, DEFAULT_NPMRC_CONTENT, 'utf-8');\n}\n","import type {SAFE_ANY} from './type';\n\nimport {type InitActionOptions, templatesMap} from 'src/actions/init-action';\n\nimport {AGENTS, type Agent} from './detect';\nimport {printMostMatchText} from './math-diff';\n\nexport function checkInitOptions(template: InitActionOptions['template'], agent: Agent) {\n if (template) {\n if (!Object.keys(templatesMap).includes(template)) {\n printMostMatchText(Object.keys(templatesMap), template);\n }\n }\n if (agent) {\n if (!AGENTS.includes(agent)) {\n printMostMatchText(AGENTS as SAFE_ANY, agent);\n }\n }\n}\n","import {Logger} from '@helpers/logger';\nimport {outputComponents} from '@helpers/output-info';\nimport {getPackageInfo} from '@helpers/package';\nimport {store} from 'src/constants/store';\n\nimport {type HeroUIComponents} from '../../src/constants/component';\nimport {resolver} from '../../src/constants/path';\n\ninterface ListActionOptions {\n remote?: boolean;\n packagePath?: string;\n}\n\nexport async function listAction(options: ListActionOptions) {\n const {packagePath = resolver('package.json'), remote = false} = options;\n\n let components = store.heroUIComponents as HeroUIComponents;\n\n try {\n /** ======================== Get the installed components ======================== */\n if (!remote) {\n const {currentComponents} = await getPackageInfo(packagePath);\n\n components = currentComponents;\n }\n\n if (!components.length) {\n Logger.warn(`No HeroUI components detected in the specified package.json at: ${packagePath}`);\n\n return;\n }\n\n /** ======================== Output the components ======================== */\n remote ? outputComponents({commandName: 'list', components}) : outputComponents({components});\n } catch (error) {\n Logger.prefix('error', `An error occurred while attempting to list the components: ${error}`);\n }\n\n process.exit(0);\n}\n","/* eslint-disable no-var */\nimport type {SAFE_ANY} from '@helpers/type';\n\nimport {existsSync, readFileSync, writeFileSync} from 'node:fs';\n\nimport chalk from 'chalk';\n\nimport {checkIllegalComponents} from '@helpers/check';\nimport {detect} from '@helpers/detect';\nimport {Logger} from '@helpers/logger';\nimport {outputComponents} from '@helpers/output-info';\nimport {\n getPackageInfo,\n transformComponentsToPackage,\n transformPackageDetail\n} from '@helpers/package';\nimport {removeDependencies, removeTailwind} from '@helpers/remove';\nimport {findFiles} from '@helpers/utils';\nimport {resolver} from 'src/constants/path';\nimport {\n DOCS_PROVIDER_SETUP,\n HERO_UI,\n SYSTEM_UI,\n THEME_UI,\n pnpmRequired\n} from 'src/constants/required';\nimport {getAutocompleteMultiselect, getSelect} from 'src/prompts';\n\ninterface RemoveOptionsAction {\n packagePath: string;\n all?: boolean;\n tailwindPath?: string;\n prettier?: boolean;\n}\n\nexport async function removeAction(components: string[], options: RemoveOptionsAction) {\n const {\n all = false,\n packagePath = resolver('package.json'),\n tailwindPath = findFiles('**/tailwind.config.(j|t)s')[0]\n } = options;\n\n var {allDependencies, allDependenciesKeys, currentComponents} = getPackageInfo(packagePath);\n const packageManager = await detect();\n const prettier = options.prettier ?? allDependenciesKeys.has('prettier');\n\n let isHeroUIAll = !!allDependencies[HERO_UI];\n\n // If no Installed HeroUI components then exit\n if (!currentComponents.length && !isHeroUIAll) {\n Logger.prefix('error', `No HeroUI components detected in your package.json at: ${packagePath}`);\n\n return;\n }\n\n if (all || isHeroUIAll) {\n components = isHeroUIAll ? [HERO_UI] : currentComponents.map((component) => component.package);\n } else if (!components.length) {\n components = await getAutocompleteMultiselect(\n 'Select the components to remove',\n currentComponents.map((component) => {\n return {\n title: component.package,\n value: component.package\n };\n })\n );\n } else {\n // Check if the custom input components are valid\n if (!checkIllegalComponents(components)) {\n return;\n }\n\n // Transform components to package\n components = transformComponentsToPackage(components);\n }\n\n // Ask user whether need to remove these components\n const filteredComponents = components.includes(HERO_UI)\n ? await transformPackageDetail(components, allDependencies)\n : currentComponents.filter((component) =>\n components.some((c) => c.includes(component.package) || c.includes(component.name))\n );\n\n outputComponents({\n components: filteredComponents,\n message: chalk.yellowBright('❗️ Components slated for removal:')\n });\n\n const isRemove = await getSelect('Confirm removal of these components:', [\n {title: 'Yes', value: true},\n {title: 'No', value: false}\n ]);\n\n if (!isRemove) {\n // Exit the process\n process.exit(0);\n }\n\n /** ======================== Step 1 Remove dependencies ======================== */\n const removeDepList: string[] = [...components];\n const filterComponents = currentComponents.filter((c) => !components.includes(c.package));\n\n if (!filterComponents.length) {\n // Remove the selected components if not components leave then remove the theme-ui and system-ui\n allDependencies[THEME_UI] && removeDepList.push(THEME_UI);\n allDependencies[SYSTEM_UI] && removeDepList.push(SYSTEM_UI);\n }\n\n await removeDependencies(removeDepList, packageManager);\n\n /** ======================== Step 2 Remove the content ======================== */\n // Get the new package information\n var {allDependencies, currentComponents} = getPackageInfo(packagePath, false);\n\n isHeroUIAll = !!allDependencies[HERO_UI];\n\n const type: SAFE_ANY = isHeroUIAll ? 'all' : 'partial';\n\n removeTailwind(type, {\n currentComponents,\n isHeroUIAll,\n isPnpm: packageManager === 'pnpm',\n prettier,\n tailwindPath: tailwindPath!\n });\n\n /** ======================== Step 3 Remove the pnpm ======================== */\n if (!currentComponents.length && !isHeroUIAll) {\n if (packageManager === 'pnpm') {\n const npmrcPath = resolver('.npmrc');\n\n if (existsSync(npmrcPath)) {\n let content = readFileSync(npmrcPath, 'utf-8');\n\n content = content.replace(pnpmRequired.content, '');\n\n Logger.newLine();\n Logger.info('Removing specified .npmrc file content');\n\n writeFileSync(npmrcPath, content, 'utf-8');\n }\n }\n\n Logger.newLine();\n Logger.warn(\n `No HeroUI components remain installed. Ensure the HeroUIProvider is also removed if necessary.\\nFor more information, visit: ${DOCS_PROVIDER_SETUP}`\n );\n }\n\n Logger.newLine();\n\n Logger.success(\n `✅ Successfully removed the specified HeroUI components: ${components\n .map((c) => chalk.underline(c))\n .join(', ')}`\n );\n\n process.exit(0);\n}\n","import type {Agent} from './detect';\nimport type {HeroUIComponents} from 'src/constants/component';\n\nimport {existsSync, readFileSync, writeFileSync} from 'node:fs';\n\nimport {tailwindRequired} from 'src/constants/required';\n\nimport {type CheckType, checkTailwind} from './check';\nimport {exec} from './exec';\nimport {fixTailwind} from './fix';\nimport {Logger} from './logger';\nimport {getMatchArray, replaceMatchArray} from './match';\nimport {getPackageManagerInfo} from './utils';\n\nexport async function removeDependencies(components: string[], packageManager: Agent) {\n const {remove} = getPackageManagerInfo(packageManager);\n\n await exec(`${packageManager} ${remove} ${components.join(' ')}`);\n\n return;\n}\n\nexport async function removeTailwind(\n type: CheckType,\n options: {\n tailwindPath?: string;\n currentComponents: HeroUIComponents;\n isPnpm: boolean;\n prettier: boolean;\n isHeroUIAll: boolean;\n }\n) {\n const {currentComponents, isHeroUIAll, isPnpm, prettier, tailwindPath} = options;\n\n if (tailwindPath && !existsSync(tailwindPath)) {\n Logger.prefix('warn', `No tailwind.config.(j|t)s found remove action skipped`);\n\n return;\n }\n\n let tailwindContent = readFileSync(tailwindPath!, 'utf-8');\n const contentMatch = getMatchArray('content', tailwindContent);\n const pluginsMatch = getMatchArray('plugins', tailwindContent);\n\n const insIncludeAll = contentMatch.some((c) => c.includes(tailwindRequired.content));\n\n // Not installed HeroUI components then remove the tailwind content about heroui\n if (!currentComponents.length && !isHeroUIAll) {\n const index = pluginsMatch.findIndex((c) => c.includes('heroui'));\n\n index !== -1 && pluginsMatch.splice(index, 1);\n tailwindContent = replaceMatchArray('plugins', tailwindContent, pluginsMatch);\n\n // Remove the import heroui content\n tailwindContent = tailwindContent.replace(/(const|var|let|import)[\\W\\w]+?heroui.*?;\\n/, '');\n }\n\n // If there are already have all heroui content include then don't need to remove the content\n if (!insIncludeAll) {\n // Remove the heroui content\n while (contentMatch.some((c) => c.includes('heroui'))) {\n contentMatch.splice(\n contentMatch.findIndex((c) => c.includes('heroui')),\n 1\n );\n }\n tailwindContent = replaceMatchArray('content', tailwindContent, contentMatch);\n }\n // if (!currentComponents.length && isHeroUIAll) {\n // const index = contentMatch.findIndex(c => c.includes('heroui'));\n\n // // Remove the heroui content\n // index !== -1 &&\n // contentMatch.splice(\n // contentMatch.indexOf('./node_modules/@heroui/theme/dist/components'),\n // 1\n // );\n // tailwindContent = replaceMatchArray('content', tailwindContent, contentMatch);\n // } else if (!isHeroUIAll && currentComponents.length) {\n // const index = contentMatch.indexOf(tailwindRequired.content);\n\n // // Remove the heroui content\n // index !== -1 && contentMatch.splice(index, 1);\n // tailwindContent = replaceMatchArray('content', tailwindContent, contentMatch);\n // }\n // Write the tailwind content\n writeFileSync(tailwindPath!, tailwindContent, 'utf-8');\n\n const [, ...errorInfoList] = checkTailwind(\n type as 'partial',\n tailwindPath!,\n currentComponents,\n isPnpm,\n undefined,\n true\n );\n\n fixTailwind(type, {errorInfoList, format: prettier, tailwindPath: tailwindPath!});\n\n Logger.newLine();\n Logger.info(`Remove the removed components tailwind content in file: ${tailwindPath}`);\n}\n","import type {AppendKeyValue} from '@helpers/type';\n\nimport fs from 'node:fs';\n\nimport {catchPnpmExec} from '@helpers/actions/upgrade/catch-pnpm-exec';\nimport {checkIllegalComponents} from '@helpers/check';\nimport {getConditionVersion} from '@helpers/condition-value';\nimport {detect} from '@helpers/detect';\nimport {exec} from '@helpers/exec';\nimport {Logger} from '@helpers/logger';\nimport {colorMatchRegex} from '@helpers/output-info';\nimport {getPackageInfo} from '@helpers/package';\nimport {setupPnpm} from '@helpers/setup';\nimport {upgrade, writeUpgradeVersion} from '@helpers/upgrade';\nimport {getColorVersion, getPackageManagerInfo, transformPeerVersion} from '@helpers/utils';\nimport {type HeroUIComponents} from 'src/constants/component';\nimport {resolver} from 'src/constants/path';\nimport {HERO_UI} from 'src/constants/required';\nimport {store} from 'src/constants/store';\nimport {getAutocompleteMultiselect, getMultiselect, getSelect} from 'src/prompts';\nimport {compareVersions} from 'src/scripts/helpers';\n\ninterface UpgradeActionOptions {\n packagePath?: string;\n all?: boolean;\n major?: boolean;\n minor?: boolean;\n patch?: boolean;\n write?: boolean;\n beta?: boolean;\n}\n\ntype TransformComponent = Required<\n AppendKeyValue<HeroUIComponents[0], 'latestVersion', string> & {isLatest: boolean}\n>;\n\nfunction betaCompareVersions(version: string, latestVersion: string, beta: boolean) {\n // compareResult(beta, 2.1.0) = 0\n // So we need to check if it is autoChangeTag like `beta` or `canary` and latestVersion is not match `beta` or `canary` then return false\n // Example: `beta` Compare `2.1.0` (not latest), `beta` Compare `2.1.0-beta.0` (latest)\n const autoChangeTag = version.match(/(^\\w+$)/)?.[1];\n\n if (autoChangeTag) {\n return latestVersion.includes(autoChangeTag);\n }\n\n const compareResult = compareVersions(version, latestVersion);\n\n // Beta version is greater than latest version if beta is true\n // compareResult(2.1.0, 2.1.0-beta.0) = 1\n // Example: 2.1.0 < 2.1.0-beta.0\n return beta && compareResult === 1 && !version.includes('beta') ? false : compareResult >= 0;\n}\n\nexport async function upgradeAction(components: string[], options: UpgradeActionOptions) {\n const {\n all = false,\n beta = false,\n packagePath = resolver('package.json'),\n write = false\n } = options;\n const {allDependencies, currentComponents, dependencies, devDependencies, packageJson} =\n getPackageInfo(packagePath, false);\n\n const isHeroUIAll = !!allDependencies[HERO_UI];\n\n const transformComponents: TransformComponent[] = [];\n\n await Promise.all(\n currentComponents.map(async (component) => {\n const mergedVersion = await getConditionVersion(component.package);\n const compareResult = betaCompareVersions(component.version, mergedVersion, beta);\n\n transformComponents.push({\n ...component,\n isLatest: compareResult,\n latestVersion: mergedVersion\n });\n })\n );\n\n // If no Installed HeroUI components then exit\n if (!transformComponents.length && !isHeroUIAll) {\n Logger.prefix('error', `No HeroUI components detected in your package.json at: ${packagePath}`);\n\n return;\n }\n\n if (all) {\n components = currentComponents.map((component) => component.package);\n } else if (!components.length) {\n // If have the main heroui then add\n if (isHeroUIAll) {\n const latestVersion = await getConditionVersion(HERO_UI);\n const herouiData = {\n isLatest:\n compareVersions(latestVersion, transformPeerVersion(allDependencies[HERO_UI])) <= 0,\n latestVersion,\n package: HERO_UI,\n version: transformPeerVersion(allDependencies[HERO_UI])\n } as TransformComponent;\n\n transformComponents.push(herouiData);\n }\n\n // If all package is latest then pass\n if (transformComponents.every((component) => component.isLatest)) {\n Logger.success('✅ All HeroUI packages are up to date');\n process.exit(0);\n }\n\n components = await getAutocompleteMultiselect(\n 'Select the components to upgrade',\n transformComponents.map((component) => {\n const isUpToDate = betaCompareVersions(component.version, component.latestVersion, beta);\n\n return {\n disabled: isUpToDate,\n disabledMessage: 'Already up to date',\n title: `${component.package}${\n isUpToDate\n ? ''\n : `@${component.version} -> ${getColorVersion(\n component.version,\n component.latestVersion\n )}`\n }`,\n value: component.package\n };\n })\n );\n } else {\n // Check if the components are valid\n if (!checkIllegalComponents(components)) {\n return;\n }\n }\n\n components = components.map((c) => {\n if (store.heroUIComponentsMap[c]?.package) {\n return store.heroUIComponentsMap[c]!.package;\n }\n\n return c;\n });\n\n /** ======================== Upgrade ======================== */\n const upgradeOptionList = transformComponents.filter((c) => components.includes(c.package));\n\n let result = await upgrade({\n all,\n allDependencies,\n isHeroUIAll,\n upgradeOptionList\n });\n let ignoreList: string[] = [];\n const packageManager = await detect();\n\n if (result.length) {\n const isExecute = await getSelect('Would you like to proceed with the upgrade?', [\n {\n title: 'Yes',\n value: true\n },\n {\n description: 'Select this if you wish to exclude certain packages from the upgrade',\n title: 'No',\n value: false\n }\n ]);\n\n const {install} = getPackageManagerInfo(packageManager);\n\n if (!isExecute) {\n // Ask whether need to remove some package not to upgrade\n const isNeedRemove = await getSelect(\n 'Would you like to exclude any packages from the upgrade?',\n [\n {\n description: 'Select this to choose packages to exclude',\n title: 'Yes',\n value: true\n },\n {\n description: 'Select this to proceed without excluding any packages',\n title: 'No',\n value: false\n }\n ]\n );\n\n if (isNeedRemove) {\n ignoreList = await getMultiselect(\n 'Select the packages you want to exclude from the upgrade:',\n result.map((c) => {\n return {\n description: `${c.version} -> ${getColorVersion(c.version, c.latestVersion)}`,\n title: c.package,\n value: c.package\n };\n })\n );\n }\n }\n\n // Remove the components that need to be ignored\n result = result.filter((r) => {\n return !ignoreList.some((ignore) => r.package === ignore);\n });\n\n if (write) {\n // Write the upgrade version to the package file\n writeUpgradeVersion({\n dependencies,\n devDependencies,\n upgradePackageList: result\n });\n\n fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2), 'utf-8');\n\n Logger.newLine();\n Logger.success('✅ Upgrade version written to package.json');\n process.exit(0);\n } else {\n await catchPnpmExec(() =>\n exec(\n `${packageManager} ${install} ${result.reduce((acc, component, index) => {\n return `${acc}${index === 0 ? '' : ' '}${\n component.package\n }@${component.latestVersion.replace(colorMatchRegex, '')}`;\n }, '')}`\n )\n );\n }\n }\n\n /** ======================== Setup Pnpm ======================== */\n setupPnpm(packageManager);\n\n Logger.newLine();\n Logger.success('✅ Upgrade complete. All components are up to date.');\n\n process.exit(0);\n}\n","import type {Agent} from './detect';\n\nimport {existsSync, writeFileSync} from 'node:fs';\n\nimport {resolver} from 'src/constants/path';\nimport {pnpmRequired} from 'src/constants/required';\n\nimport {checkPnpm} from './check';\nimport {fixPnpm} from './fix';\n\nexport async function setupPnpm(packageManager: Agent) {\n if (packageManager === 'pnpm') {\n const npmrcPath = resolver('.npmrc');\n\n if (!existsSync(npmrcPath)) {\n writeFileSync(resolver('.npmrc'), pnpmRequired.content, 'utf-8');\n } else {\n const [isCorrectPnpm] = checkPnpm(npmrcPath);\n\n if (!isCorrectPnpm) {\n fixPnpm(npmrcPath);\n }\n }\n }\n}\n"]} node_modules/heroui-cli/README.md 0000664 00000041511 15114743311 0012544 0 ustar 00 <p align="center"> <a href="https://heroui.com"> <img width="20%" src="https://raw.githubusercontent.com/heroui-inc/heroui/main/apps/docs/public/isotipo.png" alt="heroui (previously nextui)" /> <h1 align="center">HeroUI CLI (Previously NextUI CLI)</h1> </a> </p> </br> <p align="center"> <a href="https://github.com/heroui-inc/heroui-cli/blob/main/license"> <img src="https://img.shields.io/npm/l/@heroui-inc/heroui?style=flat" alt="License"> </a> <a href="https://www.npmjs.com/package/heroui-cli"> <img src="https://img.shields.io/npm/dm/heroui-cli.svg?style=flat-round" alt="npm downloads"> </a> </p> The CLI offers a comprehensive suite of commands to initialize, manage, and improve your HeroUI projects. It enables you to `add`, `remove`, or `upgrade` individual components, assess the health of your project, and more. ## Quick Start > **Note**: The HeroUI CLI requires [Node.js](https://nodejs.org/en) _18.17.x+_ or later You can choose the following ways to start the HeroUI CLI. ### Npx ```bash npx heroui-cli@latest ``` ### Global Installation ```bash npm install -g heroui-cli ``` ## Usage ```bash Usage: heroui [command] Options: -v, --version Output the current version --no-cache Disable cache, by default data will be cached for 30m after the first request -d, --debug Debug mode will not install dependencies -h --help Display help information for commands Commands: init [options] [projectName] Initializes a new project add [options] [targets...] 1. Adds components to your project 2. Adds HeroUI Chat codebase to your project upgrade [options] [components...] Upgrades project components to the latest versions remove [options] [components...] Removes components from the project list [options] Lists all components, showing status, descriptions, and versions env [options] Displays debugging information for the local environment doctor [options] Checks for issues in the project help [command] Display help for command ``` ## Commands ### Init Initialize a new HeroUI project with official templates. ```bash heroui init [projectName] [options] ``` #### Init Options - `-t --template [string]` The template to use for the new project e.g. app, laravel, pages, remix, vite - `-p --package [string]` The package manager to use for the new project (default: `npm`) ##### Example ```bash # Initialize a new HeroUI project with the app template, named my-heroui-app heroui init my-heroui-app -t app ``` output: ```bash HeroUI CLI v0.2.1 ┌ Create a new project │ ◇ Select a template (Enter to select) │ ● App (A Next.js 15 with app directory template pre-configured with HeroUI (v2) and Tailwind CSS.) │ ○ Pages (A Next.js 15 with pages directory template pre-configured with HeroUI (v2) and Tailwind CSS.) │ ○ Vite (A Vite template pre-configured with HeroUI (v2) and Tailwind CSS.) │ ○ Remix (A Remix template pre-configured with HeroUI (v2) and Tailwind CSS.) │ ○ Laravel (A Laravel template pre-configured with HeroUI (v2) and Tailwind CSS.) │ ◇ New project name (Enter to skip with default name) │ my-heroui-app │ ◇ Select a package manager (Enter to select) │ ● npm │ ○ yarn │ ○ pnpm │ ○ bun │ ◇ Template created successfully! │ ◇ Next steps ───────╮ │ │ │ cd my-heroui-app │ │ npm install │ │ │ ├────────────────────╯ │ └ 🚀 Get started with npm run dev ``` ### Add 1. Add HeroUI components to your project. 2. Add HeroUI Chat codebase to your project. #### Features > 1. Auto add the missing required `dependencies` to your project > 2. Auto add the required `tailwindcss.config.js` configuration to your project > 3. Detect whether using pnpm, if so, add the required configuration to your `.npmrc` file > 4. Add HeroUI Chat codebase to your project ```bash heroui add [targets...] [options] ``` #### Add Options - `-a --all` [boolean] Add all components (default: `false`) - `-p --packagePath` [string] The path to the package.json file - `-tw --tailwindPath` [string] The path to the tailwind.config file file - `-app --appPath` [string] The path to the App.tsx file - `--prettier` [boolean] Add prettier format in the add content which required installed prettier - (default: `false`) - `--addApp` [boolean] Add App.tsx file content which required provider (default: `false`) - `-b --beta` [boolean] Add beta components (default: `false`) - `-d --directory` [string] Add HeroUI Chat codebase to a specific directory ##### Example Without setting a specific component, the `add` command will show a list of available components. ```bash heroui add ``` Output: ```bash HeroUI CLI v0.2.1 ? Which components would you like to add? › - Space to select. Return to submit Instructions: ↑/↓: Highlight option ←/→/[space]: Toggle selection [a,b,c]/delete: Filter choices enter/return: Complete answer Filtered results for: Enter something to filter ◉ accordion ◯ autocomplete ◯ avatar ◯ badge ◯ breadcrumbs ◯ button ◯ card ◯ checkbox ◯ chip ◯ code ``` If you want to add a specific component, you can specify the component name. ```bash heroui add button ``` Output: ```bash HeroUI CLI v0.2.1 Adding the required dependencies: @heroui/button pnpm add @heroui/button Packages: +1 + Progress: resolved 470, reused 462, downloaded 0, added 0, done dependencies: + @heroui/button 2.0.24 Done in 3.4s Tailwind CSS settings have been updated in: /project-path/tailwind.config.js ✅ Components added successfully ``` ### Upgrade Upgrade the HeroUI components to the latest version. ```bash heroui upgrade [components...] [options] ``` #### Upgrade Options - `-p --packagePath` [string] The path to the package.json file - `-a --all` [boolean] Upgrade all the HeroUI components (default: `false`) - `-w --write` [boolean] Write the upgrade version to package.json file (default: `false`) - `-b --beta` [boolean] Upgrade beta components (default: `false`) - `-h --help` Display help for command ##### Example Upgrade the **Button** component to the latest version. ```bash heroui upgrade button ``` Output: ```bash HeroUI CLI v0.2.1 ╭───────────────────────── Component ─────────────────────────╮ │ @heroui/button ^2.0.11 -> ^2.0.31 │ ╰─────────────────────────────────────────────────────────────╯ Required min version: @heroui/theme>=2.1.0, tailwindcss>=3.4.0, react>=18.3.1, react-dom>=18.3.1 ╭───────────────────── PeerDependencies ─────────────────────╮ │ @heroui/theme 2.0.1 -> 2.1.0 │ │ tailwindcss ^3.2.3 -> ^3.4.0 │ │ react Missing -> 18.3.1 │ │ react-dom Missing -> 18.3.1 │ ╰────────────────────────────────────────────────────────────╯ 2 major, 2 minor, 1 patch ? Would you like to proceed with the upgrade? › - Use arrow-keys. Return to submit. ❯ Yes No pnpm add @heroui/button@2.0.31 @heroui/theme@2.1.0 tailwindcss@3.4.0 react@18.3.1 react-dom@18.3.1 dependencies: - @heroui/theme 2.0.1 + @heroui/theme 2.1.0 (2.2.3 is available) + react 18.3.1 + react-dom 18.3.1 Done in 1.8s ✅ Upgrade complete. All components are up to date. ``` ### Remove Remove HeroUI components from your project. > **Note**: If there are no HeroUI components after removing, the required content will also be removed ```bash heroui remove [components...] [options] ``` #### Remove Options - `-p --packagePath` [string] The path to the package.json file - `-a --all` [boolean] Remove all the HeroUI components (default: `false`) - `-tw --tailwindPath` [string] The path to the tailwind.config file file - `--prettier` [boolean] Add prettier format in the add content which required installed prettier - (default: `false`) ##### Example Remove the **Button** component from your project. ```bash heroui remove button ``` Output: ```bash HeroUI CLI v0.2.1 ❗️ Components slated for removal: ╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ Package │ Version │ Status │ Docs │ │──────────────────────────────────────────────────────────────────────────────────────────────────────────────│ │ @heroui/button │ 2.0.27 🚀latest │ stable │ https://heroui.com/docs/components/button │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ? Confirm removal of these components: › - Use arrow-keys. Return to submit. ❯ Yes No pnpm remove @heroui/button Already up to date Progress: resolved 474, reused 465, downloaded 0, added 0, done dependencies: - @heroui/button 2.0.27 Done in 2.1s Remove the removed components tailwind content in file:/project-path/tailwind.config.js ✅ Successfully removed the specified HeroUI components: @heroui/button ``` ### List List all the current installed components. ```bash heroui list [options] ``` #### List Options - `-p --packagePath` [string] The path to the package.json file - `-r --remote` List all components available remotely ##### Example ```bash heroui list ``` Output: ```bash HeroUI CLI v0.2.1 Current installed components: ╭───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ Package │ Version │ Status │ Docs │ │───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────│ │ @heroui/autocomplete │ 2.0.10 🚀latest │ stable │ https://heroui.com/docs/components/autocomplete │ │ @heroui/badge │ 2.0.24 🚀latest │ stable │ https://heroui.com/docs/components/badge │ │ @heroui/button │ 2.0.27 🚀latest │ stable │ https://heroui.com/docs/components/button │ │ @heroui/chip │ 2.0.25 🚀latest │ stable │ https://heroui.com/docs/components/chip │ ╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ``` ### Doctor Check whether exist problem in your project by using the `doctor` command. ```bash heroui doctor [options] ``` ### Features > 1. Check whether have `redundant dependencies` in the project > 2. Check whether the HeroUI components `required dependencies are installed` in the project > 3. Check the required `tailwind.config.js` file and the content is correct > 4. Check `.npmrc` is correct when using `pnpm` > 5. Check `peerDependencies with required version` are installed in the project #### Doctor Options - `-p` `--packagePath` [string] The path to the package.json file - `-tw` `--tailwindPath` [string] The path to the tailwind.config file file - `-app` `--appPath` [string] The path to the App.tsx file - `-ca` `--checkApp` [boolean] Open check App (default: `true`) - `-ct` `--checkTailwind` [boolean] Open check tailwind.config file (default: `true`) - `-cp` `--checkPnpm` [boolean] Open check Pnpm (default: `true`) #### Example ```bash heroui doctor ``` Output: If there is a problem in your project, the `doctor` command will display the problem information. ```bash HeroUI CLI v0.2.1 HeroUI CLI: ❌ Your project has 1 issue that require attention ❗️Issue 1: missingTailwind Missing tailwind.config.(j|t)s file. To set up, visit: https://heroui.com/docs/guide/installation#tailwind-css-setup ``` Otherwise, the `doctor` command will display the following message. ```bash HeroUI CLI v0.2.1 ✅ Your project has no detected issues. ``` ### Env Display debug information about the local environment. ```bash heroui env [options] ``` #### Env Options - `-p --packagePath` [string] The path to the package.json file #### Example Display the local environment Information by using the `env` command. ```bash heroui env ``` Output: ```bash HeroUI CLI v0.2.1 Current installed components: ╭───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ Package │ Version │ Status │ Docs │ │───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────│ │ @heroui/autocomplete │ 2.0.10 🚀latest │ stable │ https://heroui.com/docs/components/autocomplete │ │ @heroui/badge │ 2.0.24 🚀latest │ stable │ https://heroui.com/docs/components/badge │ │ @heroui/button │ 2.0.27 🚀latest │ stable │ https://heroui.com/docs/components/button │ │ @heroui/chip │ 2.0.25 🚀latest │ stable │ https://heroui.com/docs/components/chip │ ╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ Environment Info: System: OS: darwin CPU: arm64 Binaries: Node: v18.18.2 ``` ## Documentation Visit [https://heroui.com/docs/guide/cli](https://heroui.com/docs/guide/cli) to view the full documentation. ### Community We're excited to see the community adopt HeroUI CLI, raise issues, and provide feedback. Whether it's a feature request, bug report, or a project to showcase, please get involved! - [Discord](https://discord.gg/9b6yyZKmH4) - [Twitter](https://twitter.com/hero_ui) - [GitHub Discussions](https://github.com/heroui-inc/heroui-cli/discussions) ## Contributing Contributions are always welcome! See [CONTRIBUTING.md](https://github.com/heroui-inc/heroui-cli/blob/main/CONTRIBUTING.md) for ways to get started. Please adhere to this project's [CODE_OF_CONDUCT](https://github.com/heroui-inc/heroui-cli/blob/main/CODE_OF_CONDUCT.md). ## License [MIT](https://choosealicense.com/licenses/mit/) node_modules/ora/license 0000664 00000002135 15114743311 0011352 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/ora/package.json 0000664 00000002235 15114743311 0012274 0 ustar 00 { "name": "ora", "version": "8.0.1", "description": "Elegant terminal spinner", "license": "MIT", "repository": "sindresorhus/ora", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "default": "./index.js" }, "sideEffects": false, "engines": { "node": ">=18" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "cli", "spinner", "spinners", "terminal", "term", "console", "ascii", "unicode", "loading", "indicator", "progress", "busy", "wait", "idle" ], "dependencies": { "chalk": "^5.3.0", "cli-cursor": "^4.0.0", "cli-spinners": "^2.9.2", "is-interactive": "^2.0.0", "is-unicode-supported": "^2.0.0", "log-symbols": "^6.0.0", "stdin-discarder": "^0.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" }, "devDependencies": { "@types/node": "^20.10.5", "ava": "^5.3.1", "get-stream": "^8.0.1", "transform-tty": "^1.0.11", "tsd": "^0.30.0", "xo": "^0.56.0" } } node_modules/ora/readme.md 0000664 00000017140 15114743311 0011566 0 ustar 00 # ora > Elegant terminal spinner <p align="center"> <br> <img src="screenshot.svg" width="500"> <br> </p> ## Install ```sh npm install ora ``` ## Usage ```js import ora from 'ora'; const spinner = ora('Loading unicorns').start(); setTimeout(() => { spinner.color = 'yellow'; spinner.text = 'Loading rainbows'; }, 1000); ``` ## API ### ora(text) ### ora(options) If a string is provided, it is treated as a shortcut for [`options.text`](#text). #### options Type: `object` ##### text Type: `string` Text to display after the spinner. ##### prefixText Type: `string | () => string` Text or a function that returns text to display before the spinner. No prefix text will be displayed if set to an empty string. ##### suffixText Type: `string | () => string` Text or a function that returns text to display after the spinner text. No suffix text will be displayed if set to an empty string. ##### spinner Type: `string | object`\ Default: `'dots'` <img src="screenshot-spinner.gif" width="14"> Name of one of the [provided spinners](#spinners). See `example.js` in this repo if you want to test out different spinners. On Windows, it will always use the `line` spinner as the Windows command-line doesn't have proper Unicode support. Or an object like: ```js { interval: 80, // Optional frames: ['-', '+', '-'] } ``` ##### color Type: `string`\ Default: `'cyan'`\ Values: `'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray'` The color of the spinner. ##### hideCursor Type: `boolean`\ Default: `true` Set to `false` to stop Ora from hiding the cursor. ##### indent Type: `number`\ Default: `0` Indent the spinner with the given number of spaces. ##### interval Type: `number`\ Default: Provided by the spinner or `100` Interval between each frame. Spinners provide their own recommended interval, so you don't really need to specify this. ##### stream Type: `stream.Writable`\ Default: `process.stderr` Stream to write the output. You could for example set this to `process.stdout` instead. ##### isEnabled Type: `boolean` Force enable/disable the spinner. If not specified, the spinner will be enabled if the `stream` is being run inside a TTY context (not spawned or piped) and/or not in a CI environment. Note that `{isEnabled: false}` doesn't mean it won't output anything. It just means it won't output the spinner, colors, and other ansi escape codes. It will still log text. ##### isSilent Type: `boolean`\ Default: `false` Disable the spinner and all log text. All output is suppressed and `isEnabled` will be considered `false`. ##### discardStdin Type: `boolean`\ Default: `true` Discard stdin input (except Ctrl+C) while running if it's TTY. This prevents the spinner from twitching on input, outputting broken lines on <kbd>Enter</kbd> key presses, and prevents buffering of input while the spinner is running. This has no effect on Windows as there is no good way to implement discarding stdin properly there. ### Instance #### .text <sup>get/set</sup> Change the text after the spinner. #### .prefixText <sup>get/set</sup> Change the text before the spinner. No prefix text will be displayed if set to an empty string. #### .suffixText <sup>get/set</sup> Change the text after the spinner text. No suffix text will be displayed if set to an empty string. #### .color <sup>get/set</sup> Change the spinner color. #### .spinner <sup>get/set</sup> Change the spinner. #### .indent <sup>get/set</sup> Change the spinner indent. #### .isSpinning <sup>get</sup> A boolean of whether the instance is currently spinning. #### .interval <sup>get</sup> The interval between each frame. The interval is decided by the chosen spinner. #### .start(text?) Start the spinner. Returns the instance. Set the current text if `text` is provided. #### .stop() Stop and clear the spinner. Returns the instance. #### .succeed(text?) Stop the spinner, change it to a green `✔` and persist the current text, or `text` if provided. Returns the instance. See the GIF below. #### .fail(text?) Stop the spinner, change it to a red `✖` and persist the current text, or `text` if provided. Returns the instance. See the GIF below. #### .warn(text?) Stop the spinner, change it to a yellow `⚠` and persist the current text, or `text` if provided. Returns the instance. #### .info(text?) Stop the spinner, change it to a blue `ℹ` and persist the current text, or `text` if provided. Returns the instance. #### .stopAndPersist(options?) Stop the spinner and change the symbol or text. Returns the instance. See the GIF below. ##### options Type: `object` ###### symbol Type: `string`\ Default: `' '` Symbol to replace the spinner with. ###### text Type: `string`\ Default: Current `'text'` Text to be persisted after the symbol. ###### prefixText Type: `string`\ Default: Current `prefixText` Text to be persisted before the symbol. No prefix text will be displayed if set to an empty string. ###### suffixText Type: `string`\ Default: Current `suffixText` Text to be persisted after the text after the symbol. No suffix text will be displayed if set to an empty string. <img src="screenshot-2.gif" width="480"> #### .clear() Clear the spinner. Returns the instance. #### .render() Manually render a new frame. Returns the instance. #### .frame() Get a new frame. ### oraPromise(action, text) ### oraPromise(action, options) Starts a spinner for a promise or promise-returning function. The spinner is stopped with `.succeed()` if the promise fulfills or with `.fail()` if it rejects. Returns the promise. ```js import {oraPromise} from 'ora'; await oraPromise(somePromise); ``` #### action Type: `Promise | ((spinner: ora.Ora) => Promise)` #### options Type: `object` All of the [options](#options) plus the following: ##### successText Type: `string | ((result: T) => string) | undefined` The new text of the spinner when the promise is resolved. Keeps the existing text if `undefined`. ##### failText Type: `string | ((error: Error) => string) | undefined` The new text of the spinner when the promise is rejected. Keeps the existing text if `undefined`. ### spinners Type: `Record<string, Spinner>` All [provided spinners](https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json). ## FAQ ### How do I change the color of the text? Use [Chalk](https://github.com/chalk/chalk): ```js import ora from 'ora'; import chalk from 'chalk'; const spinner = ora(`Loading ${chalk.red('unicorns')}`).start(); ``` ### Why does the spinner freeze? JavaScript is single-threaded, so synchronous operations blocks the thread, including the spinner animation. Prefer asynchronous operations whenever possible. ## Related - [cli-spinners](https://github.com/sindresorhus/cli-spinners) - Spinners for use in the terminal - [listr](https://github.com/SamVerschueren/listr) - Terminal task list - [CLISpinner](https://github.com/kiliankoe/CLISpinner) - Terminal spinner library for Swift - [halo](https://github.com/ManrajGrover/halo) - Python port - [spinners](https://github.com/FGRibreau/spinners) - Terminal spinners for Rust - [marquee-ora](https://github.com/joeycozza/marquee-ora) - Scrolling marquee spinner for Ora - [briandowns/spinner](https://github.com/briandowns/spinner) - Terminal spinner/progress indicator for Go - [tj/go-spin](https://github.com/tj/go-spin) - Terminal spinner package for Go - [observablehq.com/@victordidenko/ora](https://observablehq.com/@victordidenko/ora) - Ora port to Observable notebooks - [spinnies](https://github.com/jcarpanelli/spinnies) - Terminal multi-spinner library for Node.js - [kia](https://github.com/HarryPeach/kia) - Simple terminal spinners for Deno 🦕 node_modules/ora/index.d.ts 0000664 00000016415 15114743311 0011714 0 ustar 00 import {type SpinnerName} from 'cli-spinners'; export type Spinner = { readonly interval?: number; readonly frames: string[]; }; export type Color = | 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray'; export type PrefixTextGenerator = () => string; export type SuffixTextGenerator = () => string; export type Options = { /** Text to display after the spinner. */ readonly text?: string; /** Text or a function that returns text to display before the spinner. No prefix text will be displayed if set to an empty string. */ readonly prefixText?: string | PrefixTextGenerator; /** Text or a function that returns text to display after the spinner text. No suffix text will be displayed if set to an empty string. */ readonly suffixText?: string | SuffixTextGenerator; /** Name of one of the provided spinners. See [`example.js`](https://github.com/BendingBender/ora/blob/main/example.js) in this repo if you want to test out different spinners. On Windows, it will always use the line spinner as the Windows command-line doesn't have proper Unicode support. @default 'dots' Or an object like: @example ``` { interval: 80, // Optional frames: ['-', '+', '-'] } ``` */ readonly spinner?: SpinnerName | Spinner; /** The color of the spinner. @default 'cyan' */ readonly color?: Color; /** Set to `false` to stop Ora from hiding the cursor. @default true */ readonly hideCursor?: boolean; /** Indent the spinner with the given number of spaces. @default 0 */ readonly indent?: number; /** Interval between each frame. Spinners provide their own recommended interval, so you don't really need to specify this. Default: Provided by the spinner or `100`. */ readonly interval?: number; /** Stream to write the output. You could for example set this to `process.stdout` instead. @default process.stderr */ readonly stream?: NodeJS.WritableStream; /** Force enable/disable the spinner. If not specified, the spinner will be enabled if the `stream` is being run inside a TTY context (not spawned or piped) and/or not in a CI environment. Note that `{isEnabled: false}` doesn't mean it won't output anything. It just means it won't output the spinner, colors, and other ansi escape codes. It will still log text. */ readonly isEnabled?: boolean; /** Disable the spinner and all log text. All output is suppressed and `isEnabled` will be considered `false`. @default false */ readonly isSilent?: boolean; /** Discard stdin input (except Ctrl+C) while running if it's TTY. This prevents the spinner from twitching on input, outputting broken lines on `Enter` key presses, and prevents buffering of input while the spinner is running. This has no effect on Windows as there's no good way to implement discarding stdin properly there. @default true */ readonly discardStdin?: boolean; }; export type PersistOptions = { /** Symbol to replace the spinner with. @default ' ' */ readonly symbol?: string; /** Text to be persisted after the symbol. Default: Current `text`. */ readonly text?: string; /** Text or a function that returns text to be persisted before the symbol. No prefix text will be displayed if set to an empty string. Default: Current `prefixText`. */ readonly prefixText?: string | PrefixTextGenerator; /** Text or a function that returns text to be persisted after the text after the symbol. No suffix text will be displayed if set to an empty string. Default: Current `suffixText`. */ readonly suffixText?: string | SuffixTextGenerator; }; export type PromiseOptions<T> = { /** The new text of the spinner when the promise is resolved. Keeps the existing text if `undefined`. */ successText?: string | ((result: T) => string) | undefined; /** The new text of the spinner when the promise is rejected. Keeps the existing text if `undefined`. */ failText?: string | ((error: Error) => string) | undefined; } & Options; // eslint-disable-next-line @typescript-eslint/consistent-type-definitions export interface Ora { /** Change the text after the spinner. */ text: string; /** Change the text or function that returns text before the spinner. No prefix text will be displayed if set to an empty string. */ prefixText: string; /** Change the text or function that returns text after the spinner text. No suffix text will be displayed if set to an empty string. */ suffixText: string; /** Change the spinner color. */ color: Color; /** Change the spinner indent. */ indent: number; /** Get the spinner. */ get spinner(): Spinner; /** Set the spinner. */ set spinner(spinner: SpinnerName | Spinner); /** A boolean of whether the instance is currently spinning. */ get isSpinning(): boolean; /** The interval between each frame. The interval is decided by the chosen spinner. */ get interval(): number; /** Start the spinner. @param text - Set the current text. @returns The spinner instance. */ start(text?: string): this; /** Stop and clear the spinner. @returns The spinner instance. */ stop(): this; /** Stop the spinner, change it to a green `✔` and persist the current text, or `text` if provided. @param text - Will persist text if provided. @returns The spinner instance. */ succeed(text?: string): this; /** Stop the spinner, change it to a red `✖` and persist the current text, or `text` if provided. @param text - Will persist text if provided. @returns The spinner instance. */ fail(text?: string): this; /** Stop the spinner, change it to a yellow `⚠` and persist the current text, or `text` if provided. @param text - Will persist text if provided. @returns The spinner instance. */ warn(text?: string): this; /** Stop the spinner, change it to a blue `ℹ` and persist the current text, or `text` if provided. @param text - Will persist text if provided. @returns The spinner instance. */ info(text?: string): this; /** Stop the spinner and change the symbol or text. @returns The spinner instance. */ stopAndPersist(options?: PersistOptions): this; /** Clear the spinner. @returns The spinner instance. */ clear(): this; /** Manually render a new frame. @returns The spinner instance. */ render(): this; /** Get a new frame. @returns The spinner instance text. */ frame(): string; } /** Elegant terminal spinner. @param options - If a string is provided, it is treated as a shortcut for `options.text`. @example ``` import ora from 'ora'; const spinner = ora('Loading unicorns').start(); setTimeout(() => { spinner.color = 'yellow'; spinner.text = 'Loading rainbows'; }, 1000); ``` */ export default function ora(options?: string | Options): Ora; /** Starts a spinner for a promise or promise-returning function. The spinner is stopped with `.succeed()` if the promise fulfills or with `.fail()` if it rejects. @param action - The promise to start the spinner for or a promise-returning function. @param options - If a string is provided, it is treated as a shortcut for `options.text`. @returns The given promise. @example ``` import {oraPromise} from 'ora'; await oraPromise(somePromise); ``` */ export function oraPromise<T>( action: PromiseLike<T> | ((spinner: Ora) => PromiseLike<T>), options?: string | PromiseOptions<T> ): Promise<T>; export {default as spinners} from 'cli-spinners'; node_modules/ora/index.js 0000664 00000022117 15114743311 0011454 0 ustar 00 import process from 'node:process'; import chalk from 'chalk'; import cliCursor from 'cli-cursor'; import cliSpinners from 'cli-spinners'; import logSymbols from 'log-symbols'; import stripAnsi from 'strip-ansi'; import stringWidth from 'string-width'; import isInteractive from 'is-interactive'; import isUnicodeSupported from 'is-unicode-supported'; import stdinDiscarder from 'stdin-discarder'; class Ora { #linesToClear = 0; #isDiscardingStdin = false; #lineCount = 0; #frameIndex = 0; #options; #spinner; #stream; #id; #initialInterval; #isEnabled; #isSilent; #indent; #text; #prefixText; #suffixText; color; constructor(options) { if (typeof options === 'string') { options = { text: options, }; } this.#options = { color: 'cyan', stream: process.stderr, discardStdin: true, hideCursor: true, ...options, }; // Public this.color = this.#options.color; // It's important that these use the public setters. this.spinner = this.#options.spinner; this.#initialInterval = this.#options.interval; this.#stream = this.#options.stream; this.#isEnabled = typeof this.#options.isEnabled === 'boolean' ? this.#options.isEnabled : isInteractive({stream: this.#stream}); this.#isSilent = typeof this.#options.isSilent === 'boolean' ? this.#options.isSilent : false; // Set *after* `this.#stream`. // It's important that these use the public setters. this.text = this.#options.text; this.prefixText = this.#options.prefixText; this.suffixText = this.#options.suffixText; this.indent = this.#options.indent; if (process.env.NODE_ENV === 'test') { this._stream = this.#stream; this._isEnabled = this.#isEnabled; Object.defineProperty(this, '_linesToClear', { get() { return this.#linesToClear; }, set(newValue) { this.#linesToClear = newValue; }, }); Object.defineProperty(this, '_frameIndex', { get() { return this.#frameIndex; }, }); Object.defineProperty(this, '_lineCount', { get() { return this.#lineCount; }, }); } } get indent() { return this.#indent; } set indent(indent = 0) { if (!(indent >= 0 && Number.isInteger(indent))) { throw new Error('The `indent` option must be an integer from 0 and up'); } this.#indent = indent; this.#updateLineCount(); } get interval() { return this.#initialInterval ?? this.#spinner.interval ?? 100; } get spinner() { return this.#spinner; } set spinner(spinner) { this.#frameIndex = 0; this.#initialInterval = undefined; if (typeof spinner === 'object') { if (spinner.frames === undefined) { throw new Error('The given spinner must have a `frames` property'); } this.#spinner = spinner; } else if (!isUnicodeSupported()) { this.#spinner = cliSpinners.line; } else if (spinner === undefined) { // Set default spinner this.#spinner = cliSpinners.dots; } else if (spinner !== 'default' && cliSpinners[spinner]) { this.#spinner = cliSpinners[spinner]; } else { throw new Error(`There is no built-in spinner named '${spinner}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`); } } get text() { return this.#text; } set text(value = '') { this.#text = value; this.#updateLineCount(); } get prefixText() { return this.#prefixText; } set prefixText(value = '') { this.#prefixText = value; this.#updateLineCount(); } get suffixText() { return this.#suffixText; } set suffixText(value = '') { this.#suffixText = value; this.#updateLineCount(); } get isSpinning() { return this.#id !== undefined; } #getFullPrefixText(prefixText = this.#prefixText, postfix = ' ') { if (typeof prefixText === 'string' && prefixText !== '') { return prefixText + postfix; } if (typeof prefixText === 'function') { return prefixText() + postfix; } return ''; } #getFullSuffixText(suffixText = this.#suffixText, prefix = ' ') { if (typeof suffixText === 'string' && suffixText !== '') { return prefix + suffixText; } if (typeof suffixText === 'function') { return prefix + suffixText(); } return ''; } #updateLineCount() { const columns = this.#stream.columns ?? 80; const fullPrefixText = this.#getFullPrefixText(this.#prefixText, '-'); const fullSuffixText = this.#getFullSuffixText(this.#suffixText, '-'); const fullText = ' '.repeat(this.#indent) + fullPrefixText + '--' + this.#text + '--' + fullSuffixText; this.#lineCount = 0; for (const line of stripAnsi(fullText).split('\n')) { this.#lineCount += Math.max(1, Math.ceil(stringWidth(line, {countAnsiEscapeCodes: true}) / columns)); } } get isEnabled() { return this.#isEnabled && !this.#isSilent; } set isEnabled(value) { if (typeof value !== 'boolean') { throw new TypeError('The `isEnabled` option must be a boolean'); } this.#isEnabled = value; } get isSilent() { return this.#isSilent; } set isSilent(value) { if (typeof value !== 'boolean') { throw new TypeError('The `isSilent` option must be a boolean'); } this.#isSilent = value; } frame() { const {frames} = this.#spinner; let frame = frames[this.#frameIndex]; if (this.color) { frame = chalk[this.color](frame); } this.#frameIndex = ++this.#frameIndex % frames.length; const fullPrefixText = (typeof this.#prefixText === 'string' && this.#prefixText !== '') ? this.#prefixText + ' ' : ''; const fullText = typeof this.text === 'string' ? ' ' + this.text : ''; const fullSuffixText = (typeof this.#suffixText === 'string' && this.#suffixText !== '') ? ' ' + this.#suffixText : ''; return fullPrefixText + frame + fullText + fullSuffixText; } clear() { if (!this.#isEnabled || !this.#stream.isTTY) { return this; } this.#stream.cursorTo(0); for (let index = 0; index < this.#linesToClear; index++) { if (index > 0) { this.#stream.moveCursor(0, -1); } this.#stream.clearLine(1); } if (this.#indent || this.lastIndent !== this.#indent) { this.#stream.cursorTo(this.#indent); } this.lastIndent = this.#indent; this.#linesToClear = 0; return this; } render() { if (this.#isSilent) { return this; } this.clear(); this.#stream.write(this.frame()); this.#linesToClear = this.#lineCount; return this; } start(text) { if (text) { this.text = text; } if (this.#isSilent) { return this; } if (!this.#isEnabled) { if (this.text) { this.#stream.write(`- ${this.text}\n`); } return this; } if (this.isSpinning) { return this; } if (this.#options.hideCursor) { cliCursor.hide(this.#stream); } if (this.#options.discardStdin && process.stdin.isTTY) { this.#isDiscardingStdin = true; stdinDiscarder.start(); } this.render(); this.#id = setInterval(this.render.bind(this), this.interval); return this; } stop() { if (!this.#isEnabled) { return this; } clearInterval(this.#id); this.#id = undefined; this.#frameIndex = 0; this.clear(); if (this.#options.hideCursor) { cliCursor.show(this.#stream); } if (this.#options.discardStdin && process.stdin.isTTY && this.#isDiscardingStdin) { stdinDiscarder.stop(); this.#isDiscardingStdin = false; } return this; } succeed(text) { return this.stopAndPersist({symbol: logSymbols.success, text}); } fail(text) { return this.stopAndPersist({symbol: logSymbols.error, text}); } warn(text) { return this.stopAndPersist({symbol: logSymbols.warning, text}); } info(text) { return this.stopAndPersist({symbol: logSymbols.info, text}); } stopAndPersist(options = {}) { if (this.#isSilent) { return this; } const prefixText = options.prefixText ?? this.#prefixText; const fullPrefixText = this.#getFullPrefixText(prefixText, ' '); const symbolText = options.symbol ?? ' '; const text = options.text ?? this.text; const fullText = (typeof text === 'string') ? ' ' + text : ''; const suffixText = options.suffixText ?? this.#suffixText; const fullSuffixText = this.#getFullSuffixText(suffixText, ' '); const textToWrite = fullPrefixText + symbolText + fullText + fullSuffixText + '\n'; this.stop(); this.#stream.write(textToWrite); return this; } } export default function ora(options) { return new Ora(options); } export async function oraPromise(action, options) { const actionIsFunction = typeof action === 'function'; const actionIsPromise = typeof action.then === 'function'; if (!actionIsFunction && !actionIsPromise) { throw new TypeError('Parameter `action` must be a Function or a Promise'); } const {successText, failText} = typeof options === 'object' ? options : {successText: undefined, failText: undefined}; const spinner = ora(options).start(); try { const promise = actionIsFunction ? action(spinner) : action; const result = await promise; spinner.succeed( successText === undefined ? undefined : (typeof successText === 'string' ? successText : successText(result)), ); return result; } catch (error) { spinner.fail( failText === undefined ? undefined : (typeof failText === 'string' ? failText : failText(error)), ); throw error; } } export {default as spinners} from 'cli-spinners'; node_modules/@types/tinycolor2/package.json 0000664 00000002106 15114743311 0015060 0 ustar 00 { "name": "@types/tinycolor2", "version": "1.4.6", "description": "TypeScript definitions for tinycolor2", "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/tinycolor2", "license": "MIT", "contributors": [ { "name": "Mordechai Zuber", "githubUsername": "M-Zuber", "url": "https://github.com/M-Zuber" }, { "name": "Geert Jansen", "githubUsername": "geertjansen", "url": "https://github.com/geertjansen" }, { "name": "Niels van Hoorn", "githubUsername": "nvh", "url": "https://github.com/nvh" } ], "main": "", "types": "index.d.ts", "repository": { "type": "git", "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", "directory": "types/tinycolor2" }, "scripts": {}, "dependencies": {}, "typesPublisherContentHash": "c26276aefe032ca2f9187a5df23f239a447b4191d50a1417e8b9c916a20f29c0", "typeScriptVersion": "4.5" } node_modules/@types/tinycolor2/LICENSE 0000664 00000002165 15114743311 0013604 0 ustar 00 MIT License Copyright (c) Microsoft Corporation. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE node_modules/@types/tinycolor2/index.d.ts 0000664 00000050620 15114743311 0014477 0 ustar 00 declare namespace tinycolor { type ColorInputWithoutInstance = | string | ColorFormats.PRGB | ColorFormats.PRGBA | ColorFormats.RGB | ColorFormats.RGBA | ColorFormats.HSL | ColorFormats.HSLA | ColorFormats.HSV | ColorFormats.HSVA; type ColorInput = ColorInputWithoutInstance | Instance; namespace ColorFormats { interface Alpha { a: number; } interface PRGB { r: string; g: string; b: string; } interface PRGBA extends PRGB, Alpha {} interface RGB { r: number; g: number; b: number; } interface RGBA extends RGB, Alpha {} interface HSL { h: number; s: number; l: number; } interface HSLA extends HSL, Alpha {} interface HSV { h: number; s: number; v: number; } interface HSVA extends HSV { a: number; } } interface ConstructorOptions { format?: string | undefined; gradientType?: boolean | undefined; } interface WCAG2Options { level?: "AA" | "AAA" | undefined; size?: "large" | "small" | undefined; } interface MostReadableArgs extends WCAG2Options { includeFallbackColors?: boolean | undefined; } interface Constructor { /** * Create a tinycolor instance of the color named. * * @param color - the color as one of the valid color input format. */ new(color?: ColorInput, opts?: ConstructorOptions): Instance; (color?: ColorInput, opts?: ConstructorOptions): Instance; /** * Create a tinycolor instance based off the relative values. * Works with any color formats * * @param ratio - the relative color/hue values to apply to the new instance. */ fromRatio(ratio?: ColorInputWithoutInstance): Instance; /** * Compares two colors. Each colors can be any color inputs. */ equals(color1?: ColorInput, color2?: ColorInput): boolean; /** * Returns a random color */ random(): Instance; mix(color1: ColorInput, color2: ColorInput, amount?: number): Instance; /** * Compares the two colors and returns the constrast between two colors as a number. * * @param color1 - the first color to be used in the comparison. * @param color2 - the second color to be used in the comparison. */ readability(color1: ColorInput, color2: ColorInput): number; /** * Ensure that foreground and background color combinations meet WCAG2 guidelines. * * @param color1 - the fore color wanted. * @param color2 - the back color wanted. * @param wcag2 - WCAG option. If the entire object is absent, function use the default of {level:"AA",size:"small"}. * @param wcag2.level - The 'level' property states 'AA' or 'AAA' * if missing or invalid, it defaults to 'AA' * @param wcag2.size - The 'size' property states 'large' or 'small' * if missing or invalid, it defaults to 'small'. */ isReadable(color1: ColorInput, color2: ColorInput, wcag2?: WCAG2Options): boolean; /** * Given a base color and a list of possible foreground or background colors for that base, * returns the most readable color. Optionally returns Black or White if the most readable color is unreadable. * * @param color - the base color. * @param colorsToCompare - array of colors to pick the most readable one from. * @param args - and object with extra arguments */ mostReadable(baseColor: ColorInput, colorList: ColorInput[], args?: MostReadableArgs): Instance; /** * key: 'real' color name * value: hex value ex. names["red"] --> "f00" */ names: { aliceblue: "f0f8ff"; antiquewhite: "faebd7"; aqua: "0ff"; aquamarine: "7fffd4"; azure: "f0ffff"; beige: "f5f5dc"; bisque: "ffe4c4"; black: "000"; blanchedalmond: "ffebcd"; blue: "00f"; blueviolet: "8a2be2"; brown: "a52a2a"; burlywood: "deb887"; burntsienna: "ea7e5d"; cadetblue: "5f9ea0"; chartreuse: "7fff00"; chocolate: "d2691e"; coral: "ff7f50"; cornflowerblue: "6495ed"; cornsilk: "fff8dc"; crimson: "dc143c"; cyan: "0ff"; darkblue: "00008b"; darkcyan: "008b8b"; darkgoldenrod: "b8860b"; darkgray: "a9a9a9"; darkgreen: "006400"; darkgrey: "a9a9a9"; darkkhaki: "bdb76b"; darkmagenta: "8b008b"; darkolivegreen: "556b2f"; darkorange: "ff8c00"; darkorchid: "9932cc"; darkred: "8b0000"; darksalmon: "e9967a"; darkseagreen: "8fbc8f"; darkslateblue: "483d8b"; darkslategray: "2f4f4f"; darkslategrey: "2f4f4f"; darkturquoise: "00ced1"; darkviolet: "9400d3"; deeppink: "ff1493"; deepskyblue: "00bfff"; dimgray: "696969"; dimgrey: "696969"; dodgerblue: "1e90ff"; firebrick: "b22222"; floralwhite: "fffaf0"; forestgreen: "228b22"; fuchsia: "f0f"; gainsboro: "dcdcdc"; ghostwhite: "f8f8ff"; gold: "ffd700"; goldenrod: "daa520"; gray: "808080"; green: "008000"; greenyellow: "adff2f"; grey: "808080"; honeydew: "f0fff0"; hotpink: "ff69b4"; indianred: "cd5c5c"; indigo: "4b0082"; ivory: "fffff0"; khaki: "f0e68c"; lavender: "e6e6fa"; lavenderblush: "fff0f5"; lawngreen: "7cfc00"; lemonchiffon: "fffacd"; lightblue: "add8e6"; lightcoral: "f08080"; lightcyan: "e0ffff"; lightgoldenrodyellow: "fafad2"; lightgray: "d3d3d3"; lightgreen: "90ee90"; lightgrey: "d3d3d3"; lightpink: "ffb6c1"; lightsalmon: "ffa07a"; lightseagreen: "20b2aa"; lightskyblue: "87cefa"; lightslategray: "789"; lightslategrey: "789"; lightsteelblue: "b0c4de"; lightyellow: "ffffe0"; lime: "0f0"; limegreen: "32cd32"; linen: "faf0e6"; magenta: "f0f"; maroon: "800000"; mediumaquamarine: "66cdaa"; mediumblue: "0000cd"; mediumorchid: "ba55d3"; mediumpurple: "9370db"; mediumseagreen: "3cb371"; mediumslateblue: "7b68ee"; mediumspringgreen: "00fa9a"; mediumturquoise: "48d1cc"; mediumvioletred: "c71585"; midnightblue: "191970"; mintcream: "f5fffa"; mistyrose: "ffe4e1"; moccasin: "ffe4b5"; navajowhite: "ffdead"; navy: "000080"; oldlace: "fdf5e6"; olive: "808000"; olivedrab: "6b8e23"; orange: "ffa500"; orangered: "ff4500"; orchid: "da70d6"; palegoldenrod: "eee8aa"; palegreen: "98fb98"; paleturquoise: "afeeee"; palevioletred: "db7093"; papayawhip: "ffefd5"; peachpuff: "ffdab9"; peru: "cd853f"; pink: "ffc0cb"; plum: "dda0dd"; powderblue: "b0e0e6"; purple: "800080"; rebeccapurple: "663399"; red: "f00"; rosybrown: "bc8f8f"; royalblue: "4169e1"; saddlebrown: "8b4513"; salmon: "fa8072"; sandybrown: "f4a460"; seagreen: "2e8b57"; seashell: "fff5ee"; sienna: "a0522d"; silver: "c0c0c0"; skyblue: "87ceeb"; slateblue: "6a5acd"; slategray: "708090"; slategrey: "708090"; snow: "fffafa"; springgreen: "00ff7f"; steelblue: "4682b4"; tan: "d2b48c"; teal: "008080"; thistle: "d8bfd8"; tomato: "ff6347"; turquoise: "40e0d0"; violet: "ee82ee"; wheat: "f5deb3"; white: "fff"; whitesmoke: "f5f5f5"; yellow: "ff0"; yellowgreen: "9acd32"; }; /** * key: hex value * value: string name ex. hexnames["f00"] --> "red" */ hexNames: { "f0f8ff": "aliceblue"; "faebd7": "antiquewhite"; "0ff": "aqua" | "cyan"; "7fffd4": "aquamarine"; "f0ffff": "azure"; "f5f5dc": "beige"; "ffe4c4": "bisque"; "000": "black"; "ffebcd": "blanchedalmond"; "00f": "blue"; "8a2be2": "blueviolet"; "a52a2a": "brown"; "deb887": "burlywood"; "ea7e5d": "burntsienna"; "5f9ea0": "cadetblue"; "7fff00": "chartreuse"; "d2691e": "chocolate"; "ff7f50": "coral"; "6495ed": "cornflowerblue"; "fff8dc": "cornsilk"; "dc143c": "crimson"; "00008b": "darkblue"; "008b8b": "darkcyan"; "b8860b": "darkgoldenrod"; "a9a9a9": "darkgray" | "darkgrey"; "006400": "darkgreen"; "bdb76b": "darkkhaki"; "8b008b": "darkmagenta"; "556b2f": "darkolivegreen"; "ff8c00": "darkorange"; "9932cc": "darkorchid"; "8b0000": "darkred"; "e9967a": "darksalmon"; "8fbc8f": "darkseagreen"; "483d8b": "darkslateblue"; "2f4f4f": "darkslategray" | "darkslategrey"; "00ced1": "darkturquoise"; "9400d3": "darkviolet"; "ff1493": "deeppink"; "00bfff": "deepskyblue"; "696969": "dimgray" | "dimgrey"; "1e90ff": "dodgerblue"; "b22222": "firebrick"; "fffaf0": "floralwhite"; "228b22": "forestgreen"; "f0f": "fuchsia" | "magenta"; "dcdcdc": "gainsboro"; "f8f8ff": "ghostwhite"; "ffd700": "gold"; "daa520": "goldenrod"; "808080": "gray" | "grey"; "008000": "green"; "adff2f": "greenyellow"; "f0fff0": "honeydew"; "ff69b4": "hotpink"; "cd5c5c": "indianred"; "4b0082": "indigo"; "fffff0": "ivory"; "f0e68c": "khaki"; "e6e6fa": "lavender"; "fff0f5": "lavenderblush"; "7cfc00": "lawngreen"; "fffacd": "lemonchiffon"; "add8e6": "lightblue"; "f08080": "lightcoral"; "e0ffff": "lightcyan"; "fafad2": "lightgoldenrodyellow"; "d3d3d3": "lightgray" | "lightgrey"; "90ee90": "lightgreen"; "ffb6c1": "lightpink"; "ffa07a": "lightsalmon"; "20b2aa": "lightseagreen"; "87cefa": "lightskyblue"; "789": "lightslategray" | "lightslategrey"; "b0c4de": "lightsteelblue"; "ffffe0": "lightyellow"; "0f0": "lime"; "32cd32": "limegreen"; "faf0e6": "linen"; "800000": "maroon"; "66cdaa": "mediumaquamarine"; "0000cd": "mediumblue"; "ba55d3": "mediumorchid"; "9370db": "mediumpurple"; "3cb371": "mediumseagreen"; "7b68ee": "mediumslateblue"; "00fa9a": "mediumspringgreen"; "48d1cc": "mediumturquoise"; "c71585": "mediumvioletred"; "191970": "midnightblue"; "f5fffa": "mintcream"; "ffe4e1": "mistyrose"; "ffe4b5": "moccasin"; "ffdead": "navajowhite"; "000080": "navy"; "fdf5e6": "oldlace"; "808000": "olive"; "6b8e23": "olivedrab"; "ffa500": "orange"; "ff4500": "orangered"; "da70d6": "orchid"; "eee8aa": "palegoldenrod"; "98fb98": "palegreen"; "afeeee": "paleturquoise"; "db7093": "palevioletred"; "ffefd5": "papayawhip"; "ffdab9": "peachpuff"; "cd853f": "peru"; "ffc0cb": "pink"; "dda0dd": "plum"; "b0e0e6": "powderblue"; "800080": "purple"; "663399": "rebeccapurple"; "f00": "red"; "bc8f8f": "rosybrown"; "4169e1": "royalblue"; "8b4513": "saddlebrown"; "fa8072": "salmon"; "f4a460": "sandybrown"; "2e8b57": "seagreen"; "fff5ee": "seashell"; "a0522d": "sienna"; "c0c0c0": "silver"; "87ceeb": "skyblue"; "6a5acd": "slateblue"; "708090": "slategray" | "slategrey"; "fffafa": "snow"; "00ff7f": "springgreen"; "4682b4": "steelblue"; "d2b48c": "tan"; "008080": "teal"; "d8bfd8": "thistle"; "ff6347": "tomato"; "40e0d0": "turquoise"; "ee82ee": "violet"; "f5deb3": "wheat"; "fff": "white"; "f5f5f5": "whitesmoke"; "ff0": "yellow"; "9acd32": "yellowgreen"; }; } interface Instance { /** * Return an indication whether the color's perceived brightness is dark. */ isDark(): boolean; /** * Return an indication whether the color's perceived brightness is light. */ isLight(): boolean; /** * Return an indication whether the color was successfully parsed. */ isValid(): boolean; /** * Returns the input passed into the constructer used to create the tinycolor instance. */ getOriginalInput(): ColorInput; /** * Returns the format used to create the tinycolor instance. */ getFormat(): string; /** * Returns the alpha value of the color */ getAlpha(): number; /** * Returns the perceived brightness of the color, from 0-255. */ getBrightness(): number; /** * Returns the perceived luminance of a color, from 0-1. */ getLuminance(): number; /** * Sets the alpha value on the current color. * * @param alpha - The new alpha value. The accepted range is 0-1. */ setAlpha(alpha: number): Instance; /** * Returns the object as a HSVA object. */ toHsv(): ColorFormats.HSVA; /** * Returns the hsva values interpolated into a string with the following format: * "hsva(xxx, xxx, xxx, xx)". */ toHsvString(): string; /** * Returns the object as a HSLA object. */ toHsl(): ColorFormats.HSLA; /** * Returns the hsla values interpolated into a string with the following format: * "hsla(xxx, xxx, xxx, xx)". */ toHslString(): string; /** * Returns the hex value of the color. */ toHex(): string; /** * Returns the hex value of the color -with a # appened. */ toHexString(): string; /** * Returns the hex 8 value of the color. */ toHex8(): string; /** * Returns the hex 8 value of the color -with a # appened. */ toHex8String(): string; /** * Returns the object as a RGBA object. */ toRgb(): ColorFormats.RGBA; /** * Returns the RGBA values interpolated into a string with the following format: * "RGBA(xxx, xxx, xxx, xx)". */ toRgbString(): string; /** * Returns the object as a RGBA object. */ toPercentageRgb(): ColorFormats.PRGBA; /** * Returns the RGBA relative values interpolated into a string with the following format: * "RGBA(xxx, xxx, xxx, xx)". */ toPercentageRgbString(): string; /** * The 'real' name of the color -if there is one. */ toName(): string | false; /** * Returns the color represented as a Microsoft filter for use in old versions of IE. */ toFilter(): string; /** * String representation of the color. * * @param format - The format to be used when displaying the string representation. * The accepted values are: "rgb", "prgb", "hex6", "hex3", "hex8", "name", "hsl", "hsv". */ toString(format?: "rgb" | "prgb" | "hex" | "hex6" | "hex3" | "hex4" | "hex8" | "name" | "hsl" | "hsv"): string; /** * Gets a new instance with the current color */ clone(): Instance; /** * Lighten the color a given amount. Providing 100 will always return white. * * @param amount - The amount to lighten by. The valid range is 0 to 100. * Default value: 10. */ lighten(amount?: number): Instance; /** * Brighten the color a given amount. * * @param amount - The amount to brighten by. The valid range is 0 to 100. * Default value: 10. */ brighten(amount?: number): Instance; /** * Darken the color a given amount. * Providing 100 will always return black. * * @param amount - The amount to darken by. The valid range is 0 to 100. * Default value: 10. */ darken(amount?: number): Instance; /** * Desaturate the color a given amount. * Providing 100 will is the same as calling greyscale. * * @param amount - The amount to desaturate by. The valid range is 0 to 100. * Default value: 10. */ desaturate(amount?: number): Instance; /** * Saturate the color a given amount. * * @param amount - The amount to saturate by. The valid range is 0 to 100. * Default value: 10. */ saturate(amount?: number): Instance; /** * Completely desaturates a color into greyscale. * Same as calling desaturate(100). */ greyscale(): Instance; /** * Spin the hue a given amount. Calling with 0, 360, or -360 will do nothing. * * @param amount - The amount to spin by. The valid range is -360 to 360. */ spin(amount: number): Instance; /** * Gets an analogous color scheme based off of the current color. * * @param results - The amount of results to return. * Default value: 6. * @param slices - The amount to slice the input color by. * Default value: 30. */ analogous(results?: number, slices?: number): Instance[]; /** * Gets the complement of the current color */ complement(): Instance; /** * Gets a monochromatic color scheme based off of the current color. * * @param results - The amount of results to return. * Default value: 6. */ monochromatic(results?: number): Instance[]; /** * Gets a split complement color scheme based off of the current color. */ splitcomplement(): [Instance, Instance, Instance]; /** * Gets a triad based off of the current color. */ triad(): [Instance, Instance, Instance]; /** * Gets a tetrad based off of the current color. */ tetrad(): [Instance, Instance, Instance, Instance]; } } declare const tinycolor: tinycolor.Constructor; export = tinycolor; export as namespace tinycolor; node_modules/@types/tinycolor2/README.md 0000664 00000001074 15114743311 0014054 0 ustar 00 # Installation > `npm install --save @types/tinycolor2` # Summary This package contains type definitions for tinycolor2 (https://github.com/bgrins/TinyColor). # Details Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/tinycolor2. ### Additional Details * Last updated: Tue, 07 Nov 2023 15:11:36 GMT * Dependencies: none # Credits These definitions were written by [Mordechai Zuber](https://github.com/M-Zuber), [Geert Jansen](https://github.com/geertjansen), and [Niels van Hoorn](https://github.com/nvh). node_modules/supports-color/license 0000664 00000002125 15114743311 0013603 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/supports-color/package.json 0000664 00000001461 15114743311 0014526 0 ustar 00 { "name": "supports-color", "version": "7.2.0", "description": "Detect whether a terminal supports color", "license": "MIT", "repository": "chalk/supports-color", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=8" }, "scripts": { "test": "xo && ava" }, "files": [ "index.js", "browser.js" ], "keywords": [ "color", "colour", "colors", "terminal", "console", "cli", "ansi", "styles", "tty", "rgb", "256", "shell", "xterm", "command-line", "support", "supports", "capability", "detect", "truecolor", "16m" ], "dependencies": { "has-flag": "^4.0.0" }, "devDependencies": { "ava": "^1.4.1", "import-fresh": "^3.0.0", "xo": "^0.24.0" }, "browser": "browser.js" } node_modules/supports-color/readme.md 0000664 00000004366 15114743311 0014026 0 ustar 00 # supports-color [](https://travis-ci.org/chalk/supports-color) > Detect whether a terminal supports color ## Install ``` $ npm install supports-color ``` ## Usage ```js const supportsColor = require('supports-color'); if (supportsColor.stdout) { console.log('Terminal stdout supports color'); } if (supportsColor.stdout.has256) { console.log('Terminal stdout supports 256 colors'); } if (supportsColor.stderr.has16m) { console.log('Terminal stderr supports 16 million colors (truecolor)'); } ``` ## API Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: - `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) - `.level = 2` and `.has256 = true`: 256 color support - `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) ## Info It obeys the `--color` and `--no-color` CLI flags. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. ## Related - [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module - [chalk](https://github.com/chalk/chalk) - Terminal string styling done right ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) --- <div align="center"> <b> <a href="https://tidelift.com/subscription/pkg/npm-supports-color?utm_source=npm-supports-color&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> </b> <br> <sub> Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. </sub> </div> --- node_modules/supports-color/index.js 0000664 00000005274 15114743311 0013713 0 ustar 00 'use strict'; const os = require('os'); const tty = require('tty'); const hasFlag = require('has-flag'); const {env} = process; let forceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) { forceColor = 0; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor = 1; } if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { forceColor = 1; } else if (env.FORCE_COLOR === 'false') { forceColor = 0; } else { forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(haveStream, streamIsTTY) { if (forceColor === 0) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (haveStream && !streamIsTTY && forceColor === undefined) { return 0; } const min = forceColor || 0; if (env.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env) { const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } return min; } function getSupportLevel(stream) { const level = supportsColor(stream, stream && stream.isTTY); return translateLevel(level); } module.exports = { supportsColor: getSupportLevel, stdout: translateLevel(supportsColor(true, tty.isatty(1))), stderr: translateLevel(supportsColor(true, tty.isatty(2))) }; node_modules/supports-color/browser.js 0000664 00000000103 15114743311 0014251 0 ustar 00 'use strict'; module.exports = { stdout: false, stderr: false }; node_modules/async-retry/package.json 0000664 00000002220 15114743311 0013765 0 ustar 00 { "name": "async-retry", "version": "1.3.3", "description": "Retrying made simple, easy and async", "main": "./lib/index.js", "scripts": { "test": "yarn run test-lint && yarn run test-unit", "test-lint": "eslint .", "test-unit": "ava", "lint:staged": "lint-staged" }, "files": [ "lib" ], "license": "MIT", "repository": "vercel/async-retry", "ava": { "failFast": true }, "dependencies": { "retry": "0.13.1" }, "pre-commit": "lint:staged", "lint-staged": { "*.js": [ "eslint", "prettier --write --single-quote", "git add" ] }, "eslintConfig": { "extends": [ "airbnb", "prettier" ], "rules": { "no-var": 0, "prefer-arrow-callback": 0 } }, "devDependencies": { "ava": "3.15.0", "eslint": "7.32.0", "eslint-config-airbnb": "18.2.1", "eslint-config-prettier": "8.3.0", "eslint-plugin-import": "2.24.0", "eslint-plugin-jsx-a11y": "6.4.1", "eslint-plugin-react": "7.24.0", "lint-staged": "11.1.2", "node-fetch": "2.6.1", "pre-commit": "1.2.2", "prettier": "2.3.2", "then-sleep": "1.0.1" } } node_modules/async-retry/lib/index.js 0000664 00000002231 15114743311 0013714 0 ustar 00 // Packages var retrier = require('retry'); function retry(fn, opts) { function run(resolve, reject) { var options = opts || {}; var op; // Default `randomize` to true if (!('randomize' in options)) { options.randomize = true; } op = retrier.operation(options); // We allow the user to abort retrying // this makes sense in the cases where // knowledge is obtained that retrying // would be futile (e.g.: auth errors) function bail(err) { reject(err || new Error('Aborted')); } function onError(err, num) { if (err.bail) { bail(err); return; } if (!op.retry(err)) { reject(op.mainError()); } else if (options.onRetry) { options.onRetry(err, num); } } function runAttempt(num) { var val; try { val = fn(bail, num); } catch (err) { onError(err, num); return; } Promise.resolve(val) .then(resolve) .catch(function catchIt(err) { onError(err, num); }); } op.attempt(runAttempt); } return new Promise(run); } module.exports = retry; node_modules/async-retry/LICENSE.md 0000664 00000002067 15114743311 0013114 0 ustar 00 The MIT License (MIT) Copyright (c) 2021 Vercel, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/async-retry/README.md 0000664 00000003377 15114743311 0012774 0 ustar 00 # async-retry Retrying made simple, easy, and async. ## Usage ```js // Packages const retry = require('async-retry'); const fetch = require('node-fetch'); await retry( async (bail) => { // if anything throws, we retry const res = await fetch('https://google.com'); if (403 === res.status) { // don't retry upon 403 bail(new Error('Unauthorized')); return; } const data = await res.text(); return data.substr(0, 500); }, { retries: 5, } ); ``` ### API ```js retry(retrier : Function, opts : Object) => Promise ``` - The supplied function can be `async` or not. In other words, it can be a function that returns a `Promise` or a value. - The supplied function receives two parameters 1. A `Function` you can invoke to abort the retrying (bail) 2. A `Number` identifying the attempt. The absolute first attempt (before any retries) is `1`. - The `opts` are passed to `node-retry`. Read [its docs](https://github.com/tim-kos/node-retry) - `retries`: The maximum amount of times to retry the operation. Default is `10`. - `factor`: The exponential factor to use. Default is `2`. - `minTimeout`: The number of milliseconds before starting the first retry. Default is `1000`. - `maxTimeout`: The maximum number of milliseconds between two retries. Default is `Infinity`. - `randomize`: Randomizes the timeouts by multiplying with a factor between `1` to `2`. Default is `true`. - `onRetry`: an optional `Function` that is invoked after a new retry is performed. It's passed the `Error` that triggered it as a parameter. ## Authors - Guillermo Rauch ([@rauchg](https://twitter.com/rauchg)) - [Vercel](https://vercel.com) - Leo Lamprecht ([@notquiteleo](https://twitter.com/notquiteleo)) - [Vercel](https://vercel.com) node_modules/compare-versions/package.json 0000664 00000002315 15114743311 0015006 0 ustar 00 { "name": "compare-versions", "version": "6.1.1", "description": "Compare semver version strings to find greater, equal or lesser.", "repository": { "type": "git", "url": "git+https://github.com/omichelsen/compare-versions.git" }, "author": "Ole Michelsen", "license": "MIT", "bugs": { "url": "https://github.com/omichelsen/compare-versions/issues" }, "homepage": "https://github.com/omichelsen/compare-versions#readme", "keywords": [ "semver", "version", "compare", "browser", "node" ], "scripts": { "build": "npm run build:esm && npm run build:umd", "build:esm": "tsc --module esnext --target es2017 --outDir lib/esm", "build:umd": "rollup lib/esm/index.js --format umd --name compareVersions --sourcemap -o lib/umd/index.js", "prepublishOnly": "npm run build", "test": "c8 --reporter=lcov mocha" }, "main": "./lib/umd/index.js", "module": "./lib/esm/index.js", "types": "./lib/esm/index.d.ts", "sideEffects": false, "files": [ "lib", "src" ], "devDependencies": { "@types/mocha": "^10.0.7", "c8": "^10.1.2", "mocha": "^10.6.0", "rollup": "^4.18.1", "ts-node": "^10.9.2", "typescript": "^5.5.3" } } node_modules/compare-versions/LICENSE 0000664 00000002075 15114743311 0013530 0 ustar 00 The MIT License (MIT) Copyright (c) 2015-2021 Ole Michelsen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/compare-versions/src/compareVersions.ts 0000664 00000002131 15114743311 0017032 0 ustar 00 import { compareSegments, validateAndParse } from './utils.js'; /** * Compare [semver](https://semver.org/) version strings to find greater, equal or lesser. * This library supports the full semver specification, including comparing versions with different number of digits like `1.0.0`, `1.0`, `1`, and pre-release versions like `1.0.0-alpha`. * @param v1 - First version to compare * @param v2 - Second version to compare * @returns Numeric value compatible with the [Array.sort(fn) interface](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters). */ export const compareVersions = (v1: string, v2: string) => { // validate input and split into segments const n1 = validateAndParse(v1); const n2 = validateAndParse(v2); // pop off the patch const p1 = n1.pop(); const p2 = n2.pop(); // validate numbers const r = compareSegments(n1, n2); if (r !== 0) return r; // validate pre-release if (p1 && p2) { return compareSegments(p1.split('.'), p2.split('.')); } else if (p1 || p2) { return p1 ? -1 : 1; } return 0; }; node_modules/compare-versions/src/compare.ts 0000664 00000003102 15114743311 0015300 0 ustar 00 import { compareVersions } from './compareVersions.js'; import { CompareOperator } from './utils.js'; /** * Compare [semver](https://semver.org/) version strings using the specified operator. * * @param v1 First version to compare * @param v2 Second version to compare * @param operator Allowed arithmetic operator to use * @returns `true` if the comparison between the firstVersion and the secondVersion satisfies the operator, `false` otherwise. * * @example * ``` * compare('10.1.8', '10.0.4', '>'); // return true * compare('10.0.1', '10.0.1', '='); // return true * compare('10.1.1', '10.2.2', '<'); // return true * compare('10.1.1', '10.2.2', '<='); // return true * compare('10.1.1', '10.2.2', '>='); // return false * ``` */ export const compare = (v1: string, v2: string, operator: CompareOperator) => { // validate input operator assertValidOperator(operator); // since result of compareVersions can only be -1 or 0 or 1 // a simple map can be used to replace switch const res = compareVersions(v1, v2); return operatorResMap[operator].includes(res); }; const operatorResMap = { '>': [1], '>=': [0, 1], '=': [0], '<=': [-1, 0], '<': [-1], '!=': [-1, 1], }; const allowedOperators = Object.keys(operatorResMap); const assertValidOperator = (op: string) => { if (typeof op !== 'string') { throw new TypeError( `Invalid operator type, expected string but got ${typeof op}` ); } if (allowedOperators.indexOf(op) === -1) { throw new Error( `Invalid operator, expected one of ${allowedOperators.join('|')}` ); } }; node_modules/compare-versions/src/validate.ts 0000664 00000002307 15114743311 0015451 0 ustar 00 import { semver } from './utils.js'; /** * Validate [semver](https://semver.org/) version strings. * * @param version Version number to validate * @returns `true` if the version number is a valid semver version number, `false` otherwise. * * @example * ``` * validate('1.0.0-rc.1'); // return true * validate('1.0-rc.1'); // return false * validate('foo'); // return false * ``` */ export const validate = (version: string) => typeof version === 'string' && /^[v\d]/.test(version) && semver.test(version); /** * Validate [semver](https://semver.org/) version strings strictly. Will not accept wildcards and version ranges. * * @param version Version number to validate * @returns `true` if the version number is a valid semver version number `false` otherwise * * @example * ``` * validate('1.0.0-rc.1'); // return true * validate('1.0-rc.1'); // return false * validate('foo'); // return false * ``` */ export const validateStrict = (version: string) => typeof version === 'string' && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/.test( version ); node_modules/compare-versions/src/index.ts 0000664 00000000364 15114743311 0014770 0 ustar 00 export { compare } from './compare.js'; export { compareVersions } from './compareVersions.js'; export { satisfies } from './satisfies.js'; export { CompareOperator } from './utils.js'; export { validate, validateStrict } from './validate.js'; node_modules/compare-versions/src/satisfies.ts 0000664 00000004121 15114743311 0015646 0 ustar 00 import { compare } from './compare.js'; import { CompareOperator, compareSegments, validateAndParse } from './utils.js'; /** * Match [npm semver](https://docs.npmjs.com/cli/v6/using-npm/semver) version range. * * @param version Version number to match * @param range Range pattern for version * @returns `true` if the version number is within the range, `false` otherwise. * * @example * ``` * satisfies('1.1.0', '^1.0.0'); // return true * satisfies('1.1.0', '~1.0.0'); // return false * ``` */ export const satisfies = (version: string, range: string): boolean => { // clean input range = range.replace(/([><=]+)\s+/g, '$1'); // handle multiple comparators if (range.includes('||')) { return range.split('||').some((r) => satisfies(version, r)); } else if (range.includes(' - ')) { const [a, b] = range.split(' - ', 2); return satisfies(version, `>=${a} <=${b}`); } else if (range.includes(' ')) { return range .trim() .replace(/\s{2,}/g, ' ') .split(' ') .every((r) => satisfies(version, r)); } // if no range operator then "=" const m = range.match(/^([<>=~^]+)/); const op = m ? m[1] : '='; // if gt/lt/eq then operator compare if (op !== '^' && op !== '~') return compare(version, range, op as CompareOperator); // else range of either "~" or "^" is assumed const [v1, v2, v3, , vp] = validateAndParse(version); const [r1, r2, r3, , rp] = validateAndParse(range); const v = [v1, v2, v3]; const r = [r1, r2 ?? 'x', r3 ?? 'x']; // validate pre-release if (rp) { if (!vp) return false; if (compareSegments(v, r) !== 0) return false; if (compareSegments(vp.split('.'), rp.split('.')) === -1) return false; } // first non-zero number const nonZero = r.findIndex((v) => v !== '0') + 1; // pointer to where segments can be >= const i = op === '~' ? 2 : nonZero > 1 ? nonZero : 1; // before pointer must be equal if (compareSegments(v.slice(0, i), r.slice(0, i)) !== 0) return false; // after pointer must be >= if (compareSegments(v.slice(i), r.slice(i)) === -1) return false; return true; }; node_modules/compare-versions/src/utils.ts 0000664 00000002613 15114743311 0015020 0 ustar 00 /** * Allowed arithmetic operators */ export type CompareOperator = '>' | '>=' | '=' | '<' | '<=' | '!='; export const semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; export const validateAndParse = (version: string) => { if (typeof version !== 'string') { throw new TypeError('Invalid argument expected string'); } const match = version.match(semver); if (!match) { throw new Error( `Invalid argument not valid semver ('${version}' received)` ); } match.shift(); return match; }; const isWildcard = (s: string) => s === '*' || s === 'x' || s === 'X'; const tryParse = (v: string) => { const n = parseInt(v, 10); return isNaN(n) ? v : n; }; const forceType = (a: string | number, b: string | number) => typeof a !== typeof b ? [String(a), String(b)] : [a, b]; const compareStrings = (a: string, b: string) => { if (isWildcard(a) || isWildcard(b)) return 0; const [ap, bp] = forceType(tryParse(a), tryParse(b)); if (ap > bp) return 1; if (ap < bp) return -1; return 0; }; export const compareSegments = ( a: string | string[] | RegExpMatchArray, b: string | string[] | RegExpMatchArray ) => { for (let i = 0; i < Math.max(a.length, b.length); i++) { const r = compareStrings(a[i] || '0', b[i] || '0'); if (r !== 0) return r; } return 0; }; node_modules/compare-versions/lib/esm/utils.js 0000664 00000002343 15114743311 0015551 0 ustar 00 export const semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; export const validateAndParse = (version) => { if (typeof version !== 'string') { throw new TypeError('Invalid argument expected string'); } const match = version.match(semver); if (!match) { throw new Error(`Invalid argument not valid semver ('${version}' received)`); } match.shift(); return match; }; const isWildcard = (s) => s === '*' || s === 'x' || s === 'X'; const tryParse = (v) => { const n = parseInt(v, 10); return isNaN(n) ? v : n; }; const forceType = (a, b) => typeof a !== typeof b ? [String(a), String(b)] : [a, b]; const compareStrings = (a, b) => { if (isWildcard(a) || isWildcard(b)) return 0; const [ap, bp] = forceType(tryParse(a), tryParse(b)); if (ap > bp) return 1; if (ap < bp) return -1; return 0; }; export const compareSegments = (a, b) => { for (let i = 0; i < Math.max(a.length, b.length); i++) { const r = compareStrings(a[i] || '0', b[i] || '0'); if (r !== 0) return r; } return 0; }; //# sourceMappingURL=utils.js.map node_modules/compare-versions/lib/esm/compare.js.map 0000664 00000002105 15114743311 0016607 0 ustar 00 {"version":3,"file":"compare.js","sourceRoot":"","sources":["../../src/compare.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAGvD;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,EAAU,EAAE,EAAU,EAAE,QAAyB,EAAE,EAAE;IAC3E,0BAA0B;IAC1B,mBAAmB,CAAC,QAAQ,CAAC,CAAC;IAE9B,2DAA2D;IAC3D,6CAA6C;IAC7C,MAAM,GAAG,GAAG,eAAe,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAEpC,OAAO,cAAc,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AAChD,CAAC,CAAC;AAEF,MAAM,cAAc,GAAG;IACrB,GAAG,EAAE,CAAC,CAAC,CAAC;IACR,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;IACZ,GAAG,EAAE,CAAC,CAAC,CAAC;IACR,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACb,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;IACT,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;CACd,CAAC;AAEF,MAAM,gBAAgB,GAAG,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;AAErD,MAAM,mBAAmB,GAAG,CAAC,EAAU,EAAE,EAAE;IACzC,IAAI,OAAO,EAAE,KAAK,QAAQ,EAAE,CAAC;QAC3B,MAAM,IAAI,SAAS,CACjB,kDAAkD,OAAO,EAAE,EAAE,CAC9D,CAAC;IACJ,CAAC;IACD,IAAI,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CACb,qCAAqC,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAClE,CAAC;IACJ,CAAC;AACH,CAAC,CAAC"} node_modules/compare-versions/lib/esm/utils.d.ts 0000664 00000000547 15114743311 0016011 0 ustar 00 /** * Allowed arithmetic operators */ export type CompareOperator = '>' | '>=' | '=' | '<' | '<=' | '!='; export declare const semver: RegExp; export declare const validateAndParse: (version: string) => RegExpMatchArray; export declare const compareSegments: (a: string | string[] | RegExpMatchArray, b: string | string[] | RegExpMatchArray) => 0 | 1 | -1; node_modules/compare-versions/lib/esm/validate.js 0000664 00000002317 15114743311 0016203 0 ustar 00 import { semver } from './utils.js'; /** * Validate [semver](https://semver.org/) version strings. * * @param version Version number to validate * @returns `true` if the version number is a valid semver version number, `false` otherwise. * * @example * ``` * validate('1.0.0-rc.1'); // return true * validate('1.0-rc.1'); // return false * validate('foo'); // return false * ``` */ export const validate = (version) => typeof version === 'string' && /^[v\d]/.test(version) && semver.test(version); /** * Validate [semver](https://semver.org/) version strings strictly. Will not accept wildcards and version ranges. * * @param version Version number to validate * @returns `true` if the version number is a valid semver version number `false` otherwise * * @example * ``` * validate('1.0.0-rc.1'); // return true * validate('1.0-rc.1'); // return false * validate('foo'); // return false * ``` */ export const validateStrict = (version) => typeof version === 'string' && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/.test(version); //# sourceMappingURL=validate.js.map node_modules/compare-versions/lib/esm/validate.d.ts 0000664 00000001577 15114743311 0016446 0 ustar 00 /** * Validate [semver](https://semver.org/) version strings. * * @param version Version number to validate * @returns `true` if the version number is a valid semver version number, `false` otherwise. * * @example * ``` * validate('1.0.0-rc.1'); // return true * validate('1.0-rc.1'); // return false * validate('foo'); // return false * ``` */ export declare const validate: (version: string) => boolean; /** * Validate [semver](https://semver.org/) version strings strictly. Will not accept wildcards and version ranges. * * @param version Version number to validate * @returns `true` if the version number is a valid semver version number `false` otherwise * * @example * ``` * validate('1.0.0-rc.1'); // return true * validate('1.0-rc.1'); // return false * validate('foo'); // return false * ``` */ export declare const validateStrict: (version: string) => boolean; node_modules/compare-versions/lib/esm/compare.js 0000664 00000003030 15114743311 0016031 0 ustar 00 import { compareVersions } from './compareVersions.js'; /** * Compare [semver](https://semver.org/) version strings using the specified operator. * * @param v1 First version to compare * @param v2 Second version to compare * @param operator Allowed arithmetic operator to use * @returns `true` if the comparison between the firstVersion and the secondVersion satisfies the operator, `false` otherwise. * * @example * ``` * compare('10.1.8', '10.0.4', '>'); // return true * compare('10.0.1', '10.0.1', '='); // return true * compare('10.1.1', '10.2.2', '<'); // return true * compare('10.1.1', '10.2.2', '<='); // return true * compare('10.1.1', '10.2.2', '>='); // return false * ``` */ export const compare = (v1, v2, operator) => { // validate input operator assertValidOperator(operator); // since result of compareVersions can only be -1 or 0 or 1 // a simple map can be used to replace switch const res = compareVersions(v1, v2); return operatorResMap[operator].includes(res); }; const operatorResMap = { '>': [1], '>=': [0, 1], '=': [0], '<=': [-1, 0], '<': [-1], '!=': [-1, 1], }; const allowedOperators = Object.keys(operatorResMap); const assertValidOperator = (op) => { if (typeof op !== 'string') { throw new TypeError(`Invalid operator type, expected string but got ${typeof op}`); } if (allowedOperators.indexOf(op) === -1) { throw new Error(`Invalid operator, expected one of ${allowedOperators.join('|')}`); } }; //# sourceMappingURL=compare.js.map node_modules/compare-versions/lib/esm/index.d.ts 0000664 00000000364 15114743311 0015755 0 ustar 00 export { compare } from './compare.js'; export { compareVersions } from './compareVersions.js'; export { satisfies } from './satisfies.js'; export { CompareOperator } from './utils.js'; export { validate, validateStrict } from './validate.js'; node_modules/compare-versions/lib/esm/compareVersions.js.map 0000664 00000001563 15114743311 0020347 0 ustar 00 {"version":3,"file":"compareVersions.js","sourceRoot":"","sources":["../../src/compareVersions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE/D;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,EAAU,EAAE,EAAU,EAAE,EAAE;IACxD,yCAAyC;IACzC,MAAM,EAAE,GAAG,gBAAgB,CAAC,EAAE,CAAC,CAAC;IAChC,MAAM,EAAE,GAAG,gBAAgB,CAAC,EAAE,CAAC,CAAC;IAEhC,oBAAoB;IACpB,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC;IAEpB,mBAAmB;IACnB,MAAM,CAAC,GAAG,eAAe,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAClC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,CAAC,CAAC;IAEtB,uBAAuB;IACvB,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC;QACb,OAAO,eAAe,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IACvD,CAAC;SAAM,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC;QACpB,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrB,CAAC;IAED,OAAO,CAAC,CAAC;AACX,CAAC,CAAC"} node_modules/compare-versions/lib/esm/satisfies.js 0000664 00000004430 15114743311 0016402 0 ustar 00 import { compare } from './compare.js'; import { compareSegments, validateAndParse } from './utils.js'; /** * Match [npm semver](https://docs.npmjs.com/cli/v6/using-npm/semver) version range. * * @param version Version number to match * @param range Range pattern for version * @returns `true` if the version number is within the range, `false` otherwise. * * @example * ``` * satisfies('1.1.0', '^1.0.0'); // return true * satisfies('1.1.0', '~1.0.0'); // return false * ``` */ export const satisfies = (version, range) => { // clean input range = range.replace(/([><=]+)\s+/g, '$1'); // handle multiple comparators if (range.includes('||')) { return range.split('||').some((r) => satisfies(version, r)); } else if (range.includes(' - ')) { const [a, b] = range.split(' - ', 2); return satisfies(version, `>=${a} <=${b}`); } else if (range.includes(' ')) { return range .trim() .replace(/\s{2,}/g, ' ') .split(' ') .every((r) => satisfies(version, r)); } // if no range operator then "=" const m = range.match(/^([<>=~^]+)/); const op = m ? m[1] : '='; // if gt/lt/eq then operator compare if (op !== '^' && op !== '~') return compare(version, range, op); // else range of either "~" or "^" is assumed const [v1, v2, v3, , vp] = validateAndParse(version); const [r1, r2, r3, , rp] = validateAndParse(range); const v = [v1, v2, v3]; const r = [r1, r2 !== null && r2 !== void 0 ? r2 : 'x', r3 !== null && r3 !== void 0 ? r3 : 'x']; // validate pre-release if (rp) { if (!vp) return false; if (compareSegments(v, r) !== 0) return false; if (compareSegments(vp.split('.'), rp.split('.')) === -1) return false; } // first non-zero number const nonZero = r.findIndex((v) => v !== '0') + 1; // pointer to where segments can be >= const i = op === '~' ? 2 : nonZero > 1 ? nonZero : 1; // before pointer must be equal if (compareSegments(v.slice(0, i), r.slice(0, i)) !== 0) return false; // after pointer must be >= if (compareSegments(v.slice(i), r.slice(i)) === -1) return false; return true; }; //# sourceMappingURL=satisfies.js.map node_modules/compare-versions/lib/esm/compareVersions.d.ts 0000664 00000001160 15114743311 0020020 0 ustar 00 /** * Compare [semver](https://semver.org/) version strings to find greater, equal or lesser. * This library supports the full semver specification, including comparing versions with different number of digits like `1.0.0`, `1.0`, `1`, and pre-release versions like `1.0.0-alpha`. * @param v1 - First version to compare * @param v2 - Second version to compare * @returns Numeric value compatible with the [Array.sort(fn) interface](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters). */ export declare const compareVersions: (v1: string, v2: string) => 0 | 1 | -1; node_modules/compare-versions/lib/esm/validate.js.map 0000664 00000000721 15114743311 0016754 0 ustar 00 {"version":3,"file":"validate.js","sourceRoot":"","sources":["../../src/validate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEpC;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,OAAe,EAAE,EAAE,CAC1C,OAAO,OAAO,KAAK,QAAQ,IAAI,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAEhF;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,OAAe,EAAE,EAAE,CAChD,OAAO,OAAO,KAAK,QAAQ;IAC3B,qLAAqL,CAAC,IAAI,CACxL,OAAO,CACR,CAAC"} node_modules/compare-versions/lib/esm/satisfies.d.ts 0000664 00000000720 15114743311 0016634 0 ustar 00 /** * Match [npm semver](https://docs.npmjs.com/cli/v6/using-npm/semver) version range. * * @param version Version number to match * @param range Range pattern for version * @returns `true` if the version number is within the range, `false` otherwise. * * @example * ``` * satisfies('1.1.0', '^1.0.0'); // return true * satisfies('1.1.0', '~1.0.0'); // return false * ``` */ export declare const satisfies: (version: string, range: string) => boolean; node_modules/compare-versions/lib/esm/compare.d.ts 0000664 00000001424 15114743311 0016272 0 ustar 00 import { CompareOperator } from './utils.js'; /** * Compare [semver](https://semver.org/) version strings using the specified operator. * * @param v1 First version to compare * @param v2 Second version to compare * @param operator Allowed arithmetic operator to use * @returns `true` if the comparison between the firstVersion and the secondVersion satisfies the operator, `false` otherwise. * * @example * ``` * compare('10.1.8', '10.0.4', '>'); // return true * compare('10.0.1', '10.0.1', '='); // return true * compare('10.1.1', '10.2.2', '<'); // return true * compare('10.1.1', '10.2.2', '<='); // return true * compare('10.1.1', '10.2.2', '>='); // return false * ``` */ export declare const compare: (v1: string, v2: string, operator: CompareOperator) => boolean; node_modules/compare-versions/lib/esm/compareVersions.js 0000664 00000002237 15114743311 0017572 0 ustar 00 import { compareSegments, validateAndParse } from './utils.js'; /** * Compare [semver](https://semver.org/) version strings to find greater, equal or lesser. * This library supports the full semver specification, including comparing versions with different number of digits like `1.0.0`, `1.0`, `1`, and pre-release versions like `1.0.0-alpha`. * @param v1 - First version to compare * @param v2 - Second version to compare * @returns Numeric value compatible with the [Array.sort(fn) interface](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters). */ export const compareVersions = (v1, v2) => { // validate input and split into segments const n1 = validateAndParse(v1); const n2 = validateAndParse(v2); // pop off the patch const p1 = n1.pop(); const p2 = n2.pop(); // validate numbers const r = compareSegments(n1, n2); if (r !== 0) return r; // validate pre-release if (p1 && p2) { return compareSegments(p1.split('.'), p2.split('.')); } else if (p1 || p2) { return p1 ? -1 : 1; } return 0; }; //# sourceMappingURL=compareVersions.js.map node_modules/compare-versions/lib/esm/index.js.map 0000664 00000000431 15114743311 0016270 0 ustar 00 {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC"} node_modules/compare-versions/lib/esm/utils.js.map 0000664 00000003340 15114743311 0016323 0 ustar 00 {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,MAAM,GACjB,4IAA4I,CAAC;AAE/I,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,OAAe,EAAE,EAAE;IAClD,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,MAAM,IAAI,SAAS,CAAC,kCAAkC,CAAC,CAAC;IAC1D,CAAC;IACD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACpC,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CACb,uCAAuC,OAAO,aAAa,CAC5D,CAAC;IACJ,CAAC;IACD,KAAK,CAAC,KAAK,EAAE,CAAC;IACd,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;AAEF,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC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c,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC;QACnD,IAAI,CAAC,KAAK,CAAC;YAAE,OAAO,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC,CAAC"} node_modules/compare-versions/lib/esm/satisfies.js.map 0000664 00000004747 15114743311 0017171 0 ustar 00 {"version":3,"file":"satisfies.js","sourceRoot":"","sources":["../../src/satisfies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAmB,eAAe,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEhF;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,OAAe,EAAE,KAAa,EAAW,EAAE;IACnE,cAAc;IACd,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;IAE5C,8BAA8B;IAC9B,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;IAC9D,CAAC;SAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACjC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QACrC,OAAO,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAC7C,CAAC;SAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/B,OAAO,KAAK;aACT,IAAI,EAAE;aACN,OAAO,CAAC,S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AAK,CAAC,CAAC;YAAE,OAAO,KAAK,CAAC;IACzE,CAAC;IAED,wBAAwB;IACxB,MAAM,OAAO,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,GAAG,CAAC,GAAG,CAAC,CAAC;IAElD,sCAAsC;IACtC,MAAM,CAAC,GAAG,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAErD,+BAA+B;IAC/B,IAAI,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAEtE,2BAA2B;IAC3B,IAAI,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IAEjE,OAAO,IAAI,CAAC;AACd,CAAC,CAAC"} node_modules/compare-versions/lib/esm/index.js 0000664 00000000347 15114743311 0015522 0 ustar 00 export { compare } from './compare.js'; export { compareVersions } from './compareVersions.js'; export { satisfies } from './satisfies.js'; export { validate, validateStrict } from './validate.js'; //# sourceMappingURL=index.js.map node_modules/compare-versions/lib/umd/index.js.map 0000664 00000033522 15114743311 0016300 0 ustar 00 {"version":3,"file":"index.js","sources":["../esm/utils.js","../esm/compareVersions.js","../esm/compare.js","../esm/satisfies.js","../esm/validate.js"],"sourcesContent":["export const semver = /^[v^~<>=]*?(\\d+)(?:\\.([x*]|\\d+)(?:\\.([x*]|\\d+)(?:\\.([x*]|\\d+))?(?:-([\\da-z\\-]+(?:\\.[\\da-z\\-]+)*))?(?:\\+[\\da-z\\-]+(?:\\.[\\da-z\\-]+)*)?)?)?$/i;\nexport const validateAndParse = (version) => {\n if (typeof version !== 'string') {\n throw new TypeError('Invalid argument expected string');\n }\n const match = version.match(semver);\n if (!match) {\n throw new Error(`Invalid argument not valid semver ('${version}' received)`);\n }\n match.shift();\n return match;\n};\nconst isWildcard = (s) => s === '*' || s === 'x' || s === 'X';\nconst tryParse = (v) => {\n const n = parseInt(v, 10);\n return isNaN(n) ? v : n;\n};\nconst forceType = (a, b) => typeof a !== typeof b ? [String(a), String(b)] : [a, b];\nconst compareStrings = (a, b) => {\n if (isWildcard(a) || isWildcard(b))\n return 0;\n const [ap, bp] = forceType(tryParse(a), tryParse(b));\n if (ap > bp)\n return 1;\n if (ap < bp)\n return -1;\n return 0;\n};\nexport const compareSegments = (a, b) => {\n for (let i = 0; i < Math.max(a.length, b.length); i++) {\n const r = compareStrings(a[i] || '0', b[i] || '0');\n if (r !== 0)\n return r;\n }\n return 0;\n};\n//# sourceMappingURL=utils.js.map","import { compareSegments, validateAndParse } from './utils.js';\n/**\n * Compare [semver](https://semver.org/) version strings to find greater, equal or lesser.\n * This library supports the full semver specification, including comparing versions with different number of digits like `1.0.0`, `1.0`, `1`, and pre-release versions like `1.0.0-alpha`.\n * @param v1 - First version to compare\n * @param v2 - Second version to compare\n * @returns Numeric value compatible with the [Array.sort(fn) interface](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters).\n */\nexport const compareVersions = (v1, v2) => {\n // validate input and split into segments\n const n1 = validateAndParse(v1);\n const n2 = validateAndParse(v2);\n // pop off the patch\n const p1 = n1.pop();\n const p2 = n2.pop();\n // validate numbers\n const r = compareSegments(n1, n2);\n if (r !== 0)\n return r;\n // validate pre-release\n if (p1 && p2) {\n return compareSegments(p1.split('.'), p2.split('.'));\n }\n else if (p1 || p2) {\n return p1 ? -1 : 1;\n }\n return 0;\n};\n//# sourceMappingURL=compareVersions.js.map","import { compareVersions } from './compareVersions.js';\n/**\n * Compare [semver](https://semver.org/) version strings using the specified operator.\n *\n * @param v1 First version to compare\n * @param v2 Second version to compare\n * @param operator Allowed arithmetic operator to use\n * @returns `true` if the comparison between the firstVersion and the secondVersion satisfies the operator, `false` otherwise.\n *\n * @example\n * ```\n * compare('10.1.8', '10.0.4', '>'); // return true\n * compare('10.0.1', '10.0.1', '='); // return true\n * compare('10.1.1', '10.2.2', '<'); // return true\n * compare('10.1.1', '10.2.2', '<='); // return true\n * compare('10.1.1', '10.2.2', '>='); // return false\n * ```\n */\nexport const compare = (v1, v2, operator) => {\n // validate input operator\n assertValidOperator(operator);\n // since result of compareVersions can only be -1 or 0 or 1\n // a simple map can be used to replace switch\n const res = compareVersions(v1, v2);\n return operatorResMap[operator].includes(res);\n};\nconst operatorResMap = {\n '>': [1],\n '>=': [0, 1],\n '=': [0],\n '<=': [-1, 0],\n '<': [-1],\n '!=': [-1, 1],\n};\nconst allowedOperators = Object.keys(operatorResMap);\nconst assertValidOperator = (op) => {\n if (typeof op !== 'string') {\n throw new TypeError(`Invalid operator type, expected string but got ${typeof op}`);\n }\n if (allowedOperators.indexOf(op) === -1) {\n throw new Error(`Invalid operator, expected one of ${allowedOperators.join('|')}`);\n }\n};\n//# sourceMappingURL=compare.js.map","import { compare } from './compare.js';\nimport { compareSegments, validateAndParse } from './utils.js';\n/**\n * Match [npm semver](https://docs.npmjs.com/cli/v6/using-npm/semver) version range.\n *\n * @param version Version number to match\n * @param range Range pattern for version\n * @returns `true` if the version number is within the range, `false` otherwise.\n *\n * @example\n * ```\n * satisfies('1.1.0', '^1.0.0'); // return true\n * satisfies('1.1.0', '~1.0.0'); // return false\n * ```\n */\nexport const satisfies = (version, range) => {\n // clean input\n range = range.replace(/([><=]+)\\s+/g, '$1');\n // handle multiple comparators\n if (range.includes('||')) {\n return range.split('||').some((r) => satisfies(version, r));\n }\n else if (range.includes(' - ')) {\n const [a, b] = range.split(' - ', 2);\n return satisfies(version, `>=${a} <=${b}`);\n }\n else if (range.includes(' ')) {\n return range\n .trim()\n .replace(/\\s{2,}/g, ' ')\n .split(' ')\n .every((r) => satisfies(version, r));\n }\n // if no range operator then \"=\"\n const m = range.match(/^([<>=~^]+)/);\n const op = m ? m[1] : '=';\n // if gt/lt/eq then operator compare\n if (op !== '^' && op !== '~')\n return compare(version, range, op);\n // else range of either \"~\" or \"^\" is assumed\n const [v1, v2, v3, , vp] = validateAndParse(version);\n const [r1, r2, r3, , rp] = validateAndParse(range);\n const v = [v1, v2, v3];\n const r = [r1, r2 !== null && r2 !== void 0 ? r2 : 'x', r3 !== null && r3 !== void 0 ? r3 : 'x'];\n // validate pre-release\n if (rp) {\n if (!vp)\n return false;\n if (compareSegments(v, r) !== 0)\n return false;\n if (compareSegments(vp.split('.'), rp.split('.')) === -1)\n return false;\n }\n // first non-zero number\n const nonZero = r.findIndex((v) => v !== '0') + 1;\n // pointer to where segments can be >=\n const i = op === '~' ? 2 : nonZero > 1 ? nonZero : 1;\n // before pointer must be equal\n if (compareSegments(v.slice(0, i), r.slice(0, i)) !== 0)\n return false;\n // after pointer must be >=\n if (compareSegments(v.slice(i), r.slice(i)) === -1)\n return false;\n return true;\n};\n//# sourceMappingURL=satisfies.js.map","import { semver } from './utils.js';\n/**\n * Validate [semver](https://semver.org/) version strings.\n *\n * @param version Version number to validate\n * @returns `true` if the version number is a valid semver version number, `false` otherwise.\n *\n * @example\n * ```\n * validate('1.0.0-rc.1'); // return true\n * validate('1.0-rc.1'); // return false\n * validate('foo'); // return false\n * ```\n */\nexport const validate = (version) => typeof version === 'string' && /^[v\\d]/.test(version) && semver.test(version);\n/**\n * Validate [semver](https://semver.org/) version strings strictly. Will not accept wildcards and version ranges.\n *\n * @param version Version number to validate\n * @returns `true` if the version number is a valid semver version number `false` otherwise\n *\n * @example\n * ```\n * validate('1.0.0-rc.1'); // return true\n * validate('1.0-rc.1'); // return false\n * validate('foo'); // return false\n * ```\n */\nexport const validateStrict = (version) => typeof version === 'string' &&\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[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AAK,OAAO,OAAO,KAAK,QAAQ;IACtE,IAAI,qLAAqL,CAAC,IAAI,CAAC,OAAO;;;;;;;;;;;;"} node_modules/compare-versions/lib/umd/index.js 0000664 00000020364 15114743311 0015524 0 ustar 00 (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.compareVersions = {})); })(this, (function (exports) { 'use strict'; const semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; const validateAndParse = (version) => { if (typeof version !== 'string') { throw new TypeError('Invalid argument expected string'); } const match = version.match(semver); if (!match) { throw new Error(`Invalid argument not valid semver ('${version}' received)`); } match.shift(); return match; }; const isWildcard = (s) => s === '*' || s === 'x' || s === 'X'; const tryParse = (v) => { const n = parseInt(v, 10); return isNaN(n) ? v : n; }; const forceType = (a, b) => typeof a !== typeof b ? [String(a), String(b)] : [a, b]; const compareStrings = (a, b) => { if (isWildcard(a) || isWildcard(b)) return 0; const [ap, bp] = forceType(tryParse(a), tryParse(b)); if (ap > bp) return 1; if (ap < bp) return -1; return 0; }; const compareSegments = (a, b) => { for (let i = 0; i < Math.max(a.length, b.length); i++) { const r = compareStrings(a[i] || '0', b[i] || '0'); if (r !== 0) return r; } return 0; }; /** * Compare [semver](https://semver.org/) version strings to find greater, equal or lesser. * This library supports the full semver specification, including comparing versions with different number of digits like `1.0.0`, `1.0`, `1`, and pre-release versions like `1.0.0-alpha`. * @param v1 - First version to compare * @param v2 - Second version to compare * @returns Numeric value compatible with the [Array.sort(fn) interface](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters). */ const compareVersions = (v1, v2) => { // validate input and split into segments const n1 = validateAndParse(v1); const n2 = validateAndParse(v2); // pop off the patch const p1 = n1.pop(); const p2 = n2.pop(); // validate numbers const r = compareSegments(n1, n2); if (r !== 0) return r; // validate pre-release if (p1 && p2) { return compareSegments(p1.split('.'), p2.split('.')); } else if (p1 || p2) { return p1 ? -1 : 1; } return 0; }; /** * Compare [semver](https://semver.org/) version strings using the specified operator. * * @param v1 First version to compare * @param v2 Second version to compare * @param operator Allowed arithmetic operator to use * @returns `true` if the comparison between the firstVersion and the secondVersion satisfies the operator, `false` otherwise. * * @example * ``` * compare('10.1.8', '10.0.4', '>'); // return true * compare('10.0.1', '10.0.1', '='); // return true * compare('10.1.1', '10.2.2', '<'); // return true * compare('10.1.1', '10.2.2', '<='); // return true * compare('10.1.1', '10.2.2', '>='); // return false * ``` */ const compare = (v1, v2, operator) => { // validate input operator assertValidOperator(operator); // since result of compareVersions can only be -1 or 0 or 1 // a simple map can be used to replace switch const res = compareVersions(v1, v2); return operatorResMap[operator].includes(res); }; const operatorResMap = { '>': [1], '>=': [0, 1], '=': [0], '<=': [-1, 0], '<': [-1], '!=': [-1, 1], }; const allowedOperators = Object.keys(operatorResMap); const assertValidOperator = (op) => { if (typeof op !== 'string') { throw new TypeError(`Invalid operator type, expected string but got ${typeof op}`); } if (allowedOperators.indexOf(op) === -1) { throw new Error(`Invalid operator, expected one of ${allowedOperators.join('|')}`); } }; /** * Match [npm semver](https://docs.npmjs.com/cli/v6/using-npm/semver) version range. * * @param version Version number to match * @param range Range pattern for version * @returns `true` if the version number is within the range, `false` otherwise. * * @example * ``` * satisfies('1.1.0', '^1.0.0'); // return true * satisfies('1.1.0', '~1.0.0'); // return false * ``` */ const satisfies = (version, range) => { // clean input range = range.replace(/([><=]+)\s+/g, '$1'); // handle multiple comparators if (range.includes('||')) { return range.split('||').some((r) => satisfies(version, r)); } else if (range.includes(' - ')) { const [a, b] = range.split(' - ', 2); return satisfies(version, `>=${a} <=${b}`); } else if (range.includes(' ')) { return range .trim() .replace(/\s{2,}/g, ' ') .split(' ') .every((r) => satisfies(version, r)); } // if no range operator then "=" const m = range.match(/^([<>=~^]+)/); const op = m ? m[1] : '='; // if gt/lt/eq then operator compare if (op !== '^' && op !== '~') return compare(version, range, op); // else range of either "~" or "^" is assumed const [v1, v2, v3, , vp] = validateAndParse(version); const [r1, r2, r3, , rp] = validateAndParse(range); const v = [v1, v2, v3]; const r = [r1, r2 !== null && r2 !== void 0 ? r2 : 'x', r3 !== null && r3 !== void 0 ? r3 : 'x']; // validate pre-release if (rp) { if (!vp) return false; if (compareSegments(v, r) !== 0) return false; if (compareSegments(vp.split('.'), rp.split('.')) === -1) return false; } // first non-zero number const nonZero = r.findIndex((v) => v !== '0') + 1; // pointer to where segments can be >= const i = op === '~' ? 2 : nonZero > 1 ? nonZero : 1; // before pointer must be equal if (compareSegments(v.slice(0, i), r.slice(0, i)) !== 0) return false; // after pointer must be >= if (compareSegments(v.slice(i), r.slice(i)) === -1) return false; return true; }; /** * Validate [semver](https://semver.org/) version strings. * * @param version Version number to validate * @returns `true` if the version number is a valid semver version number, `false` otherwise. * * @example * ``` * validate('1.0.0-rc.1'); // return true * validate('1.0-rc.1'); // return false * validate('foo'); // return false * ``` */ const validate = (version) => typeof version === 'string' && /^[v\d]/.test(version) && semver.test(version); /** * Validate [semver](https://semver.org/) version strings strictly. Will not accept wildcards and version ranges. * * @param version Version number to validate * @returns `true` if the version number is a valid semver version number `false` otherwise * * @example * ``` * validate('1.0.0-rc.1'); // return true * validate('1.0-rc.1'); // return false * validate('foo'); // return false * ``` */ const validateStrict = (version) => typeof version === 'string' && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/.test(version); exports.compare = compare; exports.compareVersions = compareVersions; exports.satisfies = satisfies; exports.validate = validate; exports.validateStrict = validateStrict; })); //# sourceMappingURL=index.js.map node_modules/compare-versions/README.md 0000664 00000011131 15114743311 0013773 0 ustar 00 # compare-versions [](https://github.com/omichelsen/compare-versions/actions/workflows/ci.yml) [](https://coveralls.io/github/omichelsen/compare-versions?branch=main) [](https://bundlephobia.com/package/compare-versions) Compare [semver](https://semver.org/) version strings to find greater, equal or lesser. Runs in the browser as well as Node.js/React Native etc. Has no dependencies and is [tiny](https://bundlephobia.com/package/compare-versions). Supports the full semver specification including versions with different number of digits like `1.0.0`, `1.0`, `1` and pre-releases like `1.0.0-alpha`. Additionally supports the following variations: - Wildcards for minor and patch version like `1.0.x` or `1.0.*`. - [Chromium version numbers](https://www.chromium.org/developers/version-numbers) with 4 parts, e.g. version `25.0.1364.126`. - Any leading `v` is ignored, e.g. `v1.0` is interpreted as `1.0`. - Leading zero is ignored, e.g. `1.01.1` is interpreted as `1.1.1`. - [npm version ranges](https://docs.npmjs.com/cli/v6/using-npm/semver#ranges), e.g. `1.2.7 || >=1.2.9 <2.0.0` ## Install ```bash $ npm install compare-versions ``` __Note__: Starting from v5 the main export is now _named_ like so: `import { compareVersions } from 'compare-versions'`. __Note__: Starting from v4 this library includes a ESM version which will automatically be selected by your bundler (webpack, parcel etc). The CJS/UMD version is `lib/umd/index.js` and the new ESM version is `lib/esm/index.js`. ## Usage Will return `1` if first version is greater, `0` if versions are equal, and `-1` if the second version is greater: ```js import { compareVersions } from 'compare-versions'; compareVersions('11.1.1', '10.0.0'); // 1 compareVersions('10.0.0', '10.0.0'); // 0 compareVersions('10.0.0', '11.1.1'); // -1 ``` Can also be used for sorting: ```js const versions = [ '1.5.19', '1.2.3', '1.5.5' ] const sorted = versions.sort(compareVersions); /* [ '1.2.3', '1.5.5', '1.5.19' ] */ ``` ### "Human Readable" Compare The alternative `compare` function accepts an operator which will be more familiar to humans: ```js import { compare } from 'compare-versions'; compare('10.1.8', '10.0.4', '>'); // true compare('10.0.1', '10.0.1', '='); // true compare('10.1.1', '10.2.2', '<'); // true compare('10.1.1', '10.2.2', '<='); // true compare('10.1.1', '10.2.2', '>='); // false ``` ### Version ranges The `satisfies` function accepts a range to compare, compatible with [npm package versioning](https://docs.npmjs.com/cli/v6/using-npm/semver): ```js import { satisfies } from 'compare-versions'; satisfies('10.0.1', '~10.0.0'); // true satisfies('10.1.0', '~10.0.0'); // false satisfies('10.1.2', '^10.0.0'); // true satisfies('11.0.0', '^10.0.0'); // false satisfies('10.1.8', '>10.0.4'); // true satisfies('10.0.1', '=10.0.1'); // true satisfies('10.1.1', '<10.2.2'); // true satisfies('10.1.1', '<=10.2.2'); // true satisfies('10.1.1', '>=10.2.2'); // false satisfies('1.4.6', '1.2.7 || >=1.2.9 <2.0.0'); // true satisfies('1.2.8', '1.2.7 || >=1.2.9 <2.0.0'); // false satisfies('1.5.1', '1.2.3 - 2.3.4'); // true satisfies('2.3.5', '1.2.3 - 2.3.4'); // false ``` ### Validate version numbers Applies the same rules used comparing version numbers and returns a boolean: ```js import { validate } from 'compare-versions'; validate('1.0.0-rc.1'); // true validate('1.0-rc.1'); // false validate('foo'); // false ``` ### Validate version numbers (strict) Validate version numbers strictly according to semver.org; 3 integers, no wildcards, no leading zero or "v" etc: ```js import { validateStrict } from 'compare-versions'; validate('1.0.0'); // true validate('1.0.0-rc.1'); // true validate('1.0'); // false validate('1.x'); // false validate('v1.02'); // false ``` ### Browser If included directly in the browser, the functions above are available on the global window under the `compareVersions` object: ```html <script src=https://unpkg.com/compare-versions/lib/umd/index.js></script> <script> const { compareVersions, compare, satisfies, validate } = window.compareVersions console.log(compareVersions('11.0.0', '10.0.0')) console.log(compare('11.0.0', '10.0.0', '>')) console.log(satisfies('1.2.0', '^1.0.0')) console.log(validate('11.0.0')) console.log(validateStrict('11.0.0')) </script> ``` node_modules/cli-spinners/license 0000664 00000002135 15114743311 0013177 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/cli-spinners/package.json 0000664 00000001653 15114743311 0014124 0 ustar 00 { "name": "cli-spinners", "version": "2.9.2", "description": "Spinners for use in the terminal", "license": "MIT", "repository": "sindresorhus/cli-spinners", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "engines": { "node": ">=6" }, "scripts": { "test": "xo && ava && tsd", "asciicast": "asciinema rec --command='node example-all.js' --title='cli-spinner' --quiet" }, "files": [ "index.js", "index.d.ts", "spinners.json" ], "keywords": [ "cli", "spinner", "spinners", "terminal", "term", "console", "ascii", "unicode", "loading", "indicator", "progress", "busy", "wait", "idle", "json" ], "devDependencies": { "@types/node": "^17.0.41", "ava": "^1.4.1", "log-update": "^3.2.0", "string-length": "^4.0.1", "tsd": "^0.7.2", "xo": "^0.24.0" } } node_modules/cli-spinners/readme.md 0000664 00000002530 15114743311 0013410 0 ustar 00 # cli-spinners > 70+ spinners for use in the terminal <p align="center"> <br> <img width="700" src="screenshot.svg"> <br> <br> </p> The list of spinners is just a [JSON file](spinners.json) and can be used wherever. You probably want to use one of these spinners through the [`ora`](https://github.com/sindresorhus/ora) module. ## Install ```sh npm install cli-spinners ``` ## Usage ```js const cliSpinners = require('cli-spinners'); console.log(cliSpinners.dots); /* { interval: 80, frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] } */ ``` ## Preview The header GIF is outdated. See all the [spinner at once](https://jsfiddle.net/sindresorhus/2eLtsbey/embedded/result/) or [one at the time](https://asciinema.org/a/95348?size=big). ## API Each spinner comes with a recommended `interval` and an array of `frames`. [See the spinners.](spinners.json) The `random` spinner will return a random spinner each time it's called. ## Related - [ora](https://github.com/sindresorhus/ora) - Elegant terminal spinner - [CLISpinner](https://github.com/kiliankoe/CLISpinner) - Terminal spinners for Swift - [py-spinners](https://github.com/ManrajGrover/py-spinners) - Python port - [spinners](https://github.com/FGRibreau/spinners) - Terminal spinners for Rust - [go-spinners](https://github.com/gabe565/go-spinners) - Go port node_modules/cli-spinners/index.d.ts 0000664 00000003737 15114743311 0013544 0 ustar 00 declare namespace cliSpinners { type SpinnerName = | 'dots' | 'dots2' | 'dots3' | 'dots4' | 'dots5' | 'dots6' | 'dots7' | 'dots8' | 'dots9' | 'dots10' | 'dots11' | 'dots12' | 'dots8Bit' | 'sand' | 'line' | 'line2' | 'pipe' | 'simpleDots' | 'simpleDotsScrolling' | 'star' | 'star2' | 'flip' | 'hamburger' | 'growVertical' | 'growHorizontal' | 'balloon' | 'balloon2' | 'noise' | 'bounce' | 'boxBounce' | 'boxBounce2' | 'binary' | 'triangle' | 'arc' | 'circle' | 'squareCorners' | 'circleQuarters' | 'circleHalves' | 'squish' | 'toggle' | 'toggle2' | 'toggle3' | 'toggle4' | 'toggle5' | 'toggle6' | 'toggle7' | 'toggle8' | 'toggle9' | 'toggle10' | 'toggle11' | 'toggle12' | 'toggle13' | 'arrow' | 'arrow2' | 'arrow3' | 'bouncingBar' | 'bouncingBall' | 'smiley' | 'monkey' | 'hearts' | 'clock' | 'earth' | 'material' | 'moon' | 'runner' | 'pong' | 'shark' | 'dqpb' | 'weather' | 'christmas' | 'grenade' | 'point' | 'layer' | 'betaWave' | 'fingerDance' | 'fistBump' | 'soccerHeader' | 'mindblown' | 'speaker' | 'orangePulse' | 'bluePulse' | 'orangeBluePulse' | 'timeTravel' | 'aesthetic' | 'dwarfFortress'; interface Spinner { /** Recommended interval. */ readonly interval: number; /** A list of frames to show for the spinner. */ readonly frames: string[]; } } /** 70+ spinners for use in the terminal. @example ``` import cliSpinners = require('cli-spinners'); console.log(cliSpinners.dots); // { // interval: 80, // frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] // } ``` */ declare const cliSpinners: { readonly [spinnerName in cliSpinners.SpinnerName]: cliSpinners.Spinner; } & { /** Returns a random spinner each time it's called. */ readonly random: cliSpinners.Spinner; // TODO: Remove this for the next major release default: typeof cliSpinners; }; export = cliSpinners; node_modules/cli-spinners/spinners.json 0000664 00000063234 15114743311 0014375 0 ustar 00 { "dots": { "interval": 80, "frames": [ "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏" ] }, "dots2": { "interval": 80, "frames": [ "⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷" ] }, "dots3": { "interval": 80, "frames": [ "⠋", "⠙", "⠚", "⠞", "⠖", "⠦", "⠴", "⠲", "⠳", "⠓" ] }, "dots4": { "interval": 80, "frames": [ "⠄", "⠆", "⠇", "⠋", "⠙", "⠸", "⠰", "⠠", "⠰", "⠸", "⠙", "⠋", "⠇", "⠆" ] }, "dots5": { "interval": 80, "frames": [ "⠋", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋" ] }, "dots6": { "interval": 80, "frames": [ "⠁", "⠉", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠤", "⠄", "⠄", "⠤", "⠴", "⠲", "⠒", "⠂", "⠂", "⠒", "⠚", "⠙", "⠉", "⠁" ] }, "dots7": { "interval": 80, "frames": [ "⠈", "⠉", "⠋", "⠓", "⠒", "⠐", "⠐", "⠒", "⠖", "⠦", "⠤", "⠠", "⠠", "⠤", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋", "⠉", "⠈" ] }, "dots8": { "interval": 80, "frames": [ "⠁", "⠁", "⠉", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠤", "⠄", "⠄", "⠤", "⠠", "⠠", "⠤", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋", "⠉", "⠈", "⠈" ] }, "dots9": { "interval": 80, "frames": [ "⢹", "⢺", "⢼", "⣸", "⣇", "⡧", "⡗", "⡏" ] }, "dots10": { "interval": 80, "frames": [ "⢄", "⢂", "⢁", "⡁", "⡈", "⡐", "⡠" ] }, "dots11": { "interval": 100, "frames": [ "⠁", "⠂", "⠄", "⡀", "⢀", "⠠", "⠐", "⠈" ] }, "dots12": { "interval": 80, "frames": [ "⢀⠀", "⡀⠀", "⠄⠀", "⢂⠀", "⡂⠀", "⠅⠀", "⢃⠀", "⡃⠀", "⠍⠀", "⢋⠀", "⡋⠀", "⠍⠁", "⢋⠁", "⡋⠁", "⠍⠉", "⠋⠉", "⠋⠉", "⠉⠙", "⠉⠙", "⠉⠩", "⠈⢙", "⠈⡙", "⢈⠩", "⡀⢙", "⠄⡙", "⢂⠩", "⡂⢘", "⠅⡘", "⢃⠨", "⡃⢐", "⠍⡐", "⢋⠠", "⡋⢀", "⠍⡁", "⢋⠁", "⡋⠁", "⠍⠉", "⠋⠉", "⠋⠉", "⠉⠙", "⠉⠙", "⠉⠩", "⠈⢙", "⠈⡙", "⠈⠩", "⠀⢙", "⠀⡙", "⠀⠩", "⠀⢘", "⠀⡘", "⠀⠨", "⠀⢐", "⠀⡐", "⠀⠠", "⠀⢀", "⠀⡀" ] }, "dots13": { "interval": 80, "frames": [ "⣼", "⣹", "⢻", "⠿", "⡟", "⣏", "⣧", "⣶" ] }, "dots8Bit": { "interval": 80, "frames": [ "⠀", "⠁", "⠂", "⠃", "⠄", "⠅", "⠆", "⠇", "⡀", "⡁", "⡂", "⡃", "⡄", "⡅", "⡆", "⡇", "⠈", "⠉", "⠊", "⠋", "⠌", "⠍", "⠎", "⠏", "⡈", "⡉", "⡊", "⡋", "⡌", "⡍", "⡎", "⡏", "⠐", "⠑", "⠒", "⠓", "⠔", "⠕", "⠖", "⠗", "⡐", "⡑", "⡒", "⡓", "⡔", "⡕", "⡖", "⡗", "⠘", "⠙", "⠚", "⠛", "⠜", "⠝", "⠞", "⠟", "⡘", "⡙", "⡚", "⡛", "⡜", "⡝", "⡞", "⡟", "⠠", "⠡", "⠢", "⠣", "⠤", "⠥", "⠦", "⠧", "⡠", "⡡", "⡢", "⡣", "⡤", "⡥", "⡦", "⡧", "⠨", "⠩", "⠪", "⠫", "⠬", "⠭", "⠮", "⠯", "⡨", "⡩", "⡪", "⡫", "⡬", "⡭", "⡮", "⡯", "⠰", "⠱", "⠲", "⠳", "⠴", "⠵", "⠶", "⠷", "⡰", "⡱", "⡲", "⡳", "⡴", "⡵", "⡶", "⡷", "⠸", "⠹", "⠺", "⠻", "⠼", "⠽", "⠾", "⠿", "⡸", "⡹", "⡺", "⡻", "⡼", "⡽", "⡾", "⡿", "⢀", "⢁", "⢂", "⢃", "⢄", "⢅", "⢆", "⢇", "⣀", "⣁", "⣂", "⣃", "⣄", "⣅", "⣆", "⣇", "⢈", "⢉", "⢊", "⢋", "⢌", "⢍", "⢎", "⢏", "⣈", "⣉", "⣊", "⣋", "⣌", "⣍", "⣎", "⣏", "⢐", "⢑", "⢒", "⢓", "⢔", "⢕", "⢖", "⢗", "⣐", "⣑", "⣒", "⣓", "⣔", "⣕", "⣖", "⣗", "⢘", "⢙", "⢚", "⢛", "⢜", "⢝", "⢞", "⢟", "⣘", "⣙", "⣚", "⣛", "⣜", "⣝", "⣞", "⣟", "⢠", "⢡", "⢢", "⢣", "⢤", "⢥", "⢦", "⢧", "⣠", "⣡", "⣢", "⣣", "⣤", "⣥", "⣦", "⣧", "⢨", "⢩", "⢪", "⢫", "⢬", "⢭", "⢮", "⢯", "⣨", "⣩", "⣪", "⣫", "⣬", "⣭", "⣮", "⣯", "⢰", "⢱", "⢲", "⢳", "⢴", "⢵", "⢶", "⢷", "⣰", "⣱", "⣲", "⣳", "⣴", "⣵", "⣶", "⣷", "⢸", "⢹", "⢺", "⢻", "⢼", "⢽", "⢾", "⢿", "⣸", "⣹", "⣺", "⣻", "⣼", "⣽", "⣾", "⣿" ] }, "sand": { "interval": 80, "frames": [ "⠁", "⠂", "⠄", "⡀", "⡈", "⡐", "⡠", "⣀", "⣁", "⣂", "⣄", "⣌", "⣔", "⣤", "⣥", "⣦", "⣮", "⣶", "⣷", "⣿", "⡿", "⠿", "⢟", "⠟", "⡛", "⠛", "⠫", "⢋", "⠋", "⠍", "⡉", "⠉", "⠑", "⠡", "⢁" ] }, "line": { "interval": 130, "frames": [ "-", "\\", "|", "/" ] }, "line2": { "interval": 100, "frames": [ "⠂", "-", "–", "—", "–", "-" ] }, "pipe": { "interval": 100, "frames": [ "┤", "┘", "┴", "└", "├", "┌", "┬", "┐" ] }, "simpleDots": { "interval": 400, "frames": [ ". ", ".. ", "...", " " ] }, "simpleDotsScrolling": { "interval": 200, "frames": [ ". ", ".. ", "...", " ..", " .", " " ] }, "star": { "interval": 70, "frames": [ "✶", "✸", "✹", "✺", "✹", "✷" ] }, "star2": { "interval": 80, "frames": [ "+", "x", "*" ] }, "flip": { "interval": 70, "frames": [ "_", "_", "_", "-", "`", "`", "'", "´", "-", "_", "_", "_" ] }, "hamburger": { "interval": 100, "frames": [ "☱", "☲", "☴" ] }, "growVertical": { "interval": 120, "frames": [ "▁", "▃", "▄", "▅", "▆", "▇", "▆", "▅", "▄", "▃" ] }, "growHorizontal": { "interval": 120, "frames": [ "▏", "▎", "▍", "▌", "▋", "▊", "▉", "▊", "▋", "▌", "▍", "▎" ] }, "balloon": { "interval": 140, "frames": [ " ", ".", "o", "O", "@", "*", " " ] }, "balloon2": { "interval": 120, "frames": [ ".", "o", "O", "°", "O", "o", "." ] }, "noise": { "interval": 100, "frames": [ "▓", "▒", "░" ] }, "bounce": { "interval": 120, "frames": [ "⠁", "⠂", "⠄", "⠂" ] }, "boxBounce": { "interval": 120, "frames": [ "▖", "▘", "▝", "▗" ] }, "boxBounce2": { "interval": 100, "frames": [ "▌", "▀", "▐", "▄" ] }, "triangle": { "interval": 50, "frames": [ "◢", "◣", "◤", "◥" ] }, "binary": { "interval": 80, "frames": [ "010010", "001100", "100101", "111010", "111101", "010111", "101011", "111000", "110011", "110101" ] }, "arc": { "interval": 100, "frames": [ "◜", "◠", "◝", "◞", "◡", "◟" ] }, "circle": { "interval": 120, "frames": [ "◡", "⊙", "◠" ] }, "squareCorners": { "interval": 180, "frames": [ "◰", "◳", "◲", "◱" ] }, "circleQuarters": { "interval": 120, "frames": [ "◴", "◷", "◶", "◵" ] }, "circleHalves": { "interval": 50, "frames": [ "◐", "◓", "◑", "◒" ] }, "squish": { "interval": 100, "frames": [ "╫", "╪" ] }, "toggle": { "interval": 250, "frames": [ "⊶", "⊷" ] }, "toggle2": { "interval": 80, "frames": [ "▫", "▪" ] }, "toggle3": { "interval": 120, "frames": [ "□", "■" ] }, "toggle4": { "interval": 100, "frames": [ "■", "□", "▪", "▫" ] }, "toggle5": { "interval": 100, "frames": [ "▮", "▯" ] }, "toggle6": { "interval": 300, "frames": [ "ဝ", "၀" ] }, "toggle7": { "interval": 80, "frames": [ "⦾", "⦿" ] }, "toggle8": { "interval": 100, "frames": [ "◍", "◌" ] }, "toggle9": { "interval": 100, "frames": [ "◉", "◎" ] }, "toggle10": { "interval": 100, "frames": [ "㊂", "㊀", "㊁" ] }, "toggle11": { "interval": 50, "frames": [ "⧇", "⧆" ] }, "toggle12": { "interval": 120, "frames": [ "☗", "☖" ] }, "toggle13": { "interval": 80, "frames": [ "=", "*", "-" ] }, "arrow": { "interval": 100, "frames": [ "←", "↖", "↑", "↗", "→", "↘", "↓", "↙" ] }, "arrow2": { "interval": 80, "frames": [ "⬆️ ", "↗️ ", "➡️ ", "↘️ ", "⬇️ ", "↙️ ", "⬅️ ", "↖️ " ] }, "arrow3": { "interval": 120, "frames": [ "▹▹▹▹▹", "▸▹▹▹▹", "▹▸▹▹▹", "▹▹▸▹▹", "▹▹▹▸▹", "▹▹▹▹▸" ] }, "bouncingBar": { "interval": 80, "frames": [ "[ ]", "[= ]", "[== ]", "[=== ]", "[====]", "[ ===]", "[ ==]", "[ =]", "[ ]", "[ =]", "[ ==]", "[ ===]", "[====]", "[=== ]", "[== ]", "[= ]" ] }, "bouncingBall": { "interval": 80, "frames": [ "( ● )", "( ● )", "( ● )", "( ● )", "( ●)", "( ● )", "( ● )", "( ● )", "( ● )", "(● )" ] }, "smiley": { "interval": 200, "frames": [ "😄 ", "😝 " ] }, "monkey": { "interval": 300, "frames": [ "🙈 ", "🙈 ", "🙉 ", "🙊 " ] }, "hearts": { "interval": 100, "frames": [ "💛 ", "💙 ", "💜 ", "💚 ", "❤️ " ] }, "clock": { "interval": 100, "frames": [ "🕛 ", "🕐 ", "🕑 ", "🕒 ", "🕓 ", "🕔 ", "🕕 ", "🕖 ", "🕗 ", "🕘 ", "🕙 ", "🕚 " ] }, "earth": { "interval": 180, "frames": [ "🌍 ", "🌎 ", "🌏 " ] }, "material": { "interval": 17, "frames": [ "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "███████▁▁▁▁▁▁▁▁▁▁▁▁▁", "████████▁▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "██████████▁▁▁▁▁▁▁▁▁▁", "███████████▁▁▁▁▁▁▁▁▁", "█████████████▁▁▁▁▁▁▁", "██████████████▁▁▁▁▁▁", "██████████████▁▁▁▁▁▁", "▁██████████████▁▁▁▁▁", "▁██████████████▁▁▁▁▁", "▁██████████████▁▁▁▁▁", "▁▁██████████████▁▁▁▁", "▁▁▁██████████████▁▁▁", "▁▁▁▁█████████████▁▁▁", "▁▁▁▁██████████████▁▁", "▁▁▁▁██████████████▁▁", "▁▁▁▁▁██████████████▁", "▁▁▁▁▁██████████████▁", "▁▁▁▁▁██████████████▁", "▁▁▁▁▁▁██████████████", "▁▁▁▁▁▁██████████████", "▁▁▁▁▁▁▁█████████████", "▁▁▁▁▁▁▁█████████████", "▁▁▁▁▁▁▁▁████████████", "▁▁▁▁▁▁▁▁████████████", "▁▁▁▁▁▁▁▁▁███████████", "▁▁▁▁▁▁▁▁▁███████████", "▁▁▁▁▁▁▁▁▁▁██████████", "▁▁▁▁▁▁▁▁▁▁██████████", "▁▁▁▁▁▁▁▁▁▁▁▁████████", "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", "██████▁▁▁▁▁▁▁▁▁▁▁▁▁█", "████████▁▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "█████████▁▁▁▁▁▁▁▁▁▁▁", "███████████▁▁▁▁▁▁▁▁▁", "████████████▁▁▁▁▁▁▁▁", "████████████▁▁▁▁▁▁▁▁", "██████████████▁▁▁▁▁▁", "██████████████▁▁▁▁▁▁", "▁██████████████▁▁▁▁▁", "▁██████████████▁▁▁▁▁", "▁▁▁█████████████▁▁▁▁", "▁▁▁▁▁████████████▁▁▁", "▁▁▁▁▁████████████▁▁▁", "▁▁▁▁▁▁███████████▁▁▁", "▁▁▁▁▁▁▁▁█████████▁▁▁", "▁▁▁▁▁▁▁▁█████████▁▁▁", "▁▁▁▁▁▁▁▁▁█████████▁▁", "▁▁▁▁▁▁▁▁▁█████████▁▁", "▁▁▁▁▁▁▁▁▁▁█████████▁", "▁▁▁▁▁▁▁▁▁▁▁████████▁", "▁▁▁▁▁▁▁▁▁▁▁████████▁", "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁" ] }, "moon": { "interval": 80, "frames": [ "🌑 ", "🌒 ", "🌓 ", "🌔 ", "🌕 ", "🌖 ", "🌗 ", "🌘 " ] }, "runner": { "interval": 140, "frames": [ "🚶 ", "🏃 " ] }, "pong": { "interval": 80, "frames": [ "▐⠂ ▌", "▐⠈ ▌", "▐ ⠂ ▌", "▐ ⠠ ▌", "▐ ⡀ ▌", "▐ ⠠ ▌", "▐ ⠂ ▌", "▐ ⠈ ▌", "▐ ⠂ ▌", "▐ ⠠ ▌", "▐ ⡀ ▌", "▐ ⠠ ▌", "▐ ⠂ ▌", "▐ ⠈ ▌", "▐ ⠂▌", "▐ ⠠▌", "▐ ⡀▌", "▐ ⠠ ▌", "▐ ⠂ ▌", "▐ ⠈ ▌", "▐ ⠂ ▌", "▐ ⠠ ▌", "▐ ⡀ ▌", "▐ ⠠ ▌", "▐ ⠂ ▌", "▐ ⠈ ▌", "▐ ⠂ ▌", "▐ ⠠ ▌", "▐ ⡀ ▌", "▐⠠ ▌" ] }, "shark": { "interval": 120, "frames": [ "▐|\\____________▌", "▐_|\\___________▌", "▐__|\\__________▌", "▐___|\\_________▌", "▐____|\\________▌", "▐_____|\\_______▌", "▐______|\\______▌", "▐_______|\\_____▌", "▐________|\\____▌", "▐_________|\\___▌", "▐__________|\\__▌", "▐___________|\\_▌", "▐____________|\\▌", "▐____________/|▌", "▐___________/|_▌", "▐__________/|__▌", "▐_________/|___▌", "▐________/|____▌", "▐_______/|_____▌", "▐______/|______▌", "▐_____/|_______▌", "▐____/|________▌", "▐___/|_________▌", "▐__/|__________▌", "▐_/|___________▌", "▐/|____________▌" ] }, "dqpb": { "interval": 100, "frames": [ "d", "q", "p", "b" ] }, "weather": { "interval": 100, "frames": [ "☀️ ", "☀️ ", "☀️ ", "🌤 ", "⛅️ ", "🌥 ", "☁️ ", "🌧 ", "🌨 ", "🌧 ", "🌨 ", "🌧 ", "🌨 ", "⛈ ", "🌨 ", "🌧 ", "🌨 ", "☁️ ", "🌥 ", "⛅️ ", "🌤 ", "☀️ ", "☀️ " ] }, "christmas": { "interval": 400, "frames": [ "🌲", "🎄" ] }, "grenade": { "interval": 80, "frames": [ "، ", "′ ", " ´ ", " ‾ ", " ⸌", " ⸊", " |", " ⁎", " ⁕", " ෴ ", " ⁓", " ", " ", " " ] }, "point": { "interval": 125, "frames": [ "∙∙∙", "●∙∙", "∙●∙", "∙∙●", "∙∙∙" ] }, "layer": { "interval": 150, "frames": [ "-", "=", "≡" ] }, "betaWave": { "interval": 80, "frames": [ "ρββββββ", "βρβββββ", "ββρββββ", "βββρβββ", "ββββρββ", "βββββρβ", "ββββββρ" ] }, "fingerDance": { "interval": 160, "frames": [ "🤘 ", "🤟 ", "🖖 ", "✋ ", "🤚 ", "👆 " ] }, "fistBump": { "interval": 80, "frames": [ "🤜\u3000\u3000\u3000\u3000🤛 ", "🤜\u3000\u3000\u3000\u3000🤛 ", "🤜\u3000\u3000\u3000\u3000🤛 ", "\u3000🤜\u3000\u3000🤛\u3000 ", "\u3000\u3000🤜🤛\u3000\u3000 ", "\u3000🤜✨🤛\u3000\u3000 ", "🤜\u3000✨\u3000🤛\u3000 " ] }, "soccerHeader": { "interval": 80, "frames": [ " 🧑⚽️ 🧑 ", "🧑 ⚽️ 🧑 ", "🧑 ⚽️ 🧑 ", "🧑 ⚽️ 🧑 ", "🧑 ⚽️ 🧑 ", "🧑 ⚽️ 🧑 ", "🧑 ⚽️🧑 ", "🧑 ⚽️ 🧑 ", "🧑 ⚽️ 🧑 ", "🧑 ⚽️ 🧑 ", "🧑 ⚽️ 🧑 ", "🧑 ⚽️ 🧑 " ] }, "mindblown": { "interval": 160, "frames": [ "😐 ", "😐 ", "😮 ", "😮 ", "😦 ", "😦 ", "😧 ", "😧 ", "🤯 ", "💥 ", "✨ ", "\u3000 ", "\u3000 ", "\u3000 " ] }, "speaker": { "interval": 160, "frames": [ "🔈 ", "🔉 ", "🔊 ", "🔉 " ] }, "orangePulse": { "interval": 100, "frames": [ "🔸 ", "🔶 ", "🟠 ", "🟠 ", "🔶 " ] }, "bluePulse": { "interval": 100, "frames": [ "🔹 ", "🔷 ", "🔵 ", "🔵 ", "🔷 " ] }, "orangeBluePulse": { "interval": 100, "frames": [ "🔸 ", "🔶 ", "🟠 ", "🟠 ", "🔶 ", "🔹 ", "🔷 ", "🔵 ", "🔵 ", "🔷 " ] }, "timeTravel": { "interval": 100, "frames": [ "🕛 ", "🕚 ", "🕙 ", "🕘 ", "🕗 ", "🕖 ", "🕕 ", "🕔 ", "🕓 ", "🕒 ", "🕑 ", "🕐 " ] }, "aesthetic": { "interval": 80, "frames": [ "▰▱▱▱▱▱▱", "▰▰▱▱▱▱▱", "▰▰▰▱▱▱▱", "▰▰▰▰▱▱▱", "▰▰▰▰▰▱▱", "▰▰▰▰▰▰▱", "▰▰▰▰▰▰▰", "▰▱▱▱▱▱▱" ] }, "dwarfFortress": { "interval": 80, "frames": [ " ██████£££ ", "☺██████£££ ", "☺██████£££ ", "☺▓█████£££ ", "☺▓█████£££ ", "☺▒█████£££ ", "☺▒█████£££ ", "☺░█████£££ ", "☺░█████£££ ", "☺ █████£££ ", " ☺█████£££ ", " ☺█████£££ ", " ☺▓████£££ ", " ☺▓████£££ ", " ☺▒████£££ ", " ☺▒████£££ ", " ☺░████£££ ", " ☺░████£££ ", " ☺ ████£££ ", " ☺████£££ ", " ☺████£££ ", " ☺▓███£££ ", " ☺▓███£££ ", " ☺▒███£££ ", " ☺▒███£££ ", " ☺░███£££ ", " ☺░███£££ ", " ☺ ███£££ ", " ☺███£££ ", " ☺███£££ ", " ☺▓██£££ ", " ☺▓██£££ ", " ☺▒██£££ ", " ☺▒██£££ ", " ☺░██£££ ", " ☺░██£££ ", " ☺ ██£££ ", " ☺██£££ ", " ☺██£££ ", " ☺▓█£££ ", " ☺▓█£££ ", " ☺▒█£££ ", " ☺▒█£££ ", " ☺░█£££ ", " ☺░█£££ ", " ☺ █£££ ", " ☺█£££ ", " ☺█£££ ", " ☺▓£££ ", " ☺▓£££ ", " ☺▒£££ ", " ☺▒£££ ", " ☺░£££ ", " ☺░£££ ", " ☺ £££ ", " ☺£££ ", " ☺£££ ", " ☺▓££ ", " ☺▓££ ", " ☺▒££ ", " ☺▒££ ", " ☺░££ ", " ☺░££ ", " ☺ ££ ", " ☺££ ", " ☺££ ", " ☺▓£ ", " ☺▓£ ", " ☺▒£ ", " ☺▒£ ", " ☺░£ ", " ☺░£ ", " ☺ £ ", " ☺£ ", " ☺£ ", " ☺▓ ", " ☺▓ ", " ☺▒ ", " ☺▒ ", " ☺░ ", " ☺░ ", " ☺ ", " ☺ &", " ☺ ☼&", " ☺ ☼ &", " ☺☼ &", " ☺☼ & ", " ‼ & ", " ☺ & ", " ‼ & ", " ☺ & ", " ‼ & ", " ☺ & ", "‼ & ", " & ", " & ", " & ░ ", " & ▒ ", " & ▓ ", " & £ ", " & ░£ ", " & ▒£ ", " & ▓£ ", " & ££ ", " & ░££ ", " & ▒££ ", "& ▓££ ", "& £££ ", " ░£££ ", " ▒£££ ", " ▓£££ ", " █£££ ", " ░█£££ ", " ▒█£££ ", " ▓█£££ ", " ██£££ ", " ░██£££ ", " ▒██£££ ", " ▓██£££ ", " ███£££ ", " ░███£££ ", " ▒███£££ ", " ▓███£££ ", " ████£££ ", " ░████£££ ", " ▒████£££ ", " ▓████£££ ", " █████£££ ", " ░█████£££ ", " ▒█████£££ ", " ▓█████£££ ", " ██████£££ ", " ██████£££ " ] } } node_modules/cli-spinners/index.js 0000664 00000000626 15114743311 0013302 0 ustar 00 'use strict'; const spinners = Object.assign({}, require('./spinners.json')); // eslint-disable-line import/extensions const spinnersList = Object.keys(spinners); Object.defineProperty(spinners, 'random', { get() { const randomIndex = Math.floor(Math.random() * spinnersList.length); const spinnerName = spinnersList[randomIndex]; return spinners[spinnerName]; } }); module.exports = spinners; node_modules/kleur/license 0000664 00000002132 15114743311 0011710 0 ustar 00 The MIT License (MIT) Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/kleur/package.json 0000664 00000001736 15114743311 0012642 0 ustar 00 { "name": "kleur", "version": "4.1.5", "repository": "lukeed/kleur", "description": "The fastest Node.js library for formatting terminal text with ANSI colors~!", "module": "index.mjs", "types": "index.d.ts", "main": "index.js", "license": "MIT", "exports": { ".": { "types": "./index.d.ts", "import": "./index.mjs", "require": "./index.js" }, "./colors": { "types": "./colors.d.ts", "import": "./colors.mjs", "require": "./colors.js" } }, "files": [ "*.d.ts", "colors.*", "index.*" ], "author": { "name": "Luke Edwards", "email": "luke.edwards05@gmail.com", "url": "https://lukeed.com" }, "scripts": { "build": "node build", "test": "uvu -r esm -i utils -i xyz" }, "engines": { "node": ">=6" }, "keywords": [ "ansi", "cli", "color", "colors", "console", "terminal" ], "devDependencies": { "esm": "3.2.25", "uvu": "0.3.3" } } node_modules/kleur/readme.md 0000664 00000016324 15114743311 0012132 0 ustar 00 <div align="center"> <img src="shots/logo.png" alt="kleur" height="120" /> </div> <div align="center"> <a href="https://npmjs.org/package/kleur"> <img src="https://badgen.now.sh/npm/v/kleur" alt="version" /> </a> <a href="https://github.com/lukeed/kleur/actions?query=workflow%3ACI"> <img src="https://github.com/lukeed/kleur/workflows/CI/badge.svg?event=push" alt="CI" /> </a> <a href="https://npmjs.org/package/kleur"> <img src="https://badgen.now.sh/npm/dm/kleur" alt="downloads" /> </a> <a href="https://packagephobia.now.sh/result?p=kleur"> <img src="https://packagephobia.now.sh/badge?p=kleur" alt="install size" /> </a> </div> <div align="center">The fastest Node.js library for formatting terminal text with ANSI colors~!</div> ## Features * No dependencies * Super [lightweight](#load-time) & [performant](#performance) * Supports [nested](#nested-methods) & [chained](#chained-methods) colors * No `String.prototype` modifications * Conditional [color support](#conditional-support) * [Fully treeshakable](#individual-colors) * Familiar [API](#api) --- As of `v3.0` the Chalk-style syntax (magical getter) is no longer used.<br>Please visit [History](#history) for migration paths supporting that syntax. --- ## Install ``` $ npm install --save kleur ``` ## Usage ```js import kleur from 'kleur'; // basic usage kleur.red('red text'); // chained methods kleur.blue().bold().underline('howdy partner'); // nested methods kleur.bold(`${ white().bgRed('[ERROR]') } ${ kleur.red().italic('Something happened')}`); ``` ### Chained Methods ```js const { bold, green } = require('kleur'); console.log(bold().red('this is a bold red message')); console.log(bold().italic('this is a bold italicized message')); console.log(bold().yellow().bgRed().italic('this is a bold yellow italicized message')); console.log(green().bold().underline('this is a bold green underlined message')); ``` <img src="shots/1.png" width="300" /> ### Nested Methods ```js const { yellow, red, cyan } = require('kleur'); console.log(yellow(`foo ${red().bold('red')} bar ${cyan('cyan')} baz`)); console.log(yellow('foo ' + red().bold('red') + ' bar ' + cyan('cyan') + ' baz')); ``` <img src="shots/2.png" width="300" /> ### Conditional Support Toggle color support as needed; `kleur` includes simple auto-detection which may not cover all cases. > **Note:** Both `kleur` and `kleur/colors` share the same detection logic. ```js import kleur from 'kleur'; // manually disable kleur.enabled = false; // or use another library to detect support kleur.enabled = require('color-support').level > 0; console.log(kleur.red('I will only be colored red if the terminal supports colors')); ``` > **Important:** <br>Colors will be disabled automatically in non [TTY contexts](https://nodejs.org/api/process.html#process_a_note_on_process_i_o). For example, spawning another process or piping output into another process will disable colorization automatically. To force colors in your piped output, you may do so with the `FORCE_COLOR=1` environment variable: ```sh $ node app.js #=> COLORS $ node app.js > log.txt #=> NO COLORS $ FORCE_COLOR=1 node app.js > log.txt #=> COLORS $ FORCE_COLOR=0 node app.js > log.txt #=> NO COLORS ``` ## API Any `kleur` method returns a `String` when invoked with input; otherwise chaining is expected. > It's up to the developer to pass the output to destinations like `console.log`, `process.stdout.write`, etc. The methods below are grouped by type for legibility purposes only. They each can be [chained](#chained-methods) or [nested](#nested-methods) with one another. ***Colors:*** > black — red — green — yellow — blue — magenta — cyan — white — gray — grey ***Backgrounds:*** > bgBlack — bgRed — bgGreen — bgYellow — bgBlue — bgMagenta — bgCyan — bgWhite ***Modifiers:*** > reset — bold — dim — italic* — underline — inverse — hidden — strikethrough* <sup>* <em>Not widely supported</em></sup> ## Individual Colors When you only need a few colors, it doesn't make sense to import _all_ of `kleur` because, as small as it is, `kleur` is not treeshakeable, and so most of its code will be doing nothing. In order to fix this, you can import from the `kleur/colors` submodule which _fully_ supports tree-shaking. The caveat with this approach is that color functions **are not** chainable~!<br>Each function receives and colorizes its input. You may combine colors, backgrounds, and modifiers by nesting function calls within other functions. ```js // or: import * as kleur from 'kleur/colors'; import { red, underline, bgWhite } from 'kleur/colors'; red('red text'); //~> kleur.red('red text'); underline(red('red underlined text')); //~> kleur.underline().red('red underlined text'); bgWhite(underline(red('red underlined text w/ white background'))); //~> kleur.bgWhite().underline().red('red underlined text w/ white background'); ``` > **Note:** All the same [colors, backgrounds, and modifiers](#api) are available. ***Conditional Support*** The `kleur/colors` submodule also allows you to toggle color support, as needed.<br> It includes the same initial assumptions as `kleur`, in an attempt to have colors enabled by default. Unlike `kleur`, this setting exists as `kleur.$.enabled` instead of `kleur.enabled`: ```js import * as kleur from 'kleur/colors'; // or: import { $, red } from 'kleur/colors'; // manually disabled kleur.$.enabled = false; // or use another library to detect support kleur.$.enabled = require('color-support').level > 0; console.log(red('I will only be colored red if the terminal supports colors')); ``` ## Benchmarks > Using Node v10.13.0 ### Load time ``` chalk :: 5.303ms kleur :: 0.488ms kleur/colors :: 0.369ms ansi-colors :: 1.504ms ``` ### Performance ``` # All Colors ansi-colors x 177,625 ops/sec ±1.47% (92 runs sampled) chalk x 611,907 ops/sec ±0.20% (92 runs sampled) kleur x 742,509 ops/sec ±1.47% (93 runs sampled) kleur/colors x 881,742 ops/sec ±0.19% (98 runs sampled) # Stacked colors ansi-colors x 23,331 ops/sec ±1.81% (94 runs sampled) chalk x 337,178 ops/sec ±0.20% (98 runs sampled) kleur x 78,299 ops/sec ±1.01% (97 runs sampled) kleur/colors x 104,431 ops/sec ±0.22% (97 runs sampled) # Nested colors ansi-colors x 67,181 ops/sec ±1.15% (92 runs sampled) chalk x 116,361 ops/sec ±0.63% (94 runs sampled) kleur x 139,514 ops/sec ±0.76% (95 runs sampled) kleur/colors x 145,716 ops/sec ±0.97% (97 runs sampled) ``` ## History This project originally forked [`ansi-colors`](https://github.com/doowb/ansi-colors). Beginning with `kleur@3.0`, the Chalk-style syntax (magical getter) has been replaced with function calls per key: ```js // Old: c.red.bold.underline('old'); // New: c.red().bold().underline('new'); ``` > <sup><em>As I work more with Rust, the newer syntax feels so much better & more natural!</em></sup> If you prefer the old syntax, you may migrate to `ansi-colors` or newer `chalk` releases.<br>Versions below `kleur@3.0` have been officially deprecated. ## License MIT © [Luke Edwards](https://lukeed.com) node_modules/kleur/index.d.ts 0000664 00000001455 15114743311 0012253 0 ustar 00 // Originally by: Rogier Schouten <https://github.com/rogierschouten> // Adapted by: Madhav Varshney <https://github.com/madhavarshney> declare namespace kleur { interface Color { (x: string | number): string; (): Kleur; } interface Kleur { // Colors black: Color; red: Color; green: Color; yellow: Color; blue: Color; magenta: Color; cyan: Color; white: Color; gray: Color; grey: Color; // Backgrounds bgBlack: Color; bgRed: Color; bgGreen: Color; bgYellow: Color; bgBlue: Color; bgMagenta: Color; bgCyan: Color; bgWhite: Color; // Modifiers reset: Color; bold: Color; dim: Color; italic: Color; underline: Color; inverse: Color; hidden: Color; strikethrough: Color; } } declare let kleur: kleur.Kleur & { enabled: boolean }; export = kleur; node_modules/kleur/colors.d.ts 0000664 00000002424 15114743311 0012442 0 ustar 00 declare function print(input: string | boolean | number): string; declare function print(input: undefined | void): undefined; declare function print(input: null): null; type Colorize = typeof print; export declare const $: { enabled: boolean }; // Colors export declare const black: Colorize; export declare const red: Colorize; export declare const green: Colorize; export declare const yellow: Colorize; export declare const blue: Colorize; export declare const magenta: Colorize; export declare const cyan: Colorize; export declare const white: Colorize; export declare const gray: Colorize; export declare const grey: Colorize; // Backgrounds export declare const bgBlack: Colorize; export declare const bgRed: Colorize; export declare const bgGreen: Colorize; export declare const bgYellow: Colorize; export declare const bgBlue: Colorize; export declare const bgMagenta: Colorize; export declare const bgCyan: Colorize; export declare const bgWhite: Colorize; // Modifiers export declare const reset: Colorize; export declare const bold: Colorize; export declare const dim: Colorize; export declare const italic: Colorize; export declare const underline: Colorize; export declare const inverse: Colorize; export declare const hidden: Colorize; export declare const strikethrough: Colorize; node_modules/kleur/index.mjs 0000664 00000005267 15114743311 0012201 0 ustar 00 'use strict'; let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true; if (typeof process !== 'undefined') { ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}); isTTY = process.stdout && process.stdout.isTTY; } const $ = { enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && ( FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY ), // modifiers reset: init(0, 0), bold: init(1, 22), dim: init(2, 22), italic: init(3, 23), underline: init(4, 24), inverse: init(7, 27), hidden: init(8, 28), strikethrough: init(9, 29), // colors black: init(30, 39), red: init(31, 39), green: init(32, 39), yellow: init(33, 39), blue: init(34, 39), magenta: init(35, 39), cyan: init(36, 39), white: init(37, 39), gray: init(90, 39), grey: init(90, 39), // background colors bgBlack: init(40, 49), bgRed: init(41, 49), bgGreen: init(42, 49), bgYellow: init(43, 49), bgBlue: init(44, 49), bgMagenta: init(45, 49), bgCyan: init(46, 49), bgWhite: init(47, 49) }; function run(arr, str) { let i=0, tmp, beg='', end=''; for (; i < arr.length; i++) { tmp = arr[i]; beg += tmp.open; end += tmp.close; if (!!~str.indexOf(tmp.close)) { str = str.replace(tmp.rgx, tmp.close + tmp.open); } } return beg + str + end; } function chain(has, keys) { let ctx = { has, keys }; ctx.reset = $.reset.bind(ctx); ctx.bold = $.bold.bind(ctx); ctx.dim = $.dim.bind(ctx); ctx.italic = $.italic.bind(ctx); ctx.underline = $.underline.bind(ctx); ctx.inverse = $.inverse.bind(ctx); ctx.hidden = $.hidden.bind(ctx); ctx.strikethrough = $.strikethrough.bind(ctx); ctx.black = $.black.bind(ctx); ctx.red = $.red.bind(ctx); ctx.green = $.green.bind(ctx); ctx.yellow = $.yellow.bind(ctx); ctx.blue = $.blue.bind(ctx); ctx.magenta = $.magenta.bind(ctx); ctx.cyan = $.cyan.bind(ctx); ctx.white = $.white.bind(ctx); ctx.gray = $.gray.bind(ctx); ctx.grey = $.grey.bind(ctx); ctx.bgBlack = $.bgBlack.bind(ctx); ctx.bgRed = $.bgRed.bind(ctx); ctx.bgGreen = $.bgGreen.bind(ctx); ctx.bgYellow = $.bgYellow.bind(ctx); ctx.bgBlue = $.bgBlue.bind(ctx); ctx.bgMagenta = $.bgMagenta.bind(ctx); ctx.bgCyan = $.bgCyan.bind(ctx); ctx.bgWhite = $.bgWhite.bind(ctx); return ctx; } function init(open, close) { let blk = { open: `\x1b[${open}m`, close: `\x1b[${close}m`, rgx: new RegExp(`\\x1b\\[${close}m`, 'g') }; return function (txt) { if (this !== void 0 && this.has !== void 0) { !!~this.has.indexOf(open) || (this.has.push(open),this.keys.push(blk)); return txt === void 0 ? this : $.enabled ? run(this.keys, txt+'') : txt+''; } return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt+'') : txt+''; }; } export default $; node_modules/kleur/index.js 0000664 00000005271 15114743311 0012017 0 ustar 00 'use strict'; let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true; if (typeof process !== 'undefined') { ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}); isTTY = process.stdout && process.stdout.isTTY; } const $ = { enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && ( FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY ), // modifiers reset: init(0, 0), bold: init(1, 22), dim: init(2, 22), italic: init(3, 23), underline: init(4, 24), inverse: init(7, 27), hidden: init(8, 28), strikethrough: init(9, 29), // colors black: init(30, 39), red: init(31, 39), green: init(32, 39), yellow: init(33, 39), blue: init(34, 39), magenta: init(35, 39), cyan: init(36, 39), white: init(37, 39), gray: init(90, 39), grey: init(90, 39), // background colors bgBlack: init(40, 49), bgRed: init(41, 49), bgGreen: init(42, 49), bgYellow: init(43, 49), bgBlue: init(44, 49), bgMagenta: init(45, 49), bgCyan: init(46, 49), bgWhite: init(47, 49) }; function run(arr, str) { let i=0, tmp, beg='', end=''; for (; i < arr.length; i++) { tmp = arr[i]; beg += tmp.open; end += tmp.close; if (!!~str.indexOf(tmp.close)) { str = str.replace(tmp.rgx, tmp.close + tmp.open); } } return beg + str + end; } function chain(has, keys) { let ctx = { has, keys }; ctx.reset = $.reset.bind(ctx); ctx.bold = $.bold.bind(ctx); ctx.dim = $.dim.bind(ctx); ctx.italic = $.italic.bind(ctx); ctx.underline = $.underline.bind(ctx); ctx.inverse = $.inverse.bind(ctx); ctx.hidden = $.hidden.bind(ctx); ctx.strikethrough = $.strikethrough.bind(ctx); ctx.black = $.black.bind(ctx); ctx.red = $.red.bind(ctx); ctx.green = $.green.bind(ctx); ctx.yellow = $.yellow.bind(ctx); ctx.blue = $.blue.bind(ctx); ctx.magenta = $.magenta.bind(ctx); ctx.cyan = $.cyan.bind(ctx); ctx.white = $.white.bind(ctx); ctx.gray = $.gray.bind(ctx); ctx.grey = $.grey.bind(ctx); ctx.bgBlack = $.bgBlack.bind(ctx); ctx.bgRed = $.bgRed.bind(ctx); ctx.bgGreen = $.bgGreen.bind(ctx); ctx.bgYellow = $.bgYellow.bind(ctx); ctx.bgBlue = $.bgBlue.bind(ctx); ctx.bgMagenta = $.bgMagenta.bind(ctx); ctx.bgCyan = $.bgCyan.bind(ctx); ctx.bgWhite = $.bgWhite.bind(ctx); return ctx; } function init(open, close) { let blk = { open: `\x1b[${open}m`, close: `\x1b[${close}m`, rgx: new RegExp(`\\x1b\\[${close}m`, 'g') }; return function (txt) { if (this !== void 0 && this.has !== void 0) { !!~this.has.indexOf(open) || (this.has.push(open),this.keys.push(blk)); return txt === void 0 ? this : $.enabled ? run(this.keys, txt+'') : txt+''; } return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt+'') : txt+''; }; } module.exports = $; node_modules/kleur/colors.mjs 0000664 00000003155 15114743311 0012365 0 ustar 00 let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true; if (typeof process !== 'undefined') { ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}); isTTY = process.stdout && process.stdout.isTTY; } export const $ = { enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && ( FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY ) } function init(x, y) { let rgx = new RegExp(`\\x1b\\[${y}m`, 'g'); let open = `\x1b[${x}m`, close = `\x1b[${y}m`; return function (txt) { if (!$.enabled || txt == null) return txt; return open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close; }; } // modifiers export const reset = init(0, 0); export const bold = init(1, 22); export const dim = init(2, 22); export const italic = init(3, 23); export const underline = init(4, 24); export const inverse = init(7, 27); export const hidden = init(8, 28); export const strikethrough = init(9, 29); // colors export const black = init(30, 39); export const red = init(31, 39); export const green = init(32, 39); export const yellow = init(33, 39); export const blue = init(34, 39); export const magenta = init(35, 39); export const cyan = init(36, 39); export const white = init(37, 39); export const gray = init(90, 39); export const grey = init(90, 39); // background colors export const bgBlack = init(40, 49); export const bgRed = init(41, 49); export const bgGreen = init(42, 49); export const bgYellow = init(43, 49); export const bgBlue = init(44, 49); export const bgMagenta = init(45, 49); export const bgCyan = init(46, 49); export const bgWhite = init(47, 49); node_modules/kleur/colors.js 0000664 00000002760 15114743311 0012211 0 ustar 00 let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true; if (typeof process !== 'undefined') { ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}); isTTY = process.stdout && process.stdout.isTTY; } const $ = exports.$ = { enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && ( FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY ) } function init(x, y) { let rgx = new RegExp(`\\x1b\\[${y}m`, 'g'); let open = `\x1b[${x}m`, close = `\x1b[${y}m`; return function (txt) { if (!$.enabled || txt == null) return txt; return open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close; }; } // modifiers exports.reset = init(0, 0); exports.bold = init(1, 22); exports.dim = init(2, 22); exports.italic = init(3, 23); exports.underline = init(4, 24); exports.inverse = init(7, 27); exports.hidden = init(8, 28); exports.strikethrough = init(9, 29); // colors exports.black = init(30, 39); exports.red = init(31, 39); exports.green = init(32, 39); exports.yellow = init(33, 39); exports.blue = init(34, 39); exports.magenta = init(35, 39); exports.cyan = init(36, 39); exports.white = init(37, 39); exports.gray = init(90, 39); exports.grey = init(90, 39); // background colors exports.bgBlack = init(40, 49); exports.bgRed = init(41, 49); exports.bgGreen = init(42, 49); exports.bgYellow = init(43, 49); exports.bgBlue = init(44, 49); exports.bgMagenta = init(45, 49); exports.bgCyan = init(46, 49); exports.bgWhite = init(47, 49); node_modules/tinygradient/package.json 0000664 00000002673 15114743311 0014222 0 ustar 00 { "name": "tinygradient", "version": "1.1.5", "author": { "name": "Damien \"Mistic\" Sorel", "email": "contact@git.strangeplanet.fr", "url": "https://www.strangeplanet.fr" }, "description": "Fast and small gradients manipulation, built on top of TinyColor", "license": "MIT", "homepage": "https://github.com/mistic100/tinygradient", "main": "index.js", "browser": "browser.js", "types": "types.d.ts", "files": [ "browser.js", "browser.js.map", "index.js", "types.d.ts" ], "dependencies": { "@types/tinycolor2": "^1.4.0", "tinycolor2": "^1.0.0" }, "devDependencies": { "@babel/core": "^7.2.2", "@babel/preset-env": "^7.2.3", "colorbrewer": "^1.3.0", "live-server": "^1.2.1", "mocha": "^8.0.1", "nodemon": "^2.0.0", "npm-run-all": "^4.1.5", "rollup": "^2.0.2", "rollup-plugin-babel": "^4.3.0", "rollup-plugin-commonjs": "^10.0.0" }, "keywords": [ "color", "gradient" ], "repository": { "type": "git", "url": "git://github.com/mistic100/tinygradient.git" }, "bugs": { "url": "https://github.com/mistic100/tinygradient/issues" }, "scripts": { "test": "mocha tests/*", "compile": "rollup --config rollup.config.js", "serve": "live-server --watch=browser.js,index.html --entry-file=index.html", "start": "npm-run-all --parallel watch serve", "watch": "nodemon --watch index.js --exec \"npm run compile\"" } } node_modules/tinygradient/LICENSE 0000664 00000002074 15114743311 0012734 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2020 Damien Sorel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/tinygradient/browser.js.map 0000664 00000061513 15114743311 0014527 0 ustar 00 {"version":3,"file":"browser.js","sources":["index.js"],"sourcesContent":["const tinycolor = require('tinycolor2');\n\n/**\n * @typedef {Object} TinyGradient.StopInput\n * @property {ColorInput} color\n * @property {number} pos\n */\n\n/**\n * @typedef {Object} TinyGradient.StepValue\n * @type {number} [r]\n * @type {number} [g]\n * @type {number} [b]\n * @type {number} [h]\n * @type {number} [s]\n * @type {number} [v]\n * @type {number} [a]\n */\n\n/**\n * @type {StepValue}\n */\nconst RGBA_MAX = { r: 256, g: 256, b: 256, a: 1 };\n\n/**\n * @type {StepValue}\n */\nconst HSVA_MAX = { h: 360, s: 1, v: 1, a: 1 };\n\n/**\n * Linearly compute the step size between start and end (not normalized)\n * @param {StepValue} start\n * @param {StepValue} end\n * @param {number} steps - number of desired steps\n * @return {StepValue}\n */\nfunction stepize(start, end, steps) {\n let step = {};\n\n for (let k in start) {\n if (start.hasOwnProperty(k)) {\n step[k] = steps === 0 ? 0 : (end[k] - start[k]) / steps;\n }\n }\n\n return step;\n}\n\n/**\n * Compute the final step color\n * @param {StepValue} step - from `stepize`\n * @param {StepValue} start\n * @param {number} i - color index\n * @param {StepValue} max - rgba or hsva of maximum values for each channel\n * @return {StepValue}\n */\nfunction interpolate(step, start, i, max) {\n let color = {};\n\n for (let k in start) {\n if (start.hasOwnProperty(k)) {\n color[k] = step[k] * i + start[k];\n color[k] = color[k] < 0 ? color[k] + max[k] : (max[k] !== 1 ? color[k] % max[k] : color[k]);\n }\n }\n\n return color;\n}\n\n/**\n * Generate gradient with RGBa interpolation\n * @param {StopInput} stop1\n * @param {StopInput} stop2\n * @param {number} steps\n * @return {tinycolor[]} color1 included, color2 excluded\n */\nfunction interpolateRgb(stop1, stop2, steps) {\n const start = stop1.color.toRgb();\n const end = stop2.color.toRgb();\n const step = stepize(start, end, steps);\n let gradient = [stop1.color];\n\n for (let i = 1; i < steps; i++) {\n const color = interpolate(step, start, i, RGBA_MAX);\n gradient.push(tinycolor(color));\n }\n\n return gradient;\n}\n\n/**\n * Generate gradient with HSVa interpolation\n * @param {StopInput} stop1\n * @param {StopInput} stop2\n * @param {number} steps\n * @param {boolean|'long'|'short'} mode\n * @return {tinycolor[]} color1 included, color2 excluded\n */\nfunction interpolateHsv(stop1, stop2, steps, mode) {\n const start = stop1.color.toHsv();\n const end = stop2.color.toHsv();\n\n // rgb interpolation if one of the steps in grayscale\n if (start.s === 0 || end.s === 0) {\n return interpolateRgb(stop1, stop2, steps);\n }\n\n let trigonometric;\n if (typeof mode === 'boolean') {\n trigonometric = mode;\n }\n else {\n const trigShortest = (start.h < end.h && end.h - start.h < 180) || (start.h > end.h && start.h - end.h > 180);\n trigonometric = (mode === 'long' && trigShortest) || (mode === 'short' && !trigShortest);\n }\n\n const step = stepize(start, end, steps);\n let gradient = [stop1.color];\n\n // recompute hue\n let diff;\n if ((start.h <= end.h && !trigonometric) || (start.h >= end.h && trigonometric)) {\n diff = end.h - start.h;\n }\n else if (trigonometric) {\n diff = 360 - end.h + start.h;\n }\n else {\n diff = 360 - start.h + end.h;\n }\n step.h = Math.pow(-1, trigonometric ? 1 : 0) * Math.abs(diff) / steps;\n\n for (let i = 1; i < steps; i++) {\n const color = interpolate(step, start, i, HSVA_MAX);\n gradient.push(tinycolor(color));\n }\n\n return gradient;\n}\n\n/**\n * Compute substeps between each stops\n * @param {StopInput[]} stops\n * @param {number} steps\n * @return {number[]}\n */\nfunction computeSubsteps(stops, steps) {\n const l = stops.length;\n\n // validation\n steps = parseInt(steps, 10);\n\n if (isNaN(steps) || steps < 2) {\n throw new Error('Invalid number of steps (< 2)');\n }\n if (steps < l) {\n throw new Error('Number of steps cannot be inferior to number of stops');\n }\n\n // compute substeps from stop positions\n let substeps = [];\n\n for (let i = 1; i < l; i++) {\n const step = (steps - 1) * (stops[i].pos - stops[i - 1].pos);\n substeps.push(Math.max(1, Math.round(step)));\n }\n\n // adjust number of steps\n let totalSubsteps = 1;\n for (let n = l - 1; n--;) totalSubsteps += substeps[n];\n\n while (totalSubsteps !== steps) {\n if (totalSubsteps < steps) {\n const min = Math.min.apply(null, substeps);\n substeps[substeps.indexOf(min)]++;\n totalSubsteps++;\n }\n else {\n const max = Math.max.apply(null, substeps);\n substeps[substeps.indexOf(max)]--;\n totalSubsteps--;\n }\n }\n\n return substeps;\n}\n\n/**\n * Compute the color at a specific position\n * @param {StopInput[]} stops\n * @param {number} pos\n * @param {string} method\n * @param {StepValue} max\n * @returns {tinycolor}\n */\nfunction computeAt(stops, pos, method, max) {\n if (pos < 0 || pos > 1) {\n throw new Error('Position must be between 0 and 1');\n }\n\n let start, end;\n for (let i = 0, l = stops.length; i < l - 1; i++) {\n if (pos >= stops[i].pos && pos < stops[i + 1].pos) {\n start = stops[i];\n end = stops[i + 1];\n break;\n }\n }\n\n if (!start) {\n start = end = stops[stops.length - 1];\n }\n\n const step = stepize(start.color[method](), end.color[method](), (end.pos - start.pos) * 100);\n const color = interpolate(step, start.color[method](), (pos - start.pos) * 100, max);\n return tinycolor(color);\n}\n\nclass TinyGradient {\n /**\n * @param {StopInput[]|ColorInput[]} stops\n * @returns {TinyGradient}\n */\n constructor(stops) {\n // validation\n if (stops.length < 2) {\n throw new Error('Invalid number of stops (< 2)');\n }\n\n const havingPositions = stops[0].pos !== undefined;\n let l = stops.length;\n let p = -1;\n let lastColorLess = false;\n // create tinycolor objects and clean positions\n this.stops = stops.map((stop, i) => {\n const hasPosition = stop.pos !== undefined;\n if (havingPositions ^ hasPosition) {\n throw new Error('Cannot mix positionned and not posionned color stops');\n }\n\n if (hasPosition) {\n const hasColor = stop.color !== undefined;\n if (!hasColor && (lastColorLess || i === 0 || i === l - 1)) {\n throw new Error('Cannot define two consecutive position-only stops');\n }\n lastColorLess = !hasColor;\n\n stop = {\n color : hasColor ? tinycolor(stop.color) : null,\n colorLess: !hasColor,\n pos : stop.pos\n };\n\n if (stop.pos < 0 || stop.pos > 1) {\n throw new Error('Color stops positions must be between 0 and 1');\n }\n else if (stop.pos < p) {\n throw new Error('Color stops positions are not ordered');\n }\n p = stop.pos;\n }\n else {\n stop = {\n color: tinycolor(stop.color !== undefined ? stop.color : stop),\n pos : i / (l - 1)\n };\n }\n\n return stop;\n });\n\n if (this.stops[0].pos !== 0) {\n this.stops.unshift({\n color: this.stops[0].color,\n pos : 0\n });\n l++;\n }\n if (this.stops[l - 1].pos !== 1) {\n this.stops.push({\n color: this.stops[l - 1].color,\n pos : 1\n });\n }\n }\n\n /**\n * Return new instance with reversed stops\n * @return {TinyGradient}\n */\n reverse() {\n let stops = [];\n\n this.stops.forEach(function (stop) {\n stops.push({\n color: stop.color,\n pos : 1 - stop.pos\n });\n });\n\n return new TinyGradient(stops.reverse());\n }\n\n /**\n * Return new instance with looped stops\n * @return {TinyGradient}\n */\n loop() {\n let stops1 = [];\n let stops2 = [];\n\n this.stops.forEach((stop) => {\n stops1.push({\n color: stop.color,\n pos : stop.pos / 2\n });\n });\n\n this.stops.slice(0, -1).forEach((stop) => {\n stops2.push({\n color: stop.color,\n pos : 1 - stop.pos / 2\n });\n });\n\n return new TinyGradient(stops1.concat(stops2.reverse()));\n }\n\n /**\n * Generate gradient with RGBa interpolation\n * @param {number} steps\n * @return {tinycolor[]}\n */\n rgb(steps) {\n const substeps = computeSubsteps(this.stops, steps);\n let gradient = [];\n\n this.stops.forEach((stop, i) => {\n if (stop.colorLess) {\n stop.color = interpolateRgb(this.stops[i - 1], this.stops[i + 1], 2)[1];\n }\n });\n\n for (let i = 0, l = this.stops.length; i < l - 1; i++) {\n const rgb = interpolateRgb(this.stops[i], this.stops[i + 1], substeps[i]);\n gradient.splice(gradient.length, 0, ...rgb);\n }\n\n gradient.push(this.stops[this.stops.length - 1].color);\n\n return gradient;\n }\n\n /**\n * Generate gradient with HSVa interpolation\n * @param {number} steps\n * @param {boolean|'long'|'short'} [mode=false]\n * - false to step in clockwise\n * - true to step in trigonometric order\n * - 'short' to use the shortest way\n * - 'long' to use the longest way\n * @return {tinycolor[]}\n */\n hsv(steps, mode) {\n const substeps = computeSubsteps(this.stops, steps);\n let gradient = [];\n\n this.stops.forEach((stop, i) => {\n if (stop.colorLess) {\n stop.color = interpolateHsv(this.stops[i - 1], this.stops[i + 1], 2, mode)[1];\n }\n });\n\n for (let i = 0, l = this.stops.length; i < l - 1; i++) {\n const hsv = interpolateHsv(this.stops[i], this.stops[i + 1], substeps[i], mode);\n gradient.splice(gradient.length, 0, ...hsv);\n }\n\n gradient.push(this.stops[this.stops.length - 1].color);\n\n return gradient;\n }\n\n /**\n * Generate CSS3 command (no prefix) for this gradient\n * @param {String} [mode=linear] - 'linear' or 'radial'\n * @param {String} [direction] - default is 'to right' or 'ellipse at center'\n * @return {String}\n */\n css(mode, direction) {\n mode = mode || 'linear';\n direction = direction || (mode === 'linear' ? 'to right' : 'ellipse at center');\n\n let css = mode + '-gradient(' + direction;\n this.stops.forEach(function (stop) {\n css += ', ' + (stop.colorLess ? '' : stop.color.toRgbString() + ' ') + (stop.pos * 100) + '%';\n });\n css += ')';\n return css;\n }\n\n /**\n * Returns the color at specific position with RGBa interpolation\n * @param {number} pos, between 0 and 1\n * @return {tinycolor}\n */\n rgbAt(pos) {\n return computeAt(this.stops, pos, 'toRgb', RGBA_MAX);\n }\n\n /**\n * Returns the color at specific position with HSVa interpolation\n * @param {number} pos, between 0 and 1\n * @return {tinycolor}\n */\n hsvAt(pos) {\n return computeAt(this.stops, pos, 'toHsv', HSVA_MAX);\n }\n}\n\n/**\n * @param {StopInput[]|ColorInput[]|StopInput...|ColorInput...} stops\n * @returns {TinyGradient}\n */\nmodule.exports = function (stops) {\n // varargs\n if (arguments.length === 1) {\n if (!Array.isArray(arguments[0])) {\n throw new Error('\"stops\" is not an array');\n }\n stops = arguments[0];\n }\n else {\n stops = Array.prototype.slice.call(arguments);\n }\n\n return new TinyGradient(stops);\n};\n"],"names":["RGBA_MAX","r","g","b","a","HSVA_MAX","h","s","v","stepize","start","end","steps","step","k","hasOwnProperty","interpolate","i","max","color","interpolateRgb","stop1","stop2","toRgb","gradient","push","tinycolor","interpolateHsv","mode","toHsv","trigonometric","trigShortest","diff","Math","pow","abs","computeSubsteps","stops","l","length","parseInt","isNaN","Error","substeps","pos","round","totalSubsteps","n","min","apply","indexOf","computeAt","method","TinyGradient","havingPositions","undefined","p","lastColorLess","map","stop","hasPosition","hasColor","colorLess","unshift","reverse","forEach","loop","stops1","stops2","slice","concat","rgb","splice","hsv","css","direction","toRgbString","rgbAt","hsvAt","arguments","Array","isArray","prototype","call"],"mappings":";;;;;;;;;;;;;;;IAEA;IACA;IACA;IACA;IACA;;IAEA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IAEA;IACA;IACA;;IACA,IAAMA,QAAQ,GAAG;IAAEC,EAAAA,CAAC,EAAE,GAAL;IAAUC,EAAAA,CAAC,EAAE,GAAb;IAAkBC,EAAAA,CAAC,EAAE,GAArB;IAA0BC,EAAAA,CAAC,EAAE;IAA7B,CAAjB;IAEA;IACA;IACA;;IACA,IAAMC,QAAQ,GAAG;IAAEC,EAAAA,CAAC,EAAE,GAAL;IAAUC,EAAAA,CAAC,EAAE,CAAb;IAAgBC,EAAAA,CAAC,EAAE,CAAnB;IAAsBJ,EAAAA,CAAC,EAAE;IAAzB,CA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CAA2BJ,SAA3B,CAAR;IACH;;IAED,SAAO,IAAI1B,YAAJ,CAAiBhB,KAAjB,CAAP;IACH;;;;;;;;"} node_modules/tinygradient/index.js 0000664 00000027417 15114743311 0013404 0 ustar 00 const tinycolor = require('tinycolor2'); /** * @typedef {Object} TinyGradient.StopInput * @property {ColorInput} color * @property {number} pos */ /** * @typedef {Object} TinyGradient.StepValue * @type {number} [r] * @type {number} [g] * @type {number} [b] * @type {number} [h] * @type {number} [s] * @type {number} [v] * @type {number} [a] */ /** * @type {StepValue} */ const RGBA_MAX = { r: 256, g: 256, b: 256, a: 1 }; /** * @type {StepValue} */ const HSVA_MAX = { h: 360, s: 1, v: 1, a: 1 }; /** * Linearly compute the step size between start and end (not normalized) * @param {StepValue} start * @param {StepValue} end * @param {number} steps - number of desired steps * @return {StepValue} */ function stepize(start, end, steps) { let step = {}; for (let k in start) { if (start.hasOwnProperty(k)) { step[k] = steps === 0 ? 0 : (end[k] - start[k]) / steps; } } return step; } /** * Compute the final step color * @param {StepValue} step - from `stepize` * @param {StepValue} start * @param {number} i - color index * @param {StepValue} max - rgba or hsva of maximum values for each channel * @return {StepValue} */ function interpolate(step, start, i, max) { let color = {}; for (let k in start) { if (start.hasOwnProperty(k)) { color[k] = step[k] * i + start[k]; color[k] = color[k] < 0 ? color[k] + max[k] : (max[k] !== 1 ? color[k] % max[k] : color[k]); } } return color; } /** * Generate gradient with RGBa interpolation * @param {StopInput} stop1 * @param {StopInput} stop2 * @param {number} steps * @return {tinycolor[]} color1 included, color2 excluded */ function interpolateRgb(stop1, stop2, steps) { const start = stop1.color.toRgb(); const end = stop2.color.toRgb(); const step = stepize(start, end, steps); let gradient = [stop1.color]; for (let i = 1; i < steps; i++) { const color = interpolate(step, start, i, RGBA_MAX); gradient.push(tinycolor(color)); } return gradient; } /** * Generate gradient with HSVa interpolation * @param {StopInput} stop1 * @param {StopInput} stop2 * @param {number} steps * @param {boolean|'long'|'short'} mode * @return {tinycolor[]} color1 included, color2 excluded */ function interpolateHsv(stop1, stop2, steps, mode) { const start = stop1.color.toHsv(); const end = stop2.color.toHsv(); // rgb interpolation if one of the steps in grayscale if (start.s === 0 || end.s === 0) { return interpolateRgb(stop1, stop2, steps); } let trigonometric; if (typeof mode === 'boolean') { trigonometric = mode; } else { const trigShortest = (start.h < end.h && end.h - start.h < 180) || (start.h > end.h && start.h - end.h > 180); trigonometric = (mode === 'long' && trigShortest) || (mode === 'short' && !trigShortest); } const step = stepize(start, end, steps); let gradient = [stop1.color]; // recompute hue let diff; if ((start.h <= end.h && !trigonometric) || (start.h >= end.h && trigonometric)) { diff = end.h - start.h; } else if (trigonometric) { diff = 360 - end.h + start.h; } else { diff = 360 - start.h + end.h; } step.h = Math.pow(-1, trigonometric ? 1 : 0) * Math.abs(diff) / steps; for (let i = 1; i < steps; i++) { const color = interpolate(step, start, i, HSVA_MAX); gradient.push(tinycolor(color)); } return gradient; } /** * Compute substeps between each stops * @param {StopInput[]} stops * @param {number} steps * @return {number[]} */ function computeSubsteps(stops, steps) { const l = stops.length; // validation steps = parseInt(steps, 10); if (isNaN(steps) || steps < 2) { throw new Error('Invalid number of steps (< 2)'); } if (steps < l) { throw new Error('Number of steps cannot be inferior to number of stops'); } // compute substeps from stop positions let substeps = []; for (let i = 1; i < l; i++) { const step = (steps - 1) * (stops[i].pos - stops[i - 1].pos); substeps.push(Math.max(1, Math.round(step))); } // adjust number of steps let totalSubsteps = 1; for (let n = l - 1; n--;) totalSubsteps += substeps[n]; while (totalSubsteps !== steps) { if (totalSubsteps < steps) { const min = Math.min.apply(null, substeps); substeps[substeps.indexOf(min)]++; totalSubsteps++; } else { const max = Math.max.apply(null, substeps); substeps[substeps.indexOf(max)]--; totalSubsteps--; } } return substeps; } /** * Compute the color at a specific position * @param {StopInput[]} stops * @param {number} pos * @param {string} method * @param {StepValue} max * @returns {tinycolor} */ function computeAt(stops, pos, method, max) { if (pos < 0 || pos > 1) { throw new Error('Position must be between 0 and 1'); } let start, end; for (let i = 0, l = stops.length; i < l - 1; i++) { if (pos >= stops[i].pos && pos < stops[i + 1].pos) { start = stops[i]; end = stops[i + 1]; break; } } if (!start) { start = end = stops[stops.length - 1]; } const step = stepize(start.color[method](), end.color[method](), (end.pos - start.pos) * 100); const color = interpolate(step, start.color[method](), (pos - start.pos) * 100, max); return tinycolor(color); } class TinyGradient { /** * @param {StopInput[]|ColorInput[]} stops * @returns {TinyGradient} */ constructor(stops) { // validation if (stops.length < 2) { throw new Error('Invalid number of stops (< 2)'); } const havingPositions = stops[0].pos !== undefined; let l = stops.length; let p = -1; let lastColorLess = false; // create tinycolor objects and clean positions this.stops = stops.map((stop, i) => { const hasPosition = stop.pos !== undefined; if (havingPositions ^ hasPosition) { throw new Error('Cannot mix positionned and not posionned color stops'); } if (hasPosition) { const hasColor = stop.color !== undefined; if (!hasColor && (lastColorLess || i === 0 || i === l - 1)) { throw new Error('Cannot define two consecutive position-only stops'); } lastColorLess = !hasColor; stop = { color : hasColor ? tinycolor(stop.color) : null, colorLess: !hasColor, pos : stop.pos }; if (stop.pos < 0 || stop.pos > 1) { throw new Error('Color stops positions must be between 0 and 1'); } else if (stop.pos < p) { throw new Error('Color stops positions are not ordered'); } p = stop.pos; } else { stop = { color: tinycolor(stop.color !== undefined ? stop.color : stop), pos : i / (l - 1) }; } return stop; }); if (this.stops[0].pos !== 0) { this.stops.unshift({ color: this.stops[0].color, pos : 0 }); l++; } if (this.stops[l - 1].pos !== 1) { this.stops.push({ color: this.stops[l - 1].color, pos : 1 }); } } /** * Return new instance with reversed stops * @return {TinyGradient} */ reverse() { let stops = []; this.stops.forEach(function (stop) { stops.push({ color: stop.color, pos : 1 - stop.pos }); }); return new TinyGradient(stops.reverse()); } /** * Return new instance with looped stops * @return {TinyGradient} */ loop() { let stops1 = []; let stops2 = []; this.stops.forEach((stop) => { stops1.push({ color: stop.color, pos : stop.pos / 2 }); }); this.stops.slice(0, -1).forEach((stop) => { stops2.push({ color: stop.color, pos : 1 - stop.pos / 2 }); }); return new TinyGradient(stops1.concat(stops2.reverse())); } /** * Generate gradient with RGBa interpolation * @param {number} steps * @return {tinycolor[]} */ rgb(steps) { const substeps = computeSubsteps(this.stops, steps); let gradient = []; this.stops.forEach((stop, i) => { if (stop.colorLess) { stop.color = interpolateRgb(this.stops[i - 1], this.stops[i + 1], 2)[1]; } }); for (let i = 0, l = this.stops.length; i < l - 1; i++) { const rgb = interpolateRgb(this.stops[i], this.stops[i + 1], substeps[i]); gradient.splice(gradient.length, 0, ...rgb); } gradient.push(this.stops[this.stops.length - 1].color); return gradient; } /** * Generate gradient with HSVa interpolation * @param {number} steps * @param {boolean|'long'|'short'} [mode=false] * - false to step in clockwise * - true to step in trigonometric order * - 'short' to use the shortest way * - 'long' to use the longest way * @return {tinycolor[]} */ hsv(steps, mode) { const substeps = computeSubsteps(this.stops, steps); let gradient = []; this.stops.forEach((stop, i) => { if (stop.colorLess) { stop.color = interpolateHsv(this.stops[i - 1], this.stops[i + 1], 2, mode)[1]; } }); for (let i = 0, l = this.stops.length; i < l - 1; i++) { const hsv = interpolateHsv(this.stops[i], this.stops[i + 1], substeps[i], mode); gradient.splice(gradient.length, 0, ...hsv); } gradient.push(this.stops[this.stops.length - 1].color); return gradient; } /** * Generate CSS3 command (no prefix) for this gradient * @param {String} [mode=linear] - 'linear' or 'radial' * @param {String} [direction] - default is 'to right' or 'ellipse at center' * @return {String} */ css(mode, direction) { mode = mode || 'linear'; direction = direction || (mode === 'linear' ? 'to right' : 'ellipse at center'); let css = mode + '-gradient(' + direction; this.stops.forEach(function (stop) { css += ', ' + (stop.colorLess ? '' : stop.color.toRgbString() + ' ') + (stop.pos * 100) + '%'; }); css += ')'; return css; } /** * Returns the color at specific position with RGBa interpolation * @param {number} pos, between 0 and 1 * @return {tinycolor} */ rgbAt(pos) { return computeAt(this.stops, pos, 'toRgb', RGBA_MAX); } /** * Returns the color at specific position with HSVa interpolation * @param {number} pos, between 0 and 1 * @return {tinycolor} */ hsvAt(pos) { return computeAt(this.stops, pos, 'toHsv', HSVA_MAX); } } /** * @param {StopInput[]|ColorInput[]|StopInput...|ColorInput...} stops * @returns {TinyGradient} */ module.exports = function (stops) { // varargs if (arguments.length === 1) { if (!Array.isArray(arguments[0])) { throw new Error('"stops" is not an array'); } stops = arguments[0]; } else { stops = Array.prototype.slice.call(arguments); } return new TinyGradient(stops); }; node_modules/tinygradient/browser.js 0000664 00000032540 15114743311 0013751 0 ustar 00 /*! * tinygradient (v1.1.5) * @copyright 2014-2021 Damien "Mistic" Sorel <contact@git.strangeplanet.fr> * @licence MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('tinycolor2')) : typeof define === 'function' && define.amd ? define(['tinycolor2'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.tinygradient = factory(global.tinycolor)); }(this, (function (tinycolor2) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var tinycolor2__default = /*#__PURE__*/_interopDefaultLegacy(tinycolor2); /** * @typedef {Object} TinyGradient.StopInput * @property {ColorInput} color * @property {number} pos */ /** * @typedef {Object} TinyGradient.StepValue * @type {number} [r] * @type {number} [g] * @type {number} [b] * @type {number} [h] * @type {number} [s] * @type {number} [v] * @type {number} [a] */ /** * @type {StepValue} */ var RGBA_MAX = { r: 256, g: 256, b: 256, a: 1 }; /** * @type {StepValue} */ var HSVA_MAX = { h: 360, s: 1, v: 1, a: 1 }; /** * Linearly compute the step size between start and end (not normalized) * @param {StepValue} start * @param {StepValue} end * @param {number} steps - number of desired steps * @return {StepValue} */ function stepize(start, end, steps) { var step = {}; for (var k in start) { if (start.hasOwnProperty(k)) { step[k] = steps === 0 ? 0 : (end[k] - start[k]) / steps; } } return step; } /** * Compute the final step color * @param {StepValue} step - from `stepize` * @param {StepValue} start * @param {number} i - color index * @param {StepValue} max - rgba or hsva of maximum values for each channel * @return {StepValue} */ function interpolate(step, start, i, max) { var color = {}; for (var k in start) { if (start.hasOwnProperty(k)) { color[k] = step[k] * i + start[k]; color[k] = color[k] < 0 ? color[k] + max[k] : max[k] !== 1 ? color[k] % max[k] : color[k]; } } return color; } /** * Generate gradient with RGBa interpolation * @param {StopInput} stop1 * @param {StopInput} stop2 * @param {number} steps * @return {tinycolor[]} color1 included, color2 excluded */ function interpolateRgb(stop1, stop2, steps) { var start = stop1.color.toRgb(); var end = stop2.color.toRgb(); var step = stepize(start, end, steps); var gradient = [stop1.color]; for (var i = 1; i < steps; i++) { var color = interpolate(step, start, i, RGBA_MAX); gradient.push(tinycolor2__default['default'](color)); } return gradient; } /** * Generate gradient with HSVa interpolation * @param {StopInput} stop1 * @param {StopInput} stop2 * @param {number} steps * @param {boolean|'long'|'short'} mode * @return {tinycolor[]} color1 included, color2 excluded */ function interpolateHsv(stop1, stop2, steps, mode) { var start = stop1.color.toHsv(); var end = stop2.color.toHsv(); // rgb interpolation if one of the steps in grayscale if (start.s === 0 || end.s === 0) { return interpolateRgb(stop1, stop2, steps); } var trigonometric; if (typeof mode === 'boolean') { trigonometric = mode; } else { var trigShortest = start.h < end.h && end.h - start.h < 180 || start.h > end.h && start.h - end.h > 180; trigonometric = mode === 'long' && trigShortest || mode === 'short' && !trigShortest; } var step = stepize(start, end, steps); var gradient = [stop1.color]; // recompute hue var diff; if (start.h <= end.h && !trigonometric || start.h >= end.h && trigonometric) { diff = end.h - start.h; } else if (trigonometric) { diff = 360 - end.h + start.h; } else { diff = 360 - start.h + end.h; } step.h = Math.pow(-1, trigonometric ? 1 : 0) * Math.abs(diff) / steps; for (var i = 1; i < steps; i++) { var color = interpolate(step, start, i, HSVA_MAX); gradient.push(tinycolor2__default['default'](color)); } return gradient; } /** * Compute substeps between each stops * @param {StopInput[]} stops * @param {number} steps * @return {number[]} */ function computeSubsteps(stops, steps) { var l = stops.length; // validation steps = parseInt(steps, 10); if (isNaN(steps) || steps < 2) { throw new Error('Invalid number of steps (< 2)'); } if (steps < l) { throw new Error('Number of steps cannot be inferior to number of stops'); } // compute substeps from stop positions var substeps = []; for (var i = 1; i < l; i++) { var step = (steps - 1) * (stops[i].pos - stops[i - 1].pos); substeps.push(Math.max(1, Math.round(step))); } // adjust number of steps var totalSubsteps = 1; for (var n = l - 1; n--;) { totalSubsteps += substeps[n]; } while (totalSubsteps !== steps) { if (totalSubsteps < steps) { var min = Math.min.apply(null, substeps); substeps[substeps.indexOf(min)]++; totalSubsteps++; } else { var max = Math.max.apply(null, substeps); substeps[substeps.indexOf(max)]--; totalSubsteps--; } } return substeps; } /** * Compute the color at a specific position * @param {StopInput[]} stops * @param {number} pos * @param {string} method * @param {StepValue} max * @returns {tinycolor} */ function computeAt(stops, pos, method, max) { if (pos < 0 || pos > 1) { throw new Error('Position must be between 0 and 1'); } var start, end; for (var i = 0, l = stops.length; i < l - 1; i++) { if (pos >= stops[i].pos && pos < stops[i + 1].pos) { start = stops[i]; end = stops[i + 1]; break; } } if (!start) { start = end = stops[stops.length - 1]; } var step = stepize(start.color[method](), end.color[method](), (end.pos - start.pos) * 100); var color = interpolate(step, start.color[method](), (pos - start.pos) * 100, max); return tinycolor2__default['default'](color); } var TinyGradient = /*#__PURE__*/function () { /** * @param {StopInput[]|ColorInput[]} stops * @returns {TinyGradient} */ function TinyGradient(stops) { // validation if (stops.length < 2) { throw new Error('Invalid number of stops (< 2)'); } var havingPositions = stops[0].pos !== undefined; var l = stops.length; var p = -1; var lastColorLess = false; // create tinycolor objects and clean positions this.stops = stops.map(function (stop, i) { var hasPosition = stop.pos !== undefined; if (havingPositions ^ hasPosition) { throw new Error('Cannot mix positionned and not posionned color stops'); } if (hasPosition) { var hasColor = stop.color !== undefined; if (!hasColor && (lastColorLess || i === 0 || i === l - 1)) { throw new Error('Cannot define two consecutive position-only stops'); } lastColorLess = !hasColor; stop = { color: hasColor ? tinycolor2__default['default'](stop.color) : null, colorLess: !hasColor, pos: stop.pos }; if (stop.pos < 0 || stop.pos > 1) { throw new Error('Color stops positions must be between 0 and 1'); } else if (stop.pos < p) { throw new Error('Color stops positions are not ordered'); } p = stop.pos; } else { stop = { color: tinycolor2__default['default'](stop.color !== undefined ? stop.color : stop), pos: i / (l - 1) }; } return stop; }); if (this.stops[0].pos !== 0) { this.stops.unshift({ color: this.stops[0].color, pos: 0 }); l++; } if (this.stops[l - 1].pos !== 1) { this.stops.push({ color: this.stops[l - 1].color, pos: 1 }); } } /** * Return new instance with reversed stops * @return {TinyGradient} */ var _proto = TinyGradient.prototype; _proto.reverse = function reverse() { var stops = []; this.stops.forEach(function (stop) { stops.push({ color: stop.color, pos: 1 - stop.pos }); }); return new TinyGradient(stops.reverse()); } /** * Return new instance with looped stops * @return {TinyGradient} */ ; _proto.loop = function loop() { var stops1 = []; var stops2 = []; this.stops.forEach(function (stop) { stops1.push({ color: stop.color, pos: stop.pos / 2 }); }); this.stops.slice(0, -1).forEach(function (stop) { stops2.push({ color: stop.color, pos: 1 - stop.pos / 2 }); }); return new TinyGradient(stops1.concat(stops2.reverse())); } /** * Generate gradient with RGBa interpolation * @param {number} steps * @return {tinycolor[]} */ ; _proto.rgb = function rgb(steps) { var _this = this; var substeps = computeSubsteps(this.stops, steps); var gradient = []; this.stops.forEach(function (stop, i) { if (stop.colorLess) { stop.color = interpolateRgb(_this.stops[i - 1], _this.stops[i + 1], 2)[1]; } }); for (var i = 0, l = this.stops.length; i < l - 1; i++) { var rgb = interpolateRgb(this.stops[i], this.stops[i + 1], substeps[i]); gradient.splice.apply(gradient, [gradient.length, 0].concat(rgb)); } gradient.push(this.stops[this.stops.length - 1].color); return gradient; } /** * Generate gradient with HSVa interpolation * @param {number} steps * @param {boolean|'long'|'short'} [mode=false] * - false to step in clockwise * - true to step in trigonometric order * - 'short' to use the shortest way * - 'long' to use the longest way * @return {tinycolor[]} */ ; _proto.hsv = function hsv(steps, mode) { var _this2 = this; var substeps = computeSubsteps(this.stops, steps); var gradient = []; this.stops.forEach(function (stop, i) { if (stop.colorLess) { stop.color = interpolateHsv(_this2.stops[i - 1], _this2.stops[i + 1], 2, mode)[1]; } }); for (var i = 0, l = this.stops.length; i < l - 1; i++) { var hsv = interpolateHsv(this.stops[i], this.stops[i + 1], substeps[i], mode); gradient.splice.apply(gradient, [gradient.length, 0].concat(hsv)); } gradient.push(this.stops[this.stops.length - 1].color); return gradient; } /** * Generate CSS3 command (no prefix) for this gradient * @param {String} [mode=linear] - 'linear' or 'radial' * @param {String} [direction] - default is 'to right' or 'ellipse at center' * @return {String} */ ; _proto.css = function css(mode, direction) { mode = mode || 'linear'; direction = direction || (mode === 'linear' ? 'to right' : 'ellipse at center'); var css = mode + '-gradient(' + direction; this.stops.forEach(function (stop) { css += ', ' + (stop.colorLess ? '' : stop.color.toRgbString() + ' ') + stop.pos * 100 + '%'; }); css += ')'; return css; } /** * Returns the color at specific position with RGBa interpolation * @param {number} pos, between 0 and 1 * @return {tinycolor} */ ; _proto.rgbAt = function rgbAt(pos) { return computeAt(this.stops, pos, 'toRgb', RGBA_MAX); } /** * Returns the color at specific position with HSVa interpolation * @param {number} pos, between 0 and 1 * @return {tinycolor} */ ; _proto.hsvAt = function hsvAt(pos) { return computeAt(this.stops, pos, 'toHsv', HSVA_MAX); }; return TinyGradient; }(); /** * @param {StopInput[]|ColorInput[]|StopInput...|ColorInput...} stops * @returns {TinyGradient} */ var tinygradient = function tinygradient(stops) { // varargs if (arguments.length === 1) { if (!Array.isArray(arguments[0])) { throw new Error('"stops" is not an array'); } stops = arguments[0]; } else { stops = Array.prototype.slice.call(arguments); } return new TinyGradient(stops); }; return tinygradient; }))); //# sourceMappingURL=browser.js.map node_modules/tinygradient/types.d.ts 0000664 00000005544 15114743311 0013672 0 ustar 00 /*! * TinyGradient 1.1.2 * Copyright 2014-2020 Damien "Mistic" Sorel (http://www.strangeplanet.fr) * Licensed under MIT (http://opensource.org/licenses/MIT) */ import * as tinycolor from 'tinycolor2'; declare namespace tinygradient { type ArcMode = boolean | 'short' | 'long'; type CssMode = 'linear' | 'radial'; type StopInput = { color?: tinycolor.ColorInput pos?: number } interface Instance { stops: StopInput[] /** * Return new instance with reversed stops * @return {Instance} */ reverse(): Instance; /** * Return new instance with looped stops * @return {Instance} */ loop(): Instance; /** * Generate gradient with RGBa interpolation * @param {int} steps * @return {tinycolor.Instance[]} */ rgb(steps: number): tinycolor.Instance[]; /** * Generate gradient with HSVa interpolation * @param {int} steps * @param {ArcMode} [mode=false] * - false to step in clockwise * - true to step in trigonometric order * - 'short' to use the shortest way * - 'long' to use the longest way * @return {tinycolor.Instance[]} */ hsv(steps: number, mode: ArcMode): tinycolor.Instance[]; /** * Generate CSS3 command (no prefix) for this gradient * @param {CssMode} [mode=linear] - 'linear' or 'radial' * @param {String} [direction] - default is 'to right' or 'ellipse at center' * @return {String} */ css(mode?: CssMode, direction?: string): string; /** * Returns the color at specific position with RGBa interpolation * @param {float} pos, between 0 and 1 * @return {tinycolor.Instance} */ rgbAt(pos: number): tinycolor.Instance; /** * Returns the color at specific position with HSVa interpolation * @param {float} pos, between 0 and 1 * @return {tinycolor.Instance} */ hsvAt(pos: number): tinycolor.Instance; } interface Constructor { /** * @class tinygradient * @param {StopInput} stops */ new (stops: StopInput[]): Instance; new (...stops: StopInput[]): Instance; (stops: StopInput[]): Instance; (...stops: StopInput[]): Instance; /** * @class tinygradient * @param {tinycolor.ColorInput[]} stops */ new (stops: tinycolor.ColorInput[]): Instance; new (...stops: tinycolor.ColorInput[]): Instance; (stops: tinycolor.ColorInput[]): Instance; (...stops: tinycolor.ColorInput[]): Instance; } } declare const tinygradient: tinygradient.Constructor; export = tinygradient; export as namespace tinygradient; node_modules/tinygradient/README.md 0000664 00000010423 15114743311 0013203 0 ustar 00 # tinygradient [](https://www.npmjs.com/package/tinygradient) [](https://www.jsdelivr.com/package/npm/tinygradient) [](https://bundlephobia.com/result?p=tinygradient) [](https://github.com/mistic100/tinygradient/actions) Easily generate color gradients with an unlimited number of color stops and steps. [Live demo](https://mistic100.github.io/tinygradient/) ## Installation ``` $ npm install tinygradient ``` ### Dependencies - [TinyColor](https://github.com/bgrins/TinyColor) ## Usage The gradient can be generated using RGB or HSV interpolation. HSV usually produces brighter colors. ### Initialize gradient The `tinygradient` constructor takes a list or an array of colors stops. ```javascript // using varargs var gradient = tinygradient('red', 'green', 'blue'); // using array var gradient = tinygradient([ '#ff0000', '#00ff00', '#0000ff' ]); ``` The colors are parsed with TinyColor, [multiple formats are accepted](https://github.com/bgrins/TinyColor/blob/master/README.md#accepted-string-input). ```javascript var gradient = tinygradient([ tinycolor('#ff0000'), // tinycolor object {r: 0, g: 255, b: 0}, // RGB object {h: 240, s: 1, v: 1, a: 1}, // HSVa object 'rgb(120, 120, 0)', // RGB CSS string 'gold' // named color ]); ``` You can also specify the position of each color stop (between `0` and `1`). If no position is specified, stops are distributed equidistantly. ```javascript var gradient = tinygradient([ {color: '#d8e0de', pos: 0}, {color: '#255B53', pos: 0.8}, {color: '#000000', pos: 1} ]); ``` ### Generate gradient Each method takes at least the number of desired steps. > The generated gradients might have one more step in certain conditions. ```javascript // RGB interpolation var colorsRgb = gradient.rgb(9); ```  ```javascript // HSV clockwise interpolation var colorsHsv = gradient.hsv(9); ```  ```javascript // HSV counter-clockwise interpolation var colorsHsv = gradient.hsv(9, true); ```  There are also two methods which will automatically choose between clockwise and counter-clockwise. ```javascript // HSV interpolation using shortest arc between colors var colorsHsv = gradient.hsv(9, 'short'); // HSV interpolation using longest arc between colors var colorsHsv = gradient.hsv(9, 'long'); ``` Each method returns an array of TinyColor objects, [see available methods](https://github.com/bgrins/TinyColor/blob/master/README.md#methods). ### Get CSS gradient string The `css` method will output a valid W3C string (without vendors prefix) to use with `background-image` CSS property. ```javascript // linear gradient to right (default) var gradientStr = gradient.css(); // radial gradient ellipse at top left var gradientStr = gradient.css('radial', 'farthest-corner ellipse at top left'); ``` ### Get color at a specific position Returns a single TinyColor object from a defined position in the gradient (from 0 to 1). ```javascript // with RGB interpolation colorAt55Percent = gradient.rgbAt(0.55); // with HSV interpolation colorAt55Percent = gradient.hsvAt(0.55); ``` ### Reversing gradient Returns a new instance of TinyGradient with reversed colors. ```javascript var reversedGradient = gradient.reverse(); ``` ### Loop the gradient Returns a new instance of TinyGradient with looped colors. ```javascript var loopedGradient = gradient.loop(); ``` ### Position-only stops I is possible to define stops with the `pos` property only and no `color`. This allows to define the position of the mid-point between the previous and the next stop. ```js var gradient = tinygradient([ {color: 'black', pos: 0}, {pos: 0.8}, // #808080 will be at 80% instead of 50% {color: 'white', pos: 1} ]); ``` ## License This library is available under the MIT license. node_modules/yocto-queue/license 0000664 00000002135 15114743311 0013050 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/yocto-queue/package.json 0000664 00000001521 15114743311 0013767 0 ustar 00 { "name": "yocto-queue", "version": "1.2.1", "description": "Tiny queue data structure", "license": "MIT", "repository": "sindresorhus/yocto-queue", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "types": "./index.d.ts", "sideEffects": false, "engines": { "node": ">=12.20" }, "scripts": { "//test": "xo && ava && tsd", "test": "ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "queue", "data", "structure", "algorithm", "queues", "queuing", "list", "array", "linkedlist", "fifo", "enqueue", "dequeue", "data-structure" ], "devDependencies": { "ava": "^3.15.0", "tsd": "^0.17.0", "xo": "^0.44.0" } } node_modules/yocto-queue/readme.md 0000664 00000005015 15114743311 0013262 0 ustar 00 # yocto-queue [](https://bundlephobia.com/result?p=yocto-queue) > Tiny queue data structure You should use this package instead of an array if you do a lot of `Array#push()` and `Array#shift()` on large arrays, since `Array#shift()` has [linear time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(N)%E2%80%94Linear%20Time) *O(n)* while `Queue#dequeue()` has [constant time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(1)%20%E2%80%94%20Constant%20Time) *O(1)*. That makes a huge difference for large arrays. > A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is an ordered list of elements where an element is inserted at the end of the queue and is removed from the front of the queue. A queue works based on the first-in, first-out ([FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics))) principle. ## Install ```sh npm install yocto-queue ``` ## Usage ```js import Queue from 'yocto-queue'; const queue = new Queue(); queue.enqueue('🦄'); queue.enqueue('🌈'); console.log(queue.size); //=> 2 console.log(...queue); //=> '🦄 🌈' console.log(queue.dequeue()); //=> '🦄' console.log(queue.dequeue()); //=> '🌈' ``` ## API ### `queue = new Queue()` The instance is an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), which means you can iterate over the queue front to back with a “for…of” loop. Using the iterator will not remove the items from the queue. If you want that, use [`drain()`](#drain) instead. You can also use spreading to convert the queue to an array. Don't do this unless you really need to though, since it's slow. #### `.enqueue(value)` Add a value to the queue. #### `.dequeue()` Remove the next value in the queue. Returns the removed value or `undefined` if the queue is empty. #### `.peek()` Get the next value in the queue without removing it. Returns the value or `undefined` if the queue is empty. #### `.drain()` Returns an iterator that dequeues items as you consume it. This allows you to empty the queue while processing its items. If you want to not remove items as you consume it, use the `Queue` object as an iterator. #### `.clear()` Clear the queue. #### `.size` The size of the queue. ## Related - [quick-lru](https://github.com/sindresorhus/quick-lru) - Simple “Least Recently Used” (LRU) cache node_modules/yocto-queue/index.d.ts 0000664 00000003707 15114743311 0013412 0 ustar 00 export default class Queue<ValueType> implements Iterable<ValueType> { /** The size of the queue. */ readonly size: number; /** Tiny queue data structure. The instance is an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), which means you can iterate over the queue front to back with a “for…of” loop, or use spreading to convert the queue to an array. Don't do this unless you really need to though, since it's slow. @example ``` import Queue from 'yocto-queue'; const queue = new Queue(); queue.enqueue('🦄'); queue.enqueue('🌈'); console.log(queue.size); //=> 2 console.log(...queue); //=> '🦄 🌈' console.log(queue.dequeue()); //=> '🦄' console.log(queue.dequeue()); //=> '🌈' ``` */ constructor(); /** The instance is an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), which means you can iterate over the queue front to back with a “for…of” loop. Using the iterator will not remove the items from the queue. If you want that, use `drain()` instead. You can also use spreading to convert the queue to an array. Don't do this unless you really need to though, since it's slow. */ [Symbol.iterator](): IterableIterator<ValueType>; /** Returns an iterator that dequeues items as you consume it. This allows you to empty the queue while processing its items. If you want to not remove items as you consume it, use the `Queue` object as an iterator. */ drain(): IterableIterator<ValueType>; /** Add a value to the queue. */ enqueue(value: ValueType): void; /** Remove the next value in the queue. @returns The removed value or `undefined` if the queue is empty. */ dequeue(): ValueType | undefined; /** Get the next value in the queue without removing it. @returns The value or `undefined` if the queue is empty. */ peek(): ValueType | undefined; /** Clear the queue. */ clear(): void; } node_modules/yocto-queue/index.js 0000664 00000002707 15114743311 0013155 0 ustar 00 /* How it works: `this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value. */ class Node { value; next; constructor(value) { this.value = value; } } export default class Queue { #head; #tail; #size; constructor() { this.clear(); } enqueue(value) { const node = new Node(value); if (this.#head) { this.#tail.next = node; this.#tail = node; } else { this.#head = node; this.#tail = node; } this.#size++; } dequeue() { const current = this.#head; if (!current) { return; } this.#head = this.#head.next; this.#size--; return current.value; } peek() { if (!this.#head) { return; } return this.#head.value; // TODO: Node.js 18. // return this.#head?.value; } clear() { this.#head = undefined; this.#tail = undefined; this.#size = 0; } get size() { return this.#size; } * [Symbol.iterator]() { let current = this.#head; while (current) { yield current.value; current = current.next; } } * drain() { while (this.#head) { yield this.dequeue(); } } } node_modules/micromatch/package.json 0000664 00000005130 15114743311 0013636 0 ustar 00 { "name": "micromatch", "description": "Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch.", "version": "4.0.8", "homepage": "https://github.com/micromatch/micromatch", "author": "Jon Schlinkert (https://github.com/jonschlinkert)", "contributors": [ "(https://github.com/DianeLooney)", "Amila Welihinda (amilajack.com)", "Bogdan Chadkin (https://github.com/TrySound)", "Brian Woodward (https://twitter.com/doowb)", "Devon Govett (http://badassjs.com)", "Elan Shanker (https://github.com/es128)", "Fabrício Matté (https://ultcombo.js.org)", "Jon Schlinkert (http://twitter.com/jonschlinkert)", "Martin Kolárik (https://kolarik.sk)", "Olsten Larck (https://i.am.charlike.online)", "Paul Miller (paulmillr.com)", "Tom Byrer (https://github.com/tomByrer)", "Tyler Akins (http://rumkin.com)", "Peter Bright <drpizza@quiscalusmexicanus.org> (https://github.com/drpizza)", "Kuba Juszczyk (https://github.com/ku8ar)" ], "repository": "micromatch/micromatch", "bugs": { "url": "https://github.com/micromatch/micromatch/issues" }, "license": "MIT", "files": [ "index.js" ], "main": "index.js", "engines": { "node": ">=8.6" }, "scripts": { "test": "mocha" }, "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" }, "devDependencies": { "fill-range": "^7.0.1", "gulp-format-md": "^2.0.0", "minimatch": "^5.0.1", "mocha": "^9.2.2", "time-require": "github:jonschlinkert/time-require" }, "keywords": [ "bash", "bracket", "character-class", "expand", "expansion", "expression", "extglob", "extglobs", "file", "files", "filter", "find", "glob", "globbing", "globs", "globstar", "lookahead", "lookaround", "lookbehind", "match", "matcher", "matches", "matching", "micromatch", "minimatch", "multimatch", "negate", "negation", "path", "pattern", "patterns", "posix", "regex", "regexp", "regular", "shell", "star", "wildcard" ], "verb": { "toc": "collapsible", "layout": "default", "tasks": [ "readme" ], "plugins": [ "gulp-format-md" ], "lint": { "reflinks": true }, "related": { "list": [ "braces", "expand-brackets", "extglob", "fill-range", "nanomatch" ] }, "reflinks": [ "extglob", "fill-range", "glob-object", "minimatch", "multimatch" ] } } node_modules/micromatch/LICENSE 0000775 00000002103 15114743311 0012355 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-present, Jon Schlinkert. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/micromatch/index.js 0000664 00000033112 15114743311 0013016 0 ustar 00 'use strict'; const util = require('util'); const braces = require('braces'); const picomatch = require('picomatch'); const utils = require('picomatch/lib/utils'); const isEmptyString = v => v === '' || v === './'; const hasBraces = v => { const index = v.indexOf('{'); return index > -1 && v.indexOf('}', index) > -1; }; /** * Returns an array of strings that match one or more glob patterns. * * ```js * const mm = require('micromatch'); * // mm(list, patterns[, options]); * * console.log(mm(['a.js', 'a.txt'], ['*.js'])); * //=> [ 'a.js' ] * ``` * @param {String|Array<string>} `list` List of strings to match. * @param {String|Array<string>} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) * @return {Array} Returns an array of matches * @summary false * @api public */ const micromatch = (list, patterns, options) => { patterns = [].concat(patterns); list = [].concat(list); let omit = new Set(); let keep = new Set(); let items = new Set(); let negatives = 0; let onResult = state => { items.add(state.output); if (options && options.onResult) { options.onResult(state); } }; for (let i = 0; i < patterns.length; i++) { let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); let negated = isMatch.state.negated || isMatch.state.negatedExtglob; if (negated) negatives++; for (let item of list) { let matched = isMatch(item, true); let match = negated ? !matched.isMatch : matched.isMatch; if (!match) continue; if (negated) { omit.add(matched.output); } else { omit.delete(matched.output); keep.add(matched.output); } } } let result = negatives === patterns.length ? [...items] : [...keep]; let matches = result.filter(item => !omit.has(item)); if (options && matches.length === 0) { if (options.failglob === true) { throw new Error(`No matches found for "${patterns.join(', ')}"`); } if (options.nonull === true || options.nullglob === true) { return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; } } return matches; }; /** * Backwards compatibility */ micromatch.match = micromatch; /** * Returns a matcher function from the given glob `pattern` and `options`. * The returned function takes a string to match as its only argument and returns * true if the string is a match. * * ```js * const mm = require('micromatch'); * // mm.matcher(pattern[, options]); * * const isMatch = mm.matcher('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @param {String} `pattern` Glob pattern * @param {Object} `options` * @return {Function} Returns a matcher function. * @api public */ micromatch.matcher = (pattern, options) => picomatch(pattern, options); /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const mm = require('micromatch'); * // mm.isMatch(string, patterns[, options]); * * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(mm.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String} `str` The string to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `[options]` See available [options](#options). * @return {Boolean} Returns true if any patterns match `str` * @api public */ micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); /** * Backwards compatibility */ micromatch.any = micromatch.isMatch; /** * Returns a list of strings that _**do not match any**_ of the given `patterns`. * * ```js * const mm = require('micromatch'); * // mm.not(list, patterns[, options]); * * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); * //=> ['b.b', 'c.c'] * ``` * @param {Array} `list` Array of strings to match. * @param {String|Array} `patterns` One or more glob pattern to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Array} Returns an array of strings that **do not match** the given patterns. * @api public */ micromatch.not = (list, patterns, options = {}) => { patterns = [].concat(patterns).map(String); let result = new Set(); let items = []; let onResult = state => { if (options.onResult) options.onResult(state); items.push(state.output); }; let matches = new Set(micromatch(list, patterns, { ...options, onResult })); for (let item of items) { if (!matches.has(item)) { result.add(item); } } return [...result]; }; /** * Returns true if the given `string` contains the given pattern. Similar * to [.isMatch](#isMatch) but the pattern can match any part of the string. * * ```js * var mm = require('micromatch'); * // mm.contains(string, pattern[, options]); * * console.log(mm.contains('aa/bb/cc', '*b')); * //=> true * console.log(mm.contains('aa/bb/cc', '*d')); * //=> false * ``` * @param {String} `str` The string to match. * @param {String|Array} `patterns` Glob pattern to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any of the patterns matches any part of `str`. * @api public */ micromatch.contains = (str, pattern, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util.inspect(str)}"`); } if (Array.isArray(pattern)) { return pattern.some(p => micromatch.contains(str, p, options)); } if (typeof pattern === 'string') { if (isEmptyString(str) || isEmptyString(pattern)) { return false; } if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { return true; } } return micromatch.isMatch(str, pattern, { ...options, contains: true }); }; /** * Filter the keys of the given object with the given `glob` pattern * and `options`. Does not attempt to match nested keys. If you need this feature, * use [glob-object][] instead. * * ```js * const mm = require('micromatch'); * // mm.matchKeys(object, patterns[, options]); * * const obj = { aa: 'a', ab: 'b', ac: 'c' }; * console.log(mm.matchKeys(obj, '*b')); * //=> { ab: 'b' } * ``` * @param {Object} `object` The object with keys to filter. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Object} Returns an object with only keys that match the given patterns. * @api public */ micromatch.matchKeys = (obj, patterns, options) => { if (!utils.isObject(obj)) { throw new TypeError('Expected the first argument to be an object'); } let keys = micromatch(Object.keys(obj), patterns, options); let res = {}; for (let key of keys) res[key] = obj[key]; return res; }; /** * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.some(list, patterns[, options]); * * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // true * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` * @api public */ micromatch.some = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch(String(pattern), options); if (items.some(item => isMatch(item))) { return true; } } return false; }; /** * Returns true if every string in the given `list` matches * any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.every(list, patterns[, options]); * * console.log(mm.every('foo.js', ['foo.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // false * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` * @api public */ micromatch.every = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch(String(pattern), options); if (!items.every(item => isMatch(item))) { return false; } } return true; }; /** * Returns true if **all** of the given `patterns` match * the specified string. * * ```js * const mm = require('micromatch'); * // mm.all(string, patterns[, options]); * * console.log(mm.all('foo.js', ['foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); * // false * * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); * // true * ``` * @param {String|Array} `str` The string to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any patterns match `str` * @api public */ micromatch.all = (str, patterns, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util.inspect(str)}"`); } return [].concat(patterns).every(p => picomatch(p, options)(str)); }; /** * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. * * ```js * const mm = require('micromatch'); * // mm.capture(pattern, string[, options]); * * console.log(mm.capture('test/*.js', 'test/foo.js')); * //=> ['foo'] * console.log(mm.capture('test/*.js', 'foo/bar.css')); * //=> null * ``` * @param {String} `glob` Glob pattern to use for matching. * @param {String} `input` String to match * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. * @api public */ micromatch.capture = (glob, input, options) => { let posix = utils.isWindows(options); let regex = picomatch.makeRe(String(glob), { ...options, capture: true }); let match = regex.exec(posix ? utils.toPosixSlashes(input) : input); if (match) { return match.slice(1).map(v => v === void 0 ? '' : v); } }; /** * Create a regular expression from the given glob `pattern`. * * ```js * const mm = require('micromatch'); * // mm.makeRe(pattern[, options]); * * console.log(mm.makeRe('*.js')); * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ * ``` * @param {String} `pattern` A glob pattern to convert to regex. * @param {Object} `options` * @return {RegExp} Returns a regex created from the given pattern. * @api public */ micromatch.makeRe = (...args) => picomatch.makeRe(...args); /** * Scan a glob pattern to separate the pattern into segments. Used * by the [split](#split) method. * * ```js * const mm = require('micromatch'); * const state = mm.scan(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with * @api public */ micromatch.scan = (...args) => picomatch.scan(...args); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const mm = require('micromatch'); * const state = mm.parse(pattern[, options]); * ``` * @param {String} `glob` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as regex source string. * @api public */ micromatch.parse = (patterns, options) => { let res = []; for (let pattern of [].concat(patterns || [])) { for (let str of braces(String(pattern), options)) { res.push(picomatch.parse(str, options)); } } return res; }; /** * Process the given brace `pattern`. * * ```js * const { braces } = require('micromatch'); * console.log(braces('foo/{a,b,c}/bar')); * //=> [ 'foo/(a|b|c)/bar' ] * * console.log(braces('foo/{a,b,c}/bar', { expand: true })); * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] * ``` * @param {String} `pattern` String with brace pattern to process. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. * @return {Array} * @api public */ micromatch.braces = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); if ((options && options.nobrace === true) || !hasBraces(pattern)) { return [pattern]; } return braces(pattern, options); }; /** * Expand braces */ micromatch.braceExpand = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); return micromatch.braces(pattern, { ...options, expand: true }); }; /** * Expose micromatch */ // exposed for tests micromatch.hasBraces = hasBraces; module.exports = micromatch; node_modules/micromatch/README.md 0000664 00000114062 15114743311 0012634 0 ustar 00 # micromatch [](https://www.npmjs.com/package/micromatch) [](https://npmjs.org/package/micromatch) [](https://npmjs.org/package/micromatch) [](https://github.com/micromatch/micromatch/actions/workflows/test.yml) > Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Table of Contents <details> <summary><strong>Details</strong></summary> * [Install](#install) - [Sponsors](#sponsors) * [Gold Sponsors](#gold-sponsors) * [Quickstart](#quickstart) * [Why use micromatch?](#why-use-micromatch) + [Matching features](#matching-features) * [Switching to micromatch](#switching-to-micromatch) + [From minimatch](#from-minimatch) + [From multimatch](#from-multimatch) * [API](#api) * [Options](#options) * [Options Examples](#options-examples) + [options.basename](#optionsbasename) + [options.bash](#optionsbash) + [options.expandRange](#optionsexpandrange) + [options.format](#optionsformat) + [options.ignore](#optionsignore) + [options.matchBase](#optionsmatchbase) + [options.noextglob](#optionsnoextglob) + [options.nonegate](#optionsnonegate) + [options.noglobstar](#optionsnoglobstar) + [options.nonull](#optionsnonull) + [options.nullglob](#optionsnullglob) + [options.onIgnore](#optionsonignore) + [options.onMatch](#optionsonmatch) + [options.onResult](#optionsonresult) + [options.posixSlashes](#optionsposixslashes) + [options.unescape](#optionsunescape) * [Extended globbing](#extended-globbing) + [Extglobs](#extglobs) + [Braces](#braces) + [Regex character classes](#regex-character-classes) + [Regex groups](#regex-groups) + [POSIX bracket expressions](#posix-bracket-expressions) * [Notes](#notes) + [Bash 4.3 parity](#bash-43-parity) + [Backslashes](#backslashes) * [Benchmarks](#benchmarks) + [Running benchmarks](#running-benchmarks) + [Latest results](#latest-results) * [Contributing](#contributing) * [About](#about) </details> ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save micromatch ``` <br /> # Sponsors [Become a Sponsor](https://github.com/sponsors/jonschlinkert) to add your logo to this README, or any of [my other projects](https://github.com/jonschlinkert?tab=repositories&q=&type=&language=&sort=stargazers) <br /> ## Quickstart ```js const micromatch = require('micromatch'); // micromatch(list, patterns[, options]); ``` The [main export](#micromatch) takes a list of strings and one or more glob patterns: ```js console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz'] console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux'] ``` Use [.isMatch()](#ismatch) to for boolean matching: ```js console.log(micromatch.isMatch('foo', 'f*')) //=> true console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true ``` [Switching](#switching-to-micromatch) from minimatch and multimatch is easy! <br> ## Why use micromatch? > micromatch is a [replacement](#switching-to-micromatch) for minimatch and multimatch * Supports all of the same matching features as [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) * More complete support for the Bash 4.3 specification than minimatch and multimatch. Micromatch passes _all of the spec tests_ from bash, including some that bash still fails. * **Fast & Performant** - Loads in about 5ms and performs [fast matches](#benchmarks). * **Glob matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories * **[Advanced globbing](#extended-globbing)** - Supports [extglobs](#extglobs), [braces](#braces-1), and [POSIX brackets](#posix-bracket-expressions), and support for escaping special characters with `\` or quotes. * **Accurate** - Covers more scenarios [than minimatch](https://github.com/yarnpkg/yarn/pull/3339) * **Well tested** - More than 5,000 [test assertions](./test) * **Windows support** - More reliable windows support than minimatch and multimatch. * **[Safe](https://github.com/micromatch/braces#braces-is-safe)** - Micromatch is not subject to DoS with brace patterns like minimatch and multimatch. ### Matching features * Support for multiple glob patterns (no need for wrappers like multimatch) * Wildcards (`**`, `*.js`) * Negation (`'!a/*.js'`, `'*!(b).js'`) * [extglobs](#extglobs) (`+(x|y)`, `!(a|b)`) * [POSIX character classes](#posix-bracket-expressions) (`[[:alpha:][:digit:]]`) * [brace expansion](https://github.com/micromatch/braces) (`foo/{1..5}.md`, `bar/{a,b,c}.js`) * regex character classes (`foo-[1-5].js`) * regex logical "or" (`foo/(abc|xyz).js`) You can mix and match these features to create whatever patterns you need! ## Switching to micromatch _(There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See [the notes about backslashes](#backslashes) for more information.)_ ### From minimatch Use [micromatch.isMatch()](#ismatch) instead of `minimatch()`: ```js console.log(micromatch.isMatch('foo', 'b*')); //=> false ``` Use [micromatch.match()](#match) instead of `minimatch.match()`: ```js console.log(micromatch.match(['foo', 'bar'], 'b*')); //=> 'bar' ``` ### From multimatch Same signature: ```js console.log(micromatch(['foo', 'bar', 'baz'], ['f*', '*z'])); //=> ['foo', 'baz'] ``` ## API **Params** * `list` **{String|Array<string>}**: List of strings to match. * `patterns` **{String|Array<string>}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) * `returns` **{Array}**: Returns an array of matches **Example** ```js const mm = require('micromatch'); // mm(list, patterns[, options]); console.log(mm(['a.js', 'a.txt'], ['*.js'])); //=> [ 'a.js' ] ``` ### [.matcher](index.js#L109) Returns a matcher function from the given glob `pattern` and `options`. The returned function takes a string to match as its only argument and returns true if the string is a match. **Params** * `pattern` **{String}**: Glob pattern * `options` **{Object}** * `returns` **{Function}**: Returns a matcher function. **Example** ```js const mm = require('micromatch'); // mm.matcher(pattern[, options]); const isMatch = mm.matcher('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` ### [.isMatch](index.js#L128) Returns true if **any** of the given glob `patterns` match the specified `string`. **Params** * `str` **{String}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `[options]` **{Object}**: See available [options](#options). * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const mm = require('micromatch'); // mm.isMatch(string, patterns[, options]); console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true console.log(mm.isMatch('a.a', 'b.*')); //=> false ``` ### [.not](index.js#L153) Returns a list of strings that _**do not match any**_ of the given `patterns`. **Params** * `list` **{Array}**: Array of strings to match. * `patterns` **{String|Array}**: One or more glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array}**: Returns an array of strings that **do not match** the given patterns. **Example** ```js const mm = require('micromatch'); // mm.not(list, patterns[, options]); console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); //=> ['b.b', 'c.c'] ``` ### [.contains](index.js#L193) Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string. **Params** * `str` **{String}**: The string to match. * `patterns` **{String|Array}**: Glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any of the patterns matches any part of `str`. **Example** ```js var mm = require('micromatch'); // mm.contains(string, pattern[, options]); console.log(mm.contains('aa/bb/cc', '*b')); //=> true console.log(mm.contains('aa/bb/cc', '*d')); //=> false ``` ### [.matchKeys](index.js#L235) Filter the keys of the given object with the given `glob` pattern and `options`. Does not attempt to match nested keys. If you need this feature, use [glob-object](https://github.com/jonschlinkert/glob-object) instead. **Params** * `object` **{Object}**: The object with keys to filter. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Object}**: Returns an object with only keys that match the given patterns. **Example** ```js const mm = require('micromatch'); // mm.matchKeys(object, patterns[, options]); const obj = { aa: 'a', ab: 'b', ac: 'c' }; console.log(mm.matchKeys(obj, '*b')); //=> { ab: 'b' } ``` ### [.some](index.js#L264) Returns true if some of the strings in the given `list` match any of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. Returns as soon as the first match is found. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any `patterns` matches any of the strings in `list` **Example** ```js const mm = require('micromatch'); // mm.some(list, patterns[, options]); console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // true console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.every](index.js#L300) Returns true if every string in the given `list` matches any of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if all `patterns` matches all of the strings in `list` **Example** ```js const mm = require('micromatch'); // mm.every(list, patterns[, options]); console.log(mm.every('foo.js', ['foo.js'])); // true console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); // true console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // false console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.all](index.js#L339) Returns true if **all** of the given `patterns` match the specified string. **Params** * `str` **{String|Array}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const mm = require('micromatch'); // mm.all(string, patterns[, options]); console.log(mm.all('foo.js', ['foo.js'])); // true console.log(mm.all('foo.js', ['*.js', '!foo.js'])); // false console.log(mm.all('foo.js', ['*.js', 'foo.js'])); // true console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); // true ``` ### [.capture](index.js#L366) Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match. **Params** * `glob` **{String}**: Glob pattern to use for matching. * `input` **{String}**: String to match * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array|null}**: Returns an array of captures if the input matches the glob pattern, otherwise `null`. **Example** ```js const mm = require('micromatch'); // mm.capture(pattern, string[, options]); console.log(mm.capture('test/*.js', 'test/foo.js')); //=> ['foo'] console.log(mm.capture('test/*.js', 'foo/bar.css')); //=> null ``` ### [.makeRe](index.js#L392) Create a regular expression from the given glob `pattern`. **Params** * `pattern` **{String}**: A glob pattern to convert to regex. * `options` **{Object}** * `returns` **{RegExp}**: Returns a regex created from the given pattern. **Example** ```js const mm = require('micromatch'); // mm.makeRe(pattern[, options]); console.log(mm.makeRe('*.js')); //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ ``` ### [.scan](index.js#L408) Scan a glob pattern to separate the pattern into segments. Used by the [split](#split) method. **Params** * `pattern` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with **Example** ```js const mm = require('micromatch'); const state = mm.scan(pattern[, options]); ``` ### [.parse](index.js#L424) Parse a glob pattern to create the source string for a regular expression. **Params** * `glob` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with useful properties and output to be used as regex source string. **Example** ```js const mm = require('micromatch'); const state = mm.parse(pattern[, options]); ``` ### [.braces](index.js#L451) Process the given brace `pattern`. **Params** * `pattern` **{String}**: String with brace pattern to process. * `options` **{Object}**: Any [options](#options) to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options. * `returns` **{Array}** **Example** ```js const { braces } = require('micromatch'); console.log(braces('foo/{a,b,c}/bar')); //=> [ 'foo/(a|b|c)/bar' ] console.log(braces('foo/{a,b,c}/bar', { expand: true })); //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] ``` ## Options | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | | `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | | `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | | `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | | `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | | `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | | `dot` | `boolean` | `false` | Match dotfiles. Otherwise dotfiles are ignored unless a `.` is explicitly defined in the pattern. | | `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. This option is overridden by the `expandBrace` option. | | `failglob` | `boolean` | `false` | Similar to the `failglob` behavior in Bash, throws an error when no matches are found. Based on the bash option of the same name. | | `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | | `flags` | `boolean` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | | [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | | `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | | `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | | `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | | `lookbehinds` | `boolean` | `true` | Support regex positive and negative lookbehinds. Note that you must be using Node 8.1.10 or higher to enable regex lookbehinds. | | `matchBase` | `boolean` | `false` | Alias for `basename` | | `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | | `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | | `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | | `nocase` | `boolean` | `false` | Perform case-insensitive matching. Equivalent to the regex `i` flag. Note that this option is ignored when the `flags` option is defined. | | `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | | `noext` | `boolean` | `false` | Alias for `noextglob` | | `noextglob` | `boolean` | `false` | Disable support for matching with [extglobs](#extglobs) (like `+(a\|b)`) | | `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | | `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | | `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | | [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | | [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | | [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | | `posix` | `boolean` | `false` | Support [POSIX character classes](#posix-bracket-expressions) ("posix brackets"). | | `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | | `prepend` | `string` | `undefined` | String to prepend to the generated regex used for matching. | | `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | | `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | | `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | | `unescape` | `boolean` | `undefined` | Remove preceding backslashes from escaped glob characters before creating the regular expression to perform matches. | | `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatitibility. | ## Options Examples ### options.basename Allow glob patterns without slashes to match a file path based on its basename. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `matchBase`. **Type**: `Boolean` **Default**: `false` **Example** ```js micromatch(['a/b.js', 'a/c.md'], '*.js'); //=> [] micromatch(['a/b.js', 'a/c.md'], '*.js', { basename: true }); //=> ['a/b.js'] ``` ### options.bash Enabled by default, this option enforces bash-like behavior with stars immediately following a bracket expression. Bash bracket expressions are similar to regex character classes, but unlike regex, a star following a bracket expression **does not repeat the bracketed characters**. Instead, the star is treated the same as any other star. **Type**: `Boolean` **Default**: `true` **Example** ```js const files = ['abc', 'ajz']; console.log(micromatch(files, '[a-c]*')); //=> ['abc', 'ajz'] console.log(micromatch(files, '[a-c]*', { bash: false })); ``` ### options.expandRange **Type**: `function` **Default**: `undefined` Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. **Example** The following example shows how to create a glob that matches a numeric folder name between `01` and `25`, with leading zeros. ```js const fill = require('fill-range'); const regex = micromatch.makeRe('foo/{01..25}/bar', { expandRange(a, b) { return `(${fill(a, b, { toRegex: true })})`; } }); console.log(regex) //=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ console.log(regex.test('foo/00/bar')) // false console.log(regex.test('foo/01/bar')) // true console.log(regex.test('foo/10/bar')) // true console.log(regex.test('foo/22/bar')) // true console.log(regex.test('foo/25/bar')) // true console.log(regex.test('foo/26/bar')) // false ``` ### options.format **Type**: `function` **Default**: `undefined` Custom function for formatting strings before they're matched. **Example** ```js // strip leading './' from strings const format = str => str.replace(/^\.\//, ''); const isMatch = picomatch('foo/*.js', { format }); console.log(isMatch('./foo/bar.js')) //=> true ``` ### options.ignore String or array of glob patterns to match files to ignore. **Type**: `String|Array` **Default**: `undefined` ```js const isMatch = micromatch.matcher('*', { ignore: 'f*' }); console.log(isMatch('foo')) //=> false console.log(isMatch('bar')) //=> true console.log(isMatch('baz')) //=> true ``` ### options.matchBase Alias for [options.basename](#options-basename). ### options.noextglob Disable extglob support, so that [extglobs](#extglobs) are regarded as literal characters. **Type**: `Boolean` **Default**: `undefined` **Examples** ```js console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)')); //=> ['a/b', 'a/!(z)'] console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: true })); //=> ['a/!(z)'] (matches only as literal characters) ``` ### options.nonegate Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match. **Type**: `Boolean` **Default**: `undefined` ### options.noglobstar Disable matching with globstars (`**`). **Type**: `Boolean` **Default**: `undefined` ```js micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**'); //=> ['a/b', 'a/b/c', 'a/b/c/d'] micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true}); //=> ['a/b'] ``` ### options.nonull Alias for [options.nullglob](#options-nullglob). ### options.nullglob If `true`, when no matches are found the actual (arrayified) glob pattern is returned instead of an empty array. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `nonull`. **Type**: `Boolean` **Default**: `undefined` ### options.onIgnore ```js const onIgnore = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); // { glob: '*', regex: /^(?:(?!\.)(?=.)[^\/]*?\/?)$/, input: 'foo', output: 'foo' } }; const isMatch = micromatch.matcher('*', { onIgnore, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` ### options.onMatch ```js const onMatch = ({ glob, regex, input, output }) => { console.log({ input, output }); // { input: 'some\\path', output: 'some/path' } // { input: 'some\\path', output: 'some/path' } // { input: 'some\\path', output: 'some/path' } }; const isMatch = micromatch.matcher('**', { onMatch, posixSlashes: true }); isMatch('some\\path'); isMatch('some\\path'); isMatch('some\\path'); ``` ### options.onResult ```js const onResult = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = micromatch('*', { onResult, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` ### options.posixSlashes Convert path separators on returned files to posix/unix-style forward slashes. Aliased as `unixify` for backwards compatibility. **Type**: `Boolean` **Default**: `true` on windows, `false` everywhere else. **Example** ```js console.log(micromatch.match(['a\\b\\c'], 'a/**')); //=> ['a/b/c'] console.log(micromatch.match(['a\\b\\c'], { posixSlashes: false })); //=> ['a\\b\\c'] ``` ### options.unescape Remove backslashes from escaped glob characters before creating the regular expression to perform matches. **Type**: `Boolean` **Default**: `undefined` **Example** In this example we want to match a literal `*`: ```js console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c')); //=> ['a\\*c'] console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c', { unescape: true })); //=> ['a*c'] ``` <br> <br> ## Extended globbing Micromatch supports the following extended globbing features. ### Extglobs Extended globbing, as described by the bash man page: | **pattern** | **regex equivalent** | **description** | | --- | --- | --- | | `?(pattern)` | `(pattern)?` | Matches zero or one occurrence of the given patterns | | `*(pattern)` | `(pattern)*` | Matches zero or more occurrences of the given patterns | | `+(pattern)` | `(pattern)+` | Matches one or more occurrences of the given patterns | | `@(pattern)` | `(pattern)` <sup>*</sup> | Matches one of the given patterns | | `!(pattern)` | N/A (equivalent regex is much more complicated) | Matches anything except one of the given patterns | <sup><strong>*</strong></sup> Note that `@` isn't a regex character. ### Braces Brace patterns can be used to match specific ranges or sets of characters. **Example** The pattern `{f,b}*/{1..3}/{b,q}*` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar baz/1/qux baz/2/qux baz/3/qux ``` Visit [braces](https://github.com/micromatch/braces) to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues. ### Regex character classes Given the list: `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: * `[ac].js`: matches both `a` and `c`, returning `['a.js', 'c.js']` * `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']` * `a/[A-Z].js`: matches and uppercase letter, returning `['a/E.md']` Learn about [regex character classes](http://www.regular-expressions.info/charclass.html). ### Regex groups Given `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: * `(a|c).js`: would match either `a` or `c`, returning `['a.js', 'c.js']` * `(b|d).js`: would match either `b` or `d`, returning `['b.js', 'd.js']` * `(b|[A-Z]).js`: would match either `b` or an uppercase letter, returning `['b.js', 'E.js']` As with regex, parens can be nested, so patterns like `((a|b)|c)/b` will work. Although brace expansion might be friendlier to use, depending on preference. ### POSIX bracket expressions POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder. **Example** ```js console.log(micromatch.isMatch('a1', '[[:alpha:][:digit:]]')) //=> true console.log(micromatch.isMatch('a1', '[[:alpha:][:alpha:]]')) //=> false ``` *** ## Notes ### Bash 4.3 parity Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch. However, it's suprising how many edge cases and rabbit holes there are with glob matching, and since there is no real glob specification, and micromatch is more accurate than both Bash and minimatch, there are cases where best-guesses were made for behavior. In a few cases where Bash had no answers, we used wildmatch (used by git) as a fallback. ### Backslashes There is an important, notable difference between minimatch and micromatch _in regards to how backslashes are handled_ in glob patterns. * Micromatch exclusively and explicitly reserves backslashes for escaping characters in a glob pattern, even on windows, which is consistent with bash behavior. _More importantly, unescaping globs can result in unsafe regular expressions_. * Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns. We made this decision for micromatch for a couple of reasons: * Consistency with bash conventions. * Glob patterns are not filepaths. They are a type of [regular language](https://en.wikipedia.org/wiki/Regular_language) that is converted to a JavaScript regular expression. Thus, when forward slashes are defined in a glob pattern, the resulting regular expression will match windows or POSIX path separators just fine. **A note about joining paths to globs** Note that when you pass something like `path.join('foo', '*')` to micromatch, you are creating a filepath and expecting it to still work as a glob pattern. This causes problems on windows, since the `path.sep` is `\\`. In other words, since `\\` is reserved as an escape character in globs, on windows `path.join('foo', '*')` would result in `foo\\*`, which tells micromatch to match `*` as a literal character. This is the same behavior as bash. To solve this, you might be inspired to do something like `'foo\\*'.replace(/\\/g, '/')`, but this causes another, potentially much more serious, problem. ## Benchmarks ### Running benchmarks Install dependencies for running benchmarks: ```sh $ cd bench && npm install ``` Run the benchmarks: ```sh $ npm run bench ``` ### Latest results As of August 23, 2024 (longer bars are better): ```sh # .makeRe star micromatch x 2,232,802 ops/sec ±2.34% (89 runs sampled)) minimatch x 781,018 ops/sec ±6.74% (92 runs sampled)) # .makeRe star; dot=true micromatch x 1,863,453 ops/sec ±0.74% (93 runs sampled) minimatch x 723,105 ops/sec ±0.75% (93 runs sampled) # .makeRe globstar micromatch x 1,624,179 ops/sec ±2.22% (91 runs sampled) minimatch x 1,117,230 ops/sec ±2.78% (86 runs sampled)) # .makeRe globstars micromatch x 1,658,642 ops/sec ±0.86% (92 runs sampled) minimatch x 741,224 ops/sec ±1.24% (89 runs sampled)) # .makeRe with leading star micromatch x 1,525,014 ops/sec ±1.63% (90 runs sampled) minimatch x 561,074 ops/sec ±3.07% (89 runs sampled) # .makeRe - braces micromatch x 172,478 ops/sec ±2.37% (78 runs sampled) minimatch x 96,087 ops/sec ±2.34% (88 runs sampled))) # .makeRe braces - range (expanded) micromatch x 26,973 ops/sec ±0.84% (89 runs sampled) minimatch x 3,023 ops/sec ±0.99% (90 runs sampled)) # .makeRe braces - range (compiled) micromatch x 152,892 ops/sec ±1.67% (83 runs sampled) minimatch x 992 ops/sec ±3.50% (89 runs sampled)d)) # .makeRe braces - nested ranges (expanded) micromatch x 15,816 ops/sec ±13.05% (80 runs sampled) minimatch x 2,953 ops/sec ±1.64% (91 runs sampled) # .makeRe braces - nested ranges (compiled) micromatch x 110,881 ops/sec ±1.85% (82 runs sampled) minimatch x 1,008 ops/sec ±1.51% (91 runs sampled) # .makeRe braces - set (compiled) micromatch x 134,930 ops/sec ±3.54% (63 runs sampled)) minimatch x 43,242 ops/sec ±0.60% (93 runs sampled) # .makeRe braces - nested sets (compiled) micromatch x 94,455 ops/sec ±1.74% (69 runs sampled)) minimatch x 27,720 ops/sec ±1.84% (93 runs sampled)) ``` ## Contributing All contributions are welcome! Please read [the contributing guide](.github/contributing.md) to get started. **Bug reports** Please create an issue if you encounter a bug or matching behavior that doesn't seem correct. If you find a matching-related issue, please: * [research existing issues first](../../issues) (open and closed) * visit the [GNU Bash documentation](https://www.gnu.org/software/bash/manual/) to see how Bash deals with the pattern * visit the [minimatch](https://github.com/isaacs/minimatch) documentation to cross-check expected behavior in node.js * if all else fails, since there is no real specification for globs we will probably need to discuss expected behavior and decide how to resolve it. which means any detail you can provide to help with this discussion would be greatly appreciated. **Platform issues** It's important to us that micromatch work consistently on all platforms. If you encounter any platform-specific matching or path related issues, please let us know (pull requests are also greatly appreciated). ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [braces](https://www.npmjs.com/package/braces): Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… [more](https://github.com/micromatch/braces) | [homepage](https://github.com/micromatch/braces "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.") * [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/micromatch/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") * [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 523 | [jonschlinkert](https://github.com/jonschlinkert) | | 12 | [es128](https://github.com/es128) | | 9 | [danez](https://github.com/danez) | | 8 | [doowb](https://github.com/doowb) | | 6 | [paulmillr](https://github.com/paulmillr) | | 5 | [mrmlnc](https://github.com/mrmlnc) | | 3 | [DrPizza](https://github.com/DrPizza) | | 2 | [Tvrqvoise](https://github.com/Tvrqvoise) | | 2 | [antonyk](https://github.com/antonyk) | | 2 | [MartinKolarik](https://github.com/MartinKolarik) | | 2 | [Glazy](https://github.com/Glazy) | | 2 | [mceIdo](https://github.com/mceIdo) | | 2 | [TrySound](https://github.com/TrySound) | | 1 | [yvele](https://github.com/yvele) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | | 1 | [simlu](https://github.com/simlu) | | 1 | [curbengh](https://github.com/curbengh) | | 1 | [fidian](https://github.com/fidian) | | 1 | [tomByrer](https://github.com/tomByrer) | | 1 | [ZoomerTedJackson](https://github.com/ZoomerTedJackson) | | 1 | [styfle](https://github.com/styfle) | | 1 | [sebdeckers](https://github.com/sebdeckers) | | 1 | [muescha](https://github.com/muescha) | | 1 | [juszczykjakub](https://github.com/juszczykjakub) | | 1 | [joyceerhl](https://github.com/joyceerhl) | | 1 | [donatj](https://github.com/donatj) | | 1 | [frangio](https://github.com/frangio) | | 1 | [UltCombo](https://github.com/UltCombo) | | 1 | [DianeLooney](https://github.com/DianeLooney) | | 1 | [devongovett](https://github.com/devongovett) | | 1 | [Cslove](https://github.com/Cslove) | | 1 | [amilajack](https://github.com/amilajack) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2024, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on August 23, 2024._ node_modules/is-number/package.json 0000664 00000003077 15114743311 0013421 0 ustar 00 { "name": "is-number", "description": "Returns true if a number or string value is a finite number. Useful for regex matches, parsing, user input, etc.", "version": "7.0.0", "homepage": "https://github.com/jonschlinkert/is-number", "author": "Jon Schlinkert (https://github.com/jonschlinkert)", "contributors": [ "Jon Schlinkert (http://twitter.com/jonschlinkert)", "Olsten Larck (https://i.am.charlike.online)", "Rouven Weßling (www.rouvenwessling.de)" ], "repository": "jonschlinkert/is-number", "bugs": { "url": "https://github.com/jonschlinkert/is-number/issues" }, "license": "MIT", "files": [ "index.js" ], "main": "index.js", "engines": { "node": ">=0.12.0" }, "scripts": { "test": "mocha" }, "devDependencies": { "ansi": "^0.3.1", "benchmark": "^2.1.4", "gulp-format-md": "^1.0.0", "mocha": "^3.5.3" }, "keywords": [ "cast", "check", "coerce", "coercion", "finite", "integer", "is", "isnan", "is-nan", "is-num", "is-number", "isnumber", "isfinite", "istype", "kind", "math", "nan", "num", "number", "numeric", "parseFloat", "parseInt", "test", "type", "typeof", "value" ], "verb": { "toc": false, "layout": "default", "tasks": [ "readme" ], "related": { "list": [ "is-plain-object", "is-primitive", "isobject", "kind-of" ] }, "plugins": [ "gulp-format-md" ], "lint": { "reflinks": true } } } node_modules/is-number/LICENSE 0000664 00000002103 15114743311 0012125 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-present, Jon Schlinkert. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/is-number/index.js 0000664 00000000633 15114743311 0012573 0 ustar 00 /*! * is-number <https://github.com/jonschlinkert/is-number> * * Copyright (c) 2014-present, Jon Schlinkert. * Released under the MIT License. */ 'use strict'; module.exports = function(num) { if (typeof num === 'number') { return num - num === 0; } if (typeof num === 'string' && num.trim() !== '') { return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); } return false; }; node_modules/is-number/README.md 0000664 00000014562 15114743311 0012413 0 ustar 00 # is-number [](https://www.npmjs.com/package/is-number) [](https://npmjs.org/package/is-number) [](https://npmjs.org/package/is-number) [](https://travis-ci.org/jonschlinkert/is-number) > Returns true if the value is a finite number. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-number ``` ## Why is this needed? In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use `+`, `-`, or `Number()` to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results: ```js console.log(+[]); //=> 0 console.log(+''); //=> 0 console.log(+' '); //=> 0 console.log(typeof NaN); //=> 'number' ``` This library offers a performant way to smooth out edge cases like these. ## Usage ```js const isNumber = require('is-number'); ``` See the [tests](./test.js) for more examples. ### true ```js isNumber(5e3); // true isNumber(0xff); // true isNumber(-1.1); // true isNumber(0); // true isNumber(1); // true isNumber(1.1); // true isNumber(10); // true isNumber(10.10); // true isNumber(100); // true isNumber('-1.1'); // true isNumber('0'); // true isNumber('012'); // true isNumber('0xff'); // true isNumber('1'); // true isNumber('1.1'); // true isNumber('10'); // true isNumber('10.10'); // true isNumber('100'); // true isNumber('5e3'); // true isNumber(parseInt('012')); // true isNumber(parseFloat('012')); // true ``` ### False Everything else is false, as you would expect: ```js isNumber(Infinity); // false isNumber(NaN); // false isNumber(null); // false isNumber(undefined); // false isNumber(''); // false isNumber(' '); // false isNumber('foo'); // false isNumber([1]); // false isNumber([]); // false isNumber(function () {}); // false isNumber({}); // false ``` ## Release history ### 7.0.0 * Refactor. Now uses `.isFinite` if it exists. * Performance is about the same as v6.0 when the value is a string or number. But it's now 3x-4x faster when the value is not a string or number. ### 6.0.0 * Optimizations, thanks to @benaadams. ### 5.0.0 **Breaking changes** * removed support for `instanceof Number` and `instanceof String` ## Benchmarks As with all benchmarks, take these with a grain of salt. See the [benchmarks](./benchmark/index.js) for more detail. ``` # all v7.0 x 413,222 ops/sec ±2.02% (86 runs sampled) v6.0 x 111,061 ops/sec ±1.29% (85 runs sampled) parseFloat x 317,596 ops/sec ±1.36% (86 runs sampled) fastest is 'v7.0' # string v7.0 x 3,054,496 ops/sec ±1.05% (89 runs sampled) v6.0 x 2,957,781 ops/sec ±0.98% (88 runs sampled) parseFloat x 3,071,060 ops/sec ±1.13% (88 runs sampled) fastest is 'parseFloat,v7.0' # number v7.0 x 3,146,895 ops/sec ±0.89% (89 runs sampled) v6.0 x 3,214,038 ops/sec ±1.07% (89 runs sampled) parseFloat x 3,077,588 ops/sec ±1.07% (87 runs sampled) fastest is 'v6.0' ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 49 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [charlike-old](https://github.com/charlike-old) | | 1 | [benaadams](https://github.com/benaadams) | | 1 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 15, 2018._ node_modules/string-width/license 0000664 00000002135 15114743311 0013214 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/string-width/package.json 0000664 00000002164 15114743311 0014137 0 ustar 00 { "name": "string-width", "version": "7.2.0", "description": "Get the visual width of a string - the number of columns required to display it", "license": "MIT", "repository": "sindresorhus/string-width", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "default": "./index.js" }, "sideEffects": false, "engines": { "node": ">=18" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "string", "character", "unicode", "width", "visual", "column", "columns", "fullwidth", "full-width", "full", "ansi", "escape", "codes", "cli", "command-line", "terminal", "console", "cjk", "chinese", "japanese", "korean", "fixed-width", "east-asian-width" ], "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" }, "devDependencies": { "ava": "^5.3.1", "tsd": "^0.29.0", "xo": "^0.56.0" } } node_modules/string-width/readme.md 0000664 00000003624 15114743311 0013432 0 ustar 00 # string-width > Get the visual width of a string - the number of columns required to display it Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. Useful to be able to measure the actual width of command-line output. ## Install ```sh npm install string-width ``` ## Usage ```js import stringWidth from 'string-width'; stringWidth('a'); //=> 1 stringWidth('古'); //=> 2 stringWidth('\u001B[1m古\u001B[22m'); //=> 2 ``` ## API ### stringWidth(string, options?) #### string Type: `string` The string to be counted. #### options Type: `object` ##### ambiguousIsNarrow Type: `boolean`\ Default: `true` Count [ambiguous width characters](https://www.unicode.org/reports/tr11/#Ambiguous) as having narrow width (count of 1) instead of wide width (count of 2). > Ambiguous characters behave like wide or narrow characters depending on the context (language tag, script identification, associated font, source of data, or explicit markup; all can provide the context). **If the context cannot be established reliably, they should be treated as narrow characters by default.** > - http://www.unicode.org/reports/tr11/ ##### countAnsiEscapeCodes Type: `boolean`\ Default: `false` Whether [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) should be counted. ## Related - [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module - [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string - [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string - [get-east-asian-width](https://github.com/sindresorhus/get-east-asian-width) - Determine the East Asian Width of a Unicode character node_modules/string-width/index.d.ts 0000664 00000002501 15114743311 0013545 0 ustar 00 export type Options = { /** Count [ambiguous width characters](https://www.unicode.org/reports/tr11/#Ambiguous) as having narrow width (count of 1) instead of wide width (count of 2). @default true > Ambiguous characters behave like wide or narrow characters depending on the context (language tag, script identification, associated font, source of data, or explicit markup; all can provide the context). __If the context cannot be established reliably, they should be treated as narrow characters by default.__ > - http://www.unicode.org/reports/tr11/ */ readonly ambiguousIsNarrow?: boolean; /** Whether [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) should be counted. @default false */ readonly countAnsiEscapeCodes?: boolean; }; /** Get the visual width of a string - the number of columns required to display it. Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. @example ``` import stringWidth from 'string-width'; stringWidth('a'); //=> 1 stringWidth('古'); //=> 2 stringWidth('\u001B[1m古\u001B[22m'); //=> 2 ``` */ export default function stringWidth(string: string, options?: Options): number; node_modules/string-width/index.js 0000664 00000004267 15114743311 0013324 0 ustar 00 import stripAnsi from 'strip-ansi'; import {eastAsianWidth} from 'get-east-asian-width'; import emojiRegex from 'emoji-regex'; const segmenter = new Intl.Segmenter(); const defaultIgnorableCodePointRegex = /^\p{Default_Ignorable_Code_Point}$/u; export default function stringWidth(string, options = {}) { if (typeof string !== 'string' || string.length === 0) { return 0; } const { ambiguousIsNarrow = true, countAnsiEscapeCodes = false, } = options; if (!countAnsiEscapeCodes) { string = stripAnsi(string); } if (string.length === 0) { return 0; } let width = 0; const eastAsianWidthOptions = {ambiguousAsWide: !ambiguousIsNarrow}; for (const {segment: character} of segmenter.segment(string)) { const codePoint = character.codePointAt(0); // Ignore control characters if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) { continue; } // Ignore zero-width characters if ( (codePoint >= 0x20_0B && codePoint <= 0x20_0F) // Zero-width space, non-joiner, joiner, left-to-right mark, right-to-left mark || codePoint === 0xFE_FF // Zero-width no-break space ) { continue; } // Ignore combining characters if ( (codePoint >= 0x3_00 && codePoint <= 0x3_6F) // Combining diacritical marks || (codePoint >= 0x1A_B0 && codePoint <= 0x1A_FF) // Combining diacritical marks extended || (codePoint >= 0x1D_C0 && codePoint <= 0x1D_FF) // Combining diacritical marks supplement || (codePoint >= 0x20_D0 && codePoint <= 0x20_FF) // Combining diacritical marks for symbols || (codePoint >= 0xFE_20 && codePoint <= 0xFE_2F) // Combining half marks ) { continue; } // Ignore surrogate pairs if (codePoint >= 0xD8_00 && codePoint <= 0xDF_FF) { continue; } // Ignore variation selectors if (codePoint >= 0xFE_00 && codePoint <= 0xFE_0F) { continue; } // This covers some of the above cases, but we still keep them for performance reasons. if (defaultIgnorableCodePointRegex.test(character)) { continue; } // TODO: Use `/\p{RGI_Emoji}/v` when targeting Node.js 20. if (emojiRegex().test(character)) { width += 2; continue; } width += eastAsianWidth(codePoint, eastAsianWidthOptions); } return width; } node_modules/ansi-regex/license 0000664 00000002135 15114743311 0012633 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/ansi-regex/package.json 0000664 00000002013 15114743311 0013547 0 ustar 00 { "name": "ansi-regex", "version": "6.1.0", "description": "Regular expression for matching ANSI escape codes", "license": "MIT", "repository": "chalk/ansi-regex", "funding": "https://github.com/chalk/ansi-regex?sponsor=1", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "types": "./index.d.ts", "sideEffects": false, "engines": { "node": ">=12" }, "scripts": { "test": "xo && ava && tsd", "view-supported": "node fixtures/view-codes.js" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "command-line", "text", "regex", "regexp", "re", "match", "test", "find", "pattern" ], "devDependencies": { "ansi-escapes": "^5.0.0", "ava": "^3.15.0", "tsd": "^0.21.0", "xo": "^0.54.2" } } node_modules/ansi-regex/readme.md 0000664 00000004101 15114743311 0013040 0 ustar 00 # ansi-regex > Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) ## Install ```sh npm install ansi-regex ``` ## Usage ```js import ansiRegex from 'ansi-regex'; ansiRegex().test('\u001B[4mcake\u001B[0m'); //=> true ansiRegex().test('cake'); //=> false '\u001B[4mcake\u001B[0m'.match(ansiRegex()); //=> ['\u001B[4m', '\u001B[0m'] '\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); //=> ['\u001B[4m'] '\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); //=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] ``` ## API ### ansiRegex(options?) Returns a regex for matching ANSI escape codes. #### options Type: `object` ##### onlyFirst Type: `boolean`\ Default: `false` *(Matches any ANSI escape codes in a string)* Match only the first ANSI escape. ## FAQ ### Why do you test for codes not in the ECMA 48 standard? Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) node_modules/ansi-regex/index.d.ts 0000664 00000001261 15114743311 0013166 0 ustar 00 export type Options = { /** Match only the first ANSI escape. @default false */ readonly onlyFirst: boolean; }; /** Regular expression for matching ANSI escape codes. @example ``` import ansiRegex from 'ansi-regex'; ansiRegex().test('\u001B[4mcake\u001B[0m'); //=> true ansiRegex().test('cake'); //=> false '\u001B[4mcake\u001B[0m'.match(ansiRegex()); //=> ['\u001B[4m', '\u001B[0m'] '\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); //=> ['\u001B[4m'] '\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); //=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] ``` */ export default function ansiRegex(options?: Options): RegExp; node_modules/ansi-regex/index.js 0000664 00000000712 15114743311 0012732 0 ustar 00 export default function ansiRegex({onlyFirst = false} = {}) { // Valid string terminator sequences are BEL, ESC\, and 0x9c const ST = '(?:\\u0007|\\u001B\\u005C|\\u009C)'; const pattern = [ `[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?${ST})`, '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))', ].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); } node_modules/fill-range/package.json 0000664 00000003340 15114743311 0013531 0 ustar 00 { "name": "fill-range", "description": "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`", "version": "7.1.1", "homepage": "https://github.com/jonschlinkert/fill-range", "author": "Jon Schlinkert (https://github.com/jonschlinkert)", "contributors": [ "Edo Rivai (edo.rivai.nl)", "Jon Schlinkert (http://twitter.com/jonschlinkert)", "Paul Miller (paulmillr.com)", "Rouven Weßling (www.rouvenwessling.de)", "(https://github.com/wtgtybhertgeghgtwtg)" ], "repository": "jonschlinkert/fill-range", "bugs": { "url": "https://github.com/jonschlinkert/fill-range/issues" }, "license": "MIT", "files": [ "index.js" ], "main": "index.js", "engines": { "node": ">=8" }, "scripts": { "lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .", "mocha": "mocha --reporter dot", "test": "npm run lint && npm run mocha", "test:ci": "npm run test:cover", "test:cover": "nyc npm run mocha" }, "dependencies": { "to-regex-range": "^5.0.1" }, "devDependencies": { "gulp-format-md": "^2.0.0", "mocha": "^6.1.1", "nyc": "^15.1.0" }, "keywords": [ "alpha", "alphabetical", "array", "bash", "brace", "expand", "expansion", "fill", "glob", "match", "matches", "matching", "number", "numerical", "range", "ranges", "regex", "sh" ], "verb": { "toc": false, "layout": "default", "tasks": [ "readme" ], "plugins": [ "gulp-format-md" ], "lint": { "reflinks": true } } } node_modules/fill-range/LICENSE 0000664 00000002103 15114743311 0012244 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-present, Jon Schlinkert. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/fill-range/index.js 0000664 00000014406 15114743311 0012715 0 ustar 00 /*! * fill-range <https://github.com/jonschlinkert/fill-range> * * Copyright (c) 2014-present, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; const util = require('util'); const toRegexRange = require('to-regex-range'); const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); const transform = toNumber => { return value => toNumber === true ? Number(value) : String(value); }; const isValidValue = value => { return typeof value === 'number' || (typeof value === 'string' && value !== ''); }; const isNumber = num => Number.isInteger(+num); const zeros = input => { let value = `${input}`; let index = -1; if (value[0] === '-') value = value.slice(1); if (value === '0') return false; while (value[++index] === '0'); return index > 0; }; const stringify = (start, end, options) => { if (typeof start === 'string' || typeof end === 'string') { return true; } return options.stringify === true; }; const pad = (input, maxLength, toNumber) => { if (maxLength > 0) { let dash = input[0] === '-' ? '-' : ''; if (dash) input = input.slice(1); input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); } if (toNumber === false) { return String(input); } return input; }; const toMaxLen = (input, maxLength) => { let negative = input[0] === '-' ? '-' : ''; if (negative) { input = input.slice(1); maxLength--; } while (input.length < maxLength) input = '0' + input; return negative ? ('-' + input) : input; }; const toSequence = (parts, options, maxLen) => { parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); let prefix = options.capture ? '' : '?:'; let positives = ''; let negatives = ''; let result; if (parts.positives.length) { positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); } if (parts.negatives.length) { negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; } if (positives && negatives) { result = `${positives}|${negatives}`; } else { result = positives || negatives; } if (options.wrap) { return `(${prefix}${result})`; } return result; }; const toRange = (a, b, isNumbers, options) => { if (isNumbers) { return toRegexRange(a, b, { wrap: false, ...options }); } let start = String.fromCharCode(a); if (a === b) return start; let stop = String.fromCharCode(b); return `[${start}-${stop}]`; }; const toRegex = (start, end, options) => { if (Array.isArray(start)) { let wrap = options.wrap === true; let prefix = options.capture ? '' : '?:'; return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); } return toRegexRange(start, end, options); }; const rangeError = (...args) => { return new RangeError('Invalid range arguments: ' + util.inspect(...args)); }; const invalidRange = (start, end, options) => { if (options.strictRanges === true) throw rangeError([start, end]); return []; }; const invalidStep = (step, options) => { if (options.strictRanges === true) { throw new TypeError(`Expected step "${step}" to be a number`); } return []; }; const fillNumbers = (start, end, step = 1, options = {}) => { let a = Number(start); let b = Number(end); if (!Number.isInteger(a) || !Number.isInteger(b)) { if (options.strictRanges === true) throw rangeError([start, end]); return []; } // fix negative zero if (a === 0) a = 0; if (b === 0) b = 0; let descending = a > b; let startString = String(start); let endString = String(end); let stepString = String(step); step = Math.max(Math.abs(step), 1); let padded = zeros(startString) || zeros(endString) || zeros(stepString); let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; let toNumber = padded === false && stringify(start, end, options) === false; let format = options.transform || transform(toNumber); if (options.toRegex && step === 1) { return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); } let parts = { negatives: [], positives: [] }; let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); let range = []; let index = 0; while (descending ? a >= b : a <= b) { if (options.toRegex === true && step > 1) { push(a); } else { range.push(pad(format(a, index), maxLen, toNumber)); } a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return step > 1 ? toSequence(parts, options, maxLen) : toRegex(range, null, { wrap: false, ...options }); } return range; }; const fillLetters = (start, end, step = 1, options = {}) => { if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { return invalidRange(start, end, options); } let format = options.transform || (val => String.fromCharCode(val)); let a = `${start}`.charCodeAt(0); let b = `${end}`.charCodeAt(0); let descending = a > b; let min = Math.min(a, b); let max = Math.max(a, b); if (options.toRegex && step === 1) { return toRange(min, max, false, options); } let range = []; let index = 0; while (descending ? a >= b : a <= b) { range.push(format(a, index)); a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return toRegex(range, null, { wrap: false, options }); } return range; }; const fill = (start, end, step, options = {}) => { if (end == null && isValidValue(start)) { return [start]; } if (!isValidValue(start) || !isValidValue(end)) { return invalidRange(start, end, options); } if (typeof step === 'function') { return fill(start, end, 1, { transform: step }); } if (isObject(step)) { return fill(start, end, 0, step); } let opts = { ...options }; if (opts.capture === true) opts.wrap = true; step = step || opts.step || 1; if (!isNumber(step)) { if (step != null && !isObject(step)) return invalidStep(step, opts); return fill(start, end, 1, step); } if (isNumber(start) && isNumber(end)) { return fillNumbers(start, end, step, opts); } return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); }; module.exports = fill; node_modules/fill-range/README.md 0000664 00000016476 15114743311 0012540 0 ustar 00 # fill-range [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [](https://www.npmjs.com/package/fill-range) [](https://npmjs.org/package/fill-range) [](https://npmjs.org/package/fill-range) [](https://travis-ci.org/jonschlinkert/fill-range) > Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex` Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save fill-range ``` ## Usage Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_. ```js const fill = require('fill-range'); // fill(from, to[, step, options]); console.log(fill('1', '10')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] console.log(fill('1', '10', { toRegex: true })); //=> [1-9]|10 ``` **Params** * `from`: **{String|Number}** the number or letter to start with * `to`: **{String|Number}** the number or letter to end with * `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use. * `options`: **{Object|Function}**: See all available [options](#options) ## Examples By default, an array of values is returned. **Alphabetical ranges** ```js console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e'] console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ] ``` **Numerical ranges** Numbers can be defined as actual numbers or strings. ```js console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ] ``` **Negative ranges** Numbers can be defined as actual numbers or strings. ```js console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ] console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ] ``` **Steps (increments)** ```js // numerical ranges with increments console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ] console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ] console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ] // alphabetical ranges with increments console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ] console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ] ``` ## Options ### options.step **Type**: `number` (formatted as a string or number) **Default**: `undefined` **Description**: The increment to use for the range. Can be used with letters or numbers. **Example(s)** ```js // numbers console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ] console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ] console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ] // letters console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ] console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ] ``` ### options.strictRanges **Type**: `boolean` **Default**: `false` **Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges. **Example(s)** The following are all invalid: ```js fill('1.1', '2'); // decimals not supported in ranges fill('a', '2'); // incompatible range values fill(1, 10, 'foo'); // invalid "step" argument ``` ### options.stringify **Type**: `boolean` **Default**: `undefined` **Description**: Cast all returned values to strings. By default, integers are returned as numbers. **Example(s)** ```js console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] console.log(fill(1, 5, { stringify: true })); //=> [ '1', '2', '3', '4', '5' ] ``` ### options.toRegex **Type**: `boolean` **Default**: `undefined` **Description**: Create a regex-compatible source string, instead of expanding values to an array. **Example(s)** ```js // alphabetical range console.log(fill('a', 'e', { toRegex: true })); //=> '[a-e]' // alphabetical with step console.log(fill('a', 'z', 3, { toRegex: true })); //=> 'a|d|g|j|m|p|s|v|y' // numerical range console.log(fill('1', '100', { toRegex: true })); //=> '[1-9]|[1-9][0-9]|100' // numerical range with zero padding console.log(fill('000001', '100000', { toRegex: true })); //=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000' ``` ### options.transform **Type**: `function` **Default**: `undefined` **Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_. **Example(s)** ```js // add zero padding console.log(fill(1, 5, value => String(value).padStart(4, '0'))); //=> ['0001', '0002', '0003', '0004', '0005'] ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Contributors | **Commits** | **Contributor** | | --- | --- | | 116 | [jonschlinkert](https://github.com/jonschlinkert) | | 4 | [paulmillr](https://github.com/paulmillr) | | 2 | [realityking](https://github.com/realityking) | | 2 | [bluelovers](https://github.com/bluelovers) | | 1 | [edorivai](https://github.com/edorivai) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! <a href="https://www.patreon.com/jonschlinkert"> <img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" height="50"> </a> ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ node_modules/strip-ansi/license 0000664 00000002135 15114743311 0012662 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/strip-ansi/package.json 0000664 00000001622 15114743311 0013603 0 ustar 00 { "name": "strip-ansi", "version": "7.1.0", "description": "Strip ANSI escape codes from a string", "license": "MIT", "repository": "chalk/strip-ansi", "funding": "https://github.com/chalk/strip-ansi?sponsor=1", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": ">=12" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "strip", "trim", "remove", "ansi", "styles", "color", "colour", "colors", "terminal", "console", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "dependencies": { "ansi-regex": "^6.0.1" }, "devDependencies": { "ava": "^3.15.0", "tsd": "^0.17.0", "xo": "^0.44.0" } } node_modules/strip-ansi/readme.md 0000664 00000002701 15114743311 0013073 0 ustar 00 # strip-ansi > Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string ## Install ``` $ npm install strip-ansi ``` ## Usage ```js import stripAnsi from 'strip-ansi'; stripAnsi('\u001B[4mUnicorn\u001B[0m'); //=> 'Unicorn' stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); //=> 'Click' ``` ## strip-ansi for enterprise Available as part of the Tidelift Subscription. The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) ## Related - [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module - [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module - [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes - [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes - [chalk](https://github.com/chalk/chalk) - Terminal string styling done right ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) node_modules/strip-ansi/index.d.ts 0000664 00000000535 15114743311 0013220 0 ustar 00 /** Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. @example ``` import stripAnsi from 'strip-ansi'; stripAnsi('\u001B[4mUnicorn\u001B[0m'); //=> 'Unicorn' stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); //=> 'Click' ``` */ export default function stripAnsi(string: string): string; node_modules/strip-ansi/index.js 0000664 00000000724 15114743311 0012764 0 ustar 00 import ansiRegex from 'ansi-regex'; const regex = ansiRegex(); export default function stripAnsi(string) { if (typeof string !== 'string') { throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); } // Even though the regex is global, we don't need to reset the `.lastIndex` // because unlike `.exec()` and `.test()`, `.replace()` does it automatically // and doing it manually has a performance penalty. return string.replace(regex, ''); } node_modules/run-parallel/package.json 0000664 00000002413 15114743311 0014107 0 ustar 00 { "name": "run-parallel", "description": "Run an array of functions in parallel", "version": "1.2.0", "author": { "name": "Feross Aboukhadijeh", "email": "feross@feross.org", "url": "https://feross.org" }, "bugs": { "url": "https://github.com/feross/run-parallel/issues" }, "dependencies": { "queue-microtask": "^1.2.2" }, "devDependencies": { "airtap": "^3.0.0", "standard": "*", "tape": "^5.0.1" }, "homepage": "https://github.com/feross/run-parallel", "keywords": [ "parallel", "async", "function", "callback", "asynchronous", "run", "array", "run parallel" ], "license": "MIT", "main": "index.js", "repository": { "type": "git", "url": "git://github.com/feross/run-parallel.git" }, "scripts": { "test": "standard && npm run test-node && npm run test-browser", "test-browser": "airtap -- test/*.js", "test-browser-local": "airtap --local -- test/*.js", "test-node": "tape test/*.js" }, "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ] } node_modules/run-parallel/LICENSE 0000664 00000002071 15114743311 0012626 0 ustar 00 The MIT License (MIT) Copyright (c) Feross Aboukhadijeh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/run-parallel/index.js 0000664 00000002012 15114743311 0013261 0 ustar 00 /*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */ module.exports = runParallel const queueMicrotask = require('queue-microtask') function runParallel (tasks, cb) { let results, pending, keys let isSync = true if (Array.isArray(tasks)) { results = [] pending = tasks.length } else { keys = Object.keys(tasks) results = {} pending = keys.length } function done (err) { function end () { if (cb) cb(err, results) cb = null } if (isSync) queueMicrotask(end) else end() } function each (i, err, result) { results[i] = result if (--pending === 0 || err) { done(err) } } if (!pending) { // empty done(null) } else if (keys) { // object keys.forEach(function (key) { tasks[key](function (err, result) { each(key, err, result) }) }) } else { // array tasks.forEach(function (task, i) { task(function (err, result) { each(i, err, result) }) }) } isSync = false } node_modules/run-parallel/README.md 0000664 00000006125 15114743311 0013104 0 ustar 00 # run-parallel [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/run-parallel/master.svg [travis-url]: https://travis-ci.org/feross/run-parallel [npm-image]: https://img.shields.io/npm/v/run-parallel.svg [npm-url]: https://npmjs.org/package/run-parallel [downloads-image]: https://img.shields.io/npm/dm/run-parallel.svg [downloads-url]: https://npmjs.org/package/run-parallel [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com ### Run an array of functions in parallel  [](https://saucelabs.com/u/run-parallel) ### install ``` npm install run-parallel ``` ### usage #### parallel(tasks, [callback]) Run the `tasks` array of functions in parallel, without waiting until the previous function has completed. If any of the functions pass an error to its callback, the main `callback` is immediately called with the value of the error. Once the `tasks` have completed, the results are passed to the final `callback` as an array. It is also possible to use an object instead of an array. Each property will be run as a function and the results will be passed to the final `callback` as an object instead of an array. This can be a more readable way of handling the results. ##### arguments - `tasks` - An array or object containing functions to run. Each function is passed a `callback(err, result)` which it must call on completion with an error `err` (which can be `null`) and an optional `result` value. - `callback(err, results)` - An optional callback to run once all the functions have completed. This function gets a results array (or object) containing all the result arguments passed to the task callbacks. ##### example ```js var parallel = require('run-parallel') parallel([ function (callback) { setTimeout(function () { callback(null, 'one') }, 200) }, function (callback) { setTimeout(function () { callback(null, 'two') }, 100) } ], // optional callback function (err, results) { // the results array will equal ['one','two'] even though // the second function had a shorter timeout. }) ``` This module is basically equavalent to [`async.parallel`](https://github.com/caolan/async#paralleltasks-callback), but it's handy to just have the one function you need instead of the kitchen sink. Modularity! Especially handy if you're serving to the browser and need to reduce your javascript bundle size. Works great in the browser with [browserify](http://browserify.org/)! ### see also - [run-auto](https://github.com/feross/run-auto) - [run-parallel-limit](https://github.com/feross/run-parallel-limit) - [run-series](https://github.com/feross/run-series) - [run-waterfall](https://github.com/feross/run-waterfall) ### license MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). node_modules/commander/Readme.md 0000664 00000122261 15114743311 0012713 0 ustar 00 # Commander.js [](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22) [](https://www.npmjs.org/package/commander) [](https://npmcharts.com/compare/commander?minimal=true) [](https://packagephobia.now.sh/result?p=commander) The complete solution for [node.js](http://nodejs.org) command-line interfaces. Read this in other languages: English | [简体中文](./Readme_zh-CN.md) - [Commander.js](#commanderjs) - [Installation](#installation) - [Quick Start](#quick-start) - [Declaring _program_ variable](#declaring-program-variable) - [Options](#options) - [Common option types, boolean and value](#common-option-types-boolean-and-value) - [Default option value](#default-option-value) - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue) - [Required option](#required-option) - [Variadic option](#variadic-option) - [Version option](#version-option) - [More configuration](#more-configuration) - [Custom option processing](#custom-option-processing) - [Commands](#commands) - [Command-arguments](#command-arguments) - [More configuration](#more-configuration-1) - [Custom argument processing](#custom-argument-processing) - [Action handler](#action-handler) - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands) - [Life cycle hooks](#life-cycle-hooks) - [Automated help](#automated-help) - [Custom help](#custom-help) - [Display help after errors](#display-help-after-errors) - [Display help from code](#display-help-from-code) - [.name](#name) - [.usage](#usage) - [.description and .summary](#description-and-summary) - [.helpOption(flags, description)](#helpoptionflags-description) - [.addHelpCommand()](#addhelpcommand) - [More configuration](#more-configuration-2) - [Custom event listeners](#custom-event-listeners) - [Bits and pieces](#bits-and-pieces) - [.parse() and .parseAsync()](#parse-and-parseasync) - [Parsing Configuration](#parsing-configuration) - [Legacy options as properties](#legacy-options-as-properties) - [TypeScript](#typescript) - [createCommand()](#createcommand) - [Node options such as `--harmony`](#node-options-such-as---harmony) - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands) - [npm run-script](#npm-run-script) - [Display error](#display-error) - [Override exit and output handling](#override-exit-and-output-handling) - [Additional documentation](#additional-documentation) - [Support](#support) - [Commander for enterprise](#commander-for-enterprise) For information about terms used in this document see: [terminology](./docs/terminology.md) ## Installation ```sh npm install commander ``` ## Quick Start You write code to describe your command line interface. Commander looks after parsing the arguments into options and command-arguments, displays usage errors for problems, and implements a help system. Commander is strict and displays an error for unrecognised options. The two most used option types are a boolean option, and an option which takes its value from the following argument. Example file: [split.js](./examples/split.js) ```js const { program } = require('commander'); program .option('--first') .option('-s, --separator <char>'); program.parse(); const options = program.opts(); const limit = options.first ? 1 : undefined; console.log(program.args[0].split(options.separator, limit)); ``` ```console $ node split.js -s / --fits a/b/c error: unknown option '--fits' (Did you mean --first?) $ node split.js -s / --first a/b/c [ 'a' ] ``` Here is a more complete program using a subcommand and with descriptions for the help. In a multi-command program, you have an action handler for each command (or stand-alone executables for the commands). Example file: [string-util.js](./examples/string-util.js) ```js const { Command } = require('commander'); const program = new Command(); program .name('string-util') .description('CLI to some JavaScript string utilities') .version('0.8.0'); program.command('split') .description('Split a string into substrings and display as an array') .argument('<string>', 'string to split') .option('--first', 'display just the first substring') .option('-s, --separator <char>', 'separator character', ',') .action((str, options) => { const limit = options.first ? 1 : undefined; console.log(str.split(options.separator, limit)); }); program.parse(); ``` ```console $ node string-util.js help split Usage: string-util split [options] <string> Split a string into substrings and display as an array. Arguments: string string to split Options: --first display just the first substring -s, --separator <char> separator character (default: ",") -h, --help display help for command $ node string-util.js split --separator=/ a/b/c [ 'a', 'b', 'c' ] ``` More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory. ## Declaring _program_ variable Commander exports a global object which is convenient for quick programs. This is used in the examples in this README for brevity. ```js // CommonJS (.cjs) const { program } = require('commander'); ``` For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use. ```js // CommonJS (.cjs) const { Command } = require('commander'); const program = new Command(); ``` ```js // ECMAScript (.mjs) import { Command } from 'commander'; const program = new Command(); ``` ```ts // TypeScript (.ts) import { Command } from 'commander'; const program = new Command(); ``` ## Options Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|'). The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler. Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc. An option and its option-argument can be separated by a space, or combined into the same argument. The option-argument can follow the short option directly or follow an `=` for a long option. ```sh serve -p 80 serve -p80 serve --port 80 serve --port=80 ``` You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted. By default options on the command line are not positional, and can be specified before or after other arguments. There are additional related routines for when `.opts()` is not enough: - `.optsWithGlobals()` returns merged local and global option values - `.getOptionValue()` and `.setOptionValue()` work with a single option value - `.getOptionValueSource()` and `.setOptionValueWithSource()` include where the option value came from ### Common option types, boolean and value The two most used option types are a boolean option, and an option which takes its value from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line. Example file: [options-common.js](./examples/options-common.js) ```js program .option('-d, --debug', 'output extra debugging') .option('-s, --small', 'small pizza size') .option('-p, --pizza-type <type>', 'flavour of pizza'); program.parse(process.argv); const options = program.opts(); if (options.debug) console.log(options); console.log('pizza details:'); if (options.small) console.log('- small pizza size'); if (options.pizzaType) console.log(`- ${options.pizzaType}`); ``` ```console $ pizza-options -p error: option '-p, --pizza-type <type>' argument missing $ pizza-options -d -s -p vegetarian { debug: true, small: true, pizzaType: 'vegetarian' } pizza details: - small pizza size - vegetarian $ pizza-options --pizza-type=cheese pizza details: - cheese ``` Multiple boolean short options may be combined together following the dash, and may be followed by a single short option taking a value. For example `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`. Options with an expected option-argument are greedy and will consume the following argument whatever the value. So `--id -xyz` reads `-xyz` as the option-argument. `program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array. The parameter is optional and defaults to `process.argv`. ### Default option value You can specify a default value for an option. Example file: [options-defaults.js](./examples/options-defaults.js) ```js program .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue'); program.parse(); console.log(`cheese: ${program.opts().cheese}`); ``` ```console $ pizza-options cheese: blue $ pizza-options --cheese stilton cheese: stilton ``` ### Other option types, negatable boolean and boolean|value You can define a boolean option long name with a leading `no-` to set the option value to false when used. Defined alone this also makes the option true by default. If you define `--foo` first, adding `--no-foo` does not change the default value from what it would otherwise be. Example file: [options-negatable.js](./examples/options-negatable.js) ```js program .option('--no-sauce', 'Remove sauce') .option('--cheese <flavour>', 'cheese flavour', 'mozzarella') .option('--no-cheese', 'plain with no cheese') .parse(); const options = program.opts(); const sauceStr = options.sauce ? 'sauce' : 'no sauce'; const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`; console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`); ``` ```console $ pizza-options You ordered a pizza with sauce and mozzarella cheese $ pizza-options --sauce error: unknown option '--sauce' $ pizza-options --cheese=blue You ordered a pizza with sauce and blue cheese $ pizza-options --no-sauce --no-cheese You ordered a pizza with no sauce and no cheese ``` You can specify an option which may be used as a boolean option but may optionally take an option-argument (declared with square brackets like `--optional [value]`). Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js) ```js program .option('-c, --cheese [type]', 'Add cheese with optional type'); program.parse(process.argv); const options = program.opts(); if (options.cheese === undefined) console.log('no cheese'); else if (options.cheese === true) console.log('add cheese'); else console.log(`add cheese type ${options.cheese}`); ``` ```console $ pizza-options no cheese $ pizza-options --cheese add cheese $ pizza-options --cheese mozzarella add cheese type mozzarella ``` Options with an optional option-argument are not greedy and will ignore arguments starting with a dash. So `id` behaves as a boolean option for `--id -5`, but you can use a combined form if needed like `--id=-5`. For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md). ### Required option You may specify a required (mandatory) option using `.requiredOption()`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as `.option()` in format, taking flags and description, and optional default value or custom processing. Example file: [options-required.js](./examples/options-required.js) ```js program .requiredOption('-c, --cheese <type>', 'pizza must have cheese'); program.parse(); ``` ```console $ pizza error: required option '-c, --cheese <type>' not specified ``` ### Variadic option You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value is specified in the same argument as the option then no further values are read. Example file: [options-variadic.js](./examples/options-variadic.js) ```js program .option('-n, --number <numbers...>', 'specify numbers') .option('-l, --letter [letters...]', 'specify letters'); program.parse(); console.log('Options: ', program.opts()); console.log('Remaining arguments: ', program.args); ``` ```console $ collect -n 1 2 3 --letter a b c Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] } Remaining arguments: [] $ collect --letter=A -n80 operand Options: { number: [ '80' ], letter: [ 'A' ] } Remaining arguments: [ 'operand' ] $ collect --letter -n 1 -n 2 3 -- operand Options: { number: [ '1', '2', '3' ], letter: true } Remaining arguments: [ 'operand' ] ``` For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md). ### Version option The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits. ```js program.version('0.0.1'); ``` ```console $ ./examples/pizza -V 0.0.1 ``` You may change the flags and description by passing additional parameters to the `version` method, using the same syntax for flags as the `option` method. ```js program.version('0.0.1', '-v, --vers', 'output the current version'); ``` ### More configuration You can add most options using the `.option()` method, but there are some additional features available by constructing an `Option` explicitly for less common cases. Example files: [options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js), [options-conflicts.js](./examples/options-conflicts.js), [options-implies.js](./examples/options-implies.js) ```js program .addOption(new Option('-s, --secret').hideHelp()) .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute')) .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large'])) .addOption(new Option('-p, --port <number>', 'port number').env('PORT')) .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat)) .addOption(new Option('--disable-server', 'disables the server').conflicts('port')) .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' })); ``` ```console $ extra --help Usage: help [options] Options: -t, --timeout <delay> timeout in seconds (default: one minute) -d, --drink <size> drink cup size (choices: "small", "medium", "large") -p, --port <number> port number (env: PORT) --donate [amount] optional donation in dollars (preset: "20") --disable-server disables the server --free-drink small drink included free -h, --help display help for command $ extra --drink huge error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large. $ PORT=80 extra --donate --free-drink Options: { timeout: 60, donate: 20, port: '80', freeDrink: true, drink: 'small' } $ extra --disable-server --port 8000 error: option '--disable-server' cannot be used with option '-p, --port <number>' ``` Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [.requiredOption()](#required-option). ### Custom option processing You may specify a function to do custom processing of option-arguments. The callback function receives two parameters, the user specified option-argument and the previous value for the option. It returns the new value for the option. This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing. You can optionally specify the default/starting value for the option after the function parameter. Example file: [options-custom-processing.js](./examples/options-custom-processing.js) ```js function myParseInt(value, dummyPrevious) { // parseInt takes a string and a radix const parsedValue = parseInt(value, 10); if (isNaN(parsedValue)) { throw new commander.InvalidArgumentError('Not a number.'); } return parsedValue; } function increaseVerbosity(dummyValue, previous) { return previous + 1; } function collect(value, previous) { return previous.concat([value]); } function commaSeparatedList(value, dummyPrevious) { return value.split(','); } program .option('-f, --float <number>', 'float argument', parseFloat) .option('-i, --integer <number>', 'integer argument', myParseInt) .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0) .option('-c, --collect <value>', 'repeatable value', collect, []) .option('-l, --list <items>', 'comma separated list', commaSeparatedList) ; program.parse(); const options = program.opts(); if (options.float !== undefined) console.log(`float: ${options.float}`); if (options.integer !== undefined) console.log(`integer: ${options.integer}`); if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`); if (options.collect.length > 0) console.log(options.collect); if (options.list !== undefined) console.log(options.list); ``` ```console $ custom -f 1e2 float: 100 $ custom --integer 2 integer: 2 $ custom -v -v -v verbose: 3 $ custom -c a -c b -c c [ 'a', 'b', 'c' ] $ custom --list x,y,z [ 'x', 'y', 'z' ] ``` ## Commands You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)). In the first parameter to `.command()` you specify the command name. You may append the command-arguments after the command name, or specify them separately using `.argument()`. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`. You can use `.addCommand()` to add an already configured subcommand to the program. For example: ```js // Command implemented using action handler (description is supplied separately to `.command`) // Returns new command for configuring. program .command('clone <source> [destination]') .description('clone a repository into a newly created directory') .action((source, destination) => { console.log('clone command called'); }); // Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`. // Returns `this` for adding more commands. program .command('start <service>', 'start named service') .command('stop [service]', 'stop named service, or all if no name supplied'); // Command prepared separately. // Returns `this` for adding more commands. program .addCommand(build.makeBuildCommand()); ``` Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other subcommand is specified ([example](./examples/defaultCommand.js)). You can add alternative names for a command with `.alias()`. ([example](./examples/alias.js)) For safety, `.addCommand()` does not automatically copy the inherited settings from the parent command. There is a helper routine `.copyInheritedSettings()` for copying the settings when they are wanted. ### Command-arguments For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands you can instead use the following method. To configure a command, you can use `.argument()` to specify each expected command-argument. You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`. You can specify a default value for an optional command-argument. Example file: [argument.js](./examples/argument.js) ```js program .version('0.1.0') .argument('<username>', 'user to login') .argument('[password]', 'password for user, if required', 'no password given') .action((username, password) => { console.log('username:', username); console.log('password:', password); }); ``` The last argument of a command can be variadic, and only the last argument. To make an argument variadic you append `...` to the argument name. A variadic argument is passed to the action handler as an array. For example: ```js program .version('0.1.0') .command('rmdir') .argument('<dirs...>') .action(function (dirs) { dirs.forEach((dir) => { console.log('rmdir %s', dir); }); }); ``` There is a convenience method to add multiple arguments at once, but without descriptions: ```js program .arguments('<username> <password>'); ``` #### More configuration There are some additional features available by constructing an `Argument` explicitly for less common cases. Example file: [arguments-extra.js](./examples/arguments-extra.js) ```js program .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large'])) .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute')) ``` #### Custom argument processing You may specify a function to do custom processing of command-arguments (like for option-arguments). The callback function receives two parameters, the user specified command-argument and the previous value for the argument. It returns the new value for the argument. The processed argument values are passed to the action handler, and saved as `.processedArgs`. You can optionally specify the default/starting value for the argument after the function parameter. Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js) ```js program .command('add') .argument('<first>', 'integer argument', myParseInt) .argument('[second]', 'integer argument', myParseInt, 1000) .action((first, second) => { console.log(`${first} + ${second} = ${first + second}`); }) ; ``` ### Action handler The action handler gets passed a parameter for each command-argument you declared, and two additional parameters which are the parsed options and the command object itself. Example file: [thank.js](./examples/thank.js) ```js program .argument('<name>') .option('-t, --title <honorific>', 'title to use before name') .option('-d, --debug', 'display some debugging') .action((name, options, command) => { if (options.debug) { console.error('Called %s with options %o', command.name(), options); } const title = options.title ? `${options.title} ` : ''; console.log(`Thank-you ${title}${name}`); }); ``` If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. The `this` keyword is set to the running command and can be used from a function expression (but not from an arrow function). Example file: [action-this.js](./examples/action-this.js) ```js program .command('serve') .argument('<script>') .option('-p, --port <number>', 'port number', 80) .action(function() { console.error('Run script %s on port %s', this.args[0], this.opts().port); }); ``` You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`. ```js async function run() { /* code goes here */ } async function main() { program .command('run') .action(run); await program.parseAsync(process.argv); } ``` A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments will be reported as an error. You can suppress the unknown option checks with `.allowUnknownOption()`. By default it is not an error to pass more arguments than declared, but you can make this an error with `.allowExcessArguments(false)`. ### Stand-alone executable (sub)commands When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands. Commander will search the files in the directory of the entry script for a file with the name combination `command-subcommand`, like `pm-install` or `pm-search` in the example below. The search includes trying common file extensions, like `.js`. You may specify a custom name (and path) with the `executableFile` configuration option. You may specify a custom search directory for subcommands with `.executableDir()`. You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level. Example file: [pm](./examples/pm) ```js program .name('pm') .version('0.1.0') .command('install [name]', 'install one or more packages') .command('search [query]', 'search with optional query') .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' }) .command('list', 'list packages installed', { isDefault: true }); program.parse(process.argv); ``` If the program is designed to be installed globally, make sure the executables have proper modes, like `755`. ### Life cycle hooks You can add callback hooks to a command for life cycle events. Example file: [hook.js](./examples/hook.js) ```js program .option('-t, --trace', 'display trace statements for commands') .hook('preAction', (thisCommand, actionCommand) => { if (thisCommand.opts().trace) { console.log(`About to call action handler for subcommand: ${actionCommand.name()}`); console.log('arguments: %O', actionCommand.args); console.log('options: %o', actionCommand.opts()); } }); ``` The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event. The supported events are: | event name | when hook called | callback parameters | | :-- | :-- | :-- | | `preAction`, `postAction` | before/after action handler for this command and its nested subcommands | `(thisCommand, actionCommand)` | | `preSubcommand` | before parsing direct subcommand | `(thisCommand, subcommand)` | For an overview of the life cycle events see [parsing life cycle and hooks](./docs/parsing-and-hooks.md). ## Automated help The help information is auto-generated based on the information commander already knows about your program. The default help option is `-h,--help`. Example file: [pizza](./examples/pizza) ```console $ node ./examples/pizza --help Usage: pizza [options] An application for pizza ordering Options: -p, --peppers Add peppers -c, --cheese <type> Add the specified type of cheese (default: "marble") -C, --no-cheese You do not want any cheese -h, --help display help for command ``` A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show further help for the subcommand. These are effectively the same if the `shell` program has implicit help: ```sh shell help shell --help shell help spawn shell spawn --help ``` Long descriptions are wrapped to fit the available width. (However, a description that includes a line-break followed by whitespace is assumed to be pre-formatted and not wrapped.) ### Custom help You can add extra text to be displayed along with the built-in help. Example file: [custom-help](./examples/custom-help) ```js program .option('-f, --foo', 'enable some foo'); program.addHelpText('after', ` Example call: $ custom-help --help`); ``` Yields the following help output: ```Text Usage: custom-help [options] Options: -f, --foo enable some foo -h, --help display help for command Example call: $ custom-help --help ``` The positions in order displayed are: - `beforeAll`: add to the program for a global banner or header - `before`: display extra information before built-in help - `after`: display extra information after built-in help - `afterAll`: add to the program for a global footer (epilog) The positions "beforeAll" and "afterAll" apply to the command and all its subcommands. The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are: - error: a boolean for whether the help is being displayed due to a usage error - command: the Command which is displaying the help ### Display help after errors The default behaviour for usage errors is to just display a short error message. You can change the behaviour to show the full help or a custom help message after an error. ```js program.showHelpAfterError(); // or program.showHelpAfterError('(add --help for additional information)'); ``` ```console $ pizza --unknown error: unknown option '--unknown' (add --help for additional information) ``` The default behaviour is to suggest correct spelling after an error for an unknown command or option. You can disable this. ```js program.showSuggestionAfterError(false); ``` ```console $ pizza --hepl error: unknown option '--hepl' (Did you mean --help?) ``` ### Display help from code `.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status. `.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr. `.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself. ### .name The command name appears in the help, and is also used for locating stand-alone executable subcommands. You may specify the program name using `.name()` or in the Command constructor. For the program, Commander will fallback to using the script name from the full arguments passed into `.parse()`. However, the script name varies depending on how your program is launched so you may wish to specify it explicitly. ```js program.name('pizza'); const pm = new Command('pm'); ``` Subcommands get a name when specified using `.command()`. If you create the subcommand yourself to use with `.addCommand()`, then set the name using `.name()` or in the Command constructor. ### .usage This allows you to customise the usage description in the first line of the help. Given: ```js program .name("my-command") .usage("[global options] command") ``` The help will start with: ```Text Usage: my-command [global options] command ``` ### .description and .summary The description appears in the help for the command. You can optionally supply a shorter summary to use when listed as a subcommand of the program. ```js program .command("duplicate") .summary("make a copy") .description(`Make a copy of the current project. This may require additional disk space. `); ``` ### .helpOption(flags, description) By default every command has a help option. You may change the default help flags and description. Pass false to disable the built-in help option. ```js program .helpOption('-e, --HELP', 'read more information'); ``` ### .addHelpCommand() A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`. You can both turn on and customise the help command by supplying the name and description: ```js program.addHelpCommand('assist [command]', 'show assistance'); ``` ### More configuration The built-in help is formatted using the Help class. You can configure the Help behaviour by modifying data properties and methods using `.configureHelp()`, or by subclassing using `.createHelp()` if you prefer. The data properties are: - `helpWidth`: specify the wrap width, useful for unit tests - `sortSubcommands`: sort the subcommands alphabetically - `sortOptions`: sort the options alphabetically - `showGlobalOptions`: show a section with the global options from the parent command(s) You can override any method on the [Help](./lib/help.js) class. There are methods getting the visible lists of arguments, options, and subcommands. There are methods for formatting the items in the lists, with each item having a _term_ and _description_. Take a look at `.formatHelp()` to see how they are used. Example file: [configure-help.js](./examples/configure-help.js) ```js program.configureHelp({ sortSubcommands: true, subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage. }); ``` ## Custom event listeners You can execute custom actions by listening to command and option events. ```js program.on('option:verbose', function () { process.env.VERBOSE = this.opts().verbose; }); ``` ## Bits and pieces ### .parse() and .parseAsync() The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`. If the arguments follow different conventions than node you can pass a `from` option in the second parameter: - 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that - 'electron': `argv[1]` varies depending on whether the electron application is packaged - 'user': all of the arguments from the user For example: ```js program.parse(process.argv); // Explicit, node conventions program.parse(); // Implicit, and auto-detect electron program.parse(['-f', 'filename'], { from: 'user' }); ``` ### Parsing Configuration If the default parsing does not suit your needs, there are some behaviours to support other usage patterns. By default program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use an option for a different purpose in subcommands. Example file: [positional-options.js](./examples/positional-options.js) With positional options, the `-b` is a program option in the first line and a subcommand option in the second line: ```sh program -b subcommand program subcommand -b ``` By default options are recognised before and after command-arguments. To only process options that come before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program without needing to use `--` to end the option processing. To use pass through options in a subcommand, the program needs to enable positional options. Example file: [pass-through-options.js](./examples/pass-through-options.js) With pass through options, the `--port=80` is a program option in the first line and passed through as a command-argument in the second line: ```sh program --port=80 arg program arg --port=80 ``` By default the option processing shows an error for an unknown option. To have an unknown option treated as an ordinary command-argument and continue looking for options, use `.allowUnknownOption()`. This lets you mix known and unknown options. By default the argument processing does not display an error for more command-arguments than expected. To display an error for excess arguments, use`.allowExcessArguments(false)`. ### Legacy options as properties Before Commander 7, the option values were stored as properties on the command. This was convenient to code but the downside was possible clashes with existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`. ```js program .storeOptionsAsProperties() .option('-d, --debug') .action((commandAndOptions) => { if (commandAndOptions.debug) { console.error(`Called ${commandAndOptions.name()}`); } }); ``` ### TypeScript extra-typings: There is an optional project to infer extra type information from the option and argument definitions. This adds strong typing to the options returned by `.opts()` and the parameters to `.action()`. See [commander-js/extra-typings](https://github.com/commander-js/extra-typings) for more. ``` import { Command } from '@commander-js/extra-typings'; ``` ts-node: If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly. e.g. ```sh node -r ts-node/register pm.ts ``` ### createCommand() This factory function creates a new command. It is exported and may be used instead of using `new`, like: ```js const { createCommand } = require('commander'); const program = createCommand(); ``` `createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally when creating subcommands using `.command()`, and you may override it to customise the new subcommand (example file [custom-command-class.js](./examples/custom-command-class.js)). ### Node options such as `--harmony` You can enable `--harmony` option in two ways: - Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.) - Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand process. ### Debugging stand-alone executable subcommands An executable subcommand is launched as a separate child process. If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al, the inspector port is incremented by 1 for the spawned subcommand. If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration. ### npm run-script By default when you call your program using run-script, `npm` will parse any options on the command-line and they will not reach your program. Use `--` to stop the npm option parsing and pass through all the arguments. The synopsis for [npm run-script](https://docs.npmjs.com/cli/v9/commands/npm-run-script) explicitly shows the `--` for this reason: ```console npm run-script <command> [-- <args>] ``` ### Display error This routine is available to invoke the Commander error handling for your own error conditions. (See also the next section about exit handling.) As well as the error message, you can optionally specify the `exitCode` (used with `process.exit`) and `code` (used with `CommanderError`). ```js program.error('Password must be longer than four characters'); program.error('Custom processing has failed', { exitCode: 2, code: 'my.custom.error' }); ``` ### Override exit and output handling By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override this behaviour and optionally supply a callback. The default override throws a `CommanderError`. The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help is not affected by the override which is called after the display. ```js program.exitOverride(); try { program.parse(process.argv); } catch (err) { // custom processing... } ``` By default Commander is configured for a command-line application and writes to stdout and stderr. You can modify this behaviour for custom applications. In addition, you can modify the display of error messages. Example file: [configure-output.js](./examples/configure-output.js) ```js function errorColor(str) { // Add ANSI escape codes to display text in red. return `\x1b[31m${str}\x1b[0m`; } program .configureOutput({ // Visibly override write routines as example! writeOut: (str) => process.stdout.write(`[OUT] ${str}`), writeErr: (str) => process.stdout.write(`[ERR] ${str}`), // Highlight errors in color. outputError: (str, write) => write(errorColor(str)) }); ``` ### Additional documentation There is more information available about: - [deprecated](./docs/deprecated.md) features still supported for backwards compatibility - [options taking varying arguments](./docs/options-taking-varying-arguments.md) - [parsing life cycle and hooks](./docs/parsing-and-hooks.md) ## Support The current version of Commander is fully supported on Long Term Support versions of Node.js, and requires at least v16. (For older versions of Node.js, use an older version of Commander.) The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub. ### Commander for enterprise Available as part of the Tidelift Subscription The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) node_modules/commander/package-support.json 0000664 00000000347 15114743311 0015174 0 ustar 00 { "versions": [ { "version": "*", "target": { "node": "supported" }, "response": { "type": "time-permitting" }, "backing": { "npm-funding": true } } ] } node_modules/commander/package.json 0000664 00000004434 15114743311 0013463 0 ustar 00 { "name": "commander", "version": "11.0.0", "description": "the complete solution for node.js command-line programs", "keywords": [ "commander", "command", "option", "parser", "cli", "argument", "args", "argv" ], "author": "TJ Holowaychuk <tj@vision-media.ca>", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/tj/commander.js.git" }, "scripts": { "lint": "npm run lint:javascript && npm run lint:typescript", "lint:javascript": "eslint index.js esm.mjs \"lib/*.js\" \"tests/**/*.js\"", "lint:typescript": "eslint typings/*.ts tests/*.ts", "test": "jest && npm run test-typings", "test-esm": "node ./tests/esm-imports-test.mjs", "test-typings": "tsd", "typescript-checkJS": "tsc --allowJS --checkJS index.js lib/*.js --noEmit", "test-all": "npm run test && npm run lint && npm run typescript-checkJS && npm run test-esm" }, "files": [ "index.js", "lib/*.js", "esm.mjs", "typings/index.d.ts", "typings/esm.d.mts", "package-support.json" ], "type": "commonjs", "main": "./index.js", "exports": { ".": { "require": { "types": "./typings/index.d.ts", "default": "./index.js" }, "import": { "types": "./typings/esm.d.mts", "default": "./esm.mjs" }, "default": "./index.js" }, "./esm.mjs": { "types": "./typings/esm.d.mts", "import": "./esm.mjs" } }, "devDependencies": { "@types/jest": "^29.2.4", "@types/node": "^20.2.5", "@typescript-eslint/eslint-plugin": "^5.47.1", "@typescript-eslint/parser": "^5.47.1", "eslint": "^8.30.0", "eslint-config-standard": "^17.0.0", "eslint-config-standard-with-typescript": "^33.0.0", "eslint-plugin-import": "^2.26.0", "eslint-plugin-jest": "^27.1.7", "eslint-plugin-n": "^15.6.0", "eslint-plugin-promise": "^6.1.1", "jest": "^29.3.1", "ts-jest": "^29.0.3", "tsd": "^0.28.1", "typescript": "^5.0.4" }, "types": "typings/index.d.ts", "jest": { "testEnvironment": "node", "collectCoverage": true, "transform": { "^.+\\.tsx?$": "ts-jest" }, "testPathIgnorePatterns": [ "/node_modules/" ] }, "engines": { "node": ">=16" }, "support": true } node_modules/commander/LICENSE 0000664 00000002112 15114743311 0012171 0 ustar 00 (The MIT License) Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/commander/typings/index.d.ts 0000664 00000066354 15114743311 0014604 0 ustar 00 // Type definitions for commander // Original definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne> // Using method rather than property for method-signature-style, to document method overloads separately. Allow either. /* eslint-disable @typescript-eslint/method-signature-style */ /* eslint-disable @typescript-eslint/no-explicit-any */ export class CommanderError extends Error { code: string; exitCode: number; message: string; nestedError?: string; /** * Constructs the CommanderError class * @param exitCode - suggested exit code which could be used with process.exit * @param code - an id string representing the error * @param message - human-readable description of the error * @constructor */ constructor(exitCode: number, code: string, message: string); } export class InvalidArgumentError extends CommanderError { /** * Constructs the InvalidArgumentError class * @param message - explanation of why argument is invalid * @constructor */ constructor(message: string); } export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name export interface ErrorOptions { // optional parameter for error() /** an id string representing the error */ code?: string; /** suggested exit code which could be used with process.exit */ exitCode?: number; } export class Argument { description: string; required: boolean; variadic: boolean; /** * Initialize a new command argument with the given name and description. * The default is that the argument is required, and you can explicitly * indicate this with <> around the name. Put [] around the name for an optional argument. */ constructor(arg: string, description?: string); /** * Return argument name. */ name(): string; /** * Set the default value, and optionally supply the description to be displayed in the help. */ default(value: unknown, description?: string): this; /** * Set the custom handler for processing CLI command arguments into argument values. */ argParser<T>(fn: (value: string, previous: T) => T): this; /** * Only allow argument value to be one of choices. */ choices(values: readonly string[]): this; /** * Make argument required. */ argRequired(): this; /** * Make argument optional. */ argOptional(): this; } export class Option { flags: string; description: string; required: boolean; // A value must be supplied when the option is specified. optional: boolean; // A value is optional when the option is specified. variadic: boolean; mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line. short?: string; long?: string; negate: boolean; defaultValue?: any; defaultValueDescription?: string; parseArg?: <T>(value: string, previous: T) => T; hidden: boolean; argChoices?: string[]; constructor(flags: string, description?: string); /** * Set the default value, and optionally supply the description to be displayed in the help. */ default(value: unknown, description?: string): this; /** * Preset to use when option used without option-argument, especially optional but also boolean and negated. * The custom processing (parseArg) is called. * * @example * ```ts * new Option('--color').default('GREYSCALE').preset('RGB'); * new Option('--donate [amount]').preset('20').argParser(parseFloat); * ``` */ preset(arg: unknown): this; /** * Add option name(s) that conflict with this option. * An error will be displayed if conflicting options are found during parsing. * * @example * ```ts * new Option('--rgb').conflicts('cmyk'); * new Option('--js').conflicts(['ts', 'jsx']); * ``` */ conflicts(names: string | string[]): this; /** * Specify implied option values for when this option is set and the implied options are not. * * The custom processing (parseArg) is not called on the implied values. * * @example * program * .addOption(new Option('--log', 'write logging information to file')) * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' })); */ implies(optionValues: OptionValues): this; /** * Set environment variable to check for option value. * * An environment variables is only used if when processed the current option value is * undefined, or the source of the current value is 'default' or 'config' or 'env'. */ env(name: string): this; /** * Calculate the full description, including defaultValue etc. */ fullDescription(): string; /** * Set the custom handler for processing CLI option arguments into option values. */ argParser<T>(fn: (value: string, previous: T) => T): this; /** * Whether the option is mandatory and must have a value after parsing. */ makeOptionMandatory(mandatory?: boolean): this; /** * Hide option in help. */ hideHelp(hide?: boolean): this; /** * Only allow option value to be one of choices. */ choices(values: readonly string[]): this; /** * Return option name. */ name(): string; /** * Return option name, in a camelcase format that can be used * as a object attribute key. */ attributeName(): string; /** * Return whether a boolean option. * * Options are one of boolean, negated, required argument, or optional argument. */ isBoolean(): boolean; } export class Help { /** output helpWidth, long lines are wrapped to fit */ helpWidth?: number; sortSubcommands: boolean; sortOptions: boolean; showGlobalOptions: boolean; constructor(); /** Get the command term to show in the list of subcommands. */ subcommandTerm(cmd: Command): string; /** Get the command summary to show in the list of subcommands. */ subcommandDescription(cmd: Command): string; /** Get the option term to show in the list of options. */ optionTerm(option: Option): string; /** Get the option description to show in the list of options. */ optionDescription(option: Option): string; /** Get the argument term to show in the list of arguments. */ argumentTerm(argument: Argument): string; /** Get the argument description to show in the list of arguments. */ argumentDescription(argument: Argument): string; /** Get the command usage to be displayed at the top of the built-in help. */ commandUsage(cmd: Command): string; /** Get the description for the command. */ commandDescription(cmd: Command): string; /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */ visibleCommands(cmd: Command): Command[]; /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */ visibleOptions(cmd: Command): Option[]; /** Get an array of the visible global options. (Not including help.) */ visibleGlobalOptions(cmd: Command): Option[]; /** Get an array of the arguments which have descriptions. */ visibleArguments(cmd: Command): Argument[]; /** Get the longest command term length. */ longestSubcommandTermLength(cmd: Command, helper: Help): number; /** Get the longest option term length. */ longestOptionTermLength(cmd: Command, helper: Help): number; /** Get the longest global option term length. */ longestGlobalOptionTermLength(cmd: Command, helper: Help): number; /** Get the longest argument term length. */ longestArgumentTermLength(cmd: Command, helper: Help): number; /** Calculate the pad width from the maximum term length. */ padWidth(cmd: Command, helper: Help): number; /** * Wrap the given string to width characters per line, with lines after the first indented. * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted. */ wrap(str: string, width: number, indent: number, minColumnWidth?: number): string; /** Generate the built-in help text. */ formatHelp(cmd: Command, helper: Help): string; } export type HelpConfiguration = Partial<Help>; export interface ParseOptions { from: 'node' | 'electron' | 'user'; } export interface HelpContext { // optional parameter for .help() and .outputHelp() error: boolean; } export interface AddHelpTextContext { // passed to text function used with .addHelpText() error: boolean; command: Command; } export interface OutputConfiguration { writeOut?(str: string): void; writeErr?(str: string): void; getOutHelpWidth?(): number; getErrHelpWidth?(): number; outputError?(str: string, write: (str: string) => void): void; } export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll'; export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction'; export type OptionValueSource = 'default' | 'config' | 'env' | 'cli' | 'implied'; export type OptionValues = Record<string, any>; export class Command { args: string[]; processedArgs: any[]; readonly commands: readonly Command[]; readonly options: readonly Option[]; parent: Command | null; constructor(name?: string); /** * Set the program version to `str`. * * This method auto-registers the "-V, --version" flag * which will print the version number when passed. * * You can optionally supply the flags and description to override the defaults. */ version(str: string, flags?: string, description?: string): this; /** * Define a command, implemented using an action handler. * * @remarks * The command description is supplied using `.description`, not as a parameter to `.command`. * * @example * ```ts * program * .command('clone <source> [destination]') * .description('clone a repository into a newly created directory') * .action((source, destination) => { * console.log('clone command called'); * }); * ``` * * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...` * @param opts - configuration options * @returns new command */ command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>; /** * Define a command, implemented in a separate executable file. * * @remarks * The command description is supplied as the second parameter to `.command`. * * @example * ```ts * program * .command('start <service>', 'start named service') * .command('stop [service]', 'stop named service, or all if no name supplied'); * ``` * * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...` * @param description - description of executable command * @param opts - configuration options * @returns `this` command for chaining */ command(nameAndArgs: string, description: string, opts?: ExecutableCommandOptions): this; /** * Factory routine to create a new unattached command. * * See .command() for creating an attached subcommand, which uses this routine to * create the command. You can override createCommand to customise subcommands. */ createCommand(name?: string): Command; /** * Add a prepared subcommand. * * See .command() for creating an attached subcommand which inherits settings from its parent. * * @returns `this` command for chaining */ addCommand(cmd: Command, opts?: CommandOptions): this; /** * Factory routine to create a new unattached argument. * * See .argument() for creating an attached argument, which uses this routine to * create the argument. You can override createArgument to return a custom argument. */ createArgument(name: string, description?: string): Argument; /** * Define argument syntax for command. * * The default is that the argument is required, and you can explicitly * indicate this with <> around the name. Put [] around the name for an optional argument. * * @example * ``` * program.argument('<input-file>'); * program.argument('[output-file]'); * ``` * * @returns `this` command for chaining */ argument<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this; argument(name: string, description?: string, defaultValue?: unknown): this; /** * Define argument syntax for command, adding a prepared argument. * * @returns `this` command for chaining */ addArgument(arg: Argument): this; /** * Define argument syntax for command, adding multiple at once (without descriptions). * * See also .argument(). * * @example * ``` * program.arguments('<cmd> [env]'); * ``` * * @returns `this` command for chaining */ arguments(names: string): this; /** * Override default decision whether to add implicit help command. * * @example * ``` * addHelpCommand() // force on * addHelpCommand(false); // force off * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details * ``` * * @returns `this` command for chaining */ addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this; /** * Add hook for life cycle event. */ hook(event: HookEvent, listener: (thisCommand: Command, actionCommand: Command) => void | Promise<void>): this; /** * Register callback to use as replacement for calling process.exit. */ exitOverride(callback?: (err: CommanderError) => never | void): this; /** * Display error message and exit (or call exitOverride). */ error(message: string, errorOptions?: ErrorOptions): never; /** * You can customise the help with a subclass of Help by overriding createHelp, * or by overriding Help properties using configureHelp(). */ createHelp(): Help; /** * You can customise the help by overriding Help properties using configureHelp(), * or with a subclass of Help by overriding createHelp(). */ configureHelp(configuration: HelpConfiguration): this; /** Get configuration */ configureHelp(): HelpConfiguration; /** * The default output goes to stdout and stderr. You can customise this for special * applications. You can also customise the display of errors by overriding outputError. * * The configuration properties are all functions: * ``` * // functions to change where being written, stdout and stderr * writeOut(str) * writeErr(str) * // matching functions to specify width for wrapping help * getOutHelpWidth() * getErrHelpWidth() * // functions based on what is being written out * outputError(str, write) // used for displaying errors, and not used for displaying help * ``` */ configureOutput(configuration: OutputConfiguration): this; /** Get configuration */ configureOutput(): OutputConfiguration; /** * Copy settings that are useful to have in common across root command and subcommands. * * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) */ copyInheritedSettings(sourceCommand: Command): this; /** * Display the help or a custom message after an error occurs. */ showHelpAfterError(displayHelp?: boolean | string): this; /** * Display suggestion of similar commands for unknown commands, or options for unknown options. */ showSuggestionAfterError(displaySuggestion?: boolean): this; /** * Register callback `fn` for the command. * * @example * ``` * program * .command('serve') * .description('start service') * .action(function() { * // do work here * }); * ``` * * @returns `this` command for chaining */ action(fn: (...args: any[]) => void | Promise<void>): this; /** * Define option with `flags`, `description` and optional * coercion `fn`. * * The `flags` string contains the short and/or long flags, * separated by comma, a pipe or space. The following are all valid * all will output this way when `--help` is used. * * "-p, --pepper" * "-p|--pepper" * "-p --pepper" * * @example * ``` * // simple boolean defaulting to false * program.option('-p, --pepper', 'add pepper'); * * --pepper * program.pepper * // => Boolean * * // simple boolean defaulting to true * program.option('-C, --no-cheese', 'remove cheese'); * * program.cheese * // => true * * --no-cheese * program.cheese * // => false * * // required argument * program.option('-C, --chdir <path>', 'change the working directory'); * * --chdir /tmp * program.chdir * // => "/tmp" * * // optional argument * program.option('-c, --cheese [type]', 'add cheese [marble]'); * ``` * * @returns `this` command for chaining */ option(flags: string, description?: string, defaultValue?: string | boolean | string[]): this; option<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this; /** @deprecated since v7, instead use choices or a custom function */ option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this; /** * Define a required option, which must have a value after parsing. This usually means * the option must be specified on the command line. (Otherwise the same as .option().) * * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. */ requiredOption(flags: string, description?: string, defaultValue?: string | boolean | string[]): this; requiredOption<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this; /** @deprecated since v7, instead use choices or a custom function */ requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this; /** * Factory routine to create a new unattached option. * * See .option() for creating an attached option, which uses this routine to * create the option. You can override createOption to return a custom option. */ createOption(flags: string, description?: string): Option; /** * Add a prepared Option. * * See .option() and .requiredOption() for creating and attaching an option in a single call. */ addOption(option: Option): this; /** * Whether to store option values as properties on command object, * or store separately (specify false). In both cases the option values can be accessed using .opts(). * * @returns `this` command for chaining */ storeOptionsAsProperties<T extends OptionValues>(): this & T; storeOptionsAsProperties<T extends OptionValues>(storeAsProperties: true): this & T; storeOptionsAsProperties(storeAsProperties?: boolean): this; /** * Retrieve option value. */ getOptionValue(key: string): any; /** * Store option value. */ setOptionValue(key: string, value: unknown): this; /** * Store option value and where the value came from. */ setOptionValueWithSource(key: string, value: unknown, source: OptionValueSource): this; /** * Get source of option value. */ getOptionValueSource(key: string): OptionValueSource | undefined; /** * Get source of option value. See also .optsWithGlobals(). */ getOptionValueSourceWithGlobals(key: string): OptionValueSource | undefined; /** * Alter parsing of short flags with optional values. * * @example * ``` * // for `.option('-f,--flag [value]'): * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` * ``` * * @returns `this` command for chaining */ combineFlagAndOptionalValue(combine?: boolean): this; /** * Allow unknown options on the command line. * * @returns `this` command for chaining */ allowUnknownOption(allowUnknown?: boolean): this; /** * Allow excess command-arguments on the command line. Pass false to make excess arguments an error. * * @returns `this` command for chaining */ allowExcessArguments(allowExcess?: boolean): this; /** * Enable positional options. Positional means global options are specified before subcommands which lets * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. * * The default behaviour is non-positional and global options may appear anywhere on the command line. * * @returns `this` command for chaining */ enablePositionalOptions(positional?: boolean): this; /** * Pass through options that come after command-arguments rather than treat them as command-options, * so actual command-options come before command-arguments. Turning this on for a subcommand requires * positional options to have been enabled on the program (parent commands). * * The default behaviour is non-positional and options may appear before or after command-arguments. * * @returns `this` command for chaining */ passThroughOptions(passThrough?: boolean): this; /** * Parse `argv`, setting options and invoking commands when defined. * * The default expectation is that the arguments are from node and have the application as argv[0] * and the script being run in argv[1], with user parameters after that. * * @example * ``` * program.parse(process.argv); * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] * ``` * * @returns `this` command for chaining */ parse(argv?: readonly string[], options?: ParseOptions): this; /** * Parse `argv`, setting options and invoking commands when defined. * * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. * * The default expectation is that the arguments are from node and have the application as argv[0] * and the script being run in argv[1], with user parameters after that. * * @example * ``` * program.parseAsync(process.argv); * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] * ``` * * @returns Promise */ parseAsync(argv?: readonly string[], options?: ParseOptions): Promise<this>; /** * Parse options from `argv` removing known options, * and return argv split into operands and unknown arguments. * * argv => operands, unknown * --known kkk op => [op], [] * op --known kkk => [op], [] * sub --unknown uuu op => [sub], [--unknown uuu op] * sub -- --unknown uuu op => [sub --unknown uuu op], [] */ parseOptions(argv: string[]): ParseOptionsResult; /** * Return an object containing local option values as key-value pairs */ opts<T extends OptionValues>(): T; /** * Return an object containing merged local and global option values as key-value pairs. */ optsWithGlobals<T extends OptionValues>(): T; /** * Set the description. * * @returns `this` command for chaining */ description(str: string): this; /** @deprecated since v8, instead use .argument to add command argument with description */ description(str: string, argsDescription: Record<string, string>): this; /** * Get the description. */ description(): string; /** * Set the summary. Used when listed as subcommand of parent. * * @returns `this` command for chaining */ summary(str: string): this; /** * Get the summary. */ summary(): string; /** * Set an alias for the command. * * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. * * @returns `this` command for chaining */ alias(alias: string): this; /** * Get alias for the command. */ alias(): string; /** * Set aliases for the command. * * Only the first alias is shown in the auto-generated help. * * @returns `this` command for chaining */ aliases(aliases: readonly string[]): this; /** * Get aliases for the command. */ aliases(): string[]; /** * Set the command usage. * * @returns `this` command for chaining */ usage(str: string): this; /** * Get the command usage. */ usage(): string; /** * Set the name of the command. * * @returns `this` command for chaining */ name(str: string): this; /** * Get the name of the command. */ name(): string; /** * Set the name of the command from script filename, such as process.argv[1], * or require.main.filename, or __filename. * * (Used internally and public although not documented in README.) * * @example * ```ts * program.nameFromFilename(require.main.filename); * ``` * * @returns `this` command for chaining */ nameFromFilename(filename: string): this; /** * Set the directory for searching for executable subcommands of this command. * * @example * ```ts * program.executableDir(__dirname); * // or * program.executableDir('subcommands'); * ``` * * @returns `this` command for chaining */ executableDir(path: string): this; /** * Get the executable search directory. */ executableDir(): string; /** * Output help information for this command. * * Outputs built-in help, and custom text added using `.addHelpText()`. * */ outputHelp(context?: HelpContext): void; /** @deprecated since v7 */ outputHelp(cb?: (str: string) => string): void; /** * Return command help documentation. */ helpInformation(context?: HelpContext): string; /** * You can pass in flags and a description to override the help * flags and help description for your command. Pass in false * to disable the built-in help option. */ helpOption(flags?: string | boolean, description?: string): this; /** * Output help information and exit. * * Outputs built-in help, and custom text added using `.addHelpText()`. */ help(context?: HelpContext): never; /** @deprecated since v7 */ help(cb?: (str: string) => string): never; /** * Add additional text to be displayed with the built-in help. * * Position is 'before' or 'after' to affect just this command, * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands. */ addHelpText(position: AddHelpTextPosition, text: string): this; addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string): this; /** * Add a listener (callback) for when events occur. (Implemented using EventEmitter.) */ on(event: string | symbol, listener: (...args: any[]) => void): this; } export interface CommandOptions { hidden?: boolean; isDefault?: boolean; /** @deprecated since v7, replaced by hidden */ noHelp?: boolean; } export interface ExecutableCommandOptions extends CommandOptions { executableFile?: string; } export interface ParseOptionsResult { operands: string[]; unknown: string[]; } export function createCommand(name?: string): Command; export function createOption(flags: string, description?: string): Option; export function createArgument(name: string, description?: string): Argument; export const program: Command; node_modules/commander/typings/esm.d.mts 0000664 00000000250 15114743311 0014415 0 ustar 00 // Just reexport the types from cjs // This is a bit indirect. There is not an index.js, but TypeScript will look for index.d.ts for types. export * from './index.js'; node_modules/commander/lib/command.js 0000664 00000211501 15114743311 0013712 0 ustar 00 const EventEmitter = require('events').EventEmitter; const childProcess = require('child_process'); const path = require('path'); const fs = require('fs'); const process = require('process'); const { Argument, humanReadableArgName } = require('./argument.js'); const { CommanderError } = require('./error.js'); const { Help } = require('./help.js'); const { Option, splitOptionFlags, DualOptions } = require('./option.js'); const { suggestSimilar } = require('./suggestSimilar'); // @ts-check class Command extends EventEmitter { /** * Initialize a new `Command`. * * @param {string} [name] */ constructor(name) { super(); /** @type {Command[]} */ this.commands = []; /** @type {Option[]} */ this.options = []; this.parent = null; this._allowUnknownOption = false; this._allowExcessArguments = true; /** @type {Argument[]} */ this._args = []; /** @type {string[]} */ this.args = []; // cli args with options removed this.rawArgs = []; this.processedArgs = []; // like .args but after custom processing and collecting variadic this._scriptPath = null; this._name = name || ''; this._optionValues = {}; this._optionValueSources = {}; // default, env, cli etc this._storeOptionsAsProperties = false; this._actionHandler = null; this._executableHandler = false; this._executableFile = null; // custom name for executable this._executableDir = null; // custom search directory for subcommands this._defaultCommandName = null; this._exitCallback = null; this._aliases = []; this._combineFlagAndOptionalValue = true; this._description = ''; this._summary = ''; this._argsDescription = undefined; // legacy this._enablePositionalOptions = false; this._passThroughOptions = false; this._lifeCycleHooks = {}; // a hash of arrays /** @type {boolean | string} */ this._showHelpAfterError = false; this._showSuggestionAfterError = true; // see .configureOutput() for docs this._outputConfiguration = { writeOut: (str) => process.stdout.write(str), writeErr: (str) => process.stderr.write(str), getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined, getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined, outputError: (str, write) => write(str) }; this._hidden = false; this._hasHelpOption = true; this._helpFlags = '-h, --help'; this._helpDescription = 'display help for command'; this._helpShortFlag = '-h'; this._helpLongFlag = '--help'; this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false this._helpCommandName = 'help'; this._helpCommandnameAndArgs = 'help [command]'; this._helpCommandDescription = 'display help for command'; this._helpConfiguration = {}; } /** * Copy settings that are useful to have in common across root command and subcommands. * * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) * * @param {Command} sourceCommand * @return {Command} `this` command for chaining */ copyInheritedSettings(sourceCommand) { this._outputConfiguration = sourceCommand._outputConfiguration; this._hasHelpOption = sourceCommand._hasHelpOption; this._helpFlags = sourceCommand._helpFlags; this._helpDescription = sourceCommand._helpDescription; this._helpShortFlag = sourceCommand._helpShortFlag; this._helpLongFlag = sourceCommand._helpLongFlag; this._helpCommandName = sourceCommand._helpCommandName; this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs; this._helpCommandDescription = sourceCommand._helpCommandDescription; this._helpConfiguration = sourceCommand._helpConfiguration; this._exitCallback = sourceCommand._exitCallback; this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties; this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue; this._allowExcessArguments = sourceCommand._allowExcessArguments; this._enablePositionalOptions = sourceCommand._enablePositionalOptions; this._showHelpAfterError = sourceCommand._showHelpAfterError; this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError; return this; } /** * Define a command. * * There are two styles of command: pay attention to where to put the description. * * @example * // Command implemented using action handler (description is supplied separately to `.command`) * program * .command('clone <source> [destination]') * .description('clone a repository into a newly created directory') * .action((source, destination) => { * console.log('clone command called'); * }); * * // Command implemented using separate executable file (description is second parameter to `.command`) * program * .command('start <service>', 'start named service') * .command('stop [service]', 'stop named service, or all if no name supplied'); * * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...` * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) * @param {Object} [execOpts] - configuration options (for executable) * @return {Command} returns new command for action handler, or `this` for executable command */ command(nameAndArgs, actionOptsOrExecDesc, execOpts) { let desc = actionOptsOrExecDesc; let opts = execOpts; if (typeof desc === 'object' && desc !== null) { opts = desc; desc = null; } opts = opts || {}; const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/); const cmd = this.createCommand(name); if (desc) { cmd.description(desc); cmd._executableHandler = true; } if (opts.isDefault) this._defaultCommandName = cmd._name; cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor if (args) cmd.arguments(args); this.commands.push(cmd); cmd.parent = this; cmd.copyInheritedSettings(this); if (desc) return this; return cmd; } /** * Factory routine to create a new unattached command. * * See .command() for creating an attached subcommand, which uses this routine to * create the command. You can override createCommand to customise subcommands. * * @param {string} [name] * @return {Command} new command */ createCommand(name) { return new Command(name); } /** * You can customise the help with a subclass of Help by overriding createHelp, * or by overriding Help properties using configureHelp(). * * @return {Help} */ createHelp() { return Object.assign(new Help(), this.configureHelp()); } /** * You can customise the help by overriding Help properties using configureHelp(), * or with a subclass of Help by overriding createHelp(). * * @param {Object} [configuration] - configuration options * @return {Command|Object} `this` command for chaining, or stored configuration */ configureHelp(configuration) { if (configuration === undefined) return this._helpConfiguration; this._helpConfiguration = configuration; return this; } /** * The default output goes to stdout and stderr. You can customise this for special * applications. You can also customise the display of errors by overriding outputError. * * The configuration properties are all functions: * * // functions to change where being written, stdout and stderr * writeOut(str) * writeErr(str) * // matching functions to specify width for wrapping help * getOutHelpWidth() * getErrHelpWidth() * // functions based on what is being written out * outputError(str, write) // used for displaying errors, and not used for displaying help * * @param {Object} [configuration] - configuration options * @return {Command|Object} `this` command for chaining, or stored configuration */ configureOutput(configuration) { if (configuration === undefined) return this._outputConfiguration; Object.assign(this._outputConfiguration, configuration); return this; } /** * Display the help or a custom message after an error occurs. * * @param {boolean|string} [displayHelp] * @return {Command} `this` command for chaining */ showHelpAfterError(displayHelp = true) { if (typeof displayHelp !== 'string') displayHelp = !!displayHelp; this._showHelpAfterError = displayHelp; return this; } /** * Display suggestion of similar commands for unknown commands, or options for unknown options. * * @param {boolean} [displaySuggestion] * @return {Command} `this` command for chaining */ showSuggestionAfterError(displaySuggestion = true) { this._showSuggestionAfterError = !!displaySuggestion; return this; } /** * Add a prepared subcommand. * * See .command() for creating an attached subcommand which inherits settings from its parent. * * @param {Command} cmd - new subcommand * @param {Object} [opts] - configuration options * @return {Command} `this` command for chaining */ addCommand(cmd, opts) { if (!cmd._name) { throw new Error(`Command passed to .addCommand() must have a name - specify the name in Command constructor or using .name()`); } opts = opts || {}; if (opts.isDefault) this._defaultCommandName = cmd._name; if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation this.commands.push(cmd); cmd.parent = this; return this; } /** * Factory routine to create a new unattached argument. * * See .argument() for creating an attached argument, which uses this routine to * create the argument. You can override createArgument to return a custom argument. * * @param {string} name * @param {string} [description] * @return {Argument} new argument */ createArgument(name, description) { return new Argument(name, description); } /** * Define argument syntax for command. * * The default is that the argument is required, and you can explicitly * indicate this with <> around the name. Put [] around the name for an optional argument. * * @example * program.argument('<input-file>'); * program.argument('[output-file]'); * * @param {string} name * @param {string} [description] * @param {Function|*} [fn] - custom argument processing function * @param {*} [defaultValue] * @return {Command} `this` command for chaining */ argument(name, description, fn, defaultValue) { const argument = this.createArgument(name, description); if (typeof fn === 'function') { argument.default(defaultValue).argParser(fn); } else { argument.default(fn); } this.addArgument(argument); return this; } /** * Define argument syntax for command, adding multiple at once (without descriptions). * * See also .argument(). * * @example * program.arguments('<cmd> [env]'); * * @param {string} names * @return {Command} `this` command for chaining */ arguments(names) { names.trim().split(/ +/).forEach((detail) => { this.argument(detail); }); return this; } /** * Define argument syntax for command, adding a prepared argument. * * @param {Argument} argument * @return {Command} `this` command for chaining */ addArgument(argument) { const previousArgument = this._args.slice(-1)[0]; if (previousArgument && previousArgument.variadic) { throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`); } if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) { throw new Error(`a default value for a required argument is never used: '${argument.name()}'`); } this._args.push(argument); return this; } /** * Override default decision whether to add implicit help command. * * addHelpCommand() // force on * addHelpCommand(false); // force off * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details * * @return {Command} `this` command for chaining */ addHelpCommand(enableOrNameAndArgs, description) { if (enableOrNameAndArgs === false) { this._addImplicitHelpCommand = false; } else { this._addImplicitHelpCommand = true; if (typeof enableOrNameAndArgs === 'string') { this._helpCommandName = enableOrNameAndArgs.split(' ')[0]; this._helpCommandnameAndArgs = enableOrNameAndArgs; } this._helpCommandDescription = description || this._helpCommandDescription; } return this; } /** * @return {boolean} * @api private */ _hasImplicitHelpCommand() { if (this._addImplicitHelpCommand === undefined) { return this.commands.length && !this._actionHandler && !this._findCommand('help'); } return this._addImplicitHelpCommand; } /** * Add hook for life cycle event. * * @param {string} event * @param {Function} listener * @return {Command} `this` command for chaining */ hook(event, listener) { const allowedValues = ['preSubcommand', 'preAction', 'postAction']; if (!allowedValues.includes(event)) { throw new Error(`Unexpected value for event passed to hook : '${event}'. Expecting one of '${allowedValues.join("', '")}'`); } if (this._lifeCycleHooks[event]) { this._lifeCycleHooks[event].push(listener); } else { this._lifeCycleHooks[event] = [listener]; } return this; } /** * Register callback to use as replacement for calling process.exit. * * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing * @return {Command} `this` command for chaining */ exitOverride(fn) { if (fn) { this._exitCallback = fn; } else { this._exitCallback = (err) => { if (err.code !== 'commander.executeSubCommandAsync') { throw err; } else { // Async callback from spawn events, not useful to throw. } }; } return this; } /** * Call process.exit, and _exitCallback if defined. * * @param {number} exitCode exit code for using with process.exit * @param {string} code an id string representing the error * @param {string} message human-readable description of the error * @return never * @api private */ _exit(exitCode, code, message) { if (this._exitCallback) { this._exitCallback(new CommanderError(exitCode, code, message)); // Expecting this line is not reached. } process.exit(exitCode); } /** * Register callback `fn` for the command. * * @example * program * .command('serve') * .description('start service') * .action(function() { * // do work here * }); * * @param {Function} fn * @return {Command} `this` command for chaining */ action(fn) { const listener = (args) => { // The .action callback takes an extra parameter which is the command or options. const expectedArgsCount = this._args.length; const actionArgs = args.slice(0, expectedArgsCount); if (this._storeOptionsAsProperties) { actionArgs[expectedArgsCount] = this; // backwards compatible "options" } else { actionArgs[expectedArgsCount] = this.opts(); } actionArgs.push(this); return fn.apply(this, actionArgs); }; this._actionHandler = listener; return this; } /** * Factory routine to create a new unattached option. * * See .option() for creating an attached option, which uses this routine to * create the option. You can override createOption to return a custom option. * * @param {string} flags * @param {string} [description] * @return {Option} new option */ createOption(flags, description) { return new Option(flags, description); } /** * Add an option. * * @param {Option} option * @return {Command} `this` command for chaining */ addOption(option) { const oname = option.name(); const name = option.attributeName(); // store default value if (option.negate) { // --no-foo is special and defaults foo to true, unless a --foo option is already defined const positiveLongFlag = option.long.replace(/^--no-/, '--'); if (!this._findOption(positiveLongFlag)) { this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default'); } } else if (option.defaultValue !== undefined) { this.setOptionValueWithSource(name, option.defaultValue, 'default'); } // register the option this.options.push(option); // handler for cli and env supplied values const handleOptionValue = (val, invalidValueMessage, valueSource) => { // val is null for optional option used without an optional-argument. // val is undefined for boolean and negated option. if (val == null && option.presetArg !== undefined) { val = option.presetArg; } // custom processing const oldValue = this.getOptionValue(name); if (val !== null && option.parseArg) { try { val = option.parseArg(val, oldValue); } catch (err) { if (err.code === 'commander.invalidArgument') { const message = `${invalidValueMessage} ${err.message}`; this.error(message, { exitCode: err.exitCode, code: err.code }); } throw err; } } else if (val !== null && option.variadic) { val = option._concatValue(val, oldValue); } // Fill-in appropriate missing values. Long winded but easy to follow. if (val == null) { if (option.negate) { val = false; } else if (option.isBoolean() || option.optional) { val = true; } else { val = ''; // not normal, parseArg might have failed or be a mock function for testing } } this.setOptionValueWithSource(name, val, valueSource); }; this.on('option:' + oname, (val) => { const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`; handleOptionValue(val, invalidValueMessage, 'cli'); }); if (option.envVar) { this.on('optionEnv:' + oname, (val) => { const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`; handleOptionValue(val, invalidValueMessage, 'env'); }); } return this; } /** * Internal implementation shared by .option() and .requiredOption() * * @api private */ _optionEx(config, flags, description, fn, defaultValue) { if (typeof flags === 'object' && flags instanceof Option) { throw new Error('To add an Option object use addOption() instead of option() or requiredOption()'); } const option = this.createOption(flags, description); option.makeOptionMandatory(!!config.mandatory); if (typeof fn === 'function') { option.default(defaultValue).argParser(fn); } else if (fn instanceof RegExp) { // deprecated const regex = fn; fn = (val, def) => { const m = regex.exec(val); return m ? m[0] : def; }; option.default(defaultValue).argParser(fn); } else { option.default(fn); } return this.addOption(option); } /** * Define option with `flags`, `description` and optional * coercion `fn`. * * The `flags` string contains the short and/or long flags, * separated by comma, a pipe or space. The following are all valid * all will output this way when `--help` is used. * * "-p, --pepper" * "-p|--pepper" * "-p --pepper" * * @example * // simple boolean defaulting to undefined * program.option('-p, --pepper', 'add pepper'); * * program.pepper * // => undefined * * --pepper * program.pepper * // => true * * // simple boolean defaulting to true (unless non-negated option is also defined) * program.option('-C, --no-cheese', 'remove cheese'); * * program.cheese * // => true * * --no-cheese * program.cheese * // => false * * // required argument * program.option('-C, --chdir <path>', 'change the working directory'); * * --chdir /tmp * program.chdir * // => "/tmp" * * // optional argument * program.option('-c, --cheese [type]', 'add cheese [marble]'); * * @param {string} flags * @param {string} [description] * @param {Function|*} [fn] - custom option processing function or default value * @param {*} [defaultValue] * @return {Command} `this` command for chaining */ option(flags, description, fn, defaultValue) { return this._optionEx({}, flags, description, fn, defaultValue); } /** * Add a required option which must have a value after parsing. This usually means * the option must be specified on the command line. (Otherwise the same as .option().) * * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. * * @param {string} flags * @param {string} [description] * @param {Function|*} [fn] - custom option processing function or default value * @param {*} [defaultValue] * @return {Command} `this` command for chaining */ requiredOption(flags, description, fn, defaultValue) { return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); } /** * Alter parsing of short flags with optional values. * * @example * // for `.option('-f,--flag [value]'): * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` * * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag. */ combineFlagAndOptionalValue(combine = true) { this._combineFlagAndOptionalValue = !!combine; return this; } /** * Allow unknown options on the command line. * * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown * for unknown options. */ allowUnknownOption(allowUnknown = true) { this._allowUnknownOption = !!allowUnknown; return this; } /** * Allow excess command-arguments on the command line. Pass false to make excess arguments an error. * * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown * for excess arguments. */ allowExcessArguments(allowExcess = true) { this._allowExcessArguments = !!allowExcess; return this; } /** * Enable positional options. Positional means global options are specified before subcommands which lets * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. * The default behaviour is non-positional and global options may appear anywhere on the command line. * * @param {Boolean} [positional=true] */ enablePositionalOptions(positional = true) { this._enablePositionalOptions = !!positional; return this; } /** * Pass through options that come after command-arguments rather than treat them as command-options, * so actual command-options come before command-arguments. Turning this on for a subcommand requires * positional options to have been enabled on the program (parent commands). * The default behaviour is non-positional and options may appear before or after command-arguments. * * @param {Boolean} [passThrough=true] * for unknown options. */ passThroughOptions(passThrough = true) { this._passThroughOptions = !!passThrough; if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) { throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)'); } return this; } /** * Whether to store option values as properties on command object, * or store separately (specify false). In both cases the option values can be accessed using .opts(). * * @param {boolean} [storeAsProperties=true] * @return {Command} `this` command for chaining */ storeOptionsAsProperties(storeAsProperties = true) { this._storeOptionsAsProperties = !!storeAsProperties; if (this.options.length) { throw new Error('call .storeOptionsAsProperties() before adding options'); } return this; } /** * Retrieve option value. * * @param {string} key * @return {Object} value */ getOptionValue(key) { if (this._storeOptionsAsProperties) { return this[key]; } return this._optionValues[key]; } /** * Store option value. * * @param {string} key * @param {Object} value * @return {Command} `this` command for chaining */ setOptionValue(key, value) { return this.setOptionValueWithSource(key, value, undefined); } /** * Store option value and where the value came from. * * @param {string} key * @param {Object} value * @param {string} source - expected values are default/config/env/cli/implied * @return {Command} `this` command for chaining */ setOptionValueWithSource(key, value, source) { if (this._storeOptionsAsProperties) { this[key] = value; } else { this._optionValues[key] = value; } this._optionValueSources[key] = source; return this; } /** * Get source of option value. * Expected values are default | config | env | cli | implied * * @param {string} key * @return {string} */ getOptionValueSource(key) { return this._optionValueSources[key]; } /** * Get source of option value. See also .optsWithGlobals(). * Expected values are default | config | env | cli | implied * * @param {string} key * @return {string} */ getOptionValueSourceWithGlobals(key) { // global overwrites local, like optsWithGlobals let source; getCommandAndParents(this).forEach((cmd) => { if (cmd.getOptionValueSource(key) !== undefined) { source = cmd.getOptionValueSource(key); } }); return source; } /** * Get user arguments from implied or explicit arguments. * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches. * * @api private */ _prepareUserArgs(argv, parseOptions) { if (argv !== undefined && !Array.isArray(argv)) { throw new Error('first parameter to parse must be array or undefined'); } parseOptions = parseOptions || {}; // Default to using process.argv if (argv === undefined) { argv = process.argv; // @ts-ignore: unknown property if (process.versions && process.versions.electron) { parseOptions.from = 'electron'; } } this.rawArgs = argv.slice(); // make it a little easier for callers by supporting various argv conventions let userArgs; switch (parseOptions.from) { case undefined: case 'node': this._scriptPath = argv[1]; userArgs = argv.slice(2); break; case 'electron': // @ts-ignore: unknown property if (process.defaultApp) { this._scriptPath = argv[1]; userArgs = argv.slice(2); } else { userArgs = argv.slice(1); } break; case 'user': userArgs = argv.slice(0); break; default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`); } // Find default name for program from arguments. if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath); this._name = this._name || 'program'; return userArgs; } /** * Parse `argv`, setting options and invoking commands when defined. * * The default expectation is that the arguments are from node and have the application as argv[0] * and the script being run in argv[1], with user parameters after that. * * @example * program.parse(process.argv); * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] * * @param {string[]} [argv] - optional, defaults to process.argv * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' * @return {Command} `this` command for chaining */ parse(argv, parseOptions) { const userArgs = this._prepareUserArgs(argv, parseOptions); this._parseCommand([], userArgs); return this; } /** * Parse `argv`, setting options and invoking commands when defined. * * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. * * The default expectation is that the arguments are from node and have the application as argv[0] * and the script being run in argv[1], with user parameters after that. * * @example * await program.parseAsync(process.argv); * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] * * @param {string[]} [argv] * @param {Object} [parseOptions] * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' * @return {Promise} */ async parseAsync(argv, parseOptions) { const userArgs = this._prepareUserArgs(argv, parseOptions); await this._parseCommand([], userArgs); return this; } /** * Execute a sub-command executable. * * @api private */ _executeSubCommand(subcommand, args) { args = args.slice(); let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows. const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs']; function findFile(baseDir, baseName) { // Look for specified file const localBin = path.resolve(baseDir, baseName); if (fs.existsSync(localBin)) return localBin; // Stop looking if candidate already has an expected extension. if (sourceExt.includes(path.extname(baseName))) return undefined; // Try all the extensions. const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`)); if (foundExt) return `${localBin}${foundExt}`; return undefined; } // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. this._checkForMissingMandatoryOptions(); this._checkForConflictingOptions(); // executableFile and executableDir might be full path, or just a name let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`; let executableDir = this._executableDir || ''; if (this._scriptPath) { let resolvedScriptPath; // resolve possible symlink for installed npm binary try { resolvedScriptPath = fs.realpathSync(this._scriptPath); } catch (err) { resolvedScriptPath = this._scriptPath; } executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir); } // Look for a local file in preference to a command in PATH. if (executableDir) { let localFile = findFile(executableDir, executableFile); // Legacy search using prefix of script name instead of command name if (!localFile && !subcommand._executableFile && this._scriptPath) { const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath)); if (legacyName !== this._name) { localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`); } } executableFile = localFile || executableFile; } launchWithNode = sourceExt.includes(path.extname(executableFile)); let proc; if (process.platform !== 'win32') { if (launchWithNode) { args.unshift(executableFile); // add executable arguments to spawn args = incrementNodeInspectorPort(process.execArgv).concat(args); proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' }); } else { proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' }); } } else { args.unshift(executableFile); // add executable arguments to spawn args = incrementNodeInspectorPort(process.execArgv).concat(args); proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' }); } if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; signals.forEach((signal) => { // @ts-ignore process.on(signal, () => { if (proc.killed === false && proc.exitCode === null) { proc.kill(signal); } }); }); } // By default terminate process when spawned process terminates. // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running! const exitCallback = this._exitCallback; if (!exitCallback) { proc.on('close', process.exit.bind(process)); } else { proc.on('close', () => { exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)')); }); } proc.on('error', (err) => { // @ts-ignore if (err.code === 'ENOENT') { const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory'; const executableMissing = `'${executableFile}' does not exist - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead - if the default executable name is not suitable, use the executableFile option to supply a custom name or path - ${executableDirMessage}`; throw new Error(executableMissing); // @ts-ignore } else if (err.code === 'EACCES') { throw new Error(`'${executableFile}' not executable`); } if (!exitCallback) { process.exit(1); } else { const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); wrappedError.nestedError = err; exitCallback(wrappedError); } }); // Store the reference to the child process this.runningCommand = proc; } /** * @api private */ _dispatchSubcommand(commandName, operands, unknown) { const subCommand = this._findCommand(commandName); if (!subCommand) this.help({ error: true }); let hookResult; hookResult = this._chainOrCallSubCommandHook(hookResult, subCommand, 'preSubcommand'); hookResult = this._chainOrCall(hookResult, () => { if (subCommand._executableHandler) { this._executeSubCommand(subCommand, operands.concat(unknown)); } else { return subCommand._parseCommand(operands, unknown); } }); return hookResult; } /** * Invoke help directly if possible, or dispatch if necessary. * e.g. help foo * * @api private */ _dispatchHelpCommand(subcommandName) { if (!subcommandName) { this.help(); } const subCommand = this._findCommand(subcommandName); if (subCommand && !subCommand._executableHandler) { subCommand.help(); } // Fallback to parsing the help flag to invoke the help. return this._dispatchSubcommand(subcommandName, [], [this._helpLongFlag]); } /** * Check this.args against expected this._args. * * @api private */ _checkNumberOfArguments() { // too few this._args.forEach((arg, i) => { if (arg.required && this.args[i] == null) { this.missingArgument(arg.name()); } }); // too many if (this._args.length > 0 && this._args[this._args.length - 1].variadic) { return; } if (this.args.length > this._args.length) { this._excessArguments(this.args); } } /** * Process this.args using this._args and save as this.processedArgs! * * @api private */ _processArguments() { const myParseArg = (argument, value, previous) => { // Extra processing for nice error message on parsing failure. let parsedValue = value; if (value !== null && argument.parseArg) { try { parsedValue = argument.parseArg(value, previous); } catch (err) { if (err.code === 'commander.invalidArgument') { const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`; this.error(message, { exitCode: err.exitCode, code: err.code }); } throw err; } } return parsedValue; }; this._checkNumberOfArguments(); const processedArgs = []; this._args.forEach((declaredArg, index) => { let value = declaredArg.defaultValue; if (declaredArg.variadic) { // Collect together remaining arguments for passing together as an array. if (index < this.args.length) { value = this.args.slice(index); if (declaredArg.parseArg) { value = value.reduce((processed, v) => { return myParseArg(declaredArg, v, processed); }, declaredArg.defaultValue); } } else if (value === undefined) { value = []; } } else if (index < this.args.length) { value = this.args[index]; if (declaredArg.parseArg) { value = myParseArg(declaredArg, value, declaredArg.defaultValue); } } processedArgs[index] = value; }); this.processedArgs = processedArgs; } /** * Once we have a promise we chain, but call synchronously until then. * * @param {Promise|undefined} promise * @param {Function} fn * @return {Promise|undefined} * @api private */ _chainOrCall(promise, fn) { // thenable if (promise && promise.then && typeof promise.then === 'function') { // already have a promise, chain callback return promise.then(() => fn()); } // callback might return a promise return fn(); } /** * * @param {Promise|undefined} promise * @param {string} event * @return {Promise|undefined} * @api private */ _chainOrCallHooks(promise, event) { let result = promise; const hooks = []; getCommandAndParents(this) .reverse() .filter(cmd => cmd._lifeCycleHooks[event] !== undefined) .forEach(hookedCommand => { hookedCommand._lifeCycleHooks[event].forEach((callback) => { hooks.push({ hookedCommand, callback }); }); }); if (event === 'postAction') { hooks.reverse(); } hooks.forEach((hookDetail) => { result = this._chainOrCall(result, () => { return hookDetail.callback(hookDetail.hookedCommand, this); }); }); return result; } /** * * @param {Promise|undefined} promise * @param {Command} subCommand * @param {string} event * @return {Promise|undefined} * @api private */ _chainOrCallSubCommandHook(promise, subCommand, event) { let result = promise; if (this._lifeCycleHooks[event] !== undefined) { this._lifeCycleHooks[event].forEach((hook) => { result = this._chainOrCall(result, () => { return hook(this, subCommand); }); }); } return result; } /** * Process arguments in context of this command. * Returns action result, in case it is a promise. * * @api private */ _parseCommand(operands, unknown) { const parsed = this.parseOptions(unknown); this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env this._parseOptionsImplied(); operands = operands.concat(parsed.operands); unknown = parsed.unknown; this.args = operands.concat(unknown); if (operands && this._findCommand(operands[0])) { return this._dispatchSubcommand(operands[0], operands.slice(1), unknown); } if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) { return this._dispatchHelpCommand(operands[1]); } if (this._defaultCommandName) { outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command return this._dispatchSubcommand(this._defaultCommandName, operands, unknown); } if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) { // probably missing subcommand and no handler, user needs help (and exit) this.help({ error: true }); } outputHelpIfRequested(this, parsed.unknown); this._checkForMissingMandatoryOptions(); this._checkForConflictingOptions(); // We do not always call this check to avoid masking a "better" error, like unknown command. const checkForUnknownOptions = () => { if (parsed.unknown.length > 0) { this.unknownOption(parsed.unknown[0]); } }; const commandEvent = `command:${this.name()}`; if (this._actionHandler) { checkForUnknownOptions(); this._processArguments(); let actionResult; actionResult = this._chainOrCallHooks(actionResult, 'preAction'); actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs)); if (this.parent) { actionResult = this._chainOrCall(actionResult, () => { this.parent.emit(commandEvent, operands, unknown); // legacy }); } actionResult = this._chainOrCallHooks(actionResult, 'postAction'); return actionResult; } if (this.parent && this.parent.listenerCount(commandEvent)) { checkForUnknownOptions(); this._processArguments(); this.parent.emit(commandEvent, operands, unknown); // legacy } else if (operands.length) { if (this._findCommand('*')) { // legacy default command return this._dispatchSubcommand('*', operands, unknown); } if (this.listenerCount('command:*')) { // skip option check, emit event for possible misspelling suggestion this.emit('command:*', operands, unknown); } else if (this.commands.length) { this.unknownCommand(); } else { checkForUnknownOptions(); this._processArguments(); } } else if (this.commands.length) { checkForUnknownOptions(); // This command has subcommands and nothing hooked up at this level, so display help (and exit). this.help({ error: true }); } else { checkForUnknownOptions(); this._processArguments(); // fall through for caller to handle after calling .parse() } } /** * Find matching command. * * @api private */ _findCommand(name) { if (!name) return undefined; return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name)); } /** * Return an option matching `arg` if any. * * @param {string} arg * @return {Option} * @api private */ _findOption(arg) { return this.options.find(option => option.is(arg)); } /** * Display an error message if a mandatory option does not have a value. * Called after checking for help flags in leaf subcommand. * * @api private */ _checkForMissingMandatoryOptions() { // Walk up hierarchy so can call in subcommand after checking for displaying help. for (let cmd = this; cmd; cmd = cmd.parent) { cmd.options.forEach((anOption) => { if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) { cmd.missingMandatoryOptionValue(anOption); } }); } } /** * Display an error message if conflicting options are used together in this. * * @api private */ _checkForConflictingLocalOptions() { const definedNonDefaultOptions = this.options.filter( (option) => { const optionKey = option.attributeName(); if (this.getOptionValue(optionKey) === undefined) { return false; } return this.getOptionValueSource(optionKey) !== 'default'; } ); const optionsWithConflicting = definedNonDefaultOptions.filter( (option) => option.conflictsWith.length > 0 ); optionsWithConflicting.forEach((option) => { const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()) ); if (conflictingAndDefined) { this._conflictingOption(option, conflictingAndDefined); } }); } /** * Display an error message if conflicting options are used together. * Called after checking for help flags in leaf subcommand. * * @api private */ _checkForConflictingOptions() { // Walk up hierarchy so can call in subcommand after checking for displaying help. for (let cmd = this; cmd; cmd = cmd.parent) { cmd._checkForConflictingLocalOptions(); } } /** * Parse options from `argv` removing known options, * and return argv split into operands and unknown arguments. * * Examples: * * argv => operands, unknown * --known kkk op => [op], [] * op --known kkk => [op], [] * sub --unknown uuu op => [sub], [--unknown uuu op] * sub -- --unknown uuu op => [sub --unknown uuu op], [] * * @param {String[]} argv * @return {{operands: String[], unknown: String[]}} */ parseOptions(argv) { const operands = []; // operands, not options or values const unknown = []; // first unknown option and remaining unknown args let dest = operands; const args = argv.slice(); function maybeOption(arg) { return arg.length > 1 && arg[0] === '-'; } // parse options let activeVariadicOption = null; while (args.length) { const arg = args.shift(); // literal if (arg === '--') { if (dest === unknown) dest.push(arg); dest.push(...args); break; } if (activeVariadicOption && !maybeOption(arg)) { this.emit(`option:${activeVariadicOption.name()}`, arg); continue; } activeVariadicOption = null; if (maybeOption(arg)) { const option = this._findOption(arg); // recognised option, call listener to assign value with possible custom processing if (option) { if (option.required) { const value = args.shift(); if (value === undefined) this.optionMissingArgument(option); this.emit(`option:${option.name()}`, value); } else if (option.optional) { let value = null; // historical behaviour is optional value is following arg unless an option if (args.length > 0 && !maybeOption(args[0])) { value = args.shift(); } this.emit(`option:${option.name()}`, value); } else { // boolean flag this.emit(`option:${option.name()}`); } activeVariadicOption = option.variadic ? option : null; continue; } } // Look for combo options following single dash, eat first one if known. if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { const option = this._findOption(`-${arg[1]}`); if (option) { if (option.required || (option.optional && this._combineFlagAndOptionalValue)) { // option with value following in same argument this.emit(`option:${option.name()}`, arg.slice(2)); } else { // boolean option, emit and put back remainder of arg for further processing this.emit(`option:${option.name()}`); args.unshift(`-${arg.slice(2)}`); } continue; } } // Look for known long flag with value, like --foo=bar if (/^--[^=]+=/.test(arg)) { const index = arg.indexOf('='); const option = this._findOption(arg.slice(0, index)); if (option && (option.required || option.optional)) { this.emit(`option:${option.name()}`, arg.slice(index + 1)); continue; } } // Not a recognised option by this command. // Might be a command-argument, or subcommand option, or unknown option, or help command or option. // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands. if (maybeOption(arg)) { dest = unknown; } // If using positionalOptions, stop processing our options at subcommand. if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) { if (this._findCommand(arg)) { operands.push(arg); if (args.length > 0) unknown.push(...args); break; } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) { operands.push(arg); if (args.length > 0) operands.push(...args); break; } else if (this._defaultCommandName) { unknown.push(arg); if (args.length > 0) unknown.push(...args); break; } } // If using passThroughOptions, stop processing options at first command-argument. if (this._passThroughOptions) { dest.push(arg); if (args.length > 0) dest.push(...args); break; } // add arg dest.push(arg); } return { operands, unknown }; } /** * Return an object containing local option values as key-value pairs. * * @return {Object} */ opts() { if (this._storeOptionsAsProperties) { // Preserve original behaviour so backwards compatible when still using properties const result = {}; const len = this.options.length; for (let i = 0; i < len; i++) { const key = this.options[i].attributeName(); result[key] = key === this._versionOptionName ? this._version : this[key]; } return result; } return this._optionValues; } /** * Return an object containing merged local and global option values as key-value pairs. * * @return {Object} */ optsWithGlobals() { // globals overwrite locals return getCommandAndParents(this).reduce( (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {} ); } /** * Display error message and exit (or call exitOverride). * * @param {string} message * @param {Object} [errorOptions] * @param {string} [errorOptions.code] - an id string representing the error * @param {number} [errorOptions.exitCode] - used with process.exit */ error(message, errorOptions) { // output handling this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr); if (typeof this._showHelpAfterError === 'string') { this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`); } else if (this._showHelpAfterError) { this._outputConfiguration.writeErr('\n'); this.outputHelp({ error: true }); } // exit handling const config = errorOptions || {}; const exitCode = config.exitCode || 1; const code = config.code || 'commander.error'; this._exit(exitCode, code, message); } /** * Apply any option related environment variables, if option does * not have a value from cli or client code. * * @api private */ _parseOptionsEnv() { this.options.forEach((option) => { if (option.envVar && option.envVar in process.env) { const optionKey = option.attributeName(); // Priority check. Do not overwrite cli or options from unknown source (client-code). if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) { if (option.required || option.optional) { // option can take a value // keep very simple, optional always takes value this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]); } else { // boolean // keep very simple, only care that envVar defined and not the value this.emit(`optionEnv:${option.name()}`); } } } }); } /** * Apply any implied option values, if option is undefined or default value. * * @api private */ _parseOptionsImplied() { const dualHelper = new DualOptions(this.options); const hasCustomOptionValue = (optionKey) => { return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey)); }; this.options .filter(option => (option.implied !== undefined) && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)) .forEach((option) => { Object.keys(option.implied) .filter(impliedKey => !hasCustomOptionValue(impliedKey)) .forEach(impliedKey => { this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied'); }); }); } /** * Argument `name` is missing. * * @param {string} name * @api private */ missingArgument(name) { const message = `error: missing required argument '${name}'`; this.error(message, { code: 'commander.missingArgument' }); } /** * `Option` is missing an argument. * * @param {Option} option * @api private */ optionMissingArgument(option) { const message = `error: option '${option.flags}' argument missing`; this.error(message, { code: 'commander.optionMissingArgument' }); } /** * `Option` does not have a value, and is a mandatory option. * * @param {Option} option * @api private */ missingMandatoryOptionValue(option) { const message = `error: required option '${option.flags}' not specified`; this.error(message, { code: 'commander.missingMandatoryOptionValue' }); } /** * `Option` conflicts with another option. * * @param {Option} option * @param {Option} conflictingOption * @api private */ _conflictingOption(option, conflictingOption) { // The calling code does not know whether a negated option is the source of the // value, so do some work to take an educated guess. const findBestOptionFromValue = (option) => { const optionKey = option.attributeName(); const optionValue = this.getOptionValue(optionKey); const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName()); const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName()); if (negativeOption && ( (negativeOption.presetArg === undefined && optionValue === false) || (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg) )) { return negativeOption; } return positiveOption || option; }; const getErrorMessage = (option) => { const bestOption = findBestOptionFromValue(option); const optionKey = bestOption.attributeName(); const source = this.getOptionValueSource(optionKey); if (source === 'env') { return `environment variable '${bestOption.envVar}'`; } return `option '${bestOption.flags}'`; }; const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`; this.error(message, { code: 'commander.conflictingOption' }); } /** * Unknown option `flag`. * * @param {string} flag * @api private */ unknownOption(flag) { if (this._allowUnknownOption) return; let suggestion = ''; if (flag.startsWith('--') && this._showSuggestionAfterError) { // Looping to pick up the global options too let candidateFlags = []; let command = this; do { const moreFlags = command.createHelp().visibleOptions(command) .filter(option => option.long) .map(option => option.long); candidateFlags = candidateFlags.concat(moreFlags); command = command.parent; } while (command && !command._enablePositionalOptions); suggestion = suggestSimilar(flag, candidateFlags); } const message = `error: unknown option '${flag}'${suggestion}`; this.error(message, { code: 'commander.unknownOption' }); } /** * Excess arguments, more than expected. * * @param {string[]} receivedArgs * @api private */ _excessArguments(receivedArgs) { if (this._allowExcessArguments) return; const expected = this._args.length; const s = (expected === 1) ? '' : 's'; const forSubcommand = this.parent ? ` for '${this.name()}'` : ''; const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`; this.error(message, { code: 'commander.excessArguments' }); } /** * Unknown command. * * @api private */ unknownCommand() { const unknownName = this.args[0]; let suggestion = ''; if (this._showSuggestionAfterError) { const candidateNames = []; this.createHelp().visibleCommands(this).forEach((command) => { candidateNames.push(command.name()); // just visible alias if (command.alias()) candidateNames.push(command.alias()); }); suggestion = suggestSimilar(unknownName, candidateNames); } const message = `error: unknown command '${unknownName}'${suggestion}`; this.error(message, { code: 'commander.unknownCommand' }); } /** * Set the program version to `str`. * * This method auto-registers the "-V, --version" flag * which will print the version number when passed. * * You can optionally supply the flags and description to override the defaults. * * @param {string} str * @param {string} [flags] * @param {string} [description] * @return {this | string} `this` command for chaining, or version string if no arguments */ version(str, flags, description) { if (str === undefined) return this._version; this._version = str; flags = flags || '-V, --version'; description = description || 'output the version number'; const versionOption = this.createOption(flags, description); this._versionOptionName = versionOption.attributeName(); this.options.push(versionOption); this.on('option:' + versionOption.name(), () => { this._outputConfiguration.writeOut(`${str}\n`); this._exit(0, 'commander.version', str); }); return this; } /** * Set the description. * * @param {string} [str] * @param {Object} [argsDescription] * @return {string|Command} */ description(str, argsDescription) { if (str === undefined && argsDescription === undefined) return this._description; this._description = str; if (argsDescription) { this._argsDescription = argsDescription; } return this; } /** * Set the summary. Used when listed as subcommand of parent. * * @param {string} [str] * @return {string|Command} */ summary(str) { if (str === undefined) return this._summary; this._summary = str; return this; } /** * Set an alias for the command. * * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. * * @param {string} [alias] * @return {string|Command} */ alias(alias) { if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility /** @type {Command} */ let command = this; if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) { // assume adding alias for last added executable subcommand, rather than this command = this.commands[this.commands.length - 1]; } if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); command._aliases.push(alias); return this; } /** * Set aliases for the command. * * Only the first alias is shown in the auto-generated help. * * @param {string[]} [aliases] * @return {string[]|Command} */ aliases(aliases) { // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). if (aliases === undefined) return this._aliases; aliases.forEach((alias) => this.alias(alias)); return this; } /** * Set / get the command usage `str`. * * @param {string} [str] * @return {String|Command} */ usage(str) { if (str === undefined) { if (this._usage) return this._usage; const args = this._args.map((arg) => { return humanReadableArgName(arg); }); return [].concat( (this.options.length || this._hasHelpOption ? '[options]' : []), (this.commands.length ? '[command]' : []), (this._args.length ? args : []) ).join(' '); } this._usage = str; return this; } /** * Get or set the name of the command. * * @param {string} [str] * @return {string|Command} */ name(str) { if (str === undefined) return this._name; this._name = str; return this; } /** * Set the name of the command from script filename, such as process.argv[1], * or require.main.filename, or __filename. * * (Used internally and public although not documented in README.) * * @example * program.nameFromFilename(require.main.filename); * * @param {string} filename * @return {Command} */ nameFromFilename(filename) { this._name = path.basename(filename, path.extname(filename)); return this; } /** * Get or set the directory for searching for executable subcommands of this command. * * @example * program.executableDir(__dirname); * // or * program.executableDir('subcommands'); * * @param {string} [path] * @return {string|Command} */ executableDir(path) { if (path === undefined) return this._executableDir; this._executableDir = path; return this; } /** * Return program help documentation. * * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout * @return {string} */ helpInformation(contextOptions) { const helper = this.createHelp(); if (helper.helpWidth === undefined) { helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth(); } return helper.formatHelp(this, helper); } /** * @api private */ _getHelpContext(contextOptions) { contextOptions = contextOptions || {}; const context = { error: !!contextOptions.error }; let write; if (context.error) { write = (arg) => this._outputConfiguration.writeErr(arg); } else { write = (arg) => this._outputConfiguration.writeOut(arg); } context.write = contextOptions.write || write; context.command = this; return context; } /** * Output help information for this command. * * Outputs built-in help, and custom text added using `.addHelpText()`. * * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout */ outputHelp(contextOptions) { let deprecatedCallback; if (typeof contextOptions === 'function') { deprecatedCallback = contextOptions; contextOptions = undefined; } const context = this._getHelpContext(contextOptions); getCommandAndParents(this).reverse().forEach(command => command.emit('beforeAllHelp', context)); this.emit('beforeHelp', context); let helpInformation = this.helpInformation(context); if (deprecatedCallback) { helpInformation = deprecatedCallback(helpInformation); if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) { throw new Error('outputHelp callback must return a string or a Buffer'); } } context.write(helpInformation); this.emit(this._helpLongFlag); // deprecated this.emit('afterHelp', context); getCommandAndParents(this).forEach(command => command.emit('afterAllHelp', context)); } /** * You can pass in flags and a description to override the help * flags and help description for your command. Pass in false to * disable the built-in help option. * * @param {string | boolean} [flags] * @param {string} [description] * @return {Command} `this` command for chaining */ helpOption(flags, description) { if (typeof flags === 'boolean') { this._hasHelpOption = flags; return this; } this._helpFlags = flags || this._helpFlags; this._helpDescription = description || this._helpDescription; const helpFlags = splitOptionFlags(this._helpFlags); this._helpShortFlag = helpFlags.shortFlag; this._helpLongFlag = helpFlags.longFlag; return this; } /** * Output help information and exit. * * Outputs built-in help, and custom text added using `.addHelpText()`. * * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout */ help(contextOptions) { this.outputHelp(contextOptions); let exitCode = process.exitCode || 0; if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) { exitCode = 1; } // message: do not have all displayed text available so only passing placeholder. this._exit(exitCode, 'commander.help', '(outputHelp)'); } /** * Add additional text to be displayed with the built-in help. * * Position is 'before' or 'after' to affect just this command, * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands. * * @param {string} position - before or after built-in help * @param {string | Function} text - string to add, or a function returning a string * @return {Command} `this` command for chaining */ addHelpText(position, text) { const allowedValues = ['beforeAll', 'before', 'after', 'afterAll']; if (!allowedValues.includes(position)) { throw new Error(`Unexpected value for position to addHelpText. Expecting one of '${allowedValues.join("', '")}'`); } const helpEvent = `${position}Help`; this.on(helpEvent, (context) => { let helpStr; if (typeof text === 'function') { helpStr = text({ error: context.error, command: context.command }); } else { helpStr = text; } // Ignore falsy value when nothing to output. if (helpStr) { context.write(`${helpStr}\n`); } }); return this; } } /** * Output help information if help flags specified * * @param {Command} cmd - command to output help for * @param {Array} args - array of options to search for help flags * @api private */ function outputHelpIfRequested(cmd, args) { const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag); if (helpOption) { cmd.outputHelp(); // (Do not have all displayed text available so only passing placeholder.) cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); } } /** * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). * * @param {string[]} args - array of arguments from node.execArgv * @returns {string[]} * @api private */ function incrementNodeInspectorPort(args) { // Testing for these options: // --inspect[=[host:]port] // --inspect-brk[=[host:]port] // --inspect-port=[host:]port return args.map((arg) => { if (!arg.startsWith('--inspect')) { return arg; } let debugOption; let debugHost = '127.0.0.1'; let debugPort = '9229'; let match; if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { // e.g. --inspect debugOption = match[1]; } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { debugOption = match[1]; if (/^\d+$/.test(match[3])) { // e.g. --inspect=1234 debugPort = match[3]; } else { // e.g. --inspect=localhost debugHost = match[3]; } } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { // e.g. --inspect=localhost:1234 debugOption = match[1]; debugHost = match[3]; debugPort = match[4]; } if (debugOption && debugPort !== '0') { return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; } return arg; }); } /** * @param {Command} startCommand * @returns {Command[]} * @api private */ function getCommandAndParents(startCommand) { const result = []; for (let command = startCommand; command; command = command.parent) { result.push(command); } return result; } exports.Command = Command; node_modules/commander/lib/argument.js 0000664 00000006146 15114743311 0014125 0 ustar 00 const { InvalidArgumentError } = require('./error.js'); // @ts-check class Argument { /** * Initialize a new command argument with the given name and description. * The default is that the argument is required, and you can explicitly * indicate this with <> around the name. Put [] around the name for an optional argument. * * @param {string} name * @param {string} [description] */ constructor(name, description) { this.description = description || ''; this.variadic = false; this.parseArg = undefined; this.defaultValue = undefined; this.defaultValueDescription = undefined; this.argChoices = undefined; switch (name[0]) { case '<': // e.g. <required> this.required = true; this._name = name.slice(1, -1); break; case '[': // e.g. [optional] this.required = false; this._name = name.slice(1, -1); break; default: this.required = true; this._name = name; break; } if (this._name.length > 3 && this._name.slice(-3) === '...') { this.variadic = true; this._name = this._name.slice(0, -3); } } /** * Return argument name. * * @return {string} */ name() { return this._name; } /** * @api private */ _concatValue(value, previous) { if (previous === this.defaultValue || !Array.isArray(previous)) { return [value]; } return previous.concat(value); } /** * Set the default value, and optionally supply the description to be displayed in the help. * * @param {any} value * @param {string} [description] * @return {Argument} */ default(value, description) { this.defaultValue = value; this.defaultValueDescription = description; return this; } /** * Set the custom handler for processing CLI command arguments into argument values. * * @param {Function} [fn] * @return {Argument} */ argParser(fn) { this.parseArg = fn; return this; } /** * Only allow argument value to be one of choices. * * @param {string[]} values * @return {Argument} */ choices(values) { this.argChoices = values.slice(); this.parseArg = (arg, previous) => { if (!this.argChoices.includes(arg)) { throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`); } if (this.variadic) { return this._concatValue(arg, previous); } return arg; }; return this; } /** * Make argument required. */ argRequired() { this.required = true; return this; } /** * Make argument optional. */ argOptional() { this.required = false; return this; } } /** * Takes an argument and returns its human readable equivalent for help usage. * * @param {Argument} arg * @return {string} * @api private */ function humanReadableArgName(arg) { const nameOutput = arg.name() + (arg.variadic === true ? '...' : ''); return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']'; } exports.Argument = Argument; exports.humanReadableArgName = humanReadableArgName; node_modules/commander/lib/help.js 0000664 00000033711 15114743311 0013231 0 ustar 00 const { humanReadableArgName } = require('./argument.js'); /** * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS` * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types * @typedef { import("./argument.js").Argument } Argument * @typedef { import("./command.js").Command } Command * @typedef { import("./option.js").Option } Option */ // @ts-check // Although this is a class, methods are static in style to allow override using subclass or just functions. class Help { constructor() { this.helpWidth = undefined; this.sortSubcommands = false; this.sortOptions = false; this.showGlobalOptions = false; } /** * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. * * @param {Command} cmd * @returns {Command[]} */ visibleCommands(cmd) { const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden); if (cmd._hasImplicitHelpCommand()) { // Create a command matching the implicit help command. const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/); const helpCommand = cmd.createCommand(helpName) .helpOption(false); helpCommand.description(cmd._helpCommandDescription); if (helpArgs) helpCommand.arguments(helpArgs); visibleCommands.push(helpCommand); } if (this.sortSubcommands) { visibleCommands.sort((a, b) => { // @ts-ignore: overloaded return type return a.name().localeCompare(b.name()); }); } return visibleCommands; } /** * Compare options for sort. * * @param {Option} a * @param {Option} b * @returns number */ compareOptions(a, b) { const getSortKey = (option) => { // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated. return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, ''); }; return getSortKey(a).localeCompare(getSortKey(b)); } /** * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. * * @param {Command} cmd * @returns {Option[]} */ visibleOptions(cmd) { const visibleOptions = cmd.options.filter((option) => !option.hidden); // Implicit help const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag); const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag); if (showShortHelpFlag || showLongHelpFlag) { let helpOption; if (!showShortHelpFlag) { helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription); } else if (!showLongHelpFlag) { helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription); } else { helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription); } visibleOptions.push(helpOption); } if (this.sortOptions) { visibleOptions.sort(this.compareOptions); } return visibleOptions; } /** * Get an array of the visible global options. (Not including help.) * * @param {Command} cmd * @returns {Option[]} */ visibleGlobalOptions(cmd) { if (!this.showGlobalOptions) return []; const globalOptions = []; for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) { const visibleOptions = parentCmd.options.filter((option) => !option.hidden); globalOptions.push(...visibleOptions); } if (this.sortOptions) { globalOptions.sort(this.compareOptions); } return globalOptions; } /** * Get an array of the arguments if any have a description. * * @param {Command} cmd * @returns {Argument[]} */ visibleArguments(cmd) { // Side effect! Apply the legacy descriptions before the arguments are displayed. if (cmd._argsDescription) { cmd._args.forEach(argument => { argument.description = argument.description || cmd._argsDescription[argument.name()] || ''; }); } // If there are any arguments with a description then return all the arguments. if (cmd._args.find(argument => argument.description)) { return cmd._args; } return []; } /** * Get the command term to show in the list of subcommands. * * @param {Command} cmd * @returns {string} */ subcommandTerm(cmd) { // Legacy. Ignores custom usage string, and nested commands. const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' '); return cmd._name + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option (args ? ' ' + args : ''); } /** * Get the option term to show in the list of options. * * @param {Option} option * @returns {string} */ optionTerm(option) { return option.flags; } /** * Get the argument term to show in the list of arguments. * * @param {Argument} argument * @returns {string} */ argumentTerm(argument) { return argument.name(); } /** * Get the longest command term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestSubcommandTermLength(cmd, helper) { return helper.visibleCommands(cmd).reduce((max, command) => { return Math.max(max, helper.subcommandTerm(command).length); }, 0); } /** * Get the longest option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestOptionTermLength(cmd, helper) { return helper.visibleOptions(cmd).reduce((max, option) => { return Math.max(max, helper.optionTerm(option).length); }, 0); } /** * Get the longest global option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestGlobalOptionTermLength(cmd, helper) { return helper.visibleGlobalOptions(cmd).reduce((max, option) => { return Math.max(max, helper.optionTerm(option).length); }, 0); } /** * Get the longest argument term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestArgumentTermLength(cmd, helper) { return helper.visibleArguments(cmd).reduce((max, argument) => { return Math.max(max, helper.argumentTerm(argument).length); }, 0); } /** * Get the command usage to be displayed at the top of the built-in help. * * @param {Command} cmd * @returns {string} */ commandUsage(cmd) { // Usage let cmdName = cmd._name; if (cmd._aliases[0]) { cmdName = cmdName + '|' + cmd._aliases[0]; } let parentCmdNames = ''; for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) { parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; } return parentCmdNames + cmdName + ' ' + cmd.usage(); } /** * Get the description for the command. * * @param {Command} cmd * @returns {string} */ commandDescription(cmd) { // @ts-ignore: overloaded return type return cmd.description(); } /** * Get the subcommand summary to show in the list of subcommands. * (Fallback to description for backwards compatibility.) * * @param {Command} cmd * @returns {string} */ subcommandDescription(cmd) { // @ts-ignore: overloaded return type return cmd.summary() || cmd.description(); } /** * Get the option description to show in the list of options. * * @param {Option} option * @return {string} */ optionDescription(option) { const extraInfo = []; if (option.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`); } if (option.defaultValue !== undefined) { // default for boolean and negated more for programmer than end user, // but show true/false for boolean option as may be for hand-rolled env or config processing. const showDefault = option.required || option.optional || (option.isBoolean() && typeof option.defaultValue === 'boolean'); if (showDefault) { extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`); } } // preset for boolean and negated are more for programmer than end user if (option.presetArg !== undefined && option.optional) { extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`); } if (option.envVar !== undefined) { extraInfo.push(`env: ${option.envVar}`); } if (extraInfo.length > 0) { return `${option.description} (${extraInfo.join(', ')})`; } return option.description; } /** * Get the argument description to show in the list of arguments. * * @param {Argument} argument * @return {string} */ argumentDescription(argument) { const extraInfo = []; if (argument.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`); } if (argument.defaultValue !== undefined) { extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`); } if (extraInfo.length > 0) { const extraDescripton = `(${extraInfo.join(', ')})`; if (argument.description) { return `${argument.description} ${extraDescripton}`; } return extraDescripton; } return argument.description; } /** * Generate the built-in help text. * * @param {Command} cmd * @param {Help} helper * @returns {string} */ formatHelp(cmd, helper) { const termWidth = helper.padWidth(cmd, helper); const helpWidth = helper.helpWidth || 80; const itemIndentWidth = 2; const itemSeparatorWidth = 2; // between term and description function formatItem(term, description) { if (description) { const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`; return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth); } return term; } function formatList(textArray) { return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth)); } // Usage let output = [`Usage: ${helper.commandUsage(cmd)}`, '']; // Description const commandDescription = helper.commandDescription(cmd); if (commandDescription.length > 0) { output = output.concat([helper.wrap(commandDescription, helpWidth, 0), '']); } // Arguments const argumentList = helper.visibleArguments(cmd).map((argument) => { return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument)); }); if (argumentList.length > 0) { output = output.concat(['Arguments:', formatList(argumentList), '']); } // Options const optionList = helper.visibleOptions(cmd).map((option) => { return formatItem(helper.optionTerm(option), helper.optionDescription(option)); }); if (optionList.length > 0) { output = output.concat(['Options:', formatList(optionList), '']); } if (this.showGlobalOptions) { const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => { return formatItem(helper.optionTerm(option), helper.optionDescription(option)); }); if (globalOptionList.length > 0) { output = output.concat(['Global Options:', formatList(globalOptionList), '']); } } // Commands const commandList = helper.visibleCommands(cmd).map((cmd) => { return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd)); }); if (commandList.length > 0) { output = output.concat(['Commands:', formatList(commandList), '']); } return output.join('\n'); } /** * Calculate the pad width from the maximum term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ padWidth(cmd, helper) { return Math.max( helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper) ); } /** * Wrap the given string to width characters per line, with lines after the first indented. * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted. * * @param {string} str * @param {number} width * @param {number} indent * @param {number} [minColumnWidth=40] * @return {string} * */ wrap(str, width, indent, minColumnWidth = 40) { // Full \s characters, minus the linefeeds. const indents = ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff'; // Detect manually wrapped and indented strings by searching for line break followed by spaces. const manualIndent = new RegExp(`[\\n][${indents}]+`); if (str.match(manualIndent)) return str; // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line). const columnWidth = width - indent; if (columnWidth < minColumnWidth) return str; const leadingStr = str.slice(0, indent); const columnText = str.slice(indent).replace('\r\n', '\n'); const indentString = ' '.repeat(indent); const zeroWidthSpace = '\u200B'; const breaks = `\\s${zeroWidthSpace}`; // Match line end (so empty lines don't collapse), // or as much text as will fit in column, or excess text up to first break. const regex = new RegExp(`\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, 'g'); const lines = columnText.match(regex) || []; return leadingStr + lines.map((line, i) => { if (line === '\n') return ''; // preserve empty lines return ((i > 0) ? indentString : '') + line.trimEnd(); }).join('\n'); } } exports.Help = Help; node_modules/commander/lib/suggestSimilar.js 0000664 00000005315 15114743311 0015302 0 ustar 00 const maxDistance = 3; function editDistance(a, b) { // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance // Calculating optimal string alignment distance, no substring is edited more than once. // (Simple implementation.) // Quick early exit, return worst case. if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length); // distance between prefix substrings of a and b const d = []; // pure deletions turn a into empty string for (let i = 0; i <= a.length; i++) { d[i] = [i]; } // pure insertions turn empty string into b for (let j = 0; j <= b.length; j++) { d[0][j] = j; } // fill matrix for (let j = 1; j <= b.length; j++) { for (let i = 1; i <= a.length; i++) { let cost = 1; if (a[i - 1] === b[j - 1]) { cost = 0; } else { cost = 1; } d[i][j] = Math.min( d[i - 1][j] + 1, // deletion d[i][j - 1] + 1, // insertion d[i - 1][j - 1] + cost // substitution ); // transposition if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1); } } } return d[a.length][b.length]; } /** * Find close matches, restricted to same number of edits. * * @param {string} word * @param {string[]} candidates * @returns {string} */ function suggestSimilar(word, candidates) { if (!candidates || candidates.length === 0) return ''; // remove possible duplicates candidates = Array.from(new Set(candidates)); const searchingOptions = word.startsWith('--'); if (searchingOptions) { word = word.slice(2); candidates = candidates.map(candidate => candidate.slice(2)); } let similar = []; let bestDistance = maxDistance; const minSimilarity = 0.4; candidates.forEach((candidate) => { if (candidate.length <= 1) return; // no one character guesses const distance = editDistance(word, candidate); const length = Math.max(word.length, candidate.length); const similarity = (length - distance) / length; if (similarity > minSimilarity) { if (distance < bestDistance) { // better edit distance, throw away previous worse matches bestDistance = distance; similar = [candidate]; } else if (distance === bestDistance) { similar.push(candidate); } } }); similar.sort((a, b) => a.localeCompare(b)); if (searchingOptions) { similar = similar.map(candidate => `--${candidate}`); } if (similar.length > 1) { return `\n(Did you mean one of ${similar.join(', ')}?)`; } if (similar.length === 1) { return `\n(Did you mean ${similar[0]}?)`; } return ''; } exports.suggestSimilar = suggestSimilar; node_modules/commander/lib/option.js 0000664 00000020713 15114743311 0013607 0 ustar 00 const { InvalidArgumentError } = require('./error.js'); // @ts-check class Option { /** * Initialize a new `Option` with the given `flags` and `description`. * * @param {string} flags * @param {string} [description] */ constructor(flags, description) { this.flags = flags; this.description = description || ''; this.required = flags.includes('<'); // A value must be supplied when the option is specified. this.optional = flags.includes('['); // A value is optional when the option is specified. // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. const optionFlags = splitOptionFlags(flags); this.short = optionFlags.shortFlag; this.long = optionFlags.longFlag; this.negate = false; if (this.long) { this.negate = this.long.startsWith('--no-'); } this.defaultValue = undefined; this.defaultValueDescription = undefined; this.presetArg = undefined; this.envVar = undefined; this.parseArg = undefined; this.hidden = false; this.argChoices = undefined; this.conflictsWith = []; this.implied = undefined; } /** * Set the default value, and optionally supply the description to be displayed in the help. * * @param {any} value * @param {string} [description] * @return {Option} */ default(value, description) { this.defaultValue = value; this.defaultValueDescription = description; return this; } /** * Preset to use when option used without option-argument, especially optional but also boolean and negated. * The custom processing (parseArg) is called. * * @example * new Option('--color').default('GREYSCALE').preset('RGB'); * new Option('--donate [amount]').preset('20').argParser(parseFloat); * * @param {any} arg * @return {Option} */ preset(arg) { this.presetArg = arg; return this; } /** * Add option name(s) that conflict with this option. * An error will be displayed if conflicting options are found during parsing. * * @example * new Option('--rgb').conflicts('cmyk'); * new Option('--js').conflicts(['ts', 'jsx']); * * @param {string | string[]} names * @return {Option} */ conflicts(names) { this.conflictsWith = this.conflictsWith.concat(names); return this; } /** * Specify implied option values for when this option is set and the implied options are not. * * The custom processing (parseArg) is not called on the implied values. * * @example * program * .addOption(new Option('--log', 'write logging information to file')) * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' })); * * @param {Object} impliedOptionValues * @return {Option} */ implies(impliedOptionValues) { let newImplied = impliedOptionValues; if (typeof impliedOptionValues === 'string') { // string is not documented, but easy mistake and we can do what user probably intended. newImplied = { [impliedOptionValues]: true }; } this.implied = Object.assign(this.implied || {}, newImplied); return this; } /** * Set environment variable to check for option value. * * An environment variable is only used if when processed the current option value is * undefined, or the source of the current value is 'default' or 'config' or 'env'. * * @param {string} name * @return {Option} */ env(name) { this.envVar = name; return this; } /** * Set the custom handler for processing CLI option arguments into option values. * * @param {Function} [fn] * @return {Option} */ argParser(fn) { this.parseArg = fn; return this; } /** * Whether the option is mandatory and must have a value after parsing. * * @param {boolean} [mandatory=true] * @return {Option} */ makeOptionMandatory(mandatory = true) { this.mandatory = !!mandatory; return this; } /** * Hide option in help. * * @param {boolean} [hide=true] * @return {Option} */ hideHelp(hide = true) { this.hidden = !!hide; return this; } /** * @api private */ _concatValue(value, previous) { if (previous === this.defaultValue || !Array.isArray(previous)) { return [value]; } return previous.concat(value); } /** * Only allow option value to be one of choices. * * @param {string[]} values * @return {Option} */ choices(values) { this.argChoices = values.slice(); this.parseArg = (arg, previous) => { if (!this.argChoices.includes(arg)) { throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`); } if (this.variadic) { return this._concatValue(arg, previous); } return arg; }; return this; } /** * Return option name. * * @return {string} */ name() { if (this.long) { return this.long.replace(/^--/, ''); } return this.short.replace(/^-/, ''); } /** * Return option name, in a camelcase format that can be used * as a object attribute key. * * @return {string} * @api private */ attributeName() { return camelcase(this.name().replace(/^no-/, '')); } /** * Check if `arg` matches the short or long flag. * * @param {string} arg * @return {boolean} * @api private */ is(arg) { return this.short === arg || this.long === arg; } /** * Return whether a boolean option. * * Options are one of boolean, negated, required argument, or optional argument. * * @return {boolean} * @api private */ isBoolean() { return !this.required && !this.optional && !this.negate; } } /** * This class is to make it easier to work with dual options, without changing the existing * implementation. We support separate dual options for separate positive and negative options, * like `--build` and `--no-build`, which share a single option value. This works nicely for some * use cases, but is tricky for others where we want separate behaviours despite * the single shared option value. */ class DualOptions { /** * @param {Option[]} options */ constructor(options) { this.positiveOptions = new Map(); this.negativeOptions = new Map(); this.dualOptions = new Set(); options.forEach(option => { if (option.negate) { this.negativeOptions.set(option.attributeName(), option); } else { this.positiveOptions.set(option.attributeName(), option); } }); this.negativeOptions.forEach((value, key) => { if (this.positiveOptions.has(key)) { this.dualOptions.add(key); } }); } /** * Did the value come from the option, and not from possible matching dual option? * * @param {any} value * @param {Option} option * @returns {boolean} */ valueFromOption(value, option) { const optionKey = option.attributeName(); if (!this.dualOptions.has(optionKey)) return true; // Use the value to deduce if (probably) came from the option. const preset = this.negativeOptions.get(optionKey).presetArg; const negativeValue = (preset !== undefined) ? preset : false; return option.negate === (negativeValue === value); } } /** * Convert string from kebab-case to camelCase. * * @param {string} str * @return {string} * @api private */ function camelcase(str) { return str.split('-').reduce((str, word) => { return str + word[0].toUpperCase() + word.slice(1); }); } /** * Split the short and long flag out of something like '-m,--mixed <value>' * * @api private */ function splitOptionFlags(flags) { let shortFlag; let longFlag; // Use original very loose parsing to maintain backwards compatibility for now, // which allowed for example unintended `-sw, --short-word` [sic]. const flagParts = flags.split(/[ |,]+/); if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift(); longFlag = flagParts.shift(); // Add support for lone short flag without significantly changing parsing! if (!shortFlag && /^-[^-]$/.test(longFlag)) { shortFlag = longFlag; longFlag = undefined; } return { shortFlag, longFlag }; } exports.Option = Option; exports.splitOptionFlags = splitOptionFlags; exports.DualOptions = DualOptions; node_modules/commander/lib/error.js 0000664 00000002330 15114743311 0013423 0 ustar 00 // @ts-check /** * CommanderError class * @class */ class CommanderError extends Error { /** * Constructs the CommanderError class * @param {number} exitCode suggested exit code which could be used with process.exit * @param {string} code an id string representing the error * @param {string} message human-readable description of the error * @constructor */ constructor(exitCode, code, message) { super(message); // properly capture stack trace in Node.js Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.code = code; this.exitCode = exitCode; this.nestedError = undefined; } } /** * InvalidArgumentError class * @class */ class InvalidArgumentError extends CommanderError { /** * Constructs the InvalidArgumentError class * @param {string} [message] explanation of why argument is invalid * @constructor */ constructor(message) { super(1, 'commander.invalidArgument', message); // properly capture stack trace in Node.js Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; } } exports.CommanderError = CommanderError; exports.InvalidArgumentError = InvalidArgumentError; node_modules/commander/esm.mjs 0000664 00000000465 15114743311 0012474 0 ustar 00 import commander from './index.js'; // wrapper to provide named exports for ESM. export const { program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, // deprecated old name Command, Argument, Option, Help } = commander; node_modules/commander/index.js 0000664 00000001436 15114743311 0012641 0 ustar 00 const { Argument } = require('./lib/argument.js'); const { Command } = require('./lib/command.js'); const { CommanderError, InvalidArgumentError } = require('./lib/error.js'); const { Help } = require('./lib/help.js'); const { Option } = require('./lib/option.js'); // @ts-check /** * Expose the root command. */ exports = module.exports = new Command(); exports.program = exports; // More explicit access to global command. // Implicit export of createArgument, createCommand, and createOption. /** * Expose classes */ exports.Argument = Argument; exports.Command = Command; exports.CommanderError = CommanderError; exports.Help = Help; exports.InvalidArgumentError = InvalidArgumentError; exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated exports.Option = Option; node_modules/tinycolor2/tinycolor.js 0000664 00000111552 15114743311 0013714 0 ustar 00 // This file is autogenerated. // It's here at this path for backwards compatibility for links to it // but the npm package now exports both CJS and ESM. // See https://github.com/bgrins/TinyColor/ for instructions. (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.tinycolor = factory()); })(this, (function () { 'use strict'; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } // https://github.com/bgrins/TinyColor // Brian Grinstead, MIT License var trimLeft = /^\s+/; var trimRight = /\s+$/; function tinycolor(color, opts) { color = color ? color : ""; opts = opts || {}; // If input is already a tinycolor, return itself if (color instanceof tinycolor) { return color; } // If we are called as a function, call using new instead if (!(this instanceof tinycolor)) { return new tinycolor(color, opts); } var rgb = inputToRGB(color); this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format; this._gradientType = opts.gradientType; // Don't let the range of [0,255] come back in [0,1]. // Potentially lose a little bit of precision here, but will fix issues where // .5 gets interpreted as half of the total, instead of half of 1 // If it was supposed to be 128, this was already taken care of by `inputToRgb` if (this._r < 1) this._r = Math.round(this._r); if (this._g < 1) this._g = Math.round(this._g); if (this._b < 1) this._b = Math.round(this._b); this._ok = rgb.ok; } tinycolor.prototype = { isDark: function isDark() { return this.getBrightness() < 128; }, isLight: function isLight() { return !this.isDark(); }, isValid: function isValid() { return this._ok; }, getOriginalInput: function getOriginalInput() { return this._originalInput; }, getFormat: function getFormat() { return this._format; }, getAlpha: function getAlpha() { return this._a; }, getBrightness: function getBrightness() { //http://www.w3.org/TR/AERT#color-contrast var rgb = this.toRgb(); return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; }, getLuminance: function getLuminance() { //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef var rgb = this.toRgb(); var RsRGB, GsRGB, BsRGB, R, G, B; RsRGB = rgb.r / 255; GsRGB = rgb.g / 255; BsRGB = rgb.b / 255; if (RsRGB <= 0.03928) R = RsRGB / 12.92;else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4); if (GsRGB <= 0.03928) G = GsRGB / 12.92;else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4); if (BsRGB <= 0.03928) B = BsRGB / 12.92;else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4); return 0.2126 * R + 0.7152 * G + 0.0722 * B; }, setAlpha: function setAlpha(value) { this._a = boundAlpha(value); this._roundA = Math.round(100 * this._a) / 100; return this; }, toHsv: function toHsv() { var hsv = rgbToHsv(this._r, this._g, this._b); return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a }; }, toHsvString: function toHsvString() { var hsv = rgbToHsv(this._r, this._g, this._b); var h = Math.round(hsv.h * 360), s = Math.round(hsv.s * 100), v = Math.round(hsv.v * 100); return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")"; }, toHsl: function toHsl() { var hsl = rgbToHsl(this._r, this._g, this._b); return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a }; }, toHslString: function toHslString() { var hsl = rgbToHsl(this._r, this._g, this._b); var h = Math.round(hsl.h * 360), s = Math.round(hsl.s * 100), l = Math.round(hsl.l * 100); return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")"; }, toHex: function toHex(allow3Char) { return rgbToHex(this._r, this._g, this._b, allow3Char); }, toHexString: function toHexString(allow3Char) { return "#" + this.toHex(allow3Char); }, toHex8: function toHex8(allow4Char) { return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); }, toHex8String: function toHex8String(allow4Char) { return "#" + this.toHex8(allow4Char); }, toRgb: function toRgb() { return { r: Math.round(this._r), g: Math.round(this._g), b: Math.round(this._b), a: this._a }; }, toRgbString: function toRgbString() { return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")"; }, toPercentageRgb: function toPercentageRgb() { return { r: Math.round(bound01(this._r, 255) * 100) + "%", g: Math.round(bound01(this._g, 255) * 100) + "%", b: Math.round(bound01(this._b, 255) * 100) + "%", a: this._a }; }, toPercentageRgbString: function toPercentageRgbString() { return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; }, toName: function toName() { if (this._a === 0) { return "transparent"; } if (this._a < 1) { return false; } return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; }, toFilter: function toFilter(secondColor) { var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a); var secondHex8String = hex8String; var gradientType = this._gradientType ? "GradientType = 1, " : ""; if (secondColor) { var s = tinycolor(secondColor); secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a); } return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")"; }, toString: function toString(format) { var formatSet = !!format; format = format || this._format; var formattedString = false; var hasAlpha = this._a < 1 && this._a >= 0; var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); if (needsAlphaFormat) { // Special case for "transparent", all other non-alpha formats // will return rgba when there is transparency. if (format === "name" && this._a === 0) { return this.toName(); } return this.toRgbString(); } if (format === "rgb") { formattedString = this.toRgbString(); } if (format === "prgb") { formattedString = this.toPercentageRgbString(); } if (format === "hex" || format === "hex6") { formattedString = this.toHexString(); } if (format === "hex3") { formattedString = this.toHexString(true); } if (format === "hex4") { formattedString = this.toHex8String(true); } if (format === "hex8") { formattedString = this.toHex8String(); } if (format === "name") { formattedString = this.toName(); } if (format === "hsl") { formattedString = this.toHslString(); } if (format === "hsv") { formattedString = this.toHsvString(); } return formattedString || this.toHexString(); }, clone: function clone() { return tinycolor(this.toString()); }, _applyModification: function _applyModification(fn, args) { var color = fn.apply(null, [this].concat([].slice.call(args))); this._r = color._r; this._g = color._g; this._b = color._b; this.setAlpha(color._a); return this; }, lighten: function lighten() { return this._applyModification(_lighten, arguments); }, brighten: function brighten() { return this._applyModification(_brighten, arguments); }, darken: function darken() { return this._applyModification(_darken, arguments); }, desaturate: function desaturate() { return this._applyModification(_desaturate, arguments); }, saturate: function saturate() { return this._applyModification(_saturate, arguments); }, greyscale: function greyscale() { return this._applyModification(_greyscale, arguments); }, spin: function spin() { return this._applyModification(_spin, arguments); }, _applyCombination: function _applyCombination(fn, args) { return fn.apply(null, [this].concat([].slice.call(args))); }, analogous: function analogous() { return this._applyCombination(_analogous, arguments); }, complement: function complement() { return this._applyCombination(_complement, arguments); }, monochromatic: function monochromatic() { return this._applyCombination(_monochromatic, arguments); }, splitcomplement: function splitcomplement() { return this._applyCombination(_splitcomplement, arguments); }, // Disabled until https://github.com/bgrins/TinyColor/issues/254 // polyad: function (number) { // return this._applyCombination(polyad, [number]); // }, triad: function triad() { return this._applyCombination(polyad, [3]); }, tetrad: function tetrad() { return this._applyCombination(polyad, [4]); } }; // If input is an object, force 1 into "1.0" to handle ratios properly // String input requires "1.0" as input, so 1 will be treated as 1 tinycolor.fromRatio = function (color, opts) { if (_typeof(color) == "object") { var newColor = {}; for (var i in color) { if (color.hasOwnProperty(i)) { if (i === "a") { newColor[i] = color[i]; } else { newColor[i] = convertToPercentage(color[i]); } } } color = newColor; } return tinycolor(color, opts); }; // Given a string or object, convert that input to RGB // Possible string inputs: // // "red" // "#f00" or "f00" // "#ff0000" or "ff0000" // "#ff000000" or "ff000000" // "rgb 255 0 0" or "rgb (255, 0, 0)" // "rgb 1.0 0 0" or "rgb (1, 0, 0)" // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" // function inputToRGB(color) { var rgb = { r: 0, g: 0, b: 0 }; var a = 1; var s = null; var v = null; var l = null; var ok = false; var format = false; if (typeof color == "string") { color = stringInputToObject(color); } if (_typeof(color) == "object") { if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { rgb = rgbToRgb(color.r, color.g, color.b); ok = true; format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { s = convertToPercentage(color.s); v = convertToPercentage(color.v); rgb = hsvToRgb(color.h, s, v); ok = true; format = "hsv"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { s = convertToPercentage(color.s); l = convertToPercentage(color.l); rgb = hslToRgb(color.h, s, l); ok = true; format = "hsl"; } if (color.hasOwnProperty("a")) { a = color.a; } } a = boundAlpha(a); return { ok: ok, format: color.format || format, r: Math.min(255, Math.max(rgb.r, 0)), g: Math.min(255, Math.max(rgb.g, 0)), b: Math.min(255, Math.max(rgb.b, 0)), a: a }; } // Conversion Functions // -------------------- // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript> // `rgbToRgb` // Handle bounds / percentage checking to conform to CSS color spec // <http://www.w3.org/TR/css3-color/> // *Assumes:* r, g, b in [0, 255] or [0, 1] // *Returns:* { r, g, b } in [0, 255] function rgbToRgb(r, g, b) { return { r: bound01(r, 255) * 255, g: bound01(g, 255) * 255, b: bound01(b, 255) * 255 }; } // `rgbToHsl` // Converts an RGB color value to HSL. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] // *Returns:* { h, s, l } in [0,1] function rgbToHsl(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, l: l }; } // `hslToRgb` // Converts an HSL color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hslToRgb(h, s, l) { var r, g, b; h = bound01(h, 360); s = bound01(s, 100); l = bound01(l, 100); function hue2rgb(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } if (s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1 / 3); } return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHsv` // Converts an RGB color value to HSV // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] // *Returns:* { h, s, v } in [0,1] function rgbToHsv(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, v = max; var d = max - min; s = max === 0 ? 0 : d / max; if (max == min) { h = 0; // achromatic } else { switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, v: v }; } // `hsvToRgb` // Converts an HSV color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hsvToRgb(h, s, v) { h = bound01(h, 360) * 6; s = bound01(s, 100); v = bound01(v, 100); var i = Math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod]; return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHex` // Converts an RGB color to hex // Assumes r, g, and b are contained in the set [0, 255] // Returns a 3 or 6 character hex function rgbToHex(r, g, b, allow3Char) { var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; // Return a 3 character hex if possible if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } return hex.join(""); } // `rgbaToHex` // Converts an RGBA color plus alpha transparency to hex // Assumes r, g, b are contained in the set [0, 255] and // a in [0, 1]. Returns a 4 or 8 character rgba hex function rgbaToHex(r, g, b, a, allow4Char) { var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))]; // Return a 4 character hex if possible if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); } return hex.join(""); } // `rgbaToArgbHex` // Converts an RGBA color to an ARGB Hex8 string // Rarely used, but required for "toFilter()" function rgbaToArgbHex(r, g, b, a) { var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; return hex.join(""); } // `equals` // Can be called with any tinycolor input tinycolor.equals = function (color1, color2) { if (!color1 || !color2) return false; return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); }; tinycolor.random = function () { return tinycolor.fromRatio({ r: Math.random(), g: Math.random(), b: Math.random() }); }; // Modification Functions // ---------------------- // Thanks to less.js for some of the basics here // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js> function _desaturate(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.s -= amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function _saturate(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.s += amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function _greyscale(color) { return tinycolor(color).desaturate(100); } function _lighten(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.l += amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } function _brighten(color, amount) { amount = amount === 0 ? 0 : amount || 10; var rgb = tinycolor(color).toRgb(); rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100)))); rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100)))); rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100)))); return tinycolor(rgb); } function _darken(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.l -= amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. // Values outside of this range will be wrapped into this range. function _spin(color, amount) { var hsl = tinycolor(color).toHsl(); var hue = (hsl.h + amount) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return tinycolor(hsl); } // Combination Functions // --------------------- // Thanks to jQuery xColor for some of the ideas behind these // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js> function _complement(color) { var hsl = tinycolor(color).toHsl(); hsl.h = (hsl.h + 180) % 360; return tinycolor(hsl); } function polyad(color, number) { if (isNaN(number) || number <= 0) { throw new Error("Argument to polyad must be a positive number"); } var hsl = tinycolor(color).toHsl(); var result = [tinycolor(color)]; var step = 360 / number; for (var i = 1; i < number; i++) { result.push(tinycolor({ h: (hsl.h + i * step) % 360, s: hsl.s, l: hsl.l })); } return result; } function _splitcomplement(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [tinycolor(color), tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l })]; } function _analogous(color, results, slices) { results = results || 6; slices = slices || 30; var hsl = tinycolor(color).toHsl(); var part = 360 / slices; var ret = [tinycolor(color)]; for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results;) { hsl.h = (hsl.h + part) % 360; ret.push(tinycolor(hsl)); } return ret; } function _monochromatic(color, results) { results = results || 6; var hsv = tinycolor(color).toHsv(); var h = hsv.h, s = hsv.s, v = hsv.v; var ret = []; var modification = 1 / results; while (results--) { ret.push(tinycolor({ h: h, s: s, v: v })); v = (v + modification) % 1; } return ret; } // Utility Functions // --------------------- tinycolor.mix = function (color1, color2, amount) { amount = amount === 0 ? 0 : amount || 50; var rgb1 = tinycolor(color1).toRgb(); var rgb2 = tinycolor(color2).toRgb(); var p = amount / 100; var rgba = { r: (rgb2.r - rgb1.r) * p + rgb1.r, g: (rgb2.g - rgb1.g) * p + rgb1.g, b: (rgb2.b - rgb1.b) * p + rgb1.b, a: (rgb2.a - rgb1.a) * p + rgb1.a }; return tinycolor(rgba); }; // Readability Functions // --------------------- // <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2) // `contrast` // Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2) tinycolor.readability = function (color1, color2) { var c1 = tinycolor(color1); var c2 = tinycolor(color2); return (Math.max(c1.getLuminance(), c2.getLuminance()) + 0.05) / (Math.min(c1.getLuminance(), c2.getLuminance()) + 0.05); }; // `isReadable` // Ensure that foreground and background color combinations meet WCAG2 guidelines. // The third argument is an optional Object. // the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA'; // the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'. // If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}. // *Example* // tinycolor.isReadable("#000", "#111") => false // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false tinycolor.isReadable = function (color1, color2, wcag2) { var readability = tinycolor.readability(color1, color2); var wcag2Parms, out; out = false; wcag2Parms = validateWCAG2Parms(wcag2); switch (wcag2Parms.level + wcag2Parms.size) { case "AAsmall": case "AAAlarge": out = readability >= 4.5; break; case "AAlarge": out = readability >= 3; break; case "AAAsmall": out = readability >= 7; break; } return out; }; // `mostReadable` // Given a base color and a list of possible foreground or background // colors for that base, returns the most readable color. // Optionally returns Black or White if the most readable color is unreadable. // *Example* // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" tinycolor.mostReadable = function (baseColor, colorList, args) { var bestColor = null; var bestScore = 0; var readability; var includeFallbackColors, level, size; args = args || {}; includeFallbackColors = args.includeFallbackColors; level = args.level; size = args.size; for (var i = 0; i < colorList.length; i++) { readability = tinycolor.readability(baseColor, colorList[i]); if (readability > bestScore) { bestScore = readability; bestColor = tinycolor(colorList[i]); } } if (tinycolor.isReadable(baseColor, bestColor, { level: level, size: size }) || !includeFallbackColors) { return bestColor; } else { args.includeFallbackColors = false; return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args); } }; // Big List of Colors // ------------------ // <https://www.w3.org/TR/css-color-4/#named-colors> var names = tinycolor.names = { aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "0ff", aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc", bisque: "ffe4c4", black: "000", blanchedalmond: "ffebcd", blue: "00f", blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", burntsienna: "ea7e5d", cadetblue: "5f9ea0", chartreuse: "7fff00", chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c", cyan: "0ff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9", darkgreen: "006400", darkgrey: "a9a9a9", darkkhaki: "bdb76b", darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f", darkslategrey: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493", deepskyblue: "00bfff", dimgray: "696969", dimgrey: "696969", dodgerblue: "1e90ff", firebrick: "b22222", floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "f0f", gainsboro: "dcdcdc", ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f", grey: "808080", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082", ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00", lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgray: "d3d3d3", lightgreen: "90ee90", lightgrey: "d3d3d3", lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslategray: "789", lightslategrey: "789", lightsteelblue: "b0c4de", lightyellow: "ffffe0", lime: "0f0", limegreen: "32cd32", linen: "faf0e6", magenta: "f0f", maroon: "800000", mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370db", mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a", mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6", olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "db7093", papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6", purple: "800080", rebeccapurple: "663399", red: "f00", rosybrown: "bc8f8f", royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd", slategray: "708090", slategrey: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee", wheat: "f5deb3", white: "fff", whitesmoke: "f5f5f5", yellow: "ff0", yellowgreen: "9acd32" }; // Make it easy to access colors via `hexNames[hex]` var hexNames = tinycolor.hexNames = flip(names); // Utilities // --------- // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` function flip(o) { var flipped = {}; for (var i in o) { if (o.hasOwnProperty(i)) { flipped[o[i]] = i; } } return flipped; } // Return a valid alpha value [0,1] with all invalid values being set to 1 function boundAlpha(a) { a = parseFloat(a); if (isNaN(a) || a < 0 || a > 1) { a = 1; } return a; } // Take input from [0, n] and return it as [0, 1] function bound01(n, max) { if (isOnePointZero(n)) n = "100%"; var processPercent = isPercentage(n); n = Math.min(max, Math.max(0, parseFloat(n))); // Automatically convert percentage into number if (processPercent) { n = parseInt(n * max, 10) / 100; } // Handle floating point rounding errors if (Math.abs(n - max) < 0.000001) { return 1; } // Convert into [0, 1] range if it isn't already return n % max / parseFloat(max); } // Force a number between 0 and 1 function clamp01(val) { return Math.min(1, Math.max(0, val)); } // Parse a base-16 hex value into a base-10 integer function parseIntFromHex(val) { return parseInt(val, 16); } // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0> function isOnePointZero(n) { return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1; } // Check to see if string passed in is a percentage function isPercentage(n) { return typeof n === "string" && n.indexOf("%") != -1; } // Force a hex value to have 2 characters function pad2(c) { return c.length == 1 ? "0" + c : "" + c; } // Replace a decimal with it's percentage value function convertToPercentage(n) { if (n <= 1) { n = n * 100 + "%"; } return n; } // Converts a decimal to a hex value function convertDecimalToHex(d) { return Math.round(parseFloat(d) * 255).toString(16); } // Converts a hex value to a decimal function convertHexToDecimal(h) { return parseIntFromHex(h) / 255; } var matchers = function () { // <http://www.w3.org/TR/css3-values/#integers> var CSS_INTEGER = "[-\\+]?\\d+%?"; // <http://www.w3.org/TR/css3-values/#number-value> var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; // Actual matching. // Parentheses and commas are optional, but not required. // Whitespace can take the place of commas or opening paren var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; return { CSS_UNIT: new RegExp(CSS_UNIT), rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ }; }(); // `isValidCSSUnit` // Take in a single string / number and check to see if it looks like a CSS unit // (see `matchers` above for definition). function isValidCSSUnit(color) { return !!matchers.CSS_UNIT.exec(color); } // `stringInputToObject` // Permissive string parsing. Take in a number of formats, and output an object // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` function stringInputToObject(color) { color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase(); var named = false; if (names[color]) { color = names[color]; named = true; } else if (color == "transparent") { return { r: 0, g: 0, b: 0, a: 0, format: "name" }; } // Try to match string input using regular expressions. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] // Just return an object and let the conversion functions handle that. // This way the result will be the same whether the tinycolor is initialized with string or object. var match; if (match = matchers.rgb.exec(color)) { return { r: match[1], g: match[2], b: match[3] }; } if (match = matchers.rgba.exec(color)) { return { r: match[1], g: match[2], b: match[3], a: match[4] }; } if (match = matchers.hsl.exec(color)) { return { h: match[1], s: match[2], l: match[3] }; } if (match = matchers.hsla.exec(color)) { return { h: match[1], s: match[2], l: match[3], a: match[4] }; } if (match = matchers.hsv.exec(color)) { return { h: match[1], s: match[2], v: match[3] }; } if (match = matchers.hsva.exec(color)) { return { h: match[1], s: match[2], v: match[3], a: match[4] }; } if (match = matchers.hex8.exec(color)) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), a: convertHexToDecimal(match[4]), format: named ? "name" : "hex8" }; } if (match = matchers.hex6.exec(color)) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), format: named ? "name" : "hex" }; } if (match = matchers.hex4.exec(color)) { return { r: parseIntFromHex(match[1] + "" + match[1]), g: parseIntFromHex(match[2] + "" + match[2]), b: parseIntFromHex(match[3] + "" + match[3]), a: convertHexToDecimal(match[4] + "" + match[4]), format: named ? "name" : "hex8" }; } if (match = matchers.hex3.exec(color)) { return { r: parseIntFromHex(match[1] + "" + match[1]), g: parseIntFromHex(match[2] + "" + match[2]), b: parseIntFromHex(match[3] + "" + match[3]), format: named ? "name" : "hex" }; } return false; } function validateWCAG2Parms(parms) { // return valid WCAG2 parms for isReadable. // If input parms are invalid, return {"level":"AA", "size":"small"} var level, size; parms = parms || { level: "AA", size: "small" }; level = (parms.level || "AA").toUpperCase(); size = (parms.size || "small").toLowerCase(); if (level !== "AA" && level !== "AAA") { level = "AA"; } if (size !== "small" && size !== "large") { size = "small"; } return { level: level, size: size }; } return tinycolor; })); node_modules/tinycolor2/esm/tinycolor.js 0000664 00000104301 15114743311 0014472 0 ustar 00 // This file is autogenerated. It's used to publish ESM to npm. function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } // https://github.com/bgrins/TinyColor // Brian Grinstead, MIT License var trimLeft = /^\s+/; var trimRight = /\s+$/; function tinycolor(color, opts) { color = color ? color : ""; opts = opts || {}; // If input is already a tinycolor, return itself if (color instanceof tinycolor) { return color; } // If we are called as a function, call using new instead if (!(this instanceof tinycolor)) { return new tinycolor(color, opts); } var rgb = inputToRGB(color); this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format; this._gradientType = opts.gradientType; // Don't let the range of [0,255] come back in [0,1]. // Potentially lose a little bit of precision here, but will fix issues where // .5 gets interpreted as half of the total, instead of half of 1 // If it was supposed to be 128, this was already taken care of by `inputToRgb` if (this._r < 1) this._r = Math.round(this._r); if (this._g < 1) this._g = Math.round(this._g); if (this._b < 1) this._b = Math.round(this._b); this._ok = rgb.ok; } tinycolor.prototype = { isDark: function isDark() { return this.getBrightness() < 128; }, isLight: function isLight() { return !this.isDark(); }, isValid: function isValid() { return this._ok; }, getOriginalInput: function getOriginalInput() { return this._originalInput; }, getFormat: function getFormat() { return this._format; }, getAlpha: function getAlpha() { return this._a; }, getBrightness: function getBrightness() { //http://www.w3.org/TR/AERT#color-contrast var rgb = this.toRgb(); return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; }, getLuminance: function getLuminance() { //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef var rgb = this.toRgb(); var RsRGB, GsRGB, BsRGB, R, G, B; RsRGB = rgb.r / 255; GsRGB = rgb.g / 255; BsRGB = rgb.b / 255; if (RsRGB <= 0.03928) R = RsRGB / 12.92;else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4); if (GsRGB <= 0.03928) G = GsRGB / 12.92;else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4); if (BsRGB <= 0.03928) B = BsRGB / 12.92;else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4); return 0.2126 * R + 0.7152 * G + 0.0722 * B; }, setAlpha: function setAlpha(value) { this._a = boundAlpha(value); this._roundA = Math.round(100 * this._a) / 100; return this; }, toHsv: function toHsv() { var hsv = rgbToHsv(this._r, this._g, this._b); return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a }; }, toHsvString: function toHsvString() { var hsv = rgbToHsv(this._r, this._g, this._b); var h = Math.round(hsv.h * 360), s = Math.round(hsv.s * 100), v = Math.round(hsv.v * 100); return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")"; }, toHsl: function toHsl() { var hsl = rgbToHsl(this._r, this._g, this._b); return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a }; }, toHslString: function toHslString() { var hsl = rgbToHsl(this._r, this._g, this._b); var h = Math.round(hsl.h * 360), s = Math.round(hsl.s * 100), l = Math.round(hsl.l * 100); return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")"; }, toHex: function toHex(allow3Char) { return rgbToHex(this._r, this._g, this._b, allow3Char); }, toHexString: function toHexString(allow3Char) { return "#" + this.toHex(allow3Char); }, toHex8: function toHex8(allow4Char) { return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); }, toHex8String: function toHex8String(allow4Char) { return "#" + this.toHex8(allow4Char); }, toRgb: function toRgb() { return { r: Math.round(this._r), g: Math.round(this._g), b: Math.round(this._b), a: this._a }; }, toRgbString: function toRgbString() { return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")"; }, toPercentageRgb: function toPercentageRgb() { return { r: Math.round(bound01(this._r, 255) * 100) + "%", g: Math.round(bound01(this._g, 255) * 100) + "%", b: Math.round(bound01(this._b, 255) * 100) + "%", a: this._a }; }, toPercentageRgbString: function toPercentageRgbString() { return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; }, toName: function toName() { if (this._a === 0) { return "transparent"; } if (this._a < 1) { return false; } return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; }, toFilter: function toFilter(secondColor) { var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a); var secondHex8String = hex8String; var gradientType = this._gradientType ? "GradientType = 1, " : ""; if (secondColor) { var s = tinycolor(secondColor); secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a); } return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")"; }, toString: function toString(format) { var formatSet = !!format; format = format || this._format; var formattedString = false; var hasAlpha = this._a < 1 && this._a >= 0; var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); if (needsAlphaFormat) { // Special case for "transparent", all other non-alpha formats // will return rgba when there is transparency. if (format === "name" && this._a === 0) { return this.toName(); } return this.toRgbString(); } if (format === "rgb") { formattedString = this.toRgbString(); } if (format === "prgb") { formattedString = this.toPercentageRgbString(); } if (format === "hex" || format === "hex6") { formattedString = this.toHexString(); } if (format === "hex3") { formattedString = this.toHexString(true); } if (format === "hex4") { formattedString = this.toHex8String(true); } if (format === "hex8") { formattedString = this.toHex8String(); } if (format === "name") { formattedString = this.toName(); } if (format === "hsl") { formattedString = this.toHslString(); } if (format === "hsv") { formattedString = this.toHsvString(); } return formattedString || this.toHexString(); }, clone: function clone() { return tinycolor(this.toString()); }, _applyModification: function _applyModification(fn, args) { var color = fn.apply(null, [this].concat([].slice.call(args))); this._r = color._r; this._g = color._g; this._b = color._b; this.setAlpha(color._a); return this; }, lighten: function lighten() { return this._applyModification(_lighten, arguments); }, brighten: function brighten() { return this._applyModification(_brighten, arguments); }, darken: function darken() { return this._applyModification(_darken, arguments); }, desaturate: function desaturate() { return this._applyModification(_desaturate, arguments); }, saturate: function saturate() { return this._applyModification(_saturate, arguments); }, greyscale: function greyscale() { return this._applyModification(_greyscale, arguments); }, spin: function spin() { return this._applyModification(_spin, arguments); }, _applyCombination: function _applyCombination(fn, args) { return fn.apply(null, [this].concat([].slice.call(args))); }, analogous: function analogous() { return this._applyCombination(_analogous, arguments); }, complement: function complement() { return this._applyCombination(_complement, arguments); }, monochromatic: function monochromatic() { return this._applyCombination(_monochromatic, arguments); }, splitcomplement: function splitcomplement() { return this._applyCombination(_splitcomplement, arguments); }, // Disabled until https://github.com/bgrins/TinyColor/issues/254 // polyad: function (number) { // return this._applyCombination(polyad, [number]); // }, triad: function triad() { return this._applyCombination(polyad, [3]); }, tetrad: function tetrad() { return this._applyCombination(polyad, [4]); } }; // If input is an object, force 1 into "1.0" to handle ratios properly // String input requires "1.0" as input, so 1 will be treated as 1 tinycolor.fromRatio = function (color, opts) { if (_typeof(color) == "object") { var newColor = {}; for (var i in color) { if (color.hasOwnProperty(i)) { if (i === "a") { newColor[i] = color[i]; } else { newColor[i] = convertToPercentage(color[i]); } } } color = newColor; } return tinycolor(color, opts); }; // Given a string or object, convert that input to RGB // Possible string inputs: // // "red" // "#f00" or "f00" // "#ff0000" or "ff0000" // "#ff000000" or "ff000000" // "rgb 255 0 0" or "rgb (255, 0, 0)" // "rgb 1.0 0 0" or "rgb (1, 0, 0)" // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" // function inputToRGB(color) { var rgb = { r: 0, g: 0, b: 0 }; var a = 1; var s = null; var v = null; var l = null; var ok = false; var format = false; if (typeof color == "string") { color = stringInputToObject(color); } if (_typeof(color) == "object") { if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { rgb = rgbToRgb(color.r, color.g, color.b); ok = true; format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { s = convertToPercentage(color.s); v = convertToPercentage(color.v); rgb = hsvToRgb(color.h, s, v); ok = true; format = "hsv"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { s = convertToPercentage(color.s); l = convertToPercentage(color.l); rgb = hslToRgb(color.h, s, l); ok = true; format = "hsl"; } if (color.hasOwnProperty("a")) { a = color.a; } } a = boundAlpha(a); return { ok: ok, format: color.format || format, r: Math.min(255, Math.max(rgb.r, 0)), g: Math.min(255, Math.max(rgb.g, 0)), b: Math.min(255, Math.max(rgb.b, 0)), a: a }; } // Conversion Functions // -------------------- // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript> // `rgbToRgb` // Handle bounds / percentage checking to conform to CSS color spec // <http://www.w3.org/TR/css3-color/> // *Assumes:* r, g, b in [0, 255] or [0, 1] // *Returns:* { r, g, b } in [0, 255] function rgbToRgb(r, g, b) { return { r: bound01(r, 255) * 255, g: bound01(g, 255) * 255, b: bound01(b, 255) * 255 }; } // `rgbToHsl` // Converts an RGB color value to HSL. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] // *Returns:* { h, s, l } in [0,1] function rgbToHsl(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, l: l }; } // `hslToRgb` // Converts an HSL color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hslToRgb(h, s, l) { var r, g, b; h = bound01(h, 360); s = bound01(s, 100); l = bound01(l, 100); function hue2rgb(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } if (s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1 / 3); } return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHsv` // Converts an RGB color value to HSV // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] // *Returns:* { h, s, v } in [0,1] function rgbToHsv(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, v = max; var d = max - min; s = max === 0 ? 0 : d / max; if (max == min) { h = 0; // achromatic } else { switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, v: v }; } // `hsvToRgb` // Converts an HSV color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hsvToRgb(h, s, v) { h = bound01(h, 360) * 6; s = bound01(s, 100); v = bound01(v, 100); var i = Math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod]; return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHex` // Converts an RGB color to hex // Assumes r, g, and b are contained in the set [0, 255] // Returns a 3 or 6 character hex function rgbToHex(r, g, b, allow3Char) { var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; // Return a 3 character hex if possible if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } return hex.join(""); } // `rgbaToHex` // Converts an RGBA color plus alpha transparency to hex // Assumes r, g, b are contained in the set [0, 255] and // a in [0, 1]. Returns a 4 or 8 character rgba hex function rgbaToHex(r, g, b, a, allow4Char) { var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))]; // Return a 4 character hex if possible if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); } return hex.join(""); } // `rgbaToArgbHex` // Converts an RGBA color to an ARGB Hex8 string // Rarely used, but required for "toFilter()" function rgbaToArgbHex(r, g, b, a) { var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; return hex.join(""); } // `equals` // Can be called with any tinycolor input tinycolor.equals = function (color1, color2) { if (!color1 || !color2) return false; return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); }; tinycolor.random = function () { return tinycolor.fromRatio({ r: Math.random(), g: Math.random(), b: Math.random() }); }; // Modification Functions // ---------------------- // Thanks to less.js for some of the basics here // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js> function _desaturate(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.s -= amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function _saturate(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.s += amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function _greyscale(color) { return tinycolor(color).desaturate(100); } function _lighten(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.l += amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } function _brighten(color, amount) { amount = amount === 0 ? 0 : amount || 10; var rgb = tinycolor(color).toRgb(); rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100)))); rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100)))); rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100)))); return tinycolor(rgb); } function _darken(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.l -= amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. // Values outside of this range will be wrapped into this range. function _spin(color, amount) { var hsl = tinycolor(color).toHsl(); var hue = (hsl.h + amount) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return tinycolor(hsl); } // Combination Functions // --------------------- // Thanks to jQuery xColor for some of the ideas behind these // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js> function _complement(color) { var hsl = tinycolor(color).toHsl(); hsl.h = (hsl.h + 180) % 360; return tinycolor(hsl); } function polyad(color, number) { if (isNaN(number) || number <= 0) { throw new Error("Argument to polyad must be a positive number"); } var hsl = tinycolor(color).toHsl(); var result = [tinycolor(color)]; var step = 360 / number; for (var i = 1; i < number; i++) { result.push(tinycolor({ h: (hsl.h + i * step) % 360, s: hsl.s, l: hsl.l })); } return result; } function _splitcomplement(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [tinycolor(color), tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l })]; } function _analogous(color, results, slices) { results = results || 6; slices = slices || 30; var hsl = tinycolor(color).toHsl(); var part = 360 / slices; var ret = [tinycolor(color)]; for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results;) { hsl.h = (hsl.h + part) % 360; ret.push(tinycolor(hsl)); } return ret; } function _monochromatic(color, results) { results = results || 6; var hsv = tinycolor(color).toHsv(); var h = hsv.h, s = hsv.s, v = hsv.v; var ret = []; var modification = 1 / results; while (results--) { ret.push(tinycolor({ h: h, s: s, v: v })); v = (v + modification) % 1; } return ret; } // Utility Functions // --------------------- tinycolor.mix = function (color1, color2, amount) { amount = amount === 0 ? 0 : amount || 50; var rgb1 = tinycolor(color1).toRgb(); var rgb2 = tinycolor(color2).toRgb(); var p = amount / 100; var rgba = { r: (rgb2.r - rgb1.r) * p + rgb1.r, g: (rgb2.g - rgb1.g) * p + rgb1.g, b: (rgb2.b - rgb1.b) * p + rgb1.b, a: (rgb2.a - rgb1.a) * p + rgb1.a }; return tinycolor(rgba); }; // Readability Functions // --------------------- // <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2) // `contrast` // Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2) tinycolor.readability = function (color1, color2) { var c1 = tinycolor(color1); var c2 = tinycolor(color2); return (Math.max(c1.getLuminance(), c2.getLuminance()) + 0.05) / (Math.min(c1.getLuminance(), c2.getLuminance()) + 0.05); }; // `isReadable` // Ensure that foreground and background color combinations meet WCAG2 guidelines. // The third argument is an optional Object. // the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA'; // the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'. // If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}. // *Example* // tinycolor.isReadable("#000", "#111") => false // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false tinycolor.isReadable = function (color1, color2, wcag2) { var readability = tinycolor.readability(color1, color2); var wcag2Parms, out; out = false; wcag2Parms = validateWCAG2Parms(wcag2); switch (wcag2Parms.level + wcag2Parms.size) { case "AAsmall": case "AAAlarge": out = readability >= 4.5; break; case "AAlarge": out = readability >= 3; break; case "AAAsmall": out = readability >= 7; break; } return out; }; // `mostReadable` // Given a base color and a list of possible foreground or background // colors for that base, returns the most readable color. // Optionally returns Black or White if the most readable color is unreadable. // *Example* // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" tinycolor.mostReadable = function (baseColor, colorList, args) { var bestColor = null; var bestScore = 0; var readability; var includeFallbackColors, level, size; args = args || {}; includeFallbackColors = args.includeFallbackColors; level = args.level; size = args.size; for (var i = 0; i < colorList.length; i++) { readability = tinycolor.readability(baseColor, colorList[i]); if (readability > bestScore) { bestScore = readability; bestColor = tinycolor(colorList[i]); } } if (tinycolor.isReadable(baseColor, bestColor, { level: level, size: size }) || !includeFallbackColors) { return bestColor; } else { args.includeFallbackColors = false; return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args); } }; // Big List of Colors // ------------------ // <https://www.w3.org/TR/css-color-4/#named-colors> var names = tinycolor.names = { aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "0ff", aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc", bisque: "ffe4c4", black: "000", blanchedalmond: "ffebcd", blue: "00f", blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", burntsienna: "ea7e5d", cadetblue: "5f9ea0", chartreuse: "7fff00", chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c", cyan: "0ff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9", darkgreen: "006400", darkgrey: "a9a9a9", darkkhaki: "bdb76b", darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f", darkslategrey: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493", deepskyblue: "00bfff", dimgray: "696969", dimgrey: "696969", dodgerblue: "1e90ff", firebrick: "b22222", floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "f0f", gainsboro: "dcdcdc", ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f", grey: "808080", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082", ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00", lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgray: "d3d3d3", lightgreen: "90ee90", lightgrey: "d3d3d3", lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslategray: "789", lightslategrey: "789", lightsteelblue: "b0c4de", lightyellow: "ffffe0", lime: "0f0", limegreen: "32cd32", linen: "faf0e6", magenta: "f0f", maroon: "800000", mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370db", mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a", mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6", olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "db7093", papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6", purple: "800080", rebeccapurple: "663399", red: "f00", rosybrown: "bc8f8f", royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd", slategray: "708090", slategrey: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee", wheat: "f5deb3", white: "fff", whitesmoke: "f5f5f5", yellow: "ff0", yellowgreen: "9acd32" }; // Make it easy to access colors via `hexNames[hex]` var hexNames = tinycolor.hexNames = flip(names); // Utilities // --------- // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` function flip(o) { var flipped = {}; for (var i in o) { if (o.hasOwnProperty(i)) { flipped[o[i]] = i; } } return flipped; } // Return a valid alpha value [0,1] with all invalid values being set to 1 function boundAlpha(a) { a = parseFloat(a); if (isNaN(a) || a < 0 || a > 1) { a = 1; } return a; } // Take input from [0, n] and return it as [0, 1] function bound01(n, max) { if (isOnePointZero(n)) n = "100%"; var processPercent = isPercentage(n); n = Math.min(max, Math.max(0, parseFloat(n))); // Automatically convert percentage into number if (processPercent) { n = parseInt(n * max, 10) / 100; } // Handle floating point rounding errors if (Math.abs(n - max) < 0.000001) { return 1; } // Convert into [0, 1] range if it isn't already return n % max / parseFloat(max); } // Force a number between 0 and 1 function clamp01(val) { return Math.min(1, Math.max(0, val)); } // Parse a base-16 hex value into a base-10 integer function parseIntFromHex(val) { return parseInt(val, 16); } // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0> function isOnePointZero(n) { return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1; } // Check to see if string passed in is a percentage function isPercentage(n) { return typeof n === "string" && n.indexOf("%") != -1; } // Force a hex value to have 2 characters function pad2(c) { return c.length == 1 ? "0" + c : "" + c; } // Replace a decimal with it's percentage value function convertToPercentage(n) { if (n <= 1) { n = n * 100 + "%"; } return n; } // Converts a decimal to a hex value function convertDecimalToHex(d) { return Math.round(parseFloat(d) * 255).toString(16); } // Converts a hex value to a decimal function convertHexToDecimal(h) { return parseIntFromHex(h) / 255; } var matchers = function () { // <http://www.w3.org/TR/css3-values/#integers> var CSS_INTEGER = "[-\\+]?\\d+%?"; // <http://www.w3.org/TR/css3-values/#number-value> var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; // Actual matching. // Parentheses and commas are optional, but not required. // Whitespace can take the place of commas or opening paren var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; return { CSS_UNIT: new RegExp(CSS_UNIT), rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ }; }(); // `isValidCSSUnit` // Take in a single string / number and check to see if it looks like a CSS unit // (see `matchers` above for definition). function isValidCSSUnit(color) { return !!matchers.CSS_UNIT.exec(color); } // `stringInputToObject` // Permissive string parsing. Take in a number of formats, and output an object // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` function stringInputToObject(color) { color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase(); var named = false; if (names[color]) { color = names[color]; named = true; } else if (color == "transparent") { return { r: 0, g: 0, b: 0, a: 0, format: "name" }; } // Try to match string input using regular expressions. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] // Just return an object and let the conversion functions handle that. // This way the result will be the same whether the tinycolor is initialized with string or object. var match; if (match = matchers.rgb.exec(color)) { return { r: match[1], g: match[2], b: match[3] }; } if (match = matchers.rgba.exec(color)) { return { r: match[1], g: match[2], b: match[3], a: match[4] }; } if (match = matchers.hsl.exec(color)) { return { h: match[1], s: match[2], l: match[3] }; } if (match = matchers.hsla.exec(color)) { return { h: match[1], s: match[2], l: match[3], a: match[4] }; } if (match = matchers.hsv.exec(color)) { return { h: match[1], s: match[2], v: match[3] }; } if (match = matchers.hsva.exec(color)) { return { h: match[1], s: match[2], v: match[3], a: match[4] }; } if (match = matchers.hex8.exec(color)) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), a: convertHexToDecimal(match[4]), format: named ? "name" : "hex8" }; } if (match = matchers.hex6.exec(color)) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), format: named ? "name" : "hex" }; } if (match = matchers.hex4.exec(color)) { return { r: parseIntFromHex(match[1] + "" + match[1]), g: parseIntFromHex(match[2] + "" + match[2]), b: parseIntFromHex(match[3] + "" + match[3]), a: convertHexToDecimal(match[4] + "" + match[4]), format: named ? "name" : "hex8" }; } if (match = matchers.hex3.exec(color)) { return { r: parseIntFromHex(match[1] + "" + match[1]), g: parseIntFromHex(match[2] + "" + match[2]), b: parseIntFromHex(match[3] + "" + match[3]), format: named ? "name" : "hex" }; } return false; } function validateWCAG2Parms(parms) { // return valid WCAG2 parms for isReadable. // If input parms are invalid, return {"level":"AA", "size":"small"} var level, size; parms = parms || { level: "AA", size: "small" }; level = (parms.level || "AA").toUpperCase(); size = (parms.size || "small").toLowerCase(); if (level !== "AA" && level !== "AAA") { level = "AA"; } if (size !== "small" && size !== "large") { size = "small"; } return { level: level, size: size }; } export { tinycolor as default }; node_modules/tinycolor2/esm/package.json 0000664 00000000027 15114743311 0014400 0 ustar 00 { "type": "module" } node_modules/tinycolor2/esm/test.js 0000664 00000155727 15114743311 0013451 0 ustar 00 // This file is autogenerated. // Ideally it wouldn't exist, but it's here to test cjs in node // Changes should go into ./test.js, and if new assertions are needed // they'll need to be shimmed here as well import tinycolor from "./tinycolor.js"; import { Deno, testDefinitions } from "@deno/shim-deno-test"; const { assertEquals, assert, assertThrows } = await import( "../deno_asserts@0.168.0.mjs" ); async function runDenoTests() { for (const test of testDefinitions) { if (test.ignore) { console.log(`Ignoring ${test.name}`); continue; } console.log(`Running ${test.name}`); await test.fn(); console.log(`> Passed ${test.name}`); } } // TEST_BEGINS_HERE Deno.test("TinyColor initialization", function () { assert( typeof tinycolor != "undefined", "tinycolor is initialized on the page" ); assert( typeof tinycolor("red") == "object", "tinycolor is able to be instantiated" ); var r = tinycolor("red"); assert( tinycolor(r) === r, "when given a tinycolor instance, tinycolor() returns it" ); assert( new tinycolor(r) === r, "when given a tinycolor instance, new tinycolor() returns it" ); assertEquals( tinycolor("red", { format: "hex" }).toString(), "#ff0000", "tinycolor options are being parsed" ); assertEquals( tinycolor.fromRatio({ r: 1, g: 0, b: 0 }, { format: "hex" }).toString(), "#ff0000", "tinycolor options are being parsed" ); var obj = { h: 180, s: 0.5, l: 0.5 }; var color = tinycolor(obj); assert( obj.s === 0.5, "when given an object, the original object is not modified" ); }); Deno.test("Original input", function () { var colorRgbUp = "RGB(39, 39, 39)"; var colorRgbLow = "rgb(39, 39, 39)"; var colorRgbMix = "RgB(39, 39, 39)"; var tinycolorObj = tinycolor(colorRgbMix); var inputObj = { r: 100, g: 100, b: 100 }; var r = tinycolor("red"); assert( tinycolor(colorRgbLow).getOriginalInput() === colorRgbLow, "original lowercase input is returned" ); assert( tinycolor(colorRgbUp).getOriginalInput() === colorRgbUp, "original uppercase input is returned" ); assert( tinycolor(colorRgbMix).getOriginalInput() === colorRgbMix, "original mixed input is returned" ); assert( tinycolor(tinycolorObj).getOriginalInput() === colorRgbMix, "when given a tinycolor instance, the color string is returned" ); assert( tinycolor(inputObj).getOriginalInput() === inputObj, "when given an object, the object is returned" ); assert( new tinycolor("").getOriginalInput() === "", "when given an empty string, an empty string is returned" ); assert( new tinycolor(null).getOriginalInput() === "", "when given a null value, an empty string is returned" ); }); Deno.test("Cloning color", function () { var originalColor = tinycolor("red"); var originalColorRgbString = originalColor.toRgbString(); var clonedColor = originalColor.clone(); assert( clonedColor.toRgbString() === originalColor.toRgbString(), "cloned color is identical" ); clonedColor.setAlpha(0.5); assert( clonedColor.toRgbString() !== originalColor.toRgbString(), "cloned color is changing independently from original color" ); assert( originalColorRgbString === originalColor.toRgbString(), "original color was not changed by cloned color change" ); }); Deno.test("Random color", function () { var randomColor = tinycolor.random(); assertEquals(randomColor.getAlpha(), 1); assertEquals(randomColor.getFormat(), "prgb"); randomColor.setAlpha(0.5); assertEquals(randomColor.toHex8String().slice(-2), "80"); }); // Taken from convertWikipediaColors.html var conversions = [ { hex: "#FFFFFF", hex8: "#FFFFFFFF", rgb: { r: "100.0%", g: "100.0%", b: "100.0%" }, hsv: { h: "0", s: "0.000", v: "1.000" }, hsl: { h: "0", s: "0.000", l: "1.000" }, }, { hex: "#808080", hex8: "#808080FF", rgb: { r: "050.0%", g: "050.0%", b: "050.0%" }, hsv: { h: "0", s: "0.000", v: "0.500" }, hsl: { h: "0", s: "0.000", l: "0.500" }, }, { hex: "#000000", hex8: "#000000FF", rgb: { r: "000.0%", g: "000.0%", b: "000.0%" }, hsv: { h: "0", s: "0.000", v: "0.000" }, hsl: { h: "0", s: "0.000", l: "0.000" }, }, { hex: "#FF0000", hex8: "#FF0000FF", rgb: { r: "100.0%", g: "000.0%", b: "000.0%" }, hsv: { h: "0.0", s: "1.000", v: "1.000" }, hsl: { h: "0.0", s: "1.000", l: "0.500" }, }, { hex: "#BFBF00", hex8: "#BFBF00FF", rgb: { r: "075.0%", g: "075.0%", b: "000.0%" }, hsv: { h: "60.0", s: "1.000", v: "0.750" }, hsl: { h: "60.0", s: "1.000", l: "0.375" }, }, { hex: "#008000", hex8: "#008000FF", rgb: { r: "000.0%", g: "050.0%", b: "000.0%" }, hsv: { h: "120.0", s: "1.000", v: "0.500" }, hsl: { h: "120.0", s: "1.000", l: "0.250" }, }, { hex: "#80FFFF", hex8: "#80FFFFFF", rgb: { r: "050.0%", g: "100.0%", b: "100.0%" }, hsv: { h: "180.0", s: "0.500", v: "1.000" }, hsl: { h: "180.0", s: "1.000", l: "0.750" }, }, { hex: "#8080FF", hex8: "#8080FFFF", rgb: { r: "050.0%", g: "050.0%", b: "100.0%" }, hsv: { h: "240.0", s: "0.500", v: "1.000" }, hsl: { h: "240.0", s: "1.000", l: "0.750" }, }, { hex: "#BF40BF", hex8: "#BF40BFFF", rgb: { r: "075.0%", g: "025.0%", b: "075.0%" }, hsv: { h: "300.0", s: "0.667", v: "0.750" }, hsl: { h: "300.0", s: "0.500", l: "0.500" }, }, { hex: "#A0A424", hex8: "#A0A424FF", rgb: { r: "062.8%", g: "064.3%", b: "014.2%" }, hsv: { h: "61.8", s: "0.779", v: "0.643" }, hsl: { h: "61.8", s: "0.638", l: "0.393" }, }, { hex: "#1EAC41", hex8: "#1EAC41FF", rgb: { r: "011.6%", g: "067.5%", b: "025.5%" }, hsv: { h: "134.9", s: "0.828", v: "0.675" }, hsl: { h: "134.9", s: "0.707", l: "0.396" }, }, { hex: "#B430E5", hex8: "#B430E5FF", rgb: { r: "070.4%", g: "018.7%", b: "089.7%" }, hsv: { h: "283.7", s: "0.792", v: "0.897" }, hsl: { h: "283.7", s: "0.775", l: "0.542" }, }, { hex: "#FEF888", hex8: "#FEF888FF", rgb: { r: "099.8%", g: "097.4%", b: "053.2%" }, hsv: { h: "56.9", s: "0.467", v: "0.998" }, hsl: { h: "56.9", s: "0.991", l: "0.765" }, }, { hex: "#19CB97", hex8: "#19CB97FF", rgb: { r: "009.9%", g: "079.5%", b: "059.1%" }, hsv: { h: "162.4", s: "0.875", v: "0.795" }, hsl: { h: "162.4", s: "0.779", l: "0.447" }, }, { hex: "#362698", hex8: "#362698FF", rgb: { r: "021.1%", g: "014.9%", b: "059.7%" }, hsv: { h: "248.3", s: "0.750", v: "0.597" }, hsl: { h: "248.3", s: "0.601", l: "0.373" }, }, { hex: "#7E7EB8", hex8: "#7E7EB8FF", rgb: { r: "049.5%", g: "049.3%", b: "072.1%" }, hsv: { h: "240.5", s: "0.316", v: "0.721" }, hsl: { h: "240.5", s: "0.290", l: "0.607" }, }, ]; Deno.test("Color Equality", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assert(true, tiny.isValid()); assert( true, "Testing " + c.hex + ": " + tiny.toRgbString() + " " + tiny.toPercentageRgbString() + " " + tiny.toHsvString() + " " + tiny.toHslString() + " " + tiny.toHexString() + "Original: " + JSON.stringify(c.rgb) + " " + JSON.stringify(c.hsv) + " " + JSON.stringify(c.hsl) ); assert(tinycolor.equals(c.rgb, c.hex), "RGB equals hex " + c.hex); assert(tinycolor.equals(c.rgb, c.hex8), "RGB equals hex " + c.hex); assert(tinycolor.equals(c.rgb, c.hsl), "RGB equals HSL " + c.hex); assert(tinycolor.equals(c.rgb, c.hsv), "RGB equals HSV " + c.hex); assert(tinycolor.equals(c.rgb, c.rgb), "RGB equals RGB " + c.hex); assert(tinycolor.equals(c.hex, c.hex), "hex equals hex " + c.hex); assert(tinycolor.equals(c.hex, c.hex8), "hex equals hex8 " + c.hex); assert(tinycolor.equals(c.hex, c.hsl), "hex equals HSL " + c.hex); assert(tinycolor.equals(c.hex, c.hsv), "hex equals HSV " + c.hex); assert(tinycolor.equals(c.hsl, c.hsv), "HSL equals HSV " + c.hex); } }); Deno.test("With Ratio", function () { assertEquals( tinycolor.fromRatio({ r: 1, g: 1, b: 1 }).toHexString(), "#ffffff", "white" ); assertEquals( tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 0.5 }).toRgbString(), "rgba(255, 0, 0, 0.5)", "alpha works when ratio is parsed" ); assertEquals( tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 1 }).toRgbString(), "rgb(255, 0, 0)", "alpha = 1 works when ratio is parsed" ); assertEquals( tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 10 }).toRgbString(), "rgb(255, 0, 0)", "alpha > 1 works when ratio is parsed" ); assertEquals( tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: -1 }).toRgbString(), "rgb(255, 0, 0)", "alpha < 1 works when ratio is parsed" ); }); Deno.test("Without Ratio", function () { assertEquals( tinycolor({ r: 1, g: 1, b: 1 }).toHexString(), "#010101", "010101" ); assertEquals( tinycolor({ r: 0.1, g: 0.1, b: 0.1 }).toHexString(), "#000000", "000000" ); assertEquals(tinycolor("rgb .1 .1 .1").toHexString(), "#000000", "000000"); }); Deno.test("RGB Text Parsing", function () { assertEquals( tinycolor("rgb 255 0 0").toHexString(), "#ff0000", "spaced input" ); assertEquals( tinycolor("rgb(255, 0, 0)").toHexString(), "#ff0000", "parenthesized input" ); assertEquals( tinycolor("rgb (255, 0, 0)").toHexString(), "#ff0000", "parenthesized spaced input" ); assertEquals( tinycolor({ r: 255, g: 0, b: 0 }).toHexString(), "#ff0000", "object input" ); assertEquals( tinycolor({ r: 255, g: 0, b: 0 }).toRgb(), { r: 255, g: 0, b: 0, a: 1, }, "object input and compare" ); assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb(200, 100, 0)")); assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); assert( tinycolor.equals({ r: 200, g: 100, b: 0, a: 0.4 }, "rgba 200 100 0 .4") ); assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgba 200 100 0 1")); assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb(200, 100, 0)")); assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); assert( tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb(200, 100, 0)") ); assert( tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") ); assert( tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") ); }); Deno.test("Percentage RGB Text Parsing", function () { assertEquals( tinycolor("rgb 100% 0% 0%").toHexString(), "#ff0000", "spaced input" ); assertEquals( tinycolor("rgb(100%, 0%, 0%)").toHexString(), "#ff0000", "parenthesized input" ); assertEquals( tinycolor("rgb (100%, 0%, 0%)").toHexString(), "#ff0000", "parenthesized spaced input" ); assertEquals( tinycolor({ r: "100%", g: "0%", b: "0%" }).toHexString(), "#ff0000", "object input" ); assertEquals( tinycolor({ r: "100%", g: "0%", b: "0%" }).toRgb(), { r: 255, g: 0, b: 0, a: 1, }, "object input and compare" ); assert( tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") ); assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); assert( tinycolor.equals( { r: "90%", g: "45%", b: "0%", a: 0.4 }, "rgba 90% 45% 0% .4" ) ); assert( !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgba 90% 45% 0% 1") ); assert( !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") ); assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); assert( tinycolor.equals( tinycolor({ r: "90%", g: "45%", b: "0%" }), "rgb(90%, 45%, 0%)" ) ); assert( tinycolor.equals( tinycolor({ r: "90%", g: "45%", b: "0%" }), "rgb 90% 45% 0%" ) ); assert( tinycolor.equals( tinycolor({ r: "90%", g: "45%", b: "0%" }), "rgb 90% 45% 0%" ) ); }); Deno.test("HSL parsing", function () { assertEquals( tinycolor({ h: 251, s: 100, l: 0.38 }).toHexString(), "#2400c2", "to hex" ); assertEquals( tinycolor({ h: 251, s: 100, l: 0.38 }).toRgbString(), "rgb(36, 0, 194)", "to rgb" ); assertEquals( tinycolor({ h: 251, s: 100, l: 0.38 }).toHslString(), "hsl(251, 100%, 38%)", "to hsl" ); assertEquals( tinycolor({ h: 251, s: 100, l: 0.38, a: 0.5 }).toHslString(), "hsla(251, 100%, 38%, 0.5)", "to hsla" ); assertEquals( tinycolor("hsl(251, 100, 38)").toHexString(), "#2400c2", "to hex" ); assertEquals( tinycolor("hsl(251, 100%, 38%)").toRgbString(), "rgb(36, 0, 194)", "to rgb" ); assertEquals( tinycolor("hsl(251, 100%, 38%)").toHslString(), "hsl(251, 100%, 38%)", "to hsl" ); assertEquals( tinycolor("hsl 100 20 10").toHslString(), "hsl(100, 20%, 10%)", "problematic hsl" ); }); Deno.test("Hex Parsing", function () { assertEquals(tinycolor("rgb 255 0 0").toHexString(), "#ff0000"); assertEquals(tinycolor("rgb 255 0 0").toHexString(true), "#f00"); assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8String(), "#ff000080"); assertEquals(tinycolor("rgba 255 0 0 0").toHex8String(), "#ff000000"); assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(), "#ff0000ff"); assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(true), "#f00f"); assertEquals(tinycolor("rgb 255 0 0").toHex(), "ff0000"); assertEquals(tinycolor("rgb 255 0 0").toHex(true), "f00"); assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8(), "ff000080"); }); Deno.test("HSV Parsing", function () { assertEquals( tinycolor("hsv 251.1 0.887 .918").toHsvString(), "hsv(251, 89%, 92%)" ); assertEquals( tinycolor("hsv 251.1 0.887 0.918").toHsvString(), "hsv(251, 89%, 92%)" ); assertEquals( tinycolor("hsva 251.1 0.887 0.918 0.5").toHsvString(), "hsva(251, 89%, 92%, 0.5)" ); }); Deno.test("Invalid Parsing", function () { var invalidColor = tinycolor("this is not a color"); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor("#red"); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor(" #red"); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor("##123456"); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor(" ##123456"); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor({ r: "invalid", g: "invalid", b: "invalid" }); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor({ h: "invalid", s: "invalid", l: "invalid" }); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor({ h: "invalid", s: "invalid", v: "invalid" }); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); }); Deno.test("Named colors", function () { assertEquals(tinycolor("aliceblue").toHex(), "f0f8ff"); assertEquals(tinycolor("antiquewhite").toHex(), "faebd7"); assertEquals(tinycolor("aqua").toHex(), "00ffff"); assertEquals(tinycolor("aquamarine").toHex(), "7fffd4"); assertEquals(tinycolor("azure").toHex(), "f0ffff"); assertEquals(tinycolor("beige").toHex(), "f5f5dc"); assertEquals(tinycolor("bisque").toHex(), "ffe4c4"); assertEquals(tinycolor("black").toHex(), "000000"); assertEquals(tinycolor("blanchedalmond").toHex(), "ffebcd"); assertEquals(tinycolor("blue").toHex(), "0000ff"); assertEquals(tinycolor("blueviolet").toHex(), "8a2be2"); assertEquals(tinycolor("brown").toHex(), "a52a2a"); assertEquals(tinycolor("burlywood").toHex(), "deb887"); assertEquals(tinycolor("cadetblue").toHex(), "5f9ea0"); assertEquals(tinycolor("chartreuse").toHex(), "7fff00"); assertEquals(tinycolor("chocolate").toHex(), "d2691e"); assertEquals(tinycolor("coral").toHex(), "ff7f50"); assertEquals(tinycolor("cornflowerblue").toHex(), "6495ed"); assertEquals(tinycolor("cornsilk").toHex(), "fff8dc"); assertEquals(tinycolor("crimson").toHex(), "dc143c"); assertEquals(tinycolor("cyan").toHex(), "00ffff"); assertEquals(tinycolor("darkblue").toHex(), "00008b"); assertEquals(tinycolor("darkcyan").toHex(), "008b8b"); assertEquals(tinycolor("darkgoldenrod").toHex(), "b8860b"); assertEquals(tinycolor("darkgray").toHex(), "a9a9a9"); assertEquals(tinycolor("darkgreen").toHex(), "006400"); assertEquals(tinycolor("darkkhaki").toHex(), "bdb76b"); assertEquals(tinycolor("darkmagenta").toHex(), "8b008b"); assertEquals(tinycolor("darkolivegreen").toHex(), "556b2f"); assertEquals(tinycolor("darkorange").toHex(), "ff8c00"); assertEquals(tinycolor("darkorchid").toHex(), "9932cc"); assertEquals(tinycolor("darkred").toHex(), "8b0000"); assertEquals(tinycolor("darksalmon").toHex(), "e9967a"); assertEquals(tinycolor("darkseagreen").toHex(), "8fbc8f"); assertEquals(tinycolor("darkslateblue").toHex(), "483d8b"); assertEquals(tinycolor("darkslategray").toHex(), "2f4f4f"); assertEquals(tinycolor("darkturquoise").toHex(), "00ced1"); assertEquals(tinycolor("darkviolet").toHex(), "9400d3"); assertEquals(tinycolor("deeppink").toHex(), "ff1493"); assertEquals(tinycolor("deepskyblue").toHex(), "00bfff"); assertEquals(tinycolor("dimgray").toHex(), "696969"); assertEquals(tinycolor("dodgerblue").toHex(), "1e90ff"); assertEquals(tinycolor("firebrick").toHex(), "b22222"); assertEquals(tinycolor("floralwhite").toHex(), "fffaf0"); assertEquals(tinycolor("forestgreen").toHex(), "228b22"); assertEquals(tinycolor("fuchsia").toHex(), "ff00ff"); assertEquals(tinycolor("gainsboro").toHex(), "dcdcdc"); assertEquals(tinycolor("ghostwhite").toHex(), "f8f8ff"); assertEquals(tinycolor("gold").toHex(), "ffd700"); assertEquals(tinycolor("goldenrod").toHex(), "daa520"); assertEquals(tinycolor("gray").toHex(), "808080"); assertEquals(tinycolor("grey").toHex(), "808080"); assertEquals(tinycolor("green").toHex(), "008000"); assertEquals(tinycolor("greenyellow").toHex(), "adff2f"); assertEquals(tinycolor("honeydew").toHex(), "f0fff0"); assertEquals(tinycolor("hotpink").toHex(), "ff69b4"); assertEquals(tinycolor("indianred ").toHex(), "cd5c5c"); assertEquals(tinycolor("indigo ").toHex(), "4b0082"); assertEquals(tinycolor("ivory").toHex(), "fffff0"); assertEquals(tinycolor("khaki").toHex(), "f0e68c"); assertEquals(tinycolor("lavender").toHex(), "e6e6fa"); assertEquals(tinycolor("lavenderblush").toHex(), "fff0f5"); assertEquals(tinycolor("lawngreen").toHex(), "7cfc00"); assertEquals(tinycolor("lemonchiffon").toHex(), "fffacd"); assertEquals(tinycolor("lightblue").toHex(), "add8e6"); assertEquals(tinycolor("lightcoral").toHex(), "f08080"); assertEquals(tinycolor("lightcyan").toHex(), "e0ffff"); assertEquals(tinycolor("lightgoldenrodyellow").toHex(), "fafad2"); assertEquals(tinycolor("lightgrey").toHex(), "d3d3d3"); assertEquals(tinycolor("lightgreen").toHex(), "90ee90"); assertEquals(tinycolor("lightpink").toHex(), "ffb6c1"); assertEquals(tinycolor("lightsalmon").toHex(), "ffa07a"); assertEquals(tinycolor("lightseagreen").toHex(), "20b2aa"); assertEquals(tinycolor("lightskyblue").toHex(), "87cefa"); assertEquals(tinycolor("lightslategray").toHex(), "778899"); assertEquals(tinycolor("lightsteelblue").toHex(), "b0c4de"); assertEquals(tinycolor("lightyellow").toHex(), "ffffe0"); assertEquals(tinycolor("lime").toHex(), "00ff00"); assertEquals(tinycolor("limegreen").toHex(), "32cd32"); assertEquals(tinycolor("linen").toHex(), "faf0e6"); assertEquals(tinycolor("magenta").toHex(), "ff00ff"); assertEquals(tinycolor("maroon").toHex(), "800000"); assertEquals(tinycolor("mediumaquamarine").toHex(), "66cdaa"); assertEquals(tinycolor("mediumblue").toHex(), "0000cd"); assertEquals(tinycolor("mediumorchid").toHex(), "ba55d3"); assertEquals(tinycolor("mediumpurple").toHex(), "9370db"); assertEquals(tinycolor("mediumseagreen").toHex(), "3cb371"); assertEquals(tinycolor("mediumslateblue").toHex(), "7b68ee"); assertEquals(tinycolor("mediumspringgreen").toHex(), "00fa9a"); assertEquals(tinycolor("mediumturquoise").toHex(), "48d1cc"); assertEquals(tinycolor("mediumvioletred").toHex(), "c71585"); assertEquals(tinycolor("midnightblue").toHex(), "191970"); assertEquals(tinycolor("mintcream").toHex(), "f5fffa"); assertEquals(tinycolor("mistyrose").toHex(), "ffe4e1"); assertEquals(tinycolor("moccasin").toHex(), "ffe4b5"); assertEquals(tinycolor("navajowhite").toHex(), "ffdead"); assertEquals(tinycolor("navy").toHex(), "000080"); assertEquals(tinycolor("oldlace").toHex(), "fdf5e6"); assertEquals(tinycolor("olive").toHex(), "808000"); assertEquals(tinycolor("olivedrab").toHex(), "6b8e23"); assertEquals(tinycolor("orange").toHex(), "ffa500"); assertEquals(tinycolor("orangered").toHex(), "ff4500"); assertEquals(tinycolor("orchid").toHex(), "da70d6"); assertEquals(tinycolor("palegoldenrod").toHex(), "eee8aa"); assertEquals(tinycolor("palegreen").toHex(), "98fb98"); assertEquals(tinycolor("paleturquoise").toHex(), "afeeee"); assertEquals(tinycolor("palevioletred").toHex(), "db7093"); assertEquals(tinycolor("papayawhip").toHex(), "ffefd5"); assertEquals(tinycolor("peachpuff").toHex(), "ffdab9"); assertEquals(tinycolor("peru").toHex(), "cd853f"); assertEquals(tinycolor("pink").toHex(), "ffc0cb"); assertEquals(tinycolor("plum").toHex(), "dda0dd"); assertEquals(tinycolor("powderblue").toHex(), "b0e0e6"); assertEquals(tinycolor("purple").toHex(), "800080"); assertEquals(tinycolor("rebeccapurple").toHex(), "663399"); assertEquals(tinycolor("red").toHex(), "ff0000"); assertEquals(tinycolor("rosybrown").toHex(), "bc8f8f"); assertEquals(tinycolor("royalblue").toHex(), "4169e1"); assertEquals(tinycolor("saddlebrown").toHex(), "8b4513"); assertEquals(tinycolor("salmon").toHex(), "fa8072"); assertEquals(tinycolor("sandybrown").toHex(), "f4a460"); assertEquals(tinycolor("seagreen").toHex(), "2e8b57"); assertEquals(tinycolor("seashell").toHex(), "fff5ee"); assertEquals(tinycolor("sienna").toHex(), "a0522d"); assertEquals(tinycolor("silver").toHex(), "c0c0c0"); assertEquals(tinycolor("skyblue").toHex(), "87ceeb"); assertEquals(tinycolor("slateblue").toHex(), "6a5acd"); assertEquals(tinycolor("slategray").toHex(), "708090"); assertEquals(tinycolor("snow").toHex(), "fffafa"); assertEquals(tinycolor("springgreen").toHex(), "00ff7f"); assertEquals(tinycolor("steelblue").toHex(), "4682b4"); assertEquals(tinycolor("tan").toHex(), "d2b48c"); assertEquals(tinycolor("teal").toHex(), "008080"); assertEquals(tinycolor("thistle").toHex(), "d8bfd8"); assertEquals(tinycolor("tomato").toHex(), "ff6347"); assertEquals(tinycolor("turquoise").toHex(), "40e0d0"); assertEquals(tinycolor("violet").toHex(), "ee82ee"); assertEquals(tinycolor("wheat").toHex(), "f5deb3"); assertEquals(tinycolor("white").toHex(), "ffffff"); assertEquals(tinycolor("whitesmoke").toHex(), "f5f5f5"); assertEquals(tinycolor("yellow").toHex(), "ffff00"); assertEquals(tinycolor("yellowgreen").toHex(), "9acd32"); assertEquals(tinycolor("#f00").toName(), "red"); assertEquals(tinycolor("#fa0a0a").toName(), false); }); Deno.test("Invalid alpha should normalize to 1", function () { assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: -1 }).toRgbString(), "rgb(255, 20, 10)", "Negative value" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: -0 }).toRgbString(), "rgba(255, 20, 10, 0)", "Negative 0" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toRgbString(), "rgba(255, 20, 10, 0)", "0" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: 0.5 }).toRgbString(), "rgba(255, 20, 10, 0.5)", ".5" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: 1 }).toRgbString(), "rgb(255, 20, 10)", "1" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: 100 }).toRgbString(), "rgb(255, 20, 10)", "Greater than 1" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: "asdfasd" }).toRgbString(), "rgb(255, 20, 10)", "Non Numeric" ); assertEquals( tinycolor("#fff").toRgbString(), "rgb(255, 255, 255)", "Hex should be 1" ); assertEquals( tinycolor("rgba 255 0 0 100").toRgbString(), "rgb(255, 0, 0)", "Greater than 1 in string parsing" ); }); Deno.test("toString() with alpha set", function () { var redNamed = tinycolor.fromRatio( { r: 255, g: 0, b: 0, a: 0.6 }, { format: "name", } ); var transparentNamed = tinycolor.fromRatio( { r: 255, g: 0, b: 0, a: 0 }, { format: "name", } ); var redHex = tinycolor.fromRatio( { r: 255, g: 0, b: 0, a: 0.4 }, { format: "hex", } ); assertEquals(redNamed.getFormat(), "name", "getFormat() is correct"); assertEquals(redHex.getFormat(), "hex", "getFormat() is correct"); assertEquals( redNamed.toString(), "rgba(255, 0, 0, 0.6)", "Names should default to rgba if alpha is < 1" ); assertEquals( redHex.toString(), "rgba(255, 0, 0, 0.4)", "Hex should default to rgba if alpha is < 1" ); assertEquals( redNamed.toString("hex"), "#ff0000", "Names should not be returned as rgba if format is specified" ); assertEquals( redNamed.toString("hex6"), "#ff0000", "Names should not be returned as rgba if format is specified" ); assertEquals( redNamed.toString("hex3"), "#f00", "Names should not be returned as rgba if format is specified" ); assertEquals( redNamed.toString("hex8"), "#ff000099", "Names should not be returned as rgba if format is specified" ); assertEquals( redNamed.toString("hex4"), "#f009", "Names should not be returned as rgba if format is specified" ); assertEquals( redNamed.toString("name"), "#ff0000", "Semi transparent names should return hex in toString() if name format is specified" ); assertEquals( redNamed.toName(), false, "Semi transparent names should be false in toName()" ); assertEquals( redHex.toString(), "rgba(255, 0, 0, 0.4)", "Hex should default to rgba if alpha is < 1" ); assertEquals( transparentNamed.toString(), "transparent", "Named color should equal transparent if alpha == 0" ); redHex.setAlpha(0); assertEquals( redHex.toString(), "rgba(255, 0, 0, 0)", "Hex should default to rgba if alpha is = 0" ); }); Deno.test("setting alpha", function () { var hexSetter = tinycolor("rgba(255, 0, 0, 1)"); assertEquals(hexSetter.getAlpha(), 1, "Alpha should start as 1"); var returnedFromSetAlpha = hexSetter.setAlpha(0.9); assertEquals( returnedFromSetAlpha, hexSetter, "setAlpha return value should be the color." ); assertEquals(hexSetter.getAlpha(), 0.9, "setAlpha should change alpha value"); hexSetter.setAlpha(0.5); assertEquals(hexSetter.getAlpha(), 0.5, "setAlpha should change alpha value"); hexSetter.setAlpha(0); assertEquals(hexSetter.getAlpha(), 0, "setAlpha should change alpha value"); hexSetter.setAlpha(-1); assertEquals( hexSetter.getAlpha(), 1, "setAlpha with value < 0 should be bound to 1" ); hexSetter.setAlpha(2); assertEquals( hexSetter.getAlpha(), 1, "setAlpha with value > 1 should be bound to 1" ); hexSetter.setAlpha(); assertEquals( hexSetter.getAlpha(), 1, "setAlpha with invalid value should be bound to 1" ); hexSetter.setAlpha(null); assertEquals( hexSetter.getAlpha(), 1, "setAlpha with invalid value should be bound to 1" ); hexSetter.setAlpha("test"); assertEquals( hexSetter.getAlpha(), 1, "setAlpha with invalid value should be bound to 1" ); }); Deno.test("Alpha = 0 should act differently on toName()", function () { assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toName(), "transparent", "0" ); assertEquals( tinycolor("transparent").toString(), "transparent", "toString when passed" ); assertEquals(tinycolor("transparent").toHex(), "000000", "toHex"); }); Deno.test("getBrightness", function () { assertEquals(tinycolor("#000").getBrightness(), 0, "returns 0 for #000"); assertEquals(tinycolor("#fff").getBrightness(), 255, "returns 255 for #fff"); }); Deno.test("getLuminance", function () { assertEquals(tinycolor("#000").getLuminance(), 0, "returns 0 for #000"); assertEquals(tinycolor("#fff").getLuminance(), 1, "returns 1 for #fff"); }); Deno.test("isDark returns true/false for dark/light colors", function () { assertEquals(tinycolor("#000").isDark(), true, "#000 is dark"); assertEquals(tinycolor("#111").isDark(), true, "#111 is dark"); assertEquals(tinycolor("#222").isDark(), true, "#222 is dark"); assertEquals(tinycolor("#333").isDark(), true, "#333 is dark"); assertEquals(tinycolor("#444").isDark(), true, "#444 is dark"); assertEquals(tinycolor("#555").isDark(), true, "#555 is dark"); assertEquals(tinycolor("#666").isDark(), true, "#666 is dark"); assertEquals(tinycolor("#777").isDark(), true, "#777 is dark"); assertEquals(tinycolor("#888").isDark(), false, "#888 is not dark"); assertEquals(tinycolor("#999").isDark(), false, "#999 is not dark"); assertEquals(tinycolor("#aaa").isDark(), false, "#aaa is not dark"); assertEquals(tinycolor("#bbb").isDark(), false, "#bbb is not dark"); assertEquals(tinycolor("#ccc").isDark(), false, "#ccc is not dark"); assertEquals(tinycolor("#ddd").isDark(), false, "#ddd is not dark"); assertEquals(tinycolor("#eee").isDark(), false, "#eee is not dark"); assertEquals(tinycolor("#fff").isDark(), false, "#fff is not dark"); }); Deno.test("isLight returns true/false for light/dark colors", function () { assertEquals(tinycolor("#000").isLight(), false, "#000 is not light"); assertEquals(tinycolor("#111").isLight(), false, "#111 is not light"); assertEquals(tinycolor("#222").isLight(), false, "#222 is not light"); assertEquals(tinycolor("#333").isLight(), false, "#333 is not light"); assertEquals(tinycolor("#444").isLight(), false, "#444 is not light"); assertEquals(tinycolor("#555").isLight(), false, "#555 is not light"); assertEquals(tinycolor("#666").isLight(), false, "#666 is not light"); assertEquals(tinycolor("#777").isLight(), false, "#777 is not light"); assertEquals(tinycolor("#888").isLight(), true, "#888 is light"); assertEquals(tinycolor("#999").isLight(), true, "#999 is light"); assertEquals(tinycolor("#aaa").isLight(), true, "#aaa is light"); assertEquals(tinycolor("#bbb").isLight(), true, "#bbb is light"); assertEquals(tinycolor("#ccc").isLight(), true, "#ccc is light"); assertEquals(tinycolor("#ddd").isLight(), true, "#ddd is light"); assertEquals(tinycolor("#eee").isLight(), true, "#eee is light"); assertEquals(tinycolor("#fff").isLight(), true, "#fff is light"); }); Deno.test("HSL Object", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assertEquals( tiny.toHexString(), tinycolor(tiny.toHsl()).toHexString(), "HSL Object" ); } }); Deno.test("HSL String", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); var input = tiny.toRgb(); var output = tinycolor(tiny.toHslString()).toRgb(); var maxDiff = 2; assertEquals( Math.abs(input.r - output.r) <= maxDiff, true, "toHslString red value difference <= " + maxDiff ); assertEquals( Math.abs(input.g - output.g) <= maxDiff, true, "toHslString green value difference <= " + maxDiff ); assertEquals( Math.abs(input.b - output.b) <= maxDiff, true, "toHslString blue value difference <= " + maxDiff ); } }); Deno.test("HSV String", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); var input = tiny.toRgb(); var output = tinycolor(tiny.toHsvString()).toRgb(); var maxDiff = 2; assertEquals( Math.abs(input.r - output.r) <= maxDiff, true, "toHsvString red value difference <= " + maxDiff ); assertEquals( Math.abs(input.g - output.g) <= maxDiff, true, "toHsvString green value difference <= " + maxDiff ); assertEquals( Math.abs(input.b - output.b) <= maxDiff, true, "toHsvString blue value difference <= " + maxDiff ); } }); Deno.test("HSV Object", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assertEquals( tiny.toHexString(), tinycolor(tiny.toHsv()).toHexString(), "HSV Object" ); } }); Deno.test("RGB Object", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assertEquals( tiny.toHexString(), tinycolor(tiny.toRgb()).toHexString(), "RGB Object" ); } }); Deno.test("RGB String", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assertEquals( tiny.toHexString(), tinycolor(tiny.toRgbString()).toHexString(), "RGB String" ); } }); Deno.test("PRGB Object", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); var input = tiny.toRgb(); var output = tinycolor(tiny.toPercentageRgb()).toRgb(); var maxDiff = 2; assertEquals( Math.abs(input.r - output.r) <= maxDiff, true, "Red value difference <= " + maxDiff ); assertEquals( Math.abs(input.g - output.g) <= maxDiff, true, "Green value difference <= " + maxDiff ); assertEquals( Math.abs(input.b - output.b) <= maxDiff, true, "Blue value difference <= " + maxDiff ); } }); Deno.test("PRGB String", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); var input = tiny.toRgb(); var output = tinycolor(tiny.toPercentageRgbString()).toRgb(); var maxDiff = 2; assertEquals( Math.abs(input.r - output.r) <= maxDiff, true, "Red value difference <= " + maxDiff ); assertEquals( Math.abs(input.g - output.g) <= maxDiff, true, "Green value difference <= " + maxDiff ); assertEquals( Math.abs(input.b - output.b) <= maxDiff, true, "Blue value difference <= " + maxDiff ); } }); Deno.test("Object", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assertEquals(tiny.toHexString(), tinycolor(tiny).toHexString(), "Object"); } }); Deno.test("Color equality", function () { assert(tinycolor.equals("#ff0000", "#ff0000"), "Same hex"); assert(tinycolor.equals("#ff0000", "rgb(255, 0, 0)"), "Same alphas"); assert( !tinycolor.equals("#ff0000", "rgba(255, 0, 0, .1)"), "Different alphas" ); assert(tinycolor.equals("#ff000066", "rgba(255, 0, 0, .4)"), "Same alphas"); assert(tinycolor.equals("#f009", "rgba(255, 0, 0, .6)"), "Same alphas"); assert(tinycolor.equals("#336699CC", "369C"), "Same hex"); assert(tinycolor.equals("ff0000", "#ff0000"), "Same hex"); assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); assert(tinycolor.equals("f00", "#ff0000"), "Same hex"); assertEquals(tinycolor("010101").toHexString(), "#010101"); assert(!tinycolor.equals("#ff0000", "#00ff00"), "Different hex"); assert( tinycolor.equals("#ff8000", "rgb(100%, 50%, 0%)"), "Percentage bounds checking" ); }); Deno.test("isReadable", function () { // "#ff0088", "#8822aa" (values used in old WCAG1 tests) assert( tinycolor.isReadable("#000000", "#ffffff", { level: "AA", size: "small" }), "white/black is readable" ); assert( !tinycolor.isReadable("#ff0088", "#5c1a72", {}), "not readable - empty wcag2 object" ); assert( !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "small" }), "not readable - AA small" ); assert( !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "large" }), "not readable - AA large" ); assert( !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AAA", size: "small", }), "not readable - AAA small" ); assert( !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AAA", size: "large", }), "not readable - AAA large" ); // values derived from and validated using the calculators at http://www.dasplankton.de/ContrastA/ // and http://webaim.org/resources/contrastchecker/ // "#ff0088", "#5c1a72": contrast ratio 3.04 assert( !tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "small" }), "not readable - AA small" ); assert( tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "large" }), "readable - AA large" ); assert( !tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AAA", size: "small", }), "not readable - AAA small" ); assert( !tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AAA", size: "large", }), "not readable - AAA large" ); // "#ff0088", "#2e0c3a": contrast ratio 4.56 assert( tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "small" }), "readable - AA small" ); assert( tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "large" }), "readable - AA large" ); assert( !tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AAA", size: "small", }), "not readable - AAA small" ); assert( tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AAA", size: "large" }), "readable - AAA large" ); // "#db91b8", "#2e0c3a": contrast ratio 7.12 assert( tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "small" }), "readable - AA small" ); assert( tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "large" }), "readable - AA large" ); assert( tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "small" }), "readable - AAA small" ); assert( tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "large" }), "readable - AAA large" ); }); Deno.test("readability", function () { // check return values from readability function. See isReadable above for standards tests. assertEquals( tinycolor.readability("#000", "#000"), 1, "Readability function test 0" ); assertEquals( tinycolor.readability("#000", "#111"), 1.1121078324840545, "Readability function test 1" ); assertEquals( tinycolor.readability("#000", "#fff"), 21, "Readability function test 2" ); }); Deno.test("mostReadable", function () { assertEquals( tinycolor .mostReadable("#000", ["#111", "#222", { wcag2: {} }]) .toHexString(), "#222222", "readable color present" ); assertEquals( tinycolor .mostReadable("#f00", ["#d00", "#0d0"], { wcag2: {} }) .toHexString(), "#00dd00", "readable color present" ); assertEquals( tinycolor .mostReadable("#fff", ["#fff", "#fff"], { wcag2: {} }) .toHexString(), "#ffffff", "no different color in list" ); //includeFallbackColors assertEquals( tinycolor .mostReadable("#fff", ["#fff", "#fff"], { includeFallbackColors: true, }) .toHexString(), "#000000", "no different color in list" ); assertEquals( tinycolor .mostReadable("#123", ["#124", "#125"], { includeFallbackColors: false, }) .toHexString(), "#112255", "no readable color in list" ); assertEquals( tinycolor .mostReadable("#123", ["#000", "#fff"], { includeFallbackColors: false, }) .toHexString(), "#ffffff", "verify assumption" ); assertEquals( tinycolor .mostReadable("#123", ["#124", "#125"], { includeFallbackColors: true, }) .toHexString(), "#ffffff", "no readable color in list" ); assertEquals( tinycolor .mostReadable("#ff0088", ["#000", "#fff"], { includeFallbackColors: false, }) .toHexString(), "#000000", "verify assumption" ); assertEquals( tinycolor .mostReadable("#ff0088", ["#2e0c3a"], { includeFallbackColors: true, level: "AAA", size: "large", }) .toHexString(), "#2e0c3a", "readable color present" ); assertEquals( tinycolor .mostReadable("#ff0088", ["#2e0c3a"], { includeFallbackColors: true, level: "AAA", size: "small", }) .toHexString(), "#000000", "no readable color in list" ); assertEquals( tinycolor .mostReadable("#371b2c", ["#000", "#fff"], { includeFallbackColors: false, }) .toHexString(), "#ffffff", "verify assumption" ); assertEquals( tinycolor .mostReadable("#371b2c", ["#a9acb6"], { includeFallbackColors: true, level: "AAA", size: "large", }) .toHexString(), "#a9acb6", "readable color present" ); assertEquals( tinycolor .mostReadable("#371b2c", ["#a9acb6"], { includeFallbackColors: true, level: "AAA", size: "small", }) .toHexString(), "#ffffff", "no readable color in list" ); }); Deno.test("Filters", function () { assertEquals( tinycolor("red").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ffff0000)" ); assertEquals( tinycolor("red").toFilter("blue"), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ff0000ff)" ); assertEquals( tinycolor("transparent").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#00000000)" ); assertEquals( tinycolor("transparent").toFilter("red"), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#ffff0000)" ); assertEquals( tinycolor("#f0f0f0dd").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ddf0f0f0,endColorstr=#ddf0f0f0)" ); assertEquals( tinycolor("rgba(0, 0, 255, .5").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#800000ff,endColorstr=#800000ff)" ); }); /* Originally generated with: var results = []; for (var i = 0; i <= 100; i++) results.push( tinycolor.saturate("red", i).toHex() ) console.log(JSON.stringify(results)) */ var DESATURATIONS = [ "ff0000", "fe0101", "fc0303", "fb0404", "fa0505", "f90606", "f70808", "f60909", "f50a0a", "f40b0b", "f20d0d", "f10e0e", "f00f0f", "ee1111", "ed1212", "ec1313", "eb1414", "e91616", "e81717", "e71818", "e61919", "e41b1b", "e31c1c", "e21d1d", "e01f1f", "df2020", "de2121", "dd2222", "db2424", "da2525", "d92626", "d72828", "d62929", "d52a2a", "d42b2b", "d22d2d", "d12e2e", "d02f2f", "cf3030", "cd3232", "cc3333", "cb3434", "c93636", "c83737", "c73838", "c63939", "c43b3b", "c33c3c", "c23d3d", "c13e3e", "bf4040", "be4141", "bd4242", "bb4444", "ba4545", "b94646", "b84747", "b64949", "b54a4a", "b44b4b", "b34d4d", "b14e4e", "b04f4f", "af5050", "ad5252", "ac5353", "ab5454", "aa5555", "a85757", "a75858", "a65959", "a45b5b", "a35c5c", "a25d5d", "a15e5e", "9f6060", "9e6161", "9d6262", "9c6363", "9a6565", "996666", "986767", "966969", "956a6a", "946b6b", "936c6c", "916e6e", "906f6f", "8f7070", "8e7171", "8c7373", "8b7474", "8a7575", "887777", "877878", "867979", "857a7a", "837c7c", "827d7d", "817e7e", "808080", ]; var SATURATIONS = [ "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", ]; var LIGHTENS = [ "ff0000", "ff0505", "ff0a0a", "ff0f0f", "ff1414", "ff1a1a", "ff1f1f", "ff2424", "ff2929", "ff2e2e", "ff3333", "ff3838", "ff3d3d", "ff4242", "ff4747", "ff4d4d", "ff5252", "ff5757", "ff5c5c", "ff6161", "ff6666", "ff6b6b", "ff7070", "ff7575", "ff7a7a", "ff8080", "ff8585", "ff8a8a", "ff8f8f", "ff9494", "ff9999", "ff9e9e", "ffa3a3", "ffa8a8", "ffadad", "ffb3b3", "ffb8b8", "ffbdbd", "ffc2c2", "ffc7c7", "ffcccc", "ffd1d1", "ffd6d6", "ffdbdb", "ffe0e0", "ffe5e5", "ffebeb", "fff0f0", "fff5f5", "fffafa", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", ]; var BRIGHTENS = [ "ff0000", "ff0303", "ff0505", "ff0808", "ff0a0a", "ff0d0d", "ff0f0f", "ff1212", "ff1414", "ff1717", "ff1919", "ff1c1c", "ff1f1f", "ff2121", "ff2424", "ff2626", "ff2929", "ff2b2b", "ff2e2e", "ff3030", "ff3333", "ff3636", "ff3838", "ff3b3b", "ff3d3d", "ff4040", "ff4242", "ff4545", "ff4747", "ff4a4a", "ff4c4c", "ff4f4f", "ff5252", "ff5454", "ff5757", "ff5959", "ff5c5c", "ff5e5e", "ff6161", "ff6363", "ff6666", "ff6969", "ff6b6b", "ff6e6e", "ff7070", "ff7373", "ff7575", "ff7878", "ff7a7a", "ff7d7d", "ff7f7f", "ff8282", "ff8585", "ff8787", "ff8a8a", "ff8c8c", "ff8f8f", "ff9191", "ff9494", "ff9696", "ff9999", "ff9c9c", "ff9e9e", "ffa1a1", "ffa3a3", "ffa6a6", "ffa8a8", "ffabab", "ffadad", "ffb0b0", "ffb2b2", "ffb5b5", "ffb8b8", "ffbaba", "ffbdbd", "ffbfbf", "ffc2c2", "ffc4c4", "ffc7c7", "ffc9c9", "ffcccc", "ffcfcf", "ffd1d1", "ffd4d4", "ffd6d6", "ffd9d9", "ffdbdb", "ffdede", "ffe0e0", "ffe3e3", "ffe5e5", "ffe8e8", "ffebeb", "ffeded", "fff0f0", "fff2f2", "fff5f5", "fff7f7", "fffafa", "fffcfc", "ffffff", ]; var DARKENS = [ "ff0000", "fa0000", "f50000", "f00000", "eb0000", "e60000", "e00000", "db0000", "d60000", "d10000", "cc0000", "c70000", "c20000", "bd0000", "b80000", "b30000", "ad0000", "a80000", "a30000", "9e0000", "990000", "940000", "8f0000", "8a0000", "850000", "800000", "7a0000", "750000", "700000", "6b0000", "660000", "610000", "5c0000", "570000", "520000", "4d0000", "470000", "420000", "3d0000", "380000", "330000", "2e0000", "290000", "240000", "1f0000", "190000", "140000", "0f0000", "0a0000", "050000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", ]; Deno.test("Modifications", function () { for (var i = 0; i <= 100; i++) { assertEquals( tinycolor("red").desaturate(i).toHex(), DESATURATIONS[i], "Desaturation " + i + " works" ); } for (var i = 0; i <= 100; i++) { assertEquals( tinycolor("red").saturate(i).toHex(), SATURATIONS[i], "Saturation " + i + " works" ); } for (var i = 0; i <= 100; i++) { assertEquals( tinycolor("red").lighten(i).toHex(), LIGHTENS[i], "Lighten " + i + " works" ); } for (var i = 0; i <= 100; i++) { assertEquals( tinycolor("red").brighten(i).toHex(), BRIGHTENS[i], "Brighter " + i + " works" ); } for (var i = 0; i <= 100; i++) { assertEquals( tinycolor("red").darken(i).toHex(), DARKENS[i], "Darken " + i + " works" ); } assertEquals( tinycolor("red").greyscale().toHex(), "808080", "Greyscale works" ); }); Deno.test("Spin", function () { assertEquals( Math.round(tinycolor("#f00").spin(-1234).toHsl().h), 206, "Spinning -1234 works" ); assertEquals( Math.round(tinycolor("#f00").spin(-360).toHsl().h), 0, "Spinning -360 works" ); assertEquals( Math.round(tinycolor("#f00").spin(-120).toHsl().h), 240, "Spinning -120 works" ); assertEquals( Math.round(tinycolor("#f00").spin(0).toHsl().h), 0, "Spinning 0 works" ); assertEquals( Math.round(tinycolor("#f00").spin(10).toHsl().h), 10, "Spinning 10 works" ); assertEquals( Math.round(tinycolor("#f00").spin(360).toHsl().h), 0, "Spinning 360 works" ); assertEquals( Math.round(tinycolor("#f00").spin(2345).toHsl().h), 185, "Spinning 2345 works" ); [-360, 0, 360].forEach(function (delta) { Object.keys(tinycolor.names).forEach(function (name) { assertEquals( tinycolor(name).toHex(), tinycolor(name).spin(delta).toHex(), "Spinning " + delta.toString() + " has no effect" ); }); }); }); Deno.test("Mix", function () { // amount 0 or none assertEquals( tinycolor.mix("#000", "#fff").toHsl().l, 0.5, "Mixing without amount works" ); assertEquals( tinycolor.mix("#f00", "#000", 0).toHex(), "ff0000", "Mixing with 0 amount works" ); // This case checks the the problem with floating point numbers (eg 255/90) assertEquals( tinycolor.mix("#fff", "#000", 90).toHex(), "1a1a1a", "Mixing with 90 amount works correctly" ); // black and white for (var i = 0; i < 100; i++) { assertEquals( Math.round(tinycolor.mix("#000", "#fff", i).toHsl().l * 100) / 100, i / 100, "Mixing black and white with " + i + " amount works" ); } // with colors for (var i = 0; i < 100; i++) { var new_hex = Math.round((255 * (100 - i)) / 100).toString(16); if (new_hex.length === 1) { new_hex = "0" + new_hex; } assertEquals( tinycolor.mix("#f00", "#000", i).toHex(), new_hex + "0000", "Mixing " + i + " (red channel)" ); assertEquals( tinycolor.mix("#0f0", "#000", i).toHex(), "00" + new_hex + "00", "Mixing " + i + " (green channel)" ); assertEquals( tinycolor.mix("#00f", "#000", i).toHex(), "0000" + new_hex, "Mixing " + i + " (blue channel)" ); assertEquals( tinycolor.mix(tinycolor("transparent"), "#000", i).toRgb().a, i / 100, "Mixing " + i + " (alpha channel)" ); } }); // The combination tests need to be expanded furthe function colorsToHexString(colors) { return colors .map(function (c) { return c.toHex(); }) .join(","); } Deno.test("complement", function () { var complementDoesntModifyInstance = tinycolor("red"); assertEquals( complementDoesntModifyInstance.complement().toHex(), "00ffff", "Complement works" ); assertEquals( complementDoesntModifyInstance.toHex(), "ff0000", "Complement did not modify this color" ); }); Deno.test("analogous", function () { var combination = tinycolor("red").analogous(); assertEquals( colorsToHexString(combination), "ff0000,ff0066,ff0033,ff0000,ff3300,ff6600", "Correct Combination" ); }); Deno.test("monochromatic", function () { var combination = tinycolor("red").monochromatic(); assertEquals( colorsToHexString(combination), "ff0000,2a0000,550000,800000,aa0000,d40000", "Correct Combination" ); }); Deno.test("splitcomplement", function () { var combination = tinycolor("red").splitcomplement(); assertEquals( colorsToHexString(combination), "ff0000,ccff00,0066ff", "Correct Combination" ); }); Deno.test("triad", function () { var combination = tinycolor("red").triad(); assertEquals( colorsToHexString(combination), "ff0000,00ff00,0000ff", "Correct Combination" ); }); Deno.test("tetrad", function () { var combination = tinycolor("red").tetrad(); assertEquals( colorsToHexString(combination), "ff0000,80ff00,00ffff,7f00ff", "Correct Combination" ); }); Deno.test({ name: "polyad", // Disabled until https://github.com/bgrins/TinyColor/issues/254 ignore: true, fn: function () { assertThrows(() => { tinycolor("red").polyad(); }); assertThrows(() => { tinycolor("red").polyad(-1); }); assertThrows(() => { tinycolor("red").polyad("invalid"); }); assertEquals(colorsToHexString(tinycolor("red").polyad(1)), "ff0000"); assertEquals(colorsToHexString(tinycolor("red").polyad("1")), "ff0000"); assertEquals( colorsToHexString(tinycolor("red").polyad(2)), "ff0000,00ffff" ); assertEquals( colorsToHexString(tinycolor("red").polyad(3)), "ff0000,00ff00,0000ff" ); assertEquals( colorsToHexString(tinycolor("red").polyad(4)), "ff0000,80ff00,00ffff,7f00ff" ); assertEquals( colorsToHexString(tinycolor("red").polyad(5)), "ff0000,ccff00,00ff66,0066ff,cc00ff" ); }, }); runDenoTests(); node_modules/tinycolor2/esm/test_template.js 0000664 00000001314 15114743311 0015322 0 ustar 00 // This file is autogenerated. // Ideally it wouldn't exist, but it's here to test cjs in node // Changes should go into ./test.js, and if new assertions are needed // they'll need to be shimmed here as well import tinycolor from "./tinycolor.js"; import { Deno, testDefinitions } from "@deno/shim-deno-test"; const { assertEquals, assert, assertThrows } = await import( "../deno_asserts@0.168.0.mjs" ); async function runDenoTests() { for (const test of testDefinitions) { if (test.ignore) { console.log(`Ignoring ${test.name}`); continue; } console.log(`Running ${test.name}`); await test.fn(); console.log(`> Passed ${test.name}`); } } // CONTENT_GOES_HERE runDenoTests(); node_modules/tinycolor2/package.json 0000664 00000001510 15114743311 0013612 0 ustar 00 { "version": "1.6.0", "name": "tinycolor2", "description": "Fast Color Parsing and Manipulation", "url": "http://bgrins.github.com/TinyColor", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/bgrins/TinyColor.git" }, "keywords": [ "color", "parser", "tinycolor" ], "author": "Brian Grinstead <briangrinstead@gmail.com> (http://briangrinstead.com)", "bugs": { "url": "https://github.com/bgrins/TinyColor/issues" }, "module": "./esm/tinycolor.js", "main": "./cjs/tinycolor.js", "browser": "./cjs/tinycolor.js", "exports": { ".": { "import": "./esm/tinycolor.js", "require": "./cjs/tinycolor.js" } }, "scripts": { "test": "node cjs/test.js && node esm/test.js" }, "devDependencies": { "@deno/shim-deno-test": "^0.4.0" } } node_modules/tinycolor2/LICENSE 0000664 00000002071 15114743311 0012334 0 ustar 00 Copyright (c), Brian Grinstead, http://briangrinstead.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/tinycolor2/dist/tinycolor-min.js 0000664 00000036365 15114743311 0015450 0 ustar 00 // This file is autogenerated. // It's here at this path for backwards compatibility for links to it // but the npm package now exports both CJS and ESM. // See https://github.com/bgrins/TinyColor/ for instructions. !function(t,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(t="undefined"!=typeof globalThis?globalThis:t||self).tinycolor=r()}(this,(function(){"use strict";function t(r){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(r)}var r=/^\s+/,e=/\s+$/;function n(a,i){if(i=i||{},(a=a||"")instanceof n)return a;if(!(this instanceof n))return new n(a,i);var o=function(n){var a={r:0,g:0,b:0},i=1,o=null,h=null,s=null,f=!1,u=!1;"string"==typeof n&&(n=function(t){t=t.replace(r,"").replace(e,"").toLowerCase();var n,a=!1;if(y[t])t=y[t],a=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(n=T.rgb.exec(t))return{r:n[1],g:n[2],b:n[3]};if(n=T.rgba.exec(t))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=T.hsl.exec(t))return{h:n[1],s:n[2],l:n[3]};if(n=T.hsla.exec(t))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=T.hsv.exec(t))return{h:n[1],s:n[2],v:n[3]};if(n=T.hsva.exec(t))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=T.hex8.exec(t))return{r:w(n[1]),g:w(n[2]),b:w(n[3]),a:F(n[4]),format:a?"name":"hex8"};if(n=T.hex6.exec(t))return{r:w(n[1]),g:w(n[2]),b:w(n[3]),format:a?"name":"hex"};if(n=T.hex4.exec(t))return{r:w(n[1]+""+n[1]),g:w(n[2]+""+n[2]),b:w(n[3]+""+n[3]),a:F(n[4]+""+n[4]),format:a?"name":"hex8"};if(n=T.hex3.exec(t))return{r:w(n[1]+""+n[1]),g:w(n[2]+""+n[2]),b:w(n[3]+""+n[3]),format:a?"name":"hex"};return!1}(n));"object"==t(n)&&(E(n.r)&&E(n.g)&&E(n.b)?(l=n.r,c=n.g,d=n.b,a={r:255*A(l,255),g:255*A(c,255),b:255*A(d,255)},f=!0,u="%"===String(n.r).substr(-1)?"prgb":"rgb"):E(n.h)&&E(n.s)&&E(n.v)?(o=H(n.s),h=H(n.v),a=function(t,r,e){t=6*A(t,360),r=A(r,100),e=A(e,100);var n=Math.floor(t),a=t-n,i=e*(1-r),o=e*(1-a*r),h=e*(1-(1-a)*r),s=n%6,f=[e,o,i,i,h,e][s],u=[h,e,e,o,i,i][s],l=[i,i,h,e,e,o][s];return{r:255*f,g:255*u,b:255*l}}(n.h,o,h),f=!0,u="hsv"):E(n.h)&&E(n.s)&&E(n.l)&&(o=H(n.s),s=H(n.l),a=function(t,r,e){var n,a,i;function o(t,r,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?t+6*(r-t)*e:e<.5?r:e<2/3?t+(r-t)*(2/3-e)*6:t}if(t=A(t,360),r=A(r,100),e=A(e,100),0===r)n=a=i=e;else{var h=e<.5?e*(1+r):e+r-e*r,s=2*e-h;n=o(s,h,t+1/3),a=o(s,h,t),i=o(s,h,t-1/3)}return{r:255*n,g:255*a,b:255*i}}(n.h,o,s),f=!0,u="hsl"),n.hasOwnProperty("a")&&(i=n.a));var l,c,d;return i=x(i),{ok:f,format:n.format||u,r:Math.min(255,Math.max(a.r,0)),g:Math.min(255,Math.max(a.g,0)),b:Math.min(255,Math.max(a.b,0)),a:i}}(a);this._originalInput=a,this._r=o.r,this._g=o.g,this._b=o.b,this._a=o.a,this._roundA=Math.round(100*this._a)/100,this._format=i.format||o.format,this._gradientType=i.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=o.ok}function a(t,r,e){t=A(t,255),r=A(r,255),e=A(e,255);var n,a,i=Math.max(t,r,e),o=Math.min(t,r,e),h=(i+o)/2;if(i==o)n=a=0;else{var s=i-o;switch(a=h>.5?s/(2-i-o):s/(i+o),i){case t:n=(r-e)/s+(r<e?6:0);break;case r:n=(e-t)/s+2;break;case e:n=(t-r)/s+4}n/=6}return{h:n,s:a,l:h}}function i(t,r,e){t=A(t,255),r=A(r,255),e=A(e,255);var n,a,i=Math.max(t,r,e),o=Math.min(t,r,e),h=i,s=i-o;if(a=0===i?0:s/i,i==o)n=0;else{switch(i){case t:n=(r-e)/s+(r<e?6:0);break;case r:n=(e-t)/s+2;break;case e:n=(t-r)/s+4}n/=6}return{h:n,s:a,v:h}}function o(t,r,e,n){var a=[S(Math.round(t).toString(16)),S(Math.round(r).toString(16)),S(Math.round(e).toString(16))];return n&&a[0].charAt(0)==a[0].charAt(1)&&a[1].charAt(0)==a[1].charAt(1)&&a[2].charAt(0)==a[2].charAt(1)?a[0].charAt(0)+a[1].charAt(0)+a[2].charAt(0):a.join("")}function h(t,r,e,n){return[S(R(n)),S(Math.round(t).toString(16)),S(Math.round(r).toString(16)),S(Math.round(e).toString(16))].join("")}function s(t,r){r=0===r?0:r||10;var e=n(t).toHsl();return e.s-=r/100,e.s=k(e.s),n(e)}function f(t,r){r=0===r?0:r||10;var e=n(t).toHsl();return e.s+=r/100,e.s=k(e.s),n(e)}function u(t){return n(t).desaturate(100)}function l(t,r){r=0===r?0:r||10;var e=n(t).toHsl();return e.l+=r/100,e.l=k(e.l),n(e)}function c(t,r){r=0===r?0:r||10;var e=n(t).toRgb();return e.r=Math.max(0,Math.min(255,e.r-Math.round(-r/100*255))),e.g=Math.max(0,Math.min(255,e.g-Math.round(-r/100*255))),e.b=Math.max(0,Math.min(255,e.b-Math.round(-r/100*255))),n(e)}function d(t,r){r=0===r?0:r||10;var e=n(t).toHsl();return e.l-=r/100,e.l=k(e.l),n(e)}function g(t,r){var e=n(t).toHsl(),a=(e.h+r)%360;return e.h=a<0?360+a:a,n(e)}function b(t){var r=n(t).toHsl();return r.h=(r.h+180)%360,n(r)}function m(t,r){if(isNaN(r)||r<=0)throw new Error("Argument to polyad must be a positive number");for(var e=n(t).toHsl(),a=[n(t)],i=360/r,o=1;o<r;o++)a.push(n({h:(e.h+o*i)%360,s:e.s,l:e.l}));return a}function p(t){var r=n(t).toHsl(),e=r.h;return[n(t),n({h:(e+72)%360,s:r.s,l:r.l}),n({h:(e+216)%360,s:r.s,l:r.l})]}function _(t,r,e){r=r||6,e=e||30;var a=n(t).toHsl(),i=360/e,o=[n(t)];for(a.h=(a.h-(i*r>>1)+720)%360;--r;)a.h=(a.h+i)%360,o.push(n(a));return o}function v(t,r){r=r||6;for(var e=n(t).toHsv(),a=e.h,i=e.s,o=e.v,h=[],s=1/r;r--;)h.push(n({h:a,s:i,v:o})),o=(o+s)%1;return h}n.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var t,r,e,n=this.toRgb();return t=n.r/255,r=n.g/255,e=n.b/255,.2126*(t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))},setAlpha:function(t){return this._a=x(t),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var t=i(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=i(this._r,this._g,this._b),r=Math.round(360*t.h),e=Math.round(100*t.s),n=Math.round(100*t.v);return 1==this._a?"hsv("+r+", "+e+"%, "+n+"%)":"hsva("+r+", "+e+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=a(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=a(this._r,this._g,this._b),r=Math.round(360*t.h),e=Math.round(100*t.s),n=Math.round(100*t.l);return 1==this._a?"hsl("+r+", "+e+"%, "+n+"%)":"hsla("+r+", "+e+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return o(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,r,e,n,a){var i=[S(Math.round(t).toString(16)),S(Math.round(r).toString(16)),S(Math.round(e).toString(16)),S(R(n))];if(a&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)&&i[3].charAt(0)==i[3].charAt(1))return i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0)+i[3].charAt(0);return i.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(100*A(this._r,255))+"%",g:Math.round(100*A(this._g,255))+"%",b:Math.round(100*A(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*A(this._r,255))+"%, "+Math.round(100*A(this._g,255))+"%, "+Math.round(100*A(this._b,255))+"%)":"rgba("+Math.round(100*A(this._r,255))+"%, "+Math.round(100*A(this._g,255))+"%, "+Math.round(100*A(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(M[o(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var r="#"+h(this._r,this._g,this._b,this._a),e=r,a=this._gradientType?"GradientType = 1, ":"";if(t){var i=n(t);e="#"+h(i._r,i._g,i._b,i._a)}return"progid:DXImageTransform.Microsoft.gradient("+a+"startColorstr="+r+",endColorstr="+e+")"},toString:function(t){var r=!!t;t=t||this._format;var e=!1,n=this._a<1&&this._a>=0;return r||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(e=this.toRgbString()),"prgb"===t&&(e=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(e=this.toHexString()),"hex3"===t&&(e=this.toHexString(!0)),"hex4"===t&&(e=this.toHex8String(!0)),"hex8"===t&&(e=this.toHex8String()),"name"===t&&(e=this.toName()),"hsl"===t&&(e=this.toHslString()),"hsv"===t&&(e=this.toHsvString()),e||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return n(this.toString())},_applyModification:function(t,r){var e=t.apply(null,[this].concat([].slice.call(r)));return this._r=e._r,this._g=e._g,this._b=e._b,this.setAlpha(e._a),this},lighten:function(){return this._applyModification(l,arguments)},brighten:function(){return this._applyModification(c,arguments)},darken:function(){return this._applyModification(d,arguments)},desaturate:function(){return this._applyModification(s,arguments)},saturate:function(){return this._applyModification(f,arguments)},greyscale:function(){return this._applyModification(u,arguments)},spin:function(){return this._applyModification(g,arguments)},_applyCombination:function(t,r){return t.apply(null,[this].concat([].slice.call(r)))},analogous:function(){return this._applyCombination(_,arguments)},complement:function(){return this._applyCombination(b,arguments)},monochromatic:function(){return this._applyCombination(v,arguments)},splitcomplement:function(){return this._applyCombination(p,arguments)},triad:function(){return this._applyCombination(m,[3])},tetrad:function(){return this._applyCombination(m,[4])}},n.fromRatio=function(r,e){if("object"==t(r)){var a={};for(var i in r)r.hasOwnProperty(i)&&(a[i]="a"===i?r[i]:H(r[i]));r=a}return n(r,e)},n.equals=function(t,r){return!(!t||!r)&&n(t).toRgbString()==n(r).toRgbString()},n.random=function(){return n.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},n.mix=function(t,r,e){e=0===e?0:e||50;var a=n(t).toRgb(),i=n(r).toRgb(),o=e/100;return n({r:(i.r-a.r)*o+a.r,g:(i.g-a.g)*o+a.g,b:(i.b-a.b)*o+a.b,a:(i.a-a.a)*o+a.a})},n.readability=function(t,r){var e=n(t),a=n(r);return(Math.max(e.getLuminance(),a.getLuminance())+.05)/(Math.min(e.getLuminance(),a.getLuminance())+.05)},n.isReadable=function(t,r,e){var a,i,o=n.readability(t,r);switch(i=!1,(a=function(t){var r,e;r=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),e=(t.size||"small").toLowerCase(),"AA"!==r&&"AAA"!==r&&(r="AA");"small"!==e&&"large"!==e&&(e="small");return{level:r,size:e}}(e)).level+a.size){case"AAsmall":case"AAAlarge":i=o>=4.5;break;case"AAlarge":i=o>=3;break;case"AAAsmall":i=o>=7}return i},n.mostReadable=function(t,r,e){var a,i,o,h,s=null,f=0;i=(e=e||{}).includeFallbackColors,o=e.level,h=e.size;for(var u=0;u<r.length;u++)(a=n.readability(t,r[u]))>f&&(f=a,s=n(r[u]));return n.isReadable(t,s,{level:o,size:h})||!i?s:(e.includeFallbackColors=!1,n.mostReadable(t,["#fff","#000"],e))};var y=n.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},M=n.hexNames=function(t){var r={};for(var e in t)t.hasOwnProperty(e)&&(r[t[e]]=e);return r}(y);function x(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function A(t,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(t)&&(t="100%");var e=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(t);return t=Math.min(r,Math.max(0,parseFloat(t))),e&&(t=parseInt(t*r,10)/100),Math.abs(t-r)<1e-6?1:t%r/parseFloat(r)}function k(t){return Math.min(1,Math.max(0,t))}function w(t){return parseInt(t,16)}function S(t){return 1==t.length?"0"+t:""+t}function H(t){return t<=1&&(t=100*t+"%"),t}function R(t){return Math.round(255*parseFloat(t)).toString(16)}function F(t){return w(t)/255}var C,q,N,T=(q="[\\s|\\(]+("+(C="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+C+")[,|\\s]+("+C+")\\s*\\)?",N="[\\s|\\(]+("+C+")[,|\\s]+("+C+")[,|\\s]+("+C+")[,|\\s]+("+C+")\\s*\\)?",{CSS_UNIT:new RegExp(C),rgb:new RegExp("rgb"+q),rgba:new RegExp("rgba"+N),hsl:new RegExp("hsl"+q),hsla:new RegExp("hsla"+N),hsv:new RegExp("hsv"+q),hsva:new RegExp("hsva"+N),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function E(t){return!!T.CSS_UNIT.exec(t)}return n})); node_modules/tinycolor2/deno_asserts@0.168.0.mjs 0000664 00000066540 15114743311 0015401 0 ustar 00 // deno-fmt-ignore-file // deno-lint-ignore-file // This code was bundled using `deno bundle` and it's not recommended to edit it manually // Using `deno bundle https://deno.land/std@0.168.0/testing/asserts.ts > npm/deno_asserts@0.168.0.mjs` const { Deno } = globalThis; const noColor = typeof Deno?.noColor === "boolean" ? Deno.noColor : true; let enabled = !noColor; function code(open, close) { return { open: `\x1b[${open.join(";")}m`, close: `\x1b[${close}m`, regexp: new RegExp(`\\x1b\\[${close}m`, "g") }; } function run(str, code) { return enabled ? `${code.open}${str.replace(code.regexp, code.open)}${code.close}` : str; } function bold(str) { return run(str, code([ 1 ], 22)); } function red(str) { return run(str, code([ 31 ], 39)); } function green(str) { return run(str, code([ 32 ], 39)); } function white(str) { return run(str, code([ 37 ], 39)); } function gray(str) { return brightBlack(str); } function brightBlack(str) { return run(str, code([ 90 ], 39)); } function bgRed(str) { return run(str, code([ 41 ], 49)); } function bgGreen(str) { return run(str, code([ 42 ], 49)); } const ANSI_PATTERN = new RegExp([ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))" ].join("|"), "g"); function stripColor(string) { return string.replace(ANSI_PATTERN, ""); } var DiffType; (function(DiffType) { DiffType["removed"] = "removed"; DiffType["common"] = "common"; DiffType["added"] = "added"; })(DiffType || (DiffType = {})); const REMOVED = 1; const COMMON = 2; const ADDED = 3; function createCommon(A, B, reverse) { const common = []; if (A.length === 0 || B.length === 0) return []; for(let i = 0; i < Math.min(A.length, B.length); i += 1){ if (A[reverse ? A.length - i - 1 : i] === B[reverse ? B.length - i - 1 : i]) { common.push(A[reverse ? A.length - i - 1 : i]); } else { return common; } } return common; } function diff(A, B) { const prefixCommon = createCommon(A, B); const suffixCommon = createCommon(A.slice(prefixCommon.length), B.slice(prefixCommon.length), true).reverse(); A = suffixCommon.length ? A.slice(prefixCommon.length, -suffixCommon.length) : A.slice(prefixCommon.length); B = suffixCommon.length ? B.slice(prefixCommon.length, -suffixCommon.length) : B.slice(prefixCommon.length); const swapped = B.length > A.length; [A, B] = swapped ? [ B, A ] : [ A, B ]; const M = A.length; const N = B.length; if (!M && !N && !suffixCommon.length && !prefixCommon.length) return []; if (!N) { return [ ...prefixCommon.map((c)=>({ type: DiffType.common, value: c })), ...A.map((a)=>({ type: swapped ? DiffType.added : DiffType.removed, value: a })), ...suffixCommon.map((c)=>({ type: DiffType.common, value: c })) ]; } const offset = N; const delta = M - N; const size = M + N + 1; const fp = Array.from({ length: size }, ()=>({ y: -1, id: -1 })); const routes = new Uint32Array((M * N + size + 1) * 2); const diffTypesPtrOffset = routes.length / 2; let ptr = 0; let p = -1; function backTrace(A, B, current, swapped) { const M = A.length; const N = B.length; const result = []; let a = M - 1; let b = N - 1; let j = routes[current.id]; let type = routes[current.id + diffTypesPtrOffset]; while(true){ if (!j && !type) break; const prev = j; if (type === 1) { result.unshift({ type: swapped ? DiffType.removed : DiffType.added, value: B[b] }); b -= 1; } else if (type === 3) { result.unshift({ type: swapped ? DiffType.added : DiffType.removed, value: A[a] }); a -= 1; } else { result.unshift({ type: DiffType.common, value: A[a] }); a -= 1; b -= 1; } j = routes[prev]; type = routes[prev + diffTypesPtrOffset]; } return result; } function createFP(slide, down, k, M) { if (slide && slide.y === -1 && down && down.y === -1) { return { y: 0, id: 0 }; } if (down && down.y === -1 || k === M || (slide && slide.y) > (down && down.y) + 1) { const prev = slide.id; ptr++; routes[ptr] = prev; routes[ptr + diffTypesPtrOffset] = ADDED; return { y: slide.y, id: ptr }; } else { const prev1 = down.id; ptr++; routes[ptr] = prev1; routes[ptr + diffTypesPtrOffset] = REMOVED; return { y: down.y + 1, id: ptr }; } } function snake(k, slide, down, _offset, A, B) { const M = A.length; const N = B.length; if (k < -N || M < k) return { y: -1, id: -1 }; const fp = createFP(slide, down, k, M); while(fp.y + k < M && fp.y < N && A[fp.y + k] === B[fp.y]){ const prev = fp.id; ptr++; fp.id = ptr; fp.y += 1; routes[ptr] = prev; routes[ptr + diffTypesPtrOffset] = COMMON; } return fp; } while(fp[delta + offset].y < N){ p = p + 1; for(let k = -p; k < delta; ++k){ fp[k + offset] = snake(k, fp[k - 1 + offset], fp[k + 1 + offset], offset, A, B); } for(let k1 = delta + p; k1 > delta; --k1){ fp[k1 + offset] = snake(k1, fp[k1 - 1 + offset], fp[k1 + 1 + offset], offset, A, B); } fp[delta + offset] = snake(delta, fp[delta - 1 + offset], fp[delta + 1 + offset], offset, A, B); } return [ ...prefixCommon.map((c)=>({ type: DiffType.common, value: c })), ...backTrace(A, B, fp[delta + offset], swapped), ...suffixCommon.map((c)=>({ type: DiffType.common, value: c })) ]; } function diffstr(A, B) { function unescape(string) { return string.replaceAll("\b", "\\b").replaceAll("\f", "\\f").replaceAll("\t", "\\t").replaceAll("\v", "\\v").replaceAll(/\r\n|\r|\n/g, (str)=>str === "\r" ? "\\r" : str === "\n" ? "\\n\n" : "\\r\\n\r\n"); } function tokenize(string, { wordDiff =false } = {}) { if (wordDiff) { const tokens = string.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); const words = /^[a-zA-Z\u{C0}-\u{FF}\u{D8}-\u{F6}\u{F8}-\u{2C6}\u{2C8}-\u{2D7}\u{2DE}-\u{2FF}\u{1E00}-\u{1EFF}]+$/u; for(let i = 0; i < tokens.length - 1; i++){ if (!tokens[i + 1] && tokens[i + 2] && words.test(tokens[i]) && words.test(tokens[i + 2])) { tokens[i] += tokens[i + 2]; tokens.splice(i + 1, 2); i--; } } return tokens.filter((token)=>token); } else { const tokens1 = [], lines = string.split(/(\n|\r\n)/); if (!lines[lines.length - 1]) { lines.pop(); } for(let i1 = 0; i1 < lines.length; i1++){ if (i1 % 2) { tokens1[tokens1.length - 1] += lines[i1]; } else { tokens1.push(lines[i1]); } } return tokens1; } } function createDetails(line, tokens) { return tokens.filter(({ type })=>type === line.type || type === DiffType.common).map((result, i, t)=>{ if (result.type === DiffType.common && t[i - 1] && t[i - 1]?.type === t[i + 1]?.type && /\s+/.test(result.value)) { result.type = t[i - 1].type; } return result; }); } const diffResult = diff(tokenize(`${unescape(A)}\n`), tokenize(`${unescape(B)}\n`)); const added = [], removed = []; for (const result of diffResult){ if (result.type === DiffType.added) { added.push(result); } if (result.type === DiffType.removed) { removed.push(result); } } const aLines = added.length < removed.length ? added : removed; const bLines = aLines === removed ? added : removed; for (const a of aLines){ let tokens = [], b; while(bLines.length){ b = bLines.shift(); tokens = diff(tokenize(a.value, { wordDiff: true }), tokenize(b?.value ?? "", { wordDiff: true })); if (tokens.some(({ type , value })=>type === DiffType.common && value.trim().length)) { break; } } a.details = createDetails(a, tokens); if (b) { b.details = createDetails(b, tokens); } } return diffResult; } function createColor(diffType, { background =false } = {}) { background = false; switch(diffType){ case DiffType.added: return (s)=>background ? bgGreen(white(s)) : green(bold(s)); case DiffType.removed: return (s)=>background ? bgRed(white(s)) : red(bold(s)); default: return white; } } function createSign(diffType) { switch(diffType){ case DiffType.added: return "+ "; case DiffType.removed: return "- "; default: return " "; } } function buildMessage(diffResult, { stringDiff =false } = {}) { const messages = [], diffMessages = []; messages.push(""); messages.push(""); messages.push(` ${gray(bold("[Diff]"))} ${red(bold("Actual"))} / ${green(bold("Expected"))}`); messages.push(""); messages.push(""); diffResult.forEach((result)=>{ const c = createColor(result.type); const line = result.details?.map((detail)=>detail.type !== DiffType.common ? createColor(detail.type, { background: true })(detail.value) : detail.value).join("") ?? result.value; diffMessages.push(c(`${createSign(result.type)}${line}`)); }); messages.push(...stringDiff ? [ diffMessages.join("") ] : diffMessages); messages.push(""); return messages; } function format(v) { const { Deno } = globalThis; return typeof Deno?.inspect === "function" ? Deno.inspect(v, { depth: Infinity, sorted: true, trailingComma: true, compact: false, iterableLimit: Infinity, getters: true }) : `"${String(v).replace(/(?=["\\])/g, "\\")}"`; } const CAN_NOT_DISPLAY = "[Cannot display]"; class AssertionError extends Error { name = "AssertionError"; constructor(message){ super(message); } } function isKeyedCollection(x) { return [ Symbol.iterator, "size" ].every((k)=>k in x); } function equal(c, d) { const seen = new Map(); return function compare(a, b) { if (a && b && (a instanceof RegExp && b instanceof RegExp || a instanceof URL && b instanceof URL)) { return String(a) === String(b); } if (a instanceof Date && b instanceof Date) { const aTime = a.getTime(); const bTime = b.getTime(); if (Number.isNaN(aTime) && Number.isNaN(bTime)) { return true; } return aTime === bTime; } if (typeof a === "number" && typeof b === "number") { return Number.isNaN(a) && Number.isNaN(b) || a === b; } if (Object.is(a, b)) { return true; } if (a && typeof a === "object" && b && typeof b === "object") { if (a && b && !constructorsEqual(a, b)) { return false; } if (a instanceof WeakMap || b instanceof WeakMap) { if (!(a instanceof WeakMap && b instanceof WeakMap)) return false; throw new TypeError("cannot compare WeakMap instances"); } if (a instanceof WeakSet || b instanceof WeakSet) { if (!(a instanceof WeakSet && b instanceof WeakSet)) return false; throw new TypeError("cannot compare WeakSet instances"); } if (seen.get(a) === b) { return true; } if (Object.keys(a || {}).length !== Object.keys(b || {}).length) { return false; } seen.set(a, b); if (isKeyedCollection(a) && isKeyedCollection(b)) { if (a.size !== b.size) { return false; } let unmatchedEntries = a.size; for (const [aKey, aValue] of a.entries()){ for (const [bKey, bValue] of b.entries()){ if (aKey === aValue && bKey === bValue && compare(aKey, bKey) || compare(aKey, bKey) && compare(aValue, bValue)) { unmatchedEntries--; break; } } } return unmatchedEntries === 0; } const merged = { ...a, ...b }; for (const key of [ ...Object.getOwnPropertyNames(merged), ...Object.getOwnPropertySymbols(merged) ]){ if (!compare(a && a[key], b && b[key])) { return false; } if (key in a && !(key in b) || key in b && !(key in a)) { return false; } } if (a instanceof WeakRef || b instanceof WeakRef) { if (!(a instanceof WeakRef && b instanceof WeakRef)) return false; return compare(a.deref(), b.deref()); } return true; } return false; }(c, d); } function constructorsEqual(a, b) { return a.constructor === b.constructor || a.constructor === Object && !b.constructor || !a.constructor && b.constructor === Object; } function assert(expr, msg = "") { if (!expr) { throw new AssertionError(msg); } } function assertFalse(expr, msg = "") { if (expr) { throw new AssertionError(msg); } } function assertEquals(actual, expected, msg) { if (equal(actual, expected)) { return; } let message = ""; const actualString = format(actual); const expectedString = format(expected); try { const stringDiff = typeof actual === "string" && typeof expected === "string"; const diffResult = stringDiff ? diffstr(actual, expected) : diff(actualString.split("\n"), expectedString.split("\n")); const diffMsg = buildMessage(diffResult, { stringDiff }).join("\n"); message = `Values are not equal:\n${diffMsg}`; } catch { message = `\n${red(CAN_NOT_DISPLAY)} + \n\n`; } if (msg) { message = msg; } throw new AssertionError(message); } function assertNotEquals(actual, expected, msg) { if (!equal(actual, expected)) { return; } let actualString; let expectedString; try { actualString = String(actual); } catch { actualString = "[Cannot display]"; } try { expectedString = String(expected); } catch { expectedString = "[Cannot display]"; } if (!msg) { msg = `actual: ${actualString} expected not to be: ${expectedString}`; } throw new AssertionError(msg); } function assertStrictEquals(actual, expected, msg) { if (Object.is(actual, expected)) { return; } let message; if (msg) { message = msg; } else { const actualString = format(actual); const expectedString = format(expected); if (actualString === expectedString) { const withOffset = actualString.split("\n").map((l)=>` ${l}`).join("\n"); message = `Values have the same structure but are not reference-equal:\n\n${red(withOffset)}\n`; } else { try { const stringDiff = typeof actual === "string" && typeof expected === "string"; const diffResult = stringDiff ? diffstr(actual, expected) : diff(actualString.split("\n"), expectedString.split("\n")); const diffMsg = buildMessage(diffResult, { stringDiff }).join("\n"); message = `Values are not strictly equal:\n${diffMsg}`; } catch { message = `\n${red(CAN_NOT_DISPLAY)} + \n\n`; } } } throw new AssertionError(message); } function assertNotStrictEquals(actual, expected, msg) { if (!Object.is(actual, expected)) { return; } throw new AssertionError(msg ?? `Expected "actual" to be strictly unequal to: ${format(actual)}\n`); } function assertAlmostEquals(actual, expected, tolerance = 1e-7, msg) { if (Object.is(actual, expected)) { return; } const delta = Math.abs(expected - actual); if (delta <= tolerance) { return; } const f = (n)=>Number.isInteger(n) ? n : n.toExponential(); throw new AssertionError(msg ?? `actual: "${f(actual)}" expected to be close to "${f(expected)}": \ delta "${f(delta)}" is greater than "${f(tolerance)}"`); } function assertInstanceOf(actual, expectedType, msg = "") { if (!msg) { const expectedTypeStr = expectedType.name; let actualTypeStr = ""; if (actual === null) { actualTypeStr = "null"; } else if (actual === undefined) { actualTypeStr = "undefined"; } else if (typeof actual === "object") { actualTypeStr = actual.constructor?.name ?? "Object"; } else { actualTypeStr = typeof actual; } if (expectedTypeStr == actualTypeStr) { msg = `Expected object to be an instance of "${expectedTypeStr}".`; } else if (actualTypeStr == "function") { msg = `Expected object to be an instance of "${expectedTypeStr}" but was not an instanced object.`; } else { msg = `Expected object to be an instance of "${expectedTypeStr}" but was "${actualTypeStr}".`; } } assert(actual instanceof expectedType, msg); } function assertNotInstanceOf(actual, unexpectedType, msg = `Expected object to not be an instance of "${typeof unexpectedType}"`) { assertFalse(actual instanceof unexpectedType, msg); } function assertExists(actual, msg) { if (actual === undefined || actual === null) { if (!msg) { msg = `actual: "${actual}" expected to not be null or undefined`; } throw new AssertionError(msg); } } function assertStringIncludes(actual, expected, msg) { if (!actual.includes(expected)) { if (!msg) { msg = `actual: "${actual}" expected to contain: "${expected}"`; } throw new AssertionError(msg); } } function assertArrayIncludes(actual, expected, msg) { const missing = []; for(let i = 0; i < expected.length; i++){ let found = false; for(let j = 0; j < actual.length; j++){ if (equal(expected[i], actual[j])) { found = true; break; } } if (!found) { missing.push(expected[i]); } } if (missing.length === 0) { return; } if (!msg) { msg = `actual: "${format(actual)}" expected to include: "${format(expected)}"\nmissing: ${format(missing)}`; } throw new AssertionError(msg); } function assertMatch(actual, expected, msg) { if (!expected.test(actual)) { if (!msg) { msg = `actual: "${actual}" expected to match: "${expected}"`; } throw new AssertionError(msg); } } function assertNotMatch(actual, expected, msg) { if (expected.test(actual)) { if (!msg) { msg = `actual: "${actual}" expected to not match: "${expected}"`; } throw new AssertionError(msg); } } function assertObjectMatch(actual, expected) { function filter(a, b) { const seen = new WeakMap(); return fn(a, b); function fn(a, b) { if (seen.has(a) && seen.get(a) === b) { return a; } seen.set(a, b); const filtered = {}; const entries = [ ...Object.getOwnPropertyNames(a), ...Object.getOwnPropertySymbols(a) ].filter((key)=>key in b).map((key)=>[ key, a[key] ]); for (const [key, value] of entries){ if (Array.isArray(value)) { const subset = b[key]; if (Array.isArray(subset)) { filtered[key] = fn({ ...value }, { ...subset }); continue; } } else if (value instanceof RegExp) { filtered[key] = value; continue; } else if (typeof value === "object") { const subset1 = b[key]; if (typeof subset1 === "object" && subset1) { if (value instanceof Map && subset1 instanceof Map) { filtered[key] = new Map([ ...value ].filter(([k])=>subset1.has(k)).map(([k, v])=>[ k, typeof v === "object" ? fn(v, subset1.get(k)) : v ])); continue; } if (value instanceof Set && subset1 instanceof Set) { filtered[key] = new Set([ ...value ].filter((v)=>subset1.has(v))); continue; } filtered[key] = fn(value, subset1); continue; } } filtered[key] = value; } return filtered; } } return assertEquals(filter(actual, expected), filter(expected, expected)); } function fail(msg) { assert(false, `Failed assertion${msg ? `: ${msg}` : "."}`); } function assertIsError(error, ErrorClass, msgIncludes, msg) { if (error instanceof Error === false) { throw new AssertionError(`Expected "error" to be an Error object.`); } if (ErrorClass && !(error instanceof ErrorClass)) { msg = `Expected error to be instance of "${ErrorClass.name}", but was "${typeof error === "object" ? error?.constructor?.name : "[not an object]"}"${msg ? `: ${msg}` : "."}`; throw new AssertionError(msg); } if (msgIncludes && (!(error instanceof Error) || !stripColor(error.message).includes(stripColor(msgIncludes)))) { msg = `Expected error message to include "${msgIncludes}", but got "${error instanceof Error ? error.message : "[not an Error]"}"${msg ? `: ${msg}` : "."}`; throw new AssertionError(msg); } } function assertThrows(fn, errorClassOrMsg, msgIncludesOrMsg, msg) { let ErrorClass = undefined; let msgIncludes = undefined; let err; if (typeof errorClassOrMsg !== "string") { if (errorClassOrMsg === undefined || errorClassOrMsg.prototype instanceof Error || errorClassOrMsg.prototype === Error.prototype) { ErrorClass = errorClassOrMsg; msgIncludes = msgIncludesOrMsg; } else { msg = msgIncludesOrMsg; } } else { msg = errorClassOrMsg; } let doesThrow = false; const msgToAppendToError = msg ? `: ${msg}` : "."; try { fn(); } catch (error) { if (ErrorClass) { if (error instanceof Error === false) { throw new AssertionError("A non-Error object was thrown."); } assertIsError(error, ErrorClass, msgIncludes, msg); } err = error; doesThrow = true; } if (!doesThrow) { msg = `Expected function to throw${msgToAppendToError}`; throw new AssertionError(msg); } return err; } async function assertRejects(fn, errorClassOrMsg, msgIncludesOrMsg, msg) { let ErrorClass = undefined; let msgIncludes = undefined; let err; if (typeof errorClassOrMsg !== "string") { if (errorClassOrMsg === undefined || errorClassOrMsg.prototype instanceof Error || errorClassOrMsg.prototype === Error.prototype) { ErrorClass = errorClassOrMsg; msgIncludes = msgIncludesOrMsg; } } else { msg = errorClassOrMsg; } let doesThrow = false; let isPromiseReturned = false; const msgToAppendToError = msg ? `: ${msg}` : "."; try { const possiblePromise = fn(); if (possiblePromise && typeof possiblePromise === "object" && typeof possiblePromise.then === "function") { isPromiseReturned = true; await possiblePromise; } } catch (error) { if (!isPromiseReturned) { throw new AssertionError(`Function throws when expected to reject${msgToAppendToError}`); } if (ErrorClass) { if (error instanceof Error === false) { throw new AssertionError("A non-Error object was rejected."); } assertIsError(error, ErrorClass, msgIncludes, msg); } err = error; doesThrow = true; } if (!doesThrow) { throw new AssertionError(`Expected function to reject${msgToAppendToError}`); } return err; } function unimplemented(msg) { throw new AssertionError(msg || "unimplemented"); } function unreachable() { throw new AssertionError("unreachable"); } export { AssertionError as AssertionError }; export { equal as equal }; export { assert as assert }; export { assertFalse as assertFalse }; export { assertEquals as assertEquals }; export { assertNotEquals as assertNotEquals }; export { assertStrictEquals as assertStrictEquals }; export { assertNotStrictEquals as assertNotStrictEquals }; export { assertAlmostEquals as assertAlmostEquals }; export { assertInstanceOf as assertInstanceOf }; export { assertNotInstanceOf as assertNotInstanceOf }; export { assertExists as assertExists }; export { assertStringIncludes as assertStringIncludes }; export { assertArrayIncludes as assertArrayIncludes }; export { assertMatch as assertMatch }; export { assertNotMatch as assertNotMatch }; export { assertObjectMatch as assertObjectMatch }; export { fail as fail }; export { assertIsError as assertIsError }; export { assertThrows as assertThrows }; export { assertRejects as assertRejects }; export { unimplemented as unimplemented }; export { unreachable as unreachable }; node_modules/tinycolor2/cjs/tinycolor.js 0000664 00000111320 15114743311 0014464 0 ustar 00 // This file is autogenerated. It's used to publish CJS to npm. (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.tinycolor = factory()); })(this, (function () { 'use strict'; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } // https://github.com/bgrins/TinyColor // Brian Grinstead, MIT License var trimLeft = /^\s+/; var trimRight = /\s+$/; function tinycolor(color, opts) { color = color ? color : ""; opts = opts || {}; // If input is already a tinycolor, return itself if (color instanceof tinycolor) { return color; } // If we are called as a function, call using new instead if (!(this instanceof tinycolor)) { return new tinycolor(color, opts); } var rgb = inputToRGB(color); this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format; this._gradientType = opts.gradientType; // Don't let the range of [0,255] come back in [0,1]. // Potentially lose a little bit of precision here, but will fix issues where // .5 gets interpreted as half of the total, instead of half of 1 // If it was supposed to be 128, this was already taken care of by `inputToRgb` if (this._r < 1) this._r = Math.round(this._r); if (this._g < 1) this._g = Math.round(this._g); if (this._b < 1) this._b = Math.round(this._b); this._ok = rgb.ok; } tinycolor.prototype = { isDark: function isDark() { return this.getBrightness() < 128; }, isLight: function isLight() { return !this.isDark(); }, isValid: function isValid() { return this._ok; }, getOriginalInput: function getOriginalInput() { return this._originalInput; }, getFormat: function getFormat() { return this._format; }, getAlpha: function getAlpha() { return this._a; }, getBrightness: function getBrightness() { //http://www.w3.org/TR/AERT#color-contrast var rgb = this.toRgb(); return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; }, getLuminance: function getLuminance() { //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef var rgb = this.toRgb(); var RsRGB, GsRGB, BsRGB, R, G, B; RsRGB = rgb.r / 255; GsRGB = rgb.g / 255; BsRGB = rgb.b / 255; if (RsRGB <= 0.03928) R = RsRGB / 12.92;else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4); if (GsRGB <= 0.03928) G = GsRGB / 12.92;else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4); if (BsRGB <= 0.03928) B = BsRGB / 12.92;else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4); return 0.2126 * R + 0.7152 * G + 0.0722 * B; }, setAlpha: function setAlpha(value) { this._a = boundAlpha(value); this._roundA = Math.round(100 * this._a) / 100; return this; }, toHsv: function toHsv() { var hsv = rgbToHsv(this._r, this._g, this._b); return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a }; }, toHsvString: function toHsvString() { var hsv = rgbToHsv(this._r, this._g, this._b); var h = Math.round(hsv.h * 360), s = Math.round(hsv.s * 100), v = Math.round(hsv.v * 100); return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")"; }, toHsl: function toHsl() { var hsl = rgbToHsl(this._r, this._g, this._b); return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a }; }, toHslString: function toHslString() { var hsl = rgbToHsl(this._r, this._g, this._b); var h = Math.round(hsl.h * 360), s = Math.round(hsl.s * 100), l = Math.round(hsl.l * 100); return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")"; }, toHex: function toHex(allow3Char) { return rgbToHex(this._r, this._g, this._b, allow3Char); }, toHexString: function toHexString(allow3Char) { return "#" + this.toHex(allow3Char); }, toHex8: function toHex8(allow4Char) { return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); }, toHex8String: function toHex8String(allow4Char) { return "#" + this.toHex8(allow4Char); }, toRgb: function toRgb() { return { r: Math.round(this._r), g: Math.round(this._g), b: Math.round(this._b), a: this._a }; }, toRgbString: function toRgbString() { return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")"; }, toPercentageRgb: function toPercentageRgb() { return { r: Math.round(bound01(this._r, 255) * 100) + "%", g: Math.round(bound01(this._g, 255) * 100) + "%", b: Math.round(bound01(this._b, 255) * 100) + "%", a: this._a }; }, toPercentageRgbString: function toPercentageRgbString() { return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; }, toName: function toName() { if (this._a === 0) { return "transparent"; } if (this._a < 1) { return false; } return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; }, toFilter: function toFilter(secondColor) { var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a); var secondHex8String = hex8String; var gradientType = this._gradientType ? "GradientType = 1, " : ""; if (secondColor) { var s = tinycolor(secondColor); secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a); } return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")"; }, toString: function toString(format) { var formatSet = !!format; format = format || this._format; var formattedString = false; var hasAlpha = this._a < 1 && this._a >= 0; var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); if (needsAlphaFormat) { // Special case for "transparent", all other non-alpha formats // will return rgba when there is transparency. if (format === "name" && this._a === 0) { return this.toName(); } return this.toRgbString(); } if (format === "rgb") { formattedString = this.toRgbString(); } if (format === "prgb") { formattedString = this.toPercentageRgbString(); } if (format === "hex" || format === "hex6") { formattedString = this.toHexString(); } if (format === "hex3") { formattedString = this.toHexString(true); } if (format === "hex4") { formattedString = this.toHex8String(true); } if (format === "hex8") { formattedString = this.toHex8String(); } if (format === "name") { formattedString = this.toName(); } if (format === "hsl") { formattedString = this.toHslString(); } if (format === "hsv") { formattedString = this.toHsvString(); } return formattedString || this.toHexString(); }, clone: function clone() { return tinycolor(this.toString()); }, _applyModification: function _applyModification(fn, args) { var color = fn.apply(null, [this].concat([].slice.call(args))); this._r = color._r; this._g = color._g; this._b = color._b; this.setAlpha(color._a); return this; }, lighten: function lighten() { return this._applyModification(_lighten, arguments); }, brighten: function brighten() { return this._applyModification(_brighten, arguments); }, darken: function darken() { return this._applyModification(_darken, arguments); }, desaturate: function desaturate() { return this._applyModification(_desaturate, arguments); }, saturate: function saturate() { return this._applyModification(_saturate, arguments); }, greyscale: function greyscale() { return this._applyModification(_greyscale, arguments); }, spin: function spin() { return this._applyModification(_spin, arguments); }, _applyCombination: function _applyCombination(fn, args) { return fn.apply(null, [this].concat([].slice.call(args))); }, analogous: function analogous() { return this._applyCombination(_analogous, arguments); }, complement: function complement() { return this._applyCombination(_complement, arguments); }, monochromatic: function monochromatic() { return this._applyCombination(_monochromatic, arguments); }, splitcomplement: function splitcomplement() { return this._applyCombination(_splitcomplement, arguments); }, // Disabled until https://github.com/bgrins/TinyColor/issues/254 // polyad: function (number) { // return this._applyCombination(polyad, [number]); // }, triad: function triad() { return this._applyCombination(polyad, [3]); }, tetrad: function tetrad() { return this._applyCombination(polyad, [4]); } }; // If input is an object, force 1 into "1.0" to handle ratios properly // String input requires "1.0" as input, so 1 will be treated as 1 tinycolor.fromRatio = function (color, opts) { if (_typeof(color) == "object") { var newColor = {}; for (var i in color) { if (color.hasOwnProperty(i)) { if (i === "a") { newColor[i] = color[i]; } else { newColor[i] = convertToPercentage(color[i]); } } } color = newColor; } return tinycolor(color, opts); }; // Given a string or object, convert that input to RGB // Possible string inputs: // // "red" // "#f00" or "f00" // "#ff0000" or "ff0000" // "#ff000000" or "ff000000" // "rgb 255 0 0" or "rgb (255, 0, 0)" // "rgb 1.0 0 0" or "rgb (1, 0, 0)" // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" // function inputToRGB(color) { var rgb = { r: 0, g: 0, b: 0 }; var a = 1; var s = null; var v = null; var l = null; var ok = false; var format = false; if (typeof color == "string") { color = stringInputToObject(color); } if (_typeof(color) == "object") { if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { rgb = rgbToRgb(color.r, color.g, color.b); ok = true; format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { s = convertToPercentage(color.s); v = convertToPercentage(color.v); rgb = hsvToRgb(color.h, s, v); ok = true; format = "hsv"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { s = convertToPercentage(color.s); l = convertToPercentage(color.l); rgb = hslToRgb(color.h, s, l); ok = true; format = "hsl"; } if (color.hasOwnProperty("a")) { a = color.a; } } a = boundAlpha(a); return { ok: ok, format: color.format || format, r: Math.min(255, Math.max(rgb.r, 0)), g: Math.min(255, Math.max(rgb.g, 0)), b: Math.min(255, Math.max(rgb.b, 0)), a: a }; } // Conversion Functions // -------------------- // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript> // `rgbToRgb` // Handle bounds / percentage checking to conform to CSS color spec // <http://www.w3.org/TR/css3-color/> // *Assumes:* r, g, b in [0, 255] or [0, 1] // *Returns:* { r, g, b } in [0, 255] function rgbToRgb(r, g, b) { return { r: bound01(r, 255) * 255, g: bound01(g, 255) * 255, b: bound01(b, 255) * 255 }; } // `rgbToHsl` // Converts an RGB color value to HSL. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] // *Returns:* { h, s, l } in [0,1] function rgbToHsl(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, l: l }; } // `hslToRgb` // Converts an HSL color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hslToRgb(h, s, l) { var r, g, b; h = bound01(h, 360); s = bound01(s, 100); l = bound01(l, 100); function hue2rgb(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } if (s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1 / 3); } return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHsv` // Converts an RGB color value to HSV // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] // *Returns:* { h, s, v } in [0,1] function rgbToHsv(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, v = max; var d = max - min; s = max === 0 ? 0 : d / max; if (max == min) { h = 0; // achromatic } else { switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, v: v }; } // `hsvToRgb` // Converts an HSV color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hsvToRgb(h, s, v) { h = bound01(h, 360) * 6; s = bound01(s, 100); v = bound01(v, 100); var i = Math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod]; return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHex` // Converts an RGB color to hex // Assumes r, g, and b are contained in the set [0, 255] // Returns a 3 or 6 character hex function rgbToHex(r, g, b, allow3Char) { var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; // Return a 3 character hex if possible if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } return hex.join(""); } // `rgbaToHex` // Converts an RGBA color plus alpha transparency to hex // Assumes r, g, b are contained in the set [0, 255] and // a in [0, 1]. Returns a 4 or 8 character rgba hex function rgbaToHex(r, g, b, a, allow4Char) { var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))]; // Return a 4 character hex if possible if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); } return hex.join(""); } // `rgbaToArgbHex` // Converts an RGBA color to an ARGB Hex8 string // Rarely used, but required for "toFilter()" function rgbaToArgbHex(r, g, b, a) { var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; return hex.join(""); } // `equals` // Can be called with any tinycolor input tinycolor.equals = function (color1, color2) { if (!color1 || !color2) return false; return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); }; tinycolor.random = function () { return tinycolor.fromRatio({ r: Math.random(), g: Math.random(), b: Math.random() }); }; // Modification Functions // ---------------------- // Thanks to less.js for some of the basics here // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js> function _desaturate(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.s -= amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function _saturate(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.s += amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function _greyscale(color) { return tinycolor(color).desaturate(100); } function _lighten(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.l += amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } function _brighten(color, amount) { amount = amount === 0 ? 0 : amount || 10; var rgb = tinycolor(color).toRgb(); rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100)))); rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100)))); rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100)))); return tinycolor(rgb); } function _darken(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.l -= amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. // Values outside of this range will be wrapped into this range. function _spin(color, amount) { var hsl = tinycolor(color).toHsl(); var hue = (hsl.h + amount) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return tinycolor(hsl); } // Combination Functions // --------------------- // Thanks to jQuery xColor for some of the ideas behind these // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js> function _complement(color) { var hsl = tinycolor(color).toHsl(); hsl.h = (hsl.h + 180) % 360; return tinycolor(hsl); } function polyad(color, number) { if (isNaN(number) || number <= 0) { throw new Error("Argument to polyad must be a positive number"); } var hsl = tinycolor(color).toHsl(); var result = [tinycolor(color)]; var step = 360 / number; for (var i = 1; i < number; i++) { result.push(tinycolor({ h: (hsl.h + i * step) % 360, s: hsl.s, l: hsl.l })); } return result; } function _splitcomplement(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [tinycolor(color), tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l })]; } function _analogous(color, results, slices) { results = results || 6; slices = slices || 30; var hsl = tinycolor(color).toHsl(); var part = 360 / slices; var ret = [tinycolor(color)]; for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results;) { hsl.h = (hsl.h + part) % 360; ret.push(tinycolor(hsl)); } return ret; } function _monochromatic(color, results) { results = results || 6; var hsv = tinycolor(color).toHsv(); var h = hsv.h, s = hsv.s, v = hsv.v; var ret = []; var modification = 1 / results; while (results--) { ret.push(tinycolor({ h: h, s: s, v: v })); v = (v + modification) % 1; } return ret; } // Utility Functions // --------------------- tinycolor.mix = function (color1, color2, amount) { amount = amount === 0 ? 0 : amount || 50; var rgb1 = tinycolor(color1).toRgb(); var rgb2 = tinycolor(color2).toRgb(); var p = amount / 100; var rgba = { r: (rgb2.r - rgb1.r) * p + rgb1.r, g: (rgb2.g - rgb1.g) * p + rgb1.g, b: (rgb2.b - rgb1.b) * p + rgb1.b, a: (rgb2.a - rgb1.a) * p + rgb1.a }; return tinycolor(rgba); }; // Readability Functions // --------------------- // <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2) // `contrast` // Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2) tinycolor.readability = function (color1, color2) { var c1 = tinycolor(color1); var c2 = tinycolor(color2); return (Math.max(c1.getLuminance(), c2.getLuminance()) + 0.05) / (Math.min(c1.getLuminance(), c2.getLuminance()) + 0.05); }; // `isReadable` // Ensure that foreground and background color combinations meet WCAG2 guidelines. // The third argument is an optional Object. // the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA'; // the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'. // If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}. // *Example* // tinycolor.isReadable("#000", "#111") => false // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false tinycolor.isReadable = function (color1, color2, wcag2) { var readability = tinycolor.readability(color1, color2); var wcag2Parms, out; out = false; wcag2Parms = validateWCAG2Parms(wcag2); switch (wcag2Parms.level + wcag2Parms.size) { case "AAsmall": case "AAAlarge": out = readability >= 4.5; break; case "AAlarge": out = readability >= 3; break; case "AAAsmall": out = readability >= 7; break; } return out; }; // `mostReadable` // Given a base color and a list of possible foreground or background // colors for that base, returns the most readable color. // Optionally returns Black or White if the most readable color is unreadable. // *Example* // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" tinycolor.mostReadable = function (baseColor, colorList, args) { var bestColor = null; var bestScore = 0; var readability; var includeFallbackColors, level, size; args = args || {}; includeFallbackColors = args.includeFallbackColors; level = args.level; size = args.size; for (var i = 0; i < colorList.length; i++) { readability = tinycolor.readability(baseColor, colorList[i]); if (readability > bestScore) { bestScore = readability; bestColor = tinycolor(colorList[i]); } } if (tinycolor.isReadable(baseColor, bestColor, { level: level, size: size }) || !includeFallbackColors) { return bestColor; } else { args.includeFallbackColors = false; return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args); } }; // Big List of Colors // ------------------ // <https://www.w3.org/TR/css-color-4/#named-colors> var names = tinycolor.names = { aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "0ff", aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc", bisque: "ffe4c4", black: "000", blanchedalmond: "ffebcd", blue: "00f", blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", burntsienna: "ea7e5d", cadetblue: "5f9ea0", chartreuse: "7fff00", chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c", cyan: "0ff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9", darkgreen: "006400", darkgrey: "a9a9a9", darkkhaki: "bdb76b", darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f", darkslategrey: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493", deepskyblue: "00bfff", dimgray: "696969", dimgrey: "696969", dodgerblue: "1e90ff", firebrick: "b22222", floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "f0f", gainsboro: "dcdcdc", ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f", grey: "808080", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082", ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00", lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgray: "d3d3d3", lightgreen: "90ee90", lightgrey: "d3d3d3", lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslategray: "789", lightslategrey: "789", lightsteelblue: "b0c4de", lightyellow: "ffffe0", lime: "0f0", limegreen: "32cd32", linen: "faf0e6", magenta: "f0f", maroon: "800000", mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370db", mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a", mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6", olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "db7093", papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6", purple: "800080", rebeccapurple: "663399", red: "f00", rosybrown: "bc8f8f", royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd", slategray: "708090", slategrey: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee", wheat: "f5deb3", white: "fff", whitesmoke: "f5f5f5", yellow: "ff0", yellowgreen: "9acd32" }; // Make it easy to access colors via `hexNames[hex]` var hexNames = tinycolor.hexNames = flip(names); // Utilities // --------- // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` function flip(o) { var flipped = {}; for (var i in o) { if (o.hasOwnProperty(i)) { flipped[o[i]] = i; } } return flipped; } // Return a valid alpha value [0,1] with all invalid values being set to 1 function boundAlpha(a) { a = parseFloat(a); if (isNaN(a) || a < 0 || a > 1) { a = 1; } return a; } // Take input from [0, n] and return it as [0, 1] function bound01(n, max) { if (isOnePointZero(n)) n = "100%"; var processPercent = isPercentage(n); n = Math.min(max, Math.max(0, parseFloat(n))); // Automatically convert percentage into number if (processPercent) { n = parseInt(n * max, 10) / 100; } // Handle floating point rounding errors if (Math.abs(n - max) < 0.000001) { return 1; } // Convert into [0, 1] range if it isn't already return n % max / parseFloat(max); } // Force a number between 0 and 1 function clamp01(val) { return Math.min(1, Math.max(0, val)); } // Parse a base-16 hex value into a base-10 integer function parseIntFromHex(val) { return parseInt(val, 16); } // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0> function isOnePointZero(n) { return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1; } // Check to see if string passed in is a percentage function isPercentage(n) { return typeof n === "string" && n.indexOf("%") != -1; } // Force a hex value to have 2 characters function pad2(c) { return c.length == 1 ? "0" + c : "" + c; } // Replace a decimal with it's percentage value function convertToPercentage(n) { if (n <= 1) { n = n * 100 + "%"; } return n; } // Converts a decimal to a hex value function convertDecimalToHex(d) { return Math.round(parseFloat(d) * 255).toString(16); } // Converts a hex value to a decimal function convertHexToDecimal(h) { return parseIntFromHex(h) / 255; } var matchers = function () { // <http://www.w3.org/TR/css3-values/#integers> var CSS_INTEGER = "[-\\+]?\\d+%?"; // <http://www.w3.org/TR/css3-values/#number-value> var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; // Actual matching. // Parentheses and commas are optional, but not required. // Whitespace can take the place of commas or opening paren var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; return { CSS_UNIT: new RegExp(CSS_UNIT), rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ }; }(); // `isValidCSSUnit` // Take in a single string / number and check to see if it looks like a CSS unit // (see `matchers` above for definition). function isValidCSSUnit(color) { return !!matchers.CSS_UNIT.exec(color); } // `stringInputToObject` // Permissive string parsing. Take in a number of formats, and output an object // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` function stringInputToObject(color) { color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase(); var named = false; if (names[color]) { color = names[color]; named = true; } else if (color == "transparent") { return { r: 0, g: 0, b: 0, a: 0, format: "name" }; } // Try to match string input using regular expressions. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] // Just return an object and let the conversion functions handle that. // This way the result will be the same whether the tinycolor is initialized with string or object. var match; if (match = matchers.rgb.exec(color)) { return { r: match[1], g: match[2], b: match[3] }; } if (match = matchers.rgba.exec(color)) { return { r: match[1], g: match[2], b: match[3], a: match[4] }; } if (match = matchers.hsl.exec(color)) { return { h: match[1], s: match[2], l: match[3] }; } if (match = matchers.hsla.exec(color)) { return { h: match[1], s: match[2], l: match[3], a: match[4] }; } if (match = matchers.hsv.exec(color)) { return { h: match[1], s: match[2], v: match[3] }; } if (match = matchers.hsva.exec(color)) { return { h: match[1], s: match[2], v: match[3], a: match[4] }; } if (match = matchers.hex8.exec(color)) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), a: convertHexToDecimal(match[4]), format: named ? "name" : "hex8" }; } if (match = matchers.hex6.exec(color)) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), format: named ? "name" : "hex" }; } if (match = matchers.hex4.exec(color)) { return { r: parseIntFromHex(match[1] + "" + match[1]), g: parseIntFromHex(match[2] + "" + match[2]), b: parseIntFromHex(match[3] + "" + match[3]), a: convertHexToDecimal(match[4] + "" + match[4]), format: named ? "name" : "hex8" }; } if (match = matchers.hex3.exec(color)) { return { r: parseIntFromHex(match[1] + "" + match[1]), g: parseIntFromHex(match[2] + "" + match[2]), b: parseIntFromHex(match[3] + "" + match[3]), format: named ? "name" : "hex" }; } return false; } function validateWCAG2Parms(parms) { // return valid WCAG2 parms for isReadable. // If input parms are invalid, return {"level":"AA", "size":"small"} var level, size; parms = parms || { level: "AA", size: "small" }; level = (parms.level || "AA").toUpperCase(); size = (parms.size || "small").toLowerCase(); if (level !== "AA" && level !== "AAA") { level = "AA"; } if (size !== "small" && size !== "large") { size = "small"; } return { level: level, size: size }; } return tinycolor; })); node_modules/tinycolor2/cjs/package.json 0000664 00000000031 15114743311 0014366 0 ustar 00 { "type": "commonjs" } node_modules/tinycolor2/cjs/test.js 0000664 00000156000 15114743311 0013425 0 ustar 00 // This file is autogenerated. // Ideally it wouldn't exist, but it's here to test cjs in node // Changes should go into ./test.js, and if new assertions are needed // they'll need to be shimmed here as well const tinycolor = require("./tinycolor.js"); const { Deno, testDefinitions } = require("@deno/shim-deno-test"); async function runDenoTests() { for (const test of testDefinitions) { if (test.ignore) { console.log(`Ignoring ${test.name}`); continue; } console.log(`Running ${test.name}`); await test.fn(); console.log(`> Passed ${test.name}`); } } (async () => { const { assertEquals, assert, assertThrows } = await import( "../deno_asserts@0.168.0.mjs" ); // TEST_BEGINS_HERE Deno.test("TinyColor initialization", function () { assert( typeof tinycolor != "undefined", "tinycolor is initialized on the page" ); assert( typeof tinycolor("red") == "object", "tinycolor is able to be instantiated" ); var r = tinycolor("red"); assert( tinycolor(r) === r, "when given a tinycolor instance, tinycolor() returns it" ); assert( new tinycolor(r) === r, "when given a tinycolor instance, new tinycolor() returns it" ); assertEquals( tinycolor("red", { format: "hex" }).toString(), "#ff0000", "tinycolor options are being parsed" ); assertEquals( tinycolor.fromRatio({ r: 1, g: 0, b: 0 }, { format: "hex" }).toString(), "#ff0000", "tinycolor options are being parsed" ); var obj = { h: 180, s: 0.5, l: 0.5 }; var color = tinycolor(obj); assert( obj.s === 0.5, "when given an object, the original object is not modified" ); }); Deno.test("Original input", function () { var colorRgbUp = "RGB(39, 39, 39)"; var colorRgbLow = "rgb(39, 39, 39)"; var colorRgbMix = "RgB(39, 39, 39)"; var tinycolorObj = tinycolor(colorRgbMix); var inputObj = { r: 100, g: 100, b: 100 }; var r = tinycolor("red"); assert( tinycolor(colorRgbLow).getOriginalInput() === colorRgbLow, "original lowercase input is returned" ); assert( tinycolor(colorRgbUp).getOriginalInput() === colorRgbUp, "original uppercase input is returned" ); assert( tinycolor(colorRgbMix).getOriginalInput() === colorRgbMix, "original mixed input is returned" ); assert( tinycolor(tinycolorObj).getOriginalInput() === colorRgbMix, "when given a tinycolor instance, the color string is returned" ); assert( tinycolor(inputObj).getOriginalInput() === inputObj, "when given an object, the object is returned" ); assert( new tinycolor("").getOriginalInput() === "", "when given an empty string, an empty string is returned" ); assert( new tinycolor(null).getOriginalInput() === "", "when given a null value, an empty string is returned" ); }); Deno.test("Cloning color", function () { var originalColor = tinycolor("red"); var originalColorRgbString = originalColor.toRgbString(); var clonedColor = originalColor.clone(); assert( clonedColor.toRgbString() === originalColor.toRgbString(), "cloned color is identical" ); clonedColor.setAlpha(0.5); assert( clonedColor.toRgbString() !== originalColor.toRgbString(), "cloned color is changing independently from original color" ); assert( originalColorRgbString === originalColor.toRgbString(), "original color was not changed by cloned color change" ); }); Deno.test("Random color", function () { var randomColor = tinycolor.random(); assertEquals(randomColor.getAlpha(), 1); assertEquals(randomColor.getFormat(), "prgb"); randomColor.setAlpha(0.5); assertEquals(randomColor.toHex8String().slice(-2), "80"); }); // Taken from convertWikipediaColors.html var conversions = [ { hex: "#FFFFFF", hex8: "#FFFFFFFF", rgb: { r: "100.0%", g: "100.0%", b: "100.0%" }, hsv: { h: "0", s: "0.000", v: "1.000" }, hsl: { h: "0", s: "0.000", l: "1.000" }, }, { hex: "#808080", hex8: "#808080FF", rgb: { r: "050.0%", g: "050.0%", b: "050.0%" }, hsv: { h: "0", s: "0.000", v: "0.500" }, hsl: { h: "0", s: "0.000", l: "0.500" }, }, { hex: "#000000", hex8: "#000000FF", rgb: { r: "000.0%", g: "000.0%", b: "000.0%" }, hsv: { h: "0", s: "0.000", v: "0.000" }, hsl: { h: "0", s: "0.000", l: "0.000" }, }, { hex: "#FF0000", hex8: "#FF0000FF", rgb: { r: "100.0%", g: "000.0%", b: "000.0%" }, hsv: { h: "0.0", s: "1.000", v: "1.000" }, hsl: { h: "0.0", s: "1.000", l: "0.500" }, }, { hex: "#BFBF00", hex8: "#BFBF00FF", rgb: { r: "075.0%", g: "075.0%", b: "000.0%" }, hsv: { h: "60.0", s: "1.000", v: "0.750" }, hsl: { h: "60.0", s: "1.000", l: "0.375" }, }, { hex: "#008000", hex8: "#008000FF", rgb: { r: "000.0%", g: "050.0%", b: "000.0%" }, hsv: { h: "120.0", s: "1.000", v: "0.500" }, hsl: { h: "120.0", s: "1.000", l: "0.250" }, }, { hex: "#80FFFF", hex8: "#80FFFFFF", rgb: { r: "050.0%", g: "100.0%", b: "100.0%" }, hsv: { h: "180.0", s: "0.500", v: "1.000" }, hsl: { h: "180.0", s: "1.000", l: "0.750" }, }, { hex: "#8080FF", hex8: "#8080FFFF", rgb: { r: "050.0%", g: "050.0%", b: "100.0%" }, hsv: { h: "240.0", s: "0.500", v: "1.000" }, hsl: { h: "240.0", s: "1.000", l: "0.750" }, }, { hex: "#BF40BF", hex8: "#BF40BFFF", rgb: { r: "075.0%", g: "025.0%", b: "075.0%" }, hsv: { h: "300.0", s: "0.667", v: "0.750" }, hsl: { h: "300.0", s: "0.500", l: "0.500" }, }, { hex: "#A0A424", hex8: "#A0A424FF", rgb: { r: "062.8%", g: "064.3%", b: "014.2%" }, hsv: { h: "61.8", s: "0.779", v: "0.643" }, hsl: { h: "61.8", s: "0.638", l: "0.393" }, }, { hex: "#1EAC41", hex8: "#1EAC41FF", rgb: { r: "011.6%", g: "067.5%", b: "025.5%" }, hsv: { h: "134.9", s: "0.828", v: "0.675" }, hsl: { h: "134.9", s: "0.707", l: "0.396" }, }, { hex: "#B430E5", hex8: "#B430E5FF", rgb: { r: "070.4%", g: "018.7%", b: "089.7%" }, hsv: { h: "283.7", s: "0.792", v: "0.897" }, hsl: { h: "283.7", s: "0.775", l: "0.542" }, }, { hex: "#FEF888", hex8: "#FEF888FF", rgb: { r: "099.8%", g: "097.4%", b: "053.2%" }, hsv: { h: "56.9", s: "0.467", v: "0.998" }, hsl: { h: "56.9", s: "0.991", l: "0.765" }, }, { hex: "#19CB97", hex8: "#19CB97FF", rgb: { r: "009.9%", g: "079.5%", b: "059.1%" }, hsv: { h: "162.4", s: "0.875", v: "0.795" }, hsl: { h: "162.4", s: "0.779", l: "0.447" }, }, { hex: "#362698", hex8: "#362698FF", rgb: { r: "021.1%", g: "014.9%", b: "059.7%" }, hsv: { h: "248.3", s: "0.750", v: "0.597" }, hsl: { h: "248.3", s: "0.601", l: "0.373" }, }, { hex: "#7E7EB8", hex8: "#7E7EB8FF", rgb: { r: "049.5%", g: "049.3%", b: "072.1%" }, hsv: { h: "240.5", s: "0.316", v: "0.721" }, hsl: { h: "240.5", s: "0.290", l: "0.607" }, }, ]; Deno.test("Color Equality", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assert(true, tiny.isValid()); assert( true, "Testing " + c.hex + ": " + tiny.toRgbString() + " " + tiny.toPercentageRgbString() + " " + tiny.toHsvString() + " " + tiny.toHslString() + " " + tiny.toHexString() + "Original: " + JSON.stringify(c.rgb) + " " + JSON.stringify(c.hsv) + " " + JSON.stringify(c.hsl) ); assert(tinycolor.equals(c.rgb, c.hex), "RGB equals hex " + c.hex); assert(tinycolor.equals(c.rgb, c.hex8), "RGB equals hex " + c.hex); assert(tinycolor.equals(c.rgb, c.hsl), "RGB equals HSL " + c.hex); assert(tinycolor.equals(c.rgb, c.hsv), "RGB equals HSV " + c.hex); assert(tinycolor.equals(c.rgb, c.rgb), "RGB equals RGB " + c.hex); assert(tinycolor.equals(c.hex, c.hex), "hex equals hex " + c.hex); assert(tinycolor.equals(c.hex, c.hex8), "hex equals hex8 " + c.hex); assert(tinycolor.equals(c.hex, c.hsl), "hex equals HSL " + c.hex); assert(tinycolor.equals(c.hex, c.hsv), "hex equals HSV " + c.hex); assert(tinycolor.equals(c.hsl, c.hsv), "HSL equals HSV " + c.hex); } }); Deno.test("With Ratio", function () { assertEquals( tinycolor.fromRatio({ r: 1, g: 1, b: 1 }).toHexString(), "#ffffff", "white" ); assertEquals( tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 0.5 }).toRgbString(), "rgba(255, 0, 0, 0.5)", "alpha works when ratio is parsed" ); assertEquals( tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 1 }).toRgbString(), "rgb(255, 0, 0)", "alpha = 1 works when ratio is parsed" ); assertEquals( tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 10 }).toRgbString(), "rgb(255, 0, 0)", "alpha > 1 works when ratio is parsed" ); assertEquals( tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: -1 }).toRgbString(), "rgb(255, 0, 0)", "alpha < 1 works when ratio is parsed" ); }); Deno.test("Without Ratio", function () { assertEquals( tinycolor({ r: 1, g: 1, b: 1 }).toHexString(), "#010101", "010101" ); assertEquals( tinycolor({ r: 0.1, g: 0.1, b: 0.1 }).toHexString(), "#000000", "000000" ); assertEquals(tinycolor("rgb .1 .1 .1").toHexString(), "#000000", "000000"); }); Deno.test("RGB Text Parsing", function () { assertEquals( tinycolor("rgb 255 0 0").toHexString(), "#ff0000", "spaced input" ); assertEquals( tinycolor("rgb(255, 0, 0)").toHexString(), "#ff0000", "parenthesized input" ); assertEquals( tinycolor("rgb (255, 0, 0)").toHexString(), "#ff0000", "parenthesized spaced input" ); assertEquals( tinycolor({ r: 255, g: 0, b: 0 }).toHexString(), "#ff0000", "object input" ); assertEquals( tinycolor({ r: 255, g: 0, b: 0 }).toRgb(), { r: 255, g: 0, b: 0, a: 1, }, "object input and compare" ); assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb(200, 100, 0)")); assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); assert( tinycolor.equals({ r: 200, g: 100, b: 0, a: 0.4 }, "rgba 200 100 0 .4") ); assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgba 200 100 0 1")); assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb(200, 100, 0)")); assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); assert( tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb(200, 100, 0)") ); assert( tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") ); assert( tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") ); }); Deno.test("Percentage RGB Text Parsing", function () { assertEquals( tinycolor("rgb 100% 0% 0%").toHexString(), "#ff0000", "spaced input" ); assertEquals( tinycolor("rgb(100%, 0%, 0%)").toHexString(), "#ff0000", "parenthesized input" ); assertEquals( tinycolor("rgb (100%, 0%, 0%)").toHexString(), "#ff0000", "parenthesized spaced input" ); assertEquals( tinycolor({ r: "100%", g: "0%", b: "0%" }).toHexString(), "#ff0000", "object input" ); assertEquals( tinycolor({ r: "100%", g: "0%", b: "0%" }).toRgb(), { r: 255, g: 0, b: 0, a: 1, }, "object input and compare" ); assert( tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") ); assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); assert( tinycolor.equals( { r: "90%", g: "45%", b: "0%", a: 0.4 }, "rgba 90% 45% 0% .4" ) ); assert( !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgba 90% 45% 0% 1") ); assert( !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") ); assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); assert( tinycolor.equals( tinycolor({ r: "90%", g: "45%", b: "0%" }), "rgb(90%, 45%, 0%)" ) ); assert( tinycolor.equals( tinycolor({ r: "90%", g: "45%", b: "0%" }), "rgb 90% 45% 0%" ) ); assert( tinycolor.equals( tinycolor({ r: "90%", g: "45%", b: "0%" }), "rgb 90% 45% 0%" ) ); }); Deno.test("HSL parsing", function () { assertEquals( tinycolor({ h: 251, s: 100, l: 0.38 }).toHexString(), "#2400c2", "to hex" ); assertEquals( tinycolor({ h: 251, s: 100, l: 0.38 }).toRgbString(), "rgb(36, 0, 194)", "to rgb" ); assertEquals( tinycolor({ h: 251, s: 100, l: 0.38 }).toHslString(), "hsl(251, 100%, 38%)", "to hsl" ); assertEquals( tinycolor({ h: 251, s: 100, l: 0.38, a: 0.5 }).toHslString(), "hsla(251, 100%, 38%, 0.5)", "to hsla" ); assertEquals( tinycolor("hsl(251, 100, 38)").toHexString(), "#2400c2", "to hex" ); assertEquals( tinycolor("hsl(251, 100%, 38%)").toRgbString(), "rgb(36, 0, 194)", "to rgb" ); assertEquals( tinycolor("hsl(251, 100%, 38%)").toHslString(), "hsl(251, 100%, 38%)", "to hsl" ); assertEquals( tinycolor("hsl 100 20 10").toHslString(), "hsl(100, 20%, 10%)", "problematic hsl" ); }); Deno.test("Hex Parsing", function () { assertEquals(tinycolor("rgb 255 0 0").toHexString(), "#ff0000"); assertEquals(tinycolor("rgb 255 0 0").toHexString(true), "#f00"); assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8String(), "#ff000080"); assertEquals(tinycolor("rgba 255 0 0 0").toHex8String(), "#ff000000"); assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(), "#ff0000ff"); assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(true), "#f00f"); assertEquals(tinycolor("rgb 255 0 0").toHex(), "ff0000"); assertEquals(tinycolor("rgb 255 0 0").toHex(true), "f00"); assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8(), "ff000080"); }); Deno.test("HSV Parsing", function () { assertEquals( tinycolor("hsv 251.1 0.887 .918").toHsvString(), "hsv(251, 89%, 92%)" ); assertEquals( tinycolor("hsv 251.1 0.887 0.918").toHsvString(), "hsv(251, 89%, 92%)" ); assertEquals( tinycolor("hsva 251.1 0.887 0.918 0.5").toHsvString(), "hsva(251, 89%, 92%, 0.5)" ); }); Deno.test("Invalid Parsing", function () { var invalidColor = tinycolor("this is not a color"); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor("#red"); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor(" #red"); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor("##123456"); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor(" ##123456"); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor({ r: "invalid", g: "invalid", b: "invalid" }); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor({ h: "invalid", s: "invalid", l: "invalid" }); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); invalidColor = tinycolor({ h: "invalid", s: "invalid", v: "invalid" }); assertEquals(invalidColor.toHexString(), "#000000"); assertEquals(false, invalidColor.isValid()); }); Deno.test("Named colors", function () { assertEquals(tinycolor("aliceblue").toHex(), "f0f8ff"); assertEquals(tinycolor("antiquewhite").toHex(), "faebd7"); assertEquals(tinycolor("aqua").toHex(), "00ffff"); assertEquals(tinycolor("aquamarine").toHex(), "7fffd4"); assertEquals(tinycolor("azure").toHex(), "f0ffff"); assertEquals(tinycolor("beige").toHex(), "f5f5dc"); assertEquals(tinycolor("bisque").toHex(), "ffe4c4"); assertEquals(tinycolor("black").toHex(), "000000"); assertEquals(tinycolor("blanchedalmond").toHex(), "ffebcd"); assertEquals(tinycolor("blue").toHex(), "0000ff"); assertEquals(tinycolor("blueviolet").toHex(), "8a2be2"); assertEquals(tinycolor("brown").toHex(), "a52a2a"); assertEquals(tinycolor("burlywood").toHex(), "deb887"); assertEquals(tinycolor("cadetblue").toHex(), "5f9ea0"); assertEquals(tinycolor("chartreuse").toHex(), "7fff00"); assertEquals(tinycolor("chocolate").toHex(), "d2691e"); assertEquals(tinycolor("coral").toHex(), "ff7f50"); assertEquals(tinycolor("cornflowerblue").toHex(), "6495ed"); assertEquals(tinycolor("cornsilk").toHex(), "fff8dc"); assertEquals(tinycolor("crimson").toHex(), "dc143c"); assertEquals(tinycolor("cyan").toHex(), "00ffff"); assertEquals(tinycolor("darkblue").toHex(), "00008b"); assertEquals(tinycolor("darkcyan").toHex(), "008b8b"); assertEquals(tinycolor("darkgoldenrod").toHex(), "b8860b"); assertEquals(tinycolor("darkgray").toHex(), "a9a9a9"); assertEquals(tinycolor("darkgreen").toHex(), "006400"); assertEquals(tinycolor("darkkhaki").toHex(), "bdb76b"); assertEquals(tinycolor("darkmagenta").toHex(), "8b008b"); assertEquals(tinycolor("darkolivegreen").toHex(), "556b2f"); assertEquals(tinycolor("darkorange").toHex(), "ff8c00"); assertEquals(tinycolor("darkorchid").toHex(), "9932cc"); assertEquals(tinycolor("darkred").toHex(), "8b0000"); assertEquals(tinycolor("darksalmon").toHex(), "e9967a"); assertEquals(tinycolor("darkseagreen").toHex(), "8fbc8f"); assertEquals(tinycolor("darkslateblue").toHex(), "483d8b"); assertEquals(tinycolor("darkslategray").toHex(), "2f4f4f"); assertEquals(tinycolor("darkturquoise").toHex(), "00ced1"); assertEquals(tinycolor("darkviolet").toHex(), "9400d3"); assertEquals(tinycolor("deeppink").toHex(), "ff1493"); assertEquals(tinycolor("deepskyblue").toHex(), "00bfff"); assertEquals(tinycolor("dimgray").toHex(), "696969"); assertEquals(tinycolor("dodgerblue").toHex(), "1e90ff"); assertEquals(tinycolor("firebrick").toHex(), "b22222"); assertEquals(tinycolor("floralwhite").toHex(), "fffaf0"); assertEquals(tinycolor("forestgreen").toHex(), "228b22"); assertEquals(tinycolor("fuchsia").toHex(), "ff00ff"); assertEquals(tinycolor("gainsboro").toHex(), "dcdcdc"); assertEquals(tinycolor("ghostwhite").toHex(), "f8f8ff"); assertEquals(tinycolor("gold").toHex(), "ffd700"); assertEquals(tinycolor("goldenrod").toHex(), "daa520"); assertEquals(tinycolor("gray").toHex(), "808080"); assertEquals(tinycolor("grey").toHex(), "808080"); assertEquals(tinycolor("green").toHex(), "008000"); assertEquals(tinycolor("greenyellow").toHex(), "adff2f"); assertEquals(tinycolor("honeydew").toHex(), "f0fff0"); assertEquals(tinycolor("hotpink").toHex(), "ff69b4"); assertEquals(tinycolor("indianred ").toHex(), "cd5c5c"); assertEquals(tinycolor("indigo ").toHex(), "4b0082"); assertEquals(tinycolor("ivory").toHex(), "fffff0"); assertEquals(tinycolor("khaki").toHex(), "f0e68c"); assertEquals(tinycolor("lavender").toHex(), "e6e6fa"); assertEquals(tinycolor("lavenderblush").toHex(), "fff0f5"); assertEquals(tinycolor("lawngreen").toHex(), "7cfc00"); assertEquals(tinycolor("lemonchiffon").toHex(), "fffacd"); assertEquals(tinycolor("lightblue").toHex(), "add8e6"); assertEquals(tinycolor("lightcoral").toHex(), "f08080"); assertEquals(tinycolor("lightcyan").toHex(), "e0ffff"); assertEquals(tinycolor("lightgoldenrodyellow").toHex(), "fafad2"); assertEquals(tinycolor("lightgrey").toHex(), "d3d3d3"); assertEquals(tinycolor("lightgreen").toHex(), "90ee90"); assertEquals(tinycolor("lightpink").toHex(), "ffb6c1"); assertEquals(tinycolor("lightsalmon").toHex(), "ffa07a"); assertEquals(tinycolor("lightseagreen").toHex(), "20b2aa"); assertEquals(tinycolor("lightskyblue").toHex(), "87cefa"); assertEquals(tinycolor("lightslategray").toHex(), "778899"); assertEquals(tinycolor("lightsteelblue").toHex(), "b0c4de"); assertEquals(tinycolor("lightyellow").toHex(), "ffffe0"); assertEquals(tinycolor("lime").toHex(), "00ff00"); assertEquals(tinycolor("limegreen").toHex(), "32cd32"); assertEquals(tinycolor("linen").toHex(), "faf0e6"); assertEquals(tinycolor("magenta").toHex(), "ff00ff"); assertEquals(tinycolor("maroon").toHex(), "800000"); assertEquals(tinycolor("mediumaquamarine").toHex(), "66cdaa"); assertEquals(tinycolor("mediumblue").toHex(), "0000cd"); assertEquals(tinycolor("mediumorchid").toHex(), "ba55d3"); assertEquals(tinycolor("mediumpurple").toHex(), "9370db"); assertEquals(tinycolor("mediumseagreen").toHex(), "3cb371"); assertEquals(tinycolor("mediumslateblue").toHex(), "7b68ee"); assertEquals(tinycolor("mediumspringgreen").toHex(), "00fa9a"); assertEquals(tinycolor("mediumturquoise").toHex(), "48d1cc"); assertEquals(tinycolor("mediumvioletred").toHex(), "c71585"); assertEquals(tinycolor("midnightblue").toHex(), "191970"); assertEquals(tinycolor("mintcream").toHex(), "f5fffa"); assertEquals(tinycolor("mistyrose").toHex(), "ffe4e1"); assertEquals(tinycolor("moccasin").toHex(), "ffe4b5"); assertEquals(tinycolor("navajowhite").toHex(), "ffdead"); assertEquals(tinycolor("navy").toHex(), "000080"); assertEquals(tinycolor("oldlace").toHex(), "fdf5e6"); assertEquals(tinycolor("olive").toHex(), "808000"); assertEquals(tinycolor("olivedrab").toHex(), "6b8e23"); assertEquals(tinycolor("orange").toHex(), "ffa500"); assertEquals(tinycolor("orangered").toHex(), "ff4500"); assertEquals(tinycolor("orchid").toHex(), "da70d6"); assertEquals(tinycolor("palegoldenrod").toHex(), "eee8aa"); assertEquals(tinycolor("palegreen").toHex(), "98fb98"); assertEquals(tinycolor("paleturquoise").toHex(), "afeeee"); assertEquals(tinycolor("palevioletred").toHex(), "db7093"); assertEquals(tinycolor("papayawhip").toHex(), "ffefd5"); assertEquals(tinycolor("peachpuff").toHex(), "ffdab9"); assertEquals(tinycolor("peru").toHex(), "cd853f"); assertEquals(tinycolor("pink").toHex(), "ffc0cb"); assertEquals(tinycolor("plum").toHex(), "dda0dd"); assertEquals(tinycolor("powderblue").toHex(), "b0e0e6"); assertEquals(tinycolor("purple").toHex(), "800080"); assertEquals(tinycolor("rebeccapurple").toHex(), "663399"); assertEquals(tinycolor("red").toHex(), "ff0000"); assertEquals(tinycolor("rosybrown").toHex(), "bc8f8f"); assertEquals(tinycolor("royalblue").toHex(), "4169e1"); assertEquals(tinycolor("saddlebrown").toHex(), "8b4513"); assertEquals(tinycolor("salmon").toHex(), "fa8072"); assertEquals(tinycolor("sandybrown").toHex(), "f4a460"); assertEquals(tinycolor("seagreen").toHex(), "2e8b57"); assertEquals(tinycolor("seashell").toHex(), "fff5ee"); assertEquals(tinycolor("sienna").toHex(), "a0522d"); assertEquals(tinycolor("silver").toHex(), "c0c0c0"); assertEquals(tinycolor("skyblue").toHex(), "87ceeb"); assertEquals(tinycolor("slateblue").toHex(), "6a5acd"); assertEquals(tinycolor("slategray").toHex(), "708090"); assertEquals(tinycolor("snow").toHex(), "fffafa"); assertEquals(tinycolor("springgreen").toHex(), "00ff7f"); assertEquals(tinycolor("steelblue").toHex(), "4682b4"); assertEquals(tinycolor("tan").toHex(), "d2b48c"); assertEquals(tinycolor("teal").toHex(), "008080"); assertEquals(tinycolor("thistle").toHex(), "d8bfd8"); assertEquals(tinycolor("tomato").toHex(), "ff6347"); assertEquals(tinycolor("turquoise").toHex(), "40e0d0"); assertEquals(tinycolor("violet").toHex(), "ee82ee"); assertEquals(tinycolor("wheat").toHex(), "f5deb3"); assertEquals(tinycolor("white").toHex(), "ffffff"); assertEquals(tinycolor("whitesmoke").toHex(), "f5f5f5"); assertEquals(tinycolor("yellow").toHex(), "ffff00"); assertEquals(tinycolor("yellowgreen").toHex(), "9acd32"); assertEquals(tinycolor("#f00").toName(), "red"); assertEquals(tinycolor("#fa0a0a").toName(), false); }); Deno.test("Invalid alpha should normalize to 1", function () { assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: -1 }).toRgbString(), "rgb(255, 20, 10)", "Negative value" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: -0 }).toRgbString(), "rgba(255, 20, 10, 0)", "Negative 0" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toRgbString(), "rgba(255, 20, 10, 0)", "0" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: 0.5 }).toRgbString(), "rgba(255, 20, 10, 0.5)", ".5" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: 1 }).toRgbString(), "rgb(255, 20, 10)", "1" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: 100 }).toRgbString(), "rgb(255, 20, 10)", "Greater than 1" ); assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: "asdfasd" }).toRgbString(), "rgb(255, 20, 10)", "Non Numeric" ); assertEquals( tinycolor("#fff").toRgbString(), "rgb(255, 255, 255)", "Hex should be 1" ); assertEquals( tinycolor("rgba 255 0 0 100").toRgbString(), "rgb(255, 0, 0)", "Greater than 1 in string parsing" ); }); Deno.test("toString() with alpha set", function () { var redNamed = tinycolor.fromRatio( { r: 255, g: 0, b: 0, a: 0.6 }, { format: "name", } ); var transparentNamed = tinycolor.fromRatio( { r: 255, g: 0, b: 0, a: 0 }, { format: "name", } ); var redHex = tinycolor.fromRatio( { r: 255, g: 0, b: 0, a: 0.4 }, { format: "hex", } ); assertEquals(redNamed.getFormat(), "name", "getFormat() is correct"); assertEquals(redHex.getFormat(), "hex", "getFormat() is correct"); assertEquals( redNamed.toString(), "rgba(255, 0, 0, 0.6)", "Names should default to rgba if alpha is < 1" ); assertEquals( redHex.toString(), "rgba(255, 0, 0, 0.4)", "Hex should default to rgba if alpha is < 1" ); assertEquals( redNamed.toString("hex"), "#ff0000", "Names should not be returned as rgba if format is specified" ); assertEquals( redNamed.toString("hex6"), "#ff0000", "Names should not be returned as rgba if format is specified" ); assertEquals( redNamed.toString("hex3"), "#f00", "Names should not be returned as rgba if format is specified" ); assertEquals( redNamed.toString("hex8"), "#ff000099", "Names should not be returned as rgba if format is specified" ); assertEquals( redNamed.toString("hex4"), "#f009", "Names should not be returned as rgba if format is specified" ); assertEquals( redNamed.toString("name"), "#ff0000", "Semi transparent names should return hex in toString() if name format is specified" ); assertEquals( redNamed.toName(), false, "Semi transparent names should be false in toName()" ); assertEquals( redHex.toString(), "rgba(255, 0, 0, 0.4)", "Hex should default to rgba if alpha is < 1" ); assertEquals( transparentNamed.toString(), "transparent", "Named color should equal transparent if alpha == 0" ); redHex.setAlpha(0); assertEquals( redHex.toString(), "rgba(255, 0, 0, 0)", "Hex should default to rgba if alpha is = 0" ); }); Deno.test("setting alpha", function () { var hexSetter = tinycolor("rgba(255, 0, 0, 1)"); assertEquals(hexSetter.getAlpha(), 1, "Alpha should start as 1"); var returnedFromSetAlpha = hexSetter.setAlpha(0.9); assertEquals( returnedFromSetAlpha, hexSetter, "setAlpha return value should be the color." ); assertEquals(hexSetter.getAlpha(), 0.9, "setAlpha should change alpha value"); hexSetter.setAlpha(0.5); assertEquals(hexSetter.getAlpha(), 0.5, "setAlpha should change alpha value"); hexSetter.setAlpha(0); assertEquals(hexSetter.getAlpha(), 0, "setAlpha should change alpha value"); hexSetter.setAlpha(-1); assertEquals( hexSetter.getAlpha(), 1, "setAlpha with value < 0 should be bound to 1" ); hexSetter.setAlpha(2); assertEquals( hexSetter.getAlpha(), 1, "setAlpha with value > 1 should be bound to 1" ); hexSetter.setAlpha(); assertEquals( hexSetter.getAlpha(), 1, "setAlpha with invalid value should be bound to 1" ); hexSetter.setAlpha(null); assertEquals( hexSetter.getAlpha(), 1, "setAlpha with invalid value should be bound to 1" ); hexSetter.setAlpha("test"); assertEquals( hexSetter.getAlpha(), 1, "setAlpha with invalid value should be bound to 1" ); }); Deno.test("Alpha = 0 should act differently on toName()", function () { assertEquals( tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toName(), "transparent", "0" ); assertEquals( tinycolor("transparent").toString(), "transparent", "toString when passed" ); assertEquals(tinycolor("transparent").toHex(), "000000", "toHex"); }); Deno.test("getBrightness", function () { assertEquals(tinycolor("#000").getBrightness(), 0, "returns 0 for #000"); assertEquals(tinycolor("#fff").getBrightness(), 255, "returns 255 for #fff"); }); Deno.test("getLuminance", function () { assertEquals(tinycolor("#000").getLuminance(), 0, "returns 0 for #000"); assertEquals(tinycolor("#fff").getLuminance(), 1, "returns 1 for #fff"); }); Deno.test("isDark returns true/false for dark/light colors", function () { assertEquals(tinycolor("#000").isDark(), true, "#000 is dark"); assertEquals(tinycolor("#111").isDark(), true, "#111 is dark"); assertEquals(tinycolor("#222").isDark(), true, "#222 is dark"); assertEquals(tinycolor("#333").isDark(), true, "#333 is dark"); assertEquals(tinycolor("#444").isDark(), true, "#444 is dark"); assertEquals(tinycolor("#555").isDark(), true, "#555 is dark"); assertEquals(tinycolor("#666").isDark(), true, "#666 is dark"); assertEquals(tinycolor("#777").isDark(), true, "#777 is dark"); assertEquals(tinycolor("#888").isDark(), false, "#888 is not dark"); assertEquals(tinycolor("#999").isDark(), false, "#999 is not dark"); assertEquals(tinycolor("#aaa").isDark(), false, "#aaa is not dark"); assertEquals(tinycolor("#bbb").isDark(), false, "#bbb is not dark"); assertEquals(tinycolor("#ccc").isDark(), false, "#ccc is not dark"); assertEquals(tinycolor("#ddd").isDark(), false, "#ddd is not dark"); assertEquals(tinycolor("#eee").isDark(), false, "#eee is not dark"); assertEquals(tinycolor("#fff").isDark(), false, "#fff is not dark"); }); Deno.test("isLight returns true/false for light/dark colors", function () { assertEquals(tinycolor("#000").isLight(), false, "#000 is not light"); assertEquals(tinycolor("#111").isLight(), false, "#111 is not light"); assertEquals(tinycolor("#222").isLight(), false, "#222 is not light"); assertEquals(tinycolor("#333").isLight(), false, "#333 is not light"); assertEquals(tinycolor("#444").isLight(), false, "#444 is not light"); assertEquals(tinycolor("#555").isLight(), false, "#555 is not light"); assertEquals(tinycolor("#666").isLight(), false, "#666 is not light"); assertEquals(tinycolor("#777").isLight(), false, "#777 is not light"); assertEquals(tinycolor("#888").isLight(), true, "#888 is light"); assertEquals(tinycolor("#999").isLight(), true, "#999 is light"); assertEquals(tinycolor("#aaa").isLight(), true, "#aaa is light"); assertEquals(tinycolor("#bbb").isLight(), true, "#bbb is light"); assertEquals(tinycolor("#ccc").isLight(), true, "#ccc is light"); assertEquals(tinycolor("#ddd").isLight(), true, "#ddd is light"); assertEquals(tinycolor("#eee").isLight(), true, "#eee is light"); assertEquals(tinycolor("#fff").isLight(), true, "#fff is light"); }); Deno.test("HSL Object", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assertEquals( tiny.toHexString(), tinycolor(tiny.toHsl()).toHexString(), "HSL Object" ); } }); Deno.test("HSL String", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); var input = tiny.toRgb(); var output = tinycolor(tiny.toHslString()).toRgb(); var maxDiff = 2; assertEquals( Math.abs(input.r - output.r) <= maxDiff, true, "toHslString red value difference <= " + maxDiff ); assertEquals( Math.abs(input.g - output.g) <= maxDiff, true, "toHslString green value difference <= " + maxDiff ); assertEquals( Math.abs(input.b - output.b) <= maxDiff, true, "toHslString blue value difference <= " + maxDiff ); } }); Deno.test("HSV String", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); var input = tiny.toRgb(); var output = tinycolor(tiny.toHsvString()).toRgb(); var maxDiff = 2; assertEquals( Math.abs(input.r - output.r) <= maxDiff, true, "toHsvString red value difference <= " + maxDiff ); assertEquals( Math.abs(input.g - output.g) <= maxDiff, true, "toHsvString green value difference <= " + maxDiff ); assertEquals( Math.abs(input.b - output.b) <= maxDiff, true, "toHsvString blue value difference <= " + maxDiff ); } }); Deno.test("HSV Object", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assertEquals( tiny.toHexString(), tinycolor(tiny.toHsv()).toHexString(), "HSV Object" ); } }); Deno.test("RGB Object", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assertEquals( tiny.toHexString(), tinycolor(tiny.toRgb()).toHexString(), "RGB Object" ); } }); Deno.test("RGB String", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assertEquals( tiny.toHexString(), tinycolor(tiny.toRgbString()).toHexString(), "RGB String" ); } }); Deno.test("PRGB Object", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); var input = tiny.toRgb(); var output = tinycolor(tiny.toPercentageRgb()).toRgb(); var maxDiff = 2; assertEquals( Math.abs(input.r - output.r) <= maxDiff, true, "Red value difference <= " + maxDiff ); assertEquals( Math.abs(input.g - output.g) <= maxDiff, true, "Green value difference <= " + maxDiff ); assertEquals( Math.abs(input.b - output.b) <= maxDiff, true, "Blue value difference <= " + maxDiff ); } }); Deno.test("PRGB String", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); var input = tiny.toRgb(); var output = tinycolor(tiny.toPercentageRgbString()).toRgb(); var maxDiff = 2; assertEquals( Math.abs(input.r - output.r) <= maxDiff, true, "Red value difference <= " + maxDiff ); assertEquals( Math.abs(input.g - output.g) <= maxDiff, true, "Green value difference <= " + maxDiff ); assertEquals( Math.abs(input.b - output.b) <= maxDiff, true, "Blue value difference <= " + maxDiff ); } }); Deno.test("Object", function () { for (var i = 0; i < conversions.length; i++) { var c = conversions[i]; var tiny = tinycolor(c.hex); assertEquals(tiny.toHexString(), tinycolor(tiny).toHexString(), "Object"); } }); Deno.test("Color equality", function () { assert(tinycolor.equals("#ff0000", "#ff0000"), "Same hex"); assert(tinycolor.equals("#ff0000", "rgb(255, 0, 0)"), "Same alphas"); assert( !tinycolor.equals("#ff0000", "rgba(255, 0, 0, .1)"), "Different alphas" ); assert(tinycolor.equals("#ff000066", "rgba(255, 0, 0, .4)"), "Same alphas"); assert(tinycolor.equals("#f009", "rgba(255, 0, 0, .6)"), "Same alphas"); assert(tinycolor.equals("#336699CC", "369C"), "Same hex"); assert(tinycolor.equals("ff0000", "#ff0000"), "Same hex"); assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); assert(tinycolor.equals("f00", "#ff0000"), "Same hex"); assertEquals(tinycolor("010101").toHexString(), "#010101"); assert(!tinycolor.equals("#ff0000", "#00ff00"), "Different hex"); assert( tinycolor.equals("#ff8000", "rgb(100%, 50%, 0%)"), "Percentage bounds checking" ); }); Deno.test("isReadable", function () { // "#ff0088", "#8822aa" (values used in old WCAG1 tests) assert( tinycolor.isReadable("#000000", "#ffffff", { level: "AA", size: "small" }), "white/black is readable" ); assert( !tinycolor.isReadable("#ff0088", "#5c1a72", {}), "not readable - empty wcag2 object" ); assert( !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "small" }), "not readable - AA small" ); assert( !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "large" }), "not readable - AA large" ); assert( !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AAA", size: "small", }), "not readable - AAA small" ); assert( !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AAA", size: "large", }), "not readable - AAA large" ); // values derived from and validated using the calculators at http://www.dasplankton.de/ContrastA/ // and http://webaim.org/resources/contrastchecker/ // "#ff0088", "#5c1a72": contrast ratio 3.04 assert( !tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "small" }), "not readable - AA small" ); assert( tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "large" }), "readable - AA large" ); assert( !tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AAA", size: "small", }), "not readable - AAA small" ); assert( !tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AAA", size: "large", }), "not readable - AAA large" ); // "#ff0088", "#2e0c3a": contrast ratio 4.56 assert( tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "small" }), "readable - AA small" ); assert( tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "large" }), "readable - AA large" ); assert( !tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AAA", size: "small", }), "not readable - AAA small" ); assert( tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AAA", size: "large" }), "readable - AAA large" ); // "#db91b8", "#2e0c3a": contrast ratio 7.12 assert( tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "small" }), "readable - AA small" ); assert( tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "large" }), "readable - AA large" ); assert( tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "small" }), "readable - AAA small" ); assert( tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "large" }), "readable - AAA large" ); }); Deno.test("readability", function () { // check return values from readability function. See isReadable above for standards tests. assertEquals( tinycolor.readability("#000", "#000"), 1, "Readability function test 0" ); assertEquals( tinycolor.readability("#000", "#111"), 1.1121078324840545, "Readability function test 1" ); assertEquals( tinycolor.readability("#000", "#fff"), 21, "Readability function test 2" ); }); Deno.test("mostReadable", function () { assertEquals( tinycolor .mostReadable("#000", ["#111", "#222", { wcag2: {} }]) .toHexString(), "#222222", "readable color present" ); assertEquals( tinycolor .mostReadable("#f00", ["#d00", "#0d0"], { wcag2: {} }) .toHexString(), "#00dd00", "readable color present" ); assertEquals( tinycolor .mostReadable("#fff", ["#fff", "#fff"], { wcag2: {} }) .toHexString(), "#ffffff", "no different color in list" ); //includeFallbackColors assertEquals( tinycolor .mostReadable("#fff", ["#fff", "#fff"], { includeFallbackColors: true, }) .toHexString(), "#000000", "no different color in list" ); assertEquals( tinycolor .mostReadable("#123", ["#124", "#125"], { includeFallbackColors: false, }) .toHexString(), "#112255", "no readable color in list" ); assertEquals( tinycolor .mostReadable("#123", ["#000", "#fff"], { includeFallbackColors: false, }) .toHexString(), "#ffffff", "verify assumption" ); assertEquals( tinycolor .mostReadable("#123", ["#124", "#125"], { includeFallbackColors: true, }) .toHexString(), "#ffffff", "no readable color in list" ); assertEquals( tinycolor .mostReadable("#ff0088", ["#000", "#fff"], { includeFallbackColors: false, }) .toHexString(), "#000000", "verify assumption" ); assertEquals( tinycolor .mostReadable("#ff0088", ["#2e0c3a"], { includeFallbackColors: true, level: "AAA", size: "large", }) .toHexString(), "#2e0c3a", "readable color present" ); assertEquals( tinycolor .mostReadable("#ff0088", ["#2e0c3a"], { includeFallbackColors: true, level: "AAA", size: "small", }) .toHexString(), "#000000", "no readable color in list" ); assertEquals( tinycolor .mostReadable("#371b2c", ["#000", "#fff"], { includeFallbackColors: false, }) .toHexString(), "#ffffff", "verify assumption" ); assertEquals( tinycolor .mostReadable("#371b2c", ["#a9acb6"], { includeFallbackColors: true, level: "AAA", size: "large", }) .toHexString(), "#a9acb6", "readable color present" ); assertEquals( tinycolor .mostReadable("#371b2c", ["#a9acb6"], { includeFallbackColors: true, level: "AAA", size: "small", }) .toHexString(), "#ffffff", "no readable color in list" ); }); Deno.test("Filters", function () { assertEquals( tinycolor("red").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ffff0000)" ); assertEquals( tinycolor("red").toFilter("blue"), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ff0000ff)" ); assertEquals( tinycolor("transparent").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#00000000)" ); assertEquals( tinycolor("transparent").toFilter("red"), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#ffff0000)" ); assertEquals( tinycolor("#f0f0f0dd").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ddf0f0f0,endColorstr=#ddf0f0f0)" ); assertEquals( tinycolor("rgba(0, 0, 255, .5").toFilter(), "progid:DXImageTransform.Microsoft.gradient(startColorstr=#800000ff,endColorstr=#800000ff)" ); }); /* Originally generated with: var results = []; for (var i = 0; i <= 100; i++) results.push( tinycolor.saturate("red", i).toHex() ) console.log(JSON.stringify(results)) */ var DESATURATIONS = [ "ff0000", "fe0101", "fc0303", "fb0404", "fa0505", "f90606", "f70808", "f60909", "f50a0a", "f40b0b", "f20d0d", "f10e0e", "f00f0f", "ee1111", "ed1212", "ec1313", "eb1414", "e91616", "e81717", "e71818", "e61919", "e41b1b", "e31c1c", "e21d1d", "e01f1f", "df2020", "de2121", "dd2222", "db2424", "da2525", "d92626", "d72828", "d62929", "d52a2a", "d42b2b", "d22d2d", "d12e2e", "d02f2f", "cf3030", "cd3232", "cc3333", "cb3434", "c93636", "c83737", "c73838", "c63939", "c43b3b", "c33c3c", "c23d3d", "c13e3e", "bf4040", "be4141", "bd4242", "bb4444", "ba4545", "b94646", "b84747", "b64949", "b54a4a", "b44b4b", "b34d4d", "b14e4e", "b04f4f", "af5050", "ad5252", "ac5353", "ab5454", "aa5555", "a85757", "a75858", "a65959", "a45b5b", "a35c5c", "a25d5d", "a15e5e", "9f6060", "9e6161", "9d6262", "9c6363", "9a6565", "996666", "986767", "966969", "956a6a", "946b6b", "936c6c", "916e6e", "906f6f", "8f7070", "8e7171", "8c7373", "8b7474", "8a7575", "887777", "877878", "867979", "857a7a", "837c7c", "827d7d", "817e7e", "808080", ]; var SATURATIONS = [ "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", "ff0000", ]; var LIGHTENS = [ "ff0000", "ff0505", "ff0a0a", "ff0f0f", "ff1414", "ff1a1a", "ff1f1f", "ff2424", "ff2929", "ff2e2e", "ff3333", "ff3838", "ff3d3d", "ff4242", "ff4747", "ff4d4d", "ff5252", "ff5757", "ff5c5c", "ff6161", "ff6666", "ff6b6b", "ff7070", "ff7575", "ff7a7a", "ff8080", "ff8585", "ff8a8a", "ff8f8f", "ff9494", "ff9999", "ff9e9e", "ffa3a3", "ffa8a8", "ffadad", "ffb3b3", "ffb8b8", "ffbdbd", "ffc2c2", "ffc7c7", "ffcccc", "ffd1d1", "ffd6d6", "ffdbdb", "ffe0e0", "ffe5e5", "ffebeb", "fff0f0", "fff5f5", "fffafa", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", "ffffff", ]; var BRIGHTENS = [ "ff0000", "ff0303", "ff0505", "ff0808", "ff0a0a", "ff0d0d", "ff0f0f", "ff1212", "ff1414", "ff1717", "ff1919", "ff1c1c", "ff1f1f", "ff2121", "ff2424", "ff2626", "ff2929", "ff2b2b", "ff2e2e", "ff3030", "ff3333", "ff3636", "ff3838", "ff3b3b", "ff3d3d", "ff4040", "ff4242", "ff4545", "ff4747", "ff4a4a", "ff4c4c", "ff4f4f", "ff5252", "ff5454", "ff5757", "ff5959", "ff5c5c", "ff5e5e", "ff6161", "ff6363", "ff6666", "ff6969", "ff6b6b", "ff6e6e", "ff7070", "ff7373", "ff7575", "ff7878", "ff7a7a", "ff7d7d", "ff7f7f", "ff8282", "ff8585", "ff8787", "ff8a8a", "ff8c8c", "ff8f8f", "ff9191", "ff9494", "ff9696", "ff9999", "ff9c9c", "ff9e9e", "ffa1a1", "ffa3a3", "ffa6a6", "ffa8a8", "ffabab", "ffadad", "ffb0b0", "ffb2b2", "ffb5b5", "ffb8b8", "ffbaba", "ffbdbd", "ffbfbf", "ffc2c2", "ffc4c4", "ffc7c7", "ffc9c9", "ffcccc", "ffcfcf", "ffd1d1", "ffd4d4", "ffd6d6", "ffd9d9", "ffdbdb", "ffdede", "ffe0e0", "ffe3e3", "ffe5e5", "ffe8e8", "ffebeb", "ffeded", "fff0f0", "fff2f2", "fff5f5", "fff7f7", "fffafa", "fffcfc", "ffffff", ]; var DARKENS = [ "ff0000", "fa0000", "f50000", "f00000", "eb0000", "e60000", "e00000", "db0000", "d60000", "d10000", "cc0000", "c70000", "c20000", "bd0000", "b80000", "b30000", "ad0000", "a80000", "a30000", "9e0000", "990000", "940000", "8f0000", "8a0000", "850000", "800000", "7a0000", "750000", "700000", "6b0000", "660000", "610000", "5c0000", "570000", "520000", "4d0000", "470000", "420000", "3d0000", "380000", "330000", "2e0000", "290000", "240000", "1f0000", "190000", "140000", "0f0000", "0a0000", "050000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", "000000", ]; Deno.test("Modifications", function () { for (var i = 0; i <= 100; i++) { assertEquals( tinycolor("red").desaturate(i).toHex(), DESATURATIONS[i], "Desaturation " + i + " works" ); } for (var i = 0; i <= 100; i++) { assertEquals( tinycolor("red").saturate(i).toHex(), SATURATIONS[i], "Saturation " + i + " works" ); } for (var i = 0; i <= 100; i++) { assertEquals( tinycolor("red").lighten(i).toHex(), LIGHTENS[i], "Lighten " + i + " works" ); } for (var i = 0; i <= 100; i++) { assertEquals( tinycolor("red").brighten(i).toHex(), BRIGHTENS[i], "Brighter " + i + " works" ); } for (var i = 0; i <= 100; i++) { assertEquals( tinycolor("red").darken(i).toHex(), DARKENS[i], "Darken " + i + " works" ); } assertEquals( tinycolor("red").greyscale().toHex(), "808080", "Greyscale works" ); }); Deno.test("Spin", function () { assertEquals( Math.round(tinycolor("#f00").spin(-1234).toHsl().h), 206, "Spinning -1234 works" ); assertEquals( Math.round(tinycolor("#f00").spin(-360).toHsl().h), 0, "Spinning -360 works" ); assertEquals( Math.round(tinycolor("#f00").spin(-120).toHsl().h), 240, "Spinning -120 works" ); assertEquals( Math.round(tinycolor("#f00").spin(0).toHsl().h), 0, "Spinning 0 works" ); assertEquals( Math.round(tinycolor("#f00").spin(10).toHsl().h), 10, "Spinning 10 works" ); assertEquals( Math.round(tinycolor("#f00").spin(360).toHsl().h), 0, "Spinning 360 works" ); assertEquals( Math.round(tinycolor("#f00").spin(2345).toHsl().h), 185, "Spinning 2345 works" ); [-360, 0, 360].forEach(function (delta) { Object.keys(tinycolor.names).forEach(function (name) { assertEquals( tinycolor(name).toHex(), tinycolor(name).spin(delta).toHex(), "Spinning " + delta.toString() + " has no effect" ); }); }); }); Deno.test("Mix", function () { // amount 0 or none assertEquals( tinycolor.mix("#000", "#fff").toHsl().l, 0.5, "Mixing without amount works" ); assertEquals( tinycolor.mix("#f00", "#000", 0).toHex(), "ff0000", "Mixing with 0 amount works" ); // This case checks the the problem with floating point numbers (eg 255/90) assertEquals( tinycolor.mix("#fff", "#000", 90).toHex(), "1a1a1a", "Mixing with 90 amount works correctly" ); // black and white for (var i = 0; i < 100; i++) { assertEquals( Math.round(tinycolor.mix("#000", "#fff", i).toHsl().l * 100) / 100, i / 100, "Mixing black and white with " + i + " amount works" ); } // with colors for (var i = 0; i < 100; i++) { var new_hex = Math.round((255 * (100 - i)) / 100).toString(16); if (new_hex.length === 1) { new_hex = "0" + new_hex; } assertEquals( tinycolor.mix("#f00", "#000", i).toHex(), new_hex + "0000", "Mixing " + i + " (red channel)" ); assertEquals( tinycolor.mix("#0f0", "#000", i).toHex(), "00" + new_hex + "00", "Mixing " + i + " (green channel)" ); assertEquals( tinycolor.mix("#00f", "#000", i).toHex(), "0000" + new_hex, "Mixing " + i + " (blue channel)" ); assertEquals( tinycolor.mix(tinycolor("transparent"), "#000", i).toRgb().a, i / 100, "Mixing " + i + " (alpha channel)" ); } }); // The combination tests need to be expanded furthe function colorsToHexString(colors) { return colors .map(function (c) { return c.toHex(); }) .join(","); } Deno.test("complement", function () { var complementDoesntModifyInstance = tinycolor("red"); assertEquals( complementDoesntModifyInstance.complement().toHex(), "00ffff", "Complement works" ); assertEquals( complementDoesntModifyInstance.toHex(), "ff0000", "Complement did not modify this color" ); }); Deno.test("analogous", function () { var combination = tinycolor("red").analogous(); assertEquals( colorsToHexString(combination), "ff0000,ff0066,ff0033,ff0000,ff3300,ff6600", "Correct Combination" ); }); Deno.test("monochromatic", function () { var combination = tinycolor("red").monochromatic(); assertEquals( colorsToHexString(combination), "ff0000,2a0000,550000,800000,aa0000,d40000", "Correct Combination" ); }); Deno.test("splitcomplement", function () { var combination = tinycolor("red").splitcomplement(); assertEquals( colorsToHexString(combination), "ff0000,ccff00,0066ff", "Correct Combination" ); }); Deno.test("triad", function () { var combination = tinycolor("red").triad(); assertEquals( colorsToHexString(combination), "ff0000,00ff00,0000ff", "Correct Combination" ); }); Deno.test("tetrad", function () { var combination = tinycolor("red").tetrad(); assertEquals( colorsToHexString(combination), "ff0000,80ff00,00ffff,7f00ff", "Correct Combination" ); }); Deno.test({ name: "polyad", // Disabled until https://github.com/bgrins/TinyColor/issues/254 ignore: true, fn: function () { assertThrows(() => { tinycolor("red").polyad(); }); assertThrows(() => { tinycolor("red").polyad(-1); }); assertThrows(() => { tinycolor("red").polyad("invalid"); }); assertEquals(colorsToHexString(tinycolor("red").polyad(1)), "ff0000"); assertEquals(colorsToHexString(tinycolor("red").polyad("1")), "ff0000"); assertEquals( colorsToHexString(tinycolor("red").polyad(2)), "ff0000,00ffff" ); assertEquals( colorsToHexString(tinycolor("red").polyad(3)), "ff0000,00ff00,0000ff" ); assertEquals( colorsToHexString(tinycolor("red").polyad(4)), "ff0000,80ff00,00ffff,7f00ff" ); assertEquals( colorsToHexString(tinycolor("red").polyad(5)), "ff0000,ccff00,00ff66,0066ff,cc00ff" ); }, }); runDenoTests(); })(); node_modules/tinycolor2/cjs/test_template.js 0000664 00000001365 15114743311 0015323 0 ustar 00 // This file is autogenerated. // Ideally it wouldn't exist, but it's here to test cjs in node // Changes should go into ./test.js, and if new assertions are needed // they'll need to be shimmed here as well const tinycolor = require("./tinycolor.js"); const { Deno, testDefinitions } = require("@deno/shim-deno-test"); async function runDenoTests() { for (const test of testDefinitions) { if (test.ignore) { console.log(`Ignoring ${test.name}`); continue; } console.log(`Running ${test.name}`); await test.fn(); console.log(`> Passed ${test.name}`); } } (async () => { const { assertEquals, assert, assertThrows } = await import( "../deno_asserts@0.168.0.mjs" ); // CONTENT_GOES_HERE runDenoTests(); })(); node_modules/tinycolor2/README.md 0000664 00000035036 15114743311 0012615 0 ustar 00 # TinyColor ## JavaScript color tooling TinyColor is a small, fast library for color manipulation and conversion in JavaScript. It allows many forms of input, while providing color conversions and other color utility functions. It has no dependencies. ## Including in node `tinycolor` can be installed from npm: npm install tinycolor2 Then it can be used in your script like so: ```js var tinycolor = require("tinycolor2"); var color = tinycolor("red"); ``` Or in a module like so: ```js import tinycolor from "tinycolor2"; var color = tinycolor("red"); ``` ## Including in a browser The package can be bundled from npm, but if you prefer to download it locally you have two choices: ### ESM It can be used as a module by downloading [npm/esm/tinycolor.js](https://github.com/bgrins/TinyColor/blob/master/npm/esm/tinycolor.js) or using https://esm.sh/tinycolor2. ```html <script type='module'> import tinycolor from "https://esm.sh/tinycolor2"; var color = tinycolor("red"); </script> ``` ### UMD You can use it directly in a script tag by downloading the UMD file from [npm/cjs/tinycolor.js](https://github.com/bgrins/TinyColor/blob/master/npm/cjs/tinycolor.js): ```html <script type='text/javascript' src='tinycolor.js'></script> <script type='text/javascript'> var color = tinycolor("red"); </script> ``` ## Usage Call `tinycolor(input)` or `new tinycolor(input)`, and you will have an object with the following properties. See Accepted String Input and Accepted Object Input below for more information about what is accepted. ## Accepted String Input The string parsing is very permissive. It is meant to make typing a color as input as easy as possible. All commas, percentages, parenthesis are optional, and most input allow either 0-1, 0%-100%, or 0-n (where n is either 100, 255, or 360 depending on the value). HSL and HSV both require either 0%-100% or 0-1 for the `S`/`L`/`V` properties. The `H` (hue) can have values between 0%-100% or 0-360. RGB input requires either 0-255 or 0%-100%. If you call `tinycolor.fromRatio`, RGB and Hue input can also accept 0-1. Here are some examples of string input: ### Hex, 8-digit (RGBA) Hex ```js tinycolor("#000"); tinycolor("000"); tinycolor("#369C"); tinycolor("369C"); tinycolor("#f0f0f6"); tinycolor("f0f0f6"); tinycolor("#f0f0f688"); tinycolor("f0f0f688"); ``` ### RGB, RGBA ```js tinycolor("rgb (255, 0, 0)"); tinycolor("rgb 255 0 0"); tinycolor("rgba (255, 0, 0, .5)"); tinycolor({ r: 255, g: 0, b: 0 }); tinycolor.fromRatio({ r: 1, g: 0, b: 0 }); tinycolor.fromRatio({ r: .5, g: .5, b: .5 }); ``` ### HSL, HSLA ```js tinycolor("hsl(0, 100%, 50%)"); tinycolor("hsla(0, 100%, 50%, .5)"); tinycolor("hsl(0, 100%, 50%)"); tinycolor("hsl 0 1.0 0.5"); tinycolor({ h: 0, s: 1, l: .5 }); tinycolor.fromRatio({ h: 1, s: 0, l: 0 }); tinycolor.fromRatio({ h: .5, s: .5, l: .5 }); ``` ### HSV, HSVA ```js tinycolor("hsv(0, 100%, 100%)"); tinycolor("hsva(0, 100%, 100%, .5)"); tinycolor("hsv (0 100% 100%)"); tinycolor("hsv 0 1 1"); tinycolor({ h: 0, s: 100, v: 100 }); tinycolor.fromRatio({ h: 1, s: 0, v: 0 }); tinycolor.fromRatio({ h: .5, s: .5, v: .5 }); ``` ### Named Case insenstive names are accepted, using the [list of colors in the CSS spec](https://www.w3.org/TR/css-color-4/#named-colors). ```js tinycolor("RED"); tinycolor("blanchedalmond"); tinycolor("darkblue"); ``` ### Accepted Object Input If you are calling this from code, you may want to use object input. Here are some examples of the different types of accepted object inputs: { r: 255, g: 0, b: 0 } { r: 255, g: 0, b: 0, a: .5 } { h: 0, s: 100, l: 50 } { h: 0, s: 100, v: 100 } ## Methods ### getFormat Returns the format used to create the tinycolor instance ```js var color = tinycolor("red"); color.getFormat(); // "name" color = tinycolor({r:255, g:255, b:255}); color.getFormat(); // "rgb" ``` ### getOriginalInput Returns the input passed into the constructor used to create the tinycolor instance ```js var color = tinycolor("red"); color.getOriginalInput(); // "red" color = tinycolor({r:255, g:255, b:255}); color.getOriginalInput(); // "{r: 255, g: 255, b: 255}" ``` ### isValid Return a boolean indicating whether the color was successfully parsed. Note: if the color is not valid then it will act like `black` when being used with other methods. ```js var color1 = tinycolor("red"); color1.isValid(); // true color1.toHexString(); // "#ff0000" var color2 = tinycolor("not a color"); color2.isValid(); // false color2.toString(); // "#000000" ``` ### getBrightness Returns the perceived brightness of a color, from `0-255`, as defined by [Web Content Accessibility Guidelines (Version 1.0)](http://www.w3.org/TR/AERT#color-contrast). ```js var color1 = tinycolor("#fff"); color1.getBrightness(); // 255 var color2 = tinycolor("#000"); color2.getBrightness(); // 0 ``` ### isLight Return a boolean indicating whether the color's perceived brightness is light. ```js var color1 = tinycolor("#fff"); color1.isLight(); // true var color2 = tinycolor("#000"); color2.isLight(); // false ``` ### isDark Return a boolean indicating whether the color's perceived brightness is dark. ```js var color1 = tinycolor("#fff"); color1.isDark(); // false var color2 = tinycolor("#000"); color2.isDark(); // true ``` ### getLuminance Returns the perceived luminance of a color, from `0-1` as defined by [Web Content Accessibility Guidelines (Version 2.0).](http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef) ```js var color1 = tinycolor("#fff"); color1.getLuminance(); // 1 var color2 = tinycolor("#000"); color2.getLuminance(); // 0 ``` ### getAlpha Returns the alpha value of a color, from `0-1`. ```js var color1 = tinycolor("rgba(255, 0, 0, .5)"); color1.getAlpha(); // 0.5 var color2 = tinycolor("rgb(255, 0, 0)"); color2.getAlpha(); // 1 var color3 = tinycolor("transparent"); color3.getAlpha(); // 0 ``` ### setAlpha Sets the alpha value on a current color. Accepted range is in between `0-1`. ```js var color = tinycolor("red"); color.getAlpha(); // 1 color.setAlpha(.5); color.getAlpha(); // .5 color.toRgbString(); // "rgba(255, 0, 0, .5)" ``` ### String Representations The following methods will return a property for the `alpha` value, which can be ignored: `toHsv`, `toHsl`, `toRgb` ### toHsv ```js var color = tinycolor("red"); color.toHsv(); // { h: 0, s: 1, v: 1, a: 1 } ``` ### toHsvString ```js var color = tinycolor("red"); color.toHsvString(); // "hsv(0, 100%, 100%)" color.setAlpha(0.5); color.toHsvString(); // "hsva(0, 100%, 100%, 0.5)" ``` ### toHsl ```js var color = tinycolor("red"); color.toHsl(); // { h: 0, s: 1, l: 0.5, a: 1 } ``` ### toHslString ```js var color = tinycolor("red"); color.toHslString(); // "hsl(0, 100%, 50%)" color.setAlpha(0.5); color.toHslString(); // "hsla(0, 100%, 50%, 0.5)" ``` ### toHex ```js var color = tinycolor("red"); color.toHex(); // "ff0000" ``` ### toHexString ```js var color = tinycolor("red"); color.toHexString(); // "#ff0000" ``` ### toHex8 ```js var color = tinycolor("red"); color.toHex8(); // "ff0000ff" ``` ### toHex8String ```js var color = tinycolor("red"); color.toHex8String(); // "#ff0000ff" ``` ### toRgb ```js var color = tinycolor("red"); color.toRgb(); // { r: 255, g: 0, b: 0, a: 1 } ``` ### toRgbString ```js var color = tinycolor("red"); color.toRgbString(); // "rgb(255, 0, 0)" color.setAlpha(0.5); color.toRgbString(); // "rgba(255, 0, 0, 0.5)" ``` ### toPercentageRgb ```js var color = tinycolor("red"); color.toPercentageRgb() // { r: "100%", g: "0%", b: "0%", a: 1 } ``` ### toPercentageRgbString ```js var color = tinycolor("red"); color.toPercentageRgbString(); // "rgb(100%, 0%, 0%)" color.setAlpha(0.5); color.toPercentageRgbString(); // "rgba(100%, 0%, 0%, 0.5)" ``` ### toName ```js var color = tinycolor("red"); color.toName(); // "red" ``` ### toFilter ``` var color = tinycolor("red"); color.toFilter(); // "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ffff0000)" ``` ### toString Print to a string, depending on the input format. You can also override this by passing one of `"rgb", "prgb", "hex6", "hex3", "hex8", "name", "hsl", "hsv"` into the function. ```js var color1 = tinycolor("red"); color1.toString(); // "red" color1.toString("hsv"); // "hsv(0, 100%, 100%)" var color2 = tinycolor("rgb(255, 0, 0)"); color2.toString(); // "rgb(255, 0, 0)" color2.setAlpha(.5); color2.toString(); // "rgba(255, 0, 0, 0.5)" ``` ### Color Modification These methods manipulate the current color, and return it for chaining. For instance: ```js tinycolor("red").lighten().desaturate().toHexString() // "#f53d3d" ``` ### lighten `lighten: function(amount = 10) -> TinyColor`. Lighten the color a given amount, from 0 to 100. Providing 100 will always return white. ```js tinycolor("#f00").lighten().toString(); // "#ff3333" tinycolor("#f00").lighten(100).toString(); // "#ffffff" ``` ### brighten `brighten: function(amount = 10) -> TinyColor`. Brighten the color a given amount, from 0 to 100. ```js tinycolor("#f00").brighten().toString(); // "#ff1919" ``` ### darken `darken: function(amount = 10) -> TinyColor`. Darken the color a given amount, from 0 to 100. Providing 100 will always return black. ```js tinycolor("#f00").darken().toString(); // "#cc0000" tinycolor("#f00").darken(100).toString(); // "#000000" ``` ### desaturate `desaturate: function(amount = 10) -> TinyColor`. Desaturate the color a given amount, from 0 to 100. Providing 100 will is the same as calling `greyscale`. ```js tinycolor("#f00").desaturate().toString(); // "#f20d0d" tinycolor("#f00").desaturate(100).toString(); // "#808080" ``` ### saturate `saturate: function(amount = 10) -> TinyColor`. Saturate the color a given amount, from 0 to 100. ```js tinycolor("hsl(0, 10%, 50%)").saturate().toString(); // "hsl(0, 20%, 50%)" ``` ### greyscale `greyscale: function() -> TinyColor`. Completely desaturates a color into greyscale. Same as calling `desaturate(100)`. ```js tinycolor("#f00").greyscale().toString(); // "#808080" ``` ### spin `spin: function(amount = 0) -> TinyColor`. Spin the hue a given amount, from -360 to 360. Calling with 0, 360, or -360 will do nothing (since it sets the hue back to what it was before). ```js tinycolor("#f00").spin(180).toString(); // "#00ffff" tinycolor("#f00").spin(-90).toString(); // "#7f00ff" tinycolor("#f00").spin(90).toString(); // "#80ff00" // spin(0) and spin(360) do nothing tinycolor("#f00").spin(0).toString(); // "#ff0000" tinycolor("#f00").spin(360).toString(); // "#ff0000" ``` ### Color Combinations Combination functions return an array of TinyColor objects unless otherwise noted. ### analogous `analogous: function(, results = 6, slices = 30) -> array<TinyColor>`. ```js var colors = tinycolor("#f00").analogous(); colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#ff0066", "#ff0033", "#ff0000", "#ff3300", "#ff6600" ] ``` ### monochromatic `monochromatic: function(, results = 6) -> array<TinyColor>`. ```js var colors = tinycolor("#f00").monochromatic(); colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#2a0000", "#550000", "#800000", "#aa0000", "#d40000" ] ``` ### splitcomplement `splitcomplement: function() -> array<TinyColor>`. ```js var colors = tinycolor("#f00").splitcomplement(); colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#ccff00", "#0066ff" ] ``` ### triad `triad: function() -> array<TinyColor>`. ```js var colors = tinycolor("#f00").triad(); colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#00ff00", "#0000ff" ] ``` ### tetrad `tetrad: function() -> array<TinyColor>`. ```js var colors = tinycolor("#f00").tetrad(); colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#80ff00", "#00ffff", "#7f00ff" ] ``` ### complement `complement: function() -> TinyColor`. ```js tinycolor("#f00").complement().toHexString(); // "#00ffff" ``` ## Color Utilities ```js tinycolor.equals(color1, color2) tinycolor.mix(color1, color2, amount = 50) ``` ### random Returns a random color. ```js var color = tinycolor.random(); color.toRgb(); // "{r: 145, g: 40, b: 198, a: 1}" ``` ### Readability TinyColor assesses readability based on the [Web Content Accessibility Guidelines (Version 2.0)](http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef). #### readability `readability: function(TinyColor, TinyColor) -> Object`. Returns the contrast ratio between two colors. ```js tinycolor.readability("#000", "#000"); // 1 tinycolor.readability("#000", "#111"); // 1.1121078324840545 tinycolor.readability("#000", "#fff"); // 21 ``` Use the values in your own calculations, or use one of the convenience functions below. #### isReadable `isReadable: function(TinyColor, TinyColor, Object) -> Boolean`. Ensure that foreground and background color combinations meet WCAG guidelines. `Object` is optional, defaulting to `{level: "AA",size: "small"}`. `level` can be `"AA"` or "AAA" and `size` can be `"small"` or `"large"`. Here are links to read more about the [AA](http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html) and [AAA](http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast7.html) requirements. ```js tinycolor.isReadable("#000", "#111", {}); // false tinycolor.isReadable("#ff0088", "#5c1a72",{level:"AA",size:"small"}); //false tinycolor.isReadable("#ff0088", "#5c1a72",{level:"AA",size:"large"}), //true ``` #### mostReadable `mostReadable: function(TinyColor, [TinyColor, Tinycolor ...], Object) -> Boolean`. Given a base color and a list of possible foreground or background colors for that base, returns the most readable color. If none of the colors in the list is readable, `mostReadable` will return the better of black or white if `includeFallbackColors:true`. ```js tinycolor.mostReadable("#000", ["#f00", "#0f0", "#00f"]).toHexString(); // "#00ff00" tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" tinycolor.mostReadable("#ff0088", ["#2e0c3a"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString() // "#2e0c3a", tinycolor.mostReadable("#ff0088", ["#2e0c3a"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString() // "#000000", ``` See [index.html](https://github.com/bgrins/TinyColor/blob/master/index.html) in the project for a demo. ## Common operations ### clone `clone: function() -> TinyColor`. Instantiate a new TinyColor object with the same color. Any changes to the new one won't affect the old one. ```js var color1 = tinycolor("#F00"); var color2 = color1.clone(); color2.setAlpha(.5); color1.toString(); // "#ff0000" color2.toString(); // "rgba(255, 0, 0, 0.5)" ``` node_modules/color-name/package.json 0000664 00000001137 15114743311 0013547 0 ustar 00 { "name": "color-name", "version": "1.1.4", "description": "A list of color names and its values", "main": "index.js", "files": [ "index.js" ], "scripts": { "test": "node test.js" }, "repository": { "type": "git", "url": "git@github.com:colorjs/color-name.git" }, "keywords": [ "color-name", "color", "color-keyword", "keyword" ], "author": "DY <dfcreative@gmail.com>", "license": "MIT", "bugs": { "url": "https://github.com/colorjs/color-name/issues" }, "homepage": "https://github.com/colorjs/color-name" } node_modules/color-name/LICENSE 0000664 00000002075 15114743311 0012270 0 ustar 00 The MIT License (MIT) Copyright (c) 2015 Dmitry Ivanov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/color-name/index.js 0000664 00000011011 15114743311 0012716 0 ustar 00 'use strict' module.exports = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; node_modules/color-name/README.md 0000664 00000000600 15114743311 0012532 0 ustar 00 A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> node_modules/queue-microtask/package.json 0000664 00000002231 15114743311 0014625 0 ustar 00 { "name": "queue-microtask", "description": "fast, tiny `queueMicrotask` shim for modern engines", "version": "1.2.3", "author": { "name": "Feross Aboukhadijeh", "email": "feross@feross.org", "url": "https://feross.org" }, "bugs": { "url": "https://github.com/feross/queue-microtask/issues" }, "devDependencies": { "standard": "*", "tape": "^5.2.2" }, "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ], "homepage": "https://github.com/feross/queue-microtask", "keywords": [ "asap", "immediate", "micro task", "microtask", "nextTick", "process.nextTick", "queue micro task", "queue microtask", "queue-microtask", "queueMicrotask", "setImmediate", "task" ], "license": "MIT", "main": "index.js", "repository": { "type": "git", "url": "git://github.com/feross/queue-microtask.git" }, "scripts": { "test": "standard && tape test/*.js" } } node_modules/queue-microtask/LICENSE 0000775 00000002071 15114743311 0013351 0 ustar 00 The MIT License (MIT) Copyright (c) Feross Aboukhadijeh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/queue-microtask/index.d.ts 0000664 00000000117 15114743311 0014241 0 ustar 00 declare const queueMicrotask: (cb: () => void) => void export = queueMicrotask node_modules/queue-microtask/index.js 0000664 00000000622 15114743311 0014006 0 ustar 00 /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */ let promise module.exports = typeof queueMicrotask === 'function' ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global) // reuse resolved promise, and allocate it lazily : cb => (promise || (promise = Promise.resolve())) .then(cb) .catch(err => setTimeout(() => { throw err }, 0)) node_modules/queue-microtask/README.md 0000664 00000012774 15114743311 0013633 0 ustar 00 # queue-microtask [![ci][ci-image]][ci-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [ci-image]: https://img.shields.io/github/workflow/status/feross/queue-microtask/ci/master [ci-url]: https://github.com/feross/queue-microtask/actions [npm-image]: https://img.shields.io/npm/v/queue-microtask.svg [npm-url]: https://npmjs.org/package/queue-microtask [downloads-image]: https://img.shields.io/npm/dm/queue-microtask.svg [downloads-url]: https://npmjs.org/package/queue-microtask [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com ### fast, tiny [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask) shim for modern engines - Use [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask) in all modern JS engines. - No dependencies. Less than 10 lines. No shims or complicated fallbacks. - Optimal performance in all modern environments - Uses `queueMicrotask` in modern environments - Fallback to `Promise.resolve().then(fn)` in Node.js 10 and earlier, and old browsers (same performance as `queueMicrotask`) ## install ``` npm install queue-microtask ``` ## usage ```js const queueMicrotask = require('queue-microtask') queueMicrotask(() => { /* this will run soon */ }) ``` ## What is `queueMicrotask` and why would one use it? The `queueMicrotask` function is a WHATWG standard. It queues a microtask to be executed prior to control returning to the event loop. A microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the event loop. The code `queueMicrotask(fn)` is equivalent to the code `Promise.resolve().then(fn)`. It is also very similar to [`process.nextTick(fn)`](https://nodejs.org/api/process.html#process_process_nexttick_callback_args) in Node. Using microtasks lets code run without interfering with any other, potentially higher priority, code that is pending, but before the JS engine regains control over the execution context. See the [spec](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#microtask-queuing) or [Node documentation](https://nodejs.org/api/globals.html#globals_queuemicrotask_callback) for more information. ## Who is this package for? This package allows you to use `queueMicrotask` safely in all modern JS engines. Use it if you prioritize small JS bundle size over support for old browsers. If you just need to support Node 12 and later, use `queueMicrotask` directly. If you need to support all versions of Node, use this package. ## Why not use `process.nextTick`? In Node, `queueMicrotask` and `process.nextTick` are [essentially equivalent](https://nodejs.org/api/globals.html#globals_queuemicrotask_callback), though there are [subtle differences](https://github.com/YuzuJS/setImmediate#macrotasks-and-microtasks) that don't matter in most situations. You can think of `queueMicrotask` as a standardized version of `process.nextTick` that works in the browser. No need to rely on your browser bundler to shim `process` for the browser environment. ## Why not use `setTimeout(fn, 0)`? This approach is the most compatible, but it has problems. Modern browsers throttle timers severely, so `setTimeout(…, 0)` usually takes at least 4ms to run. Furthermore, the throttling gets even worse if the page is backgrounded. If you have many `setTimeout` calls, then this can severely limit the performance of your program. ## Why not use a microtask library like [`immediate`](https://www.npmjs.com/package/immediate) or [`asap`](https://www.npmjs.com/package/asap)? These packages are great! However, if you prioritize small JS bundle size over optimal performance in old browsers then you may want to consider this package. This package (`queue-microtask`) is four times smaller than `immediate`, twice as small as `asap`, and twice as small as using `process.nextTick` and letting the browser bundler shim it automatically. Note: This package throws an exception in JS environments which lack `Promise` support -- which are usually very old browsers and Node.js versions. Since the `queueMicrotask` API is supported in Node.js, Chrome, Firefox, Safari, Opera, and Edge, **the vast majority of users will get optimal performance**. Any JS environment with `Promise`, which is almost all of them, also get optimal performance. If you need support for JS environments which lack `Promise` support, use one of the alternative packages. ## What is a shim? > In computer programming, a shim is a library that transparently intercepts API calls and changes the arguments passed, handles the operation itself or redirects the operation elsewhere. – [Wikipedia](https://en.wikipedia.org/wiki/Shim_(computing)) This package could also be described as a "ponyfill". > A ponyfill is almost the same as a polyfill, but not quite. Instead of patching functionality for older browsers, a ponyfill provides that functionality as a standalone module you can use. – [PonyFoo](https://ponyfoo.com/articles/polyfills-or-ponyfills) ## API ### `queueMicrotask(fn)` The `queueMicrotask()` method queues a microtask. The `fn` argument is a function to be executed after all pending tasks have completed but before yielding control to the browser's event loop. ## license MIT. Copyright (c) [Feross Aboukhadijeh](https://feross.org). node_modules/chownr/package.json 0000664 00000001211 15114743311 0013004 0 ustar 00 { "author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)", "name": "chownr", "description": "like `chown -R`", "version": "2.0.0", "repository": { "type": "git", "url": "git://github.com/isaacs/chownr.git" }, "main": "chownr.js", "files": [ "chownr.js" ], "devDependencies": { "mkdirp": "0.3", "rimraf": "^2.7.1", "tap": "^14.10.6" }, "tap": { "check-coverage": true }, "scripts": { "test": "tap", "preversion": "npm test", "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags" }, "license": "ISC", "engines": { "node": ">=10" } } node_modules/chownr/LICENSE 0000664 00000001375 15114743311 0011536 0 ustar 00 The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node_modules/chownr/chownr.js 0000664 00000010263 15114743311 0012363 0 ustar 00 'use strict' const fs = require('fs') const path = require('path') /* istanbul ignore next */ const LCHOWN = fs.lchown ? 'lchown' : 'chown' /* istanbul ignore next */ const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' /* istanbul ignore next */ const needEISDIRHandled = fs.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/) const lchownSync = (path, uid, gid) => { try { return fs[LCHOWNSYNC](path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } } /* istanbul ignore next */ const chownSync = (path, uid, gid) => { try { return fs.chownSync(path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } } /* istanbul ignore next */ const handleEISDIR = needEISDIRHandled ? (path, uid, gid, cb) => er => { // Node prior to v10 had a very questionable implementation of // fs.lchown, which would always try to call fs.open on a directory // Fall back to fs.chown in those cases. if (!er || er.code !== 'EISDIR') cb(er) else fs.chown(path, uid, gid, cb) } : (_, __, ___, cb) => cb /* istanbul ignore next */ const handleEISDirSync = needEISDIRHandled ? (path, uid, gid) => { try { return lchownSync(path, uid, gid) } catch (er) { if (er.code !== 'EISDIR') throw er chownSync(path, uid, gid) } } : (path, uid, gid) => lchownSync(path, uid, gid) // fs.readdir could only accept an options object as of node v6 const nodeVersion = process.version let readdir = (path, options, cb) => fs.readdir(path, options, cb) let readdirSync = (path, options) => fs.readdirSync(path, options) /* istanbul ignore next */ if (/^v4\./.test(nodeVersion)) readdir = (path, options, cb) => fs.readdir(path, cb) const chown = (cpath, uid, gid, cb) => { fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { // Skip ENOENT error cb(er && er.code !== 'ENOENT' ? er : null) })) } const chownrKid = (p, child, uid, gid, cb) => { if (typeof child === 'string') return fs.lstat(path.resolve(p, child), (er, stats) => { // Skip ENOENT error if (er) return cb(er.code !== 'ENOENT' ? er : null) stats.name = child chownrKid(p, stats, uid, gid, cb) }) if (child.isDirectory()) { chownr(path.resolve(p, child.name), uid, gid, er => { if (er) return cb(er) const cpath = path.resolve(p, child.name) chown(cpath, uid, gid, cb) }) } else { const cpath = path.resolve(p, child.name) chown(cpath, uid, gid, cb) } } const chownr = (p, uid, gid, cb) => { readdir(p, { withFileTypes: true }, (er, children) => { // any error other than ENOTDIR or ENOTSUP means it's not readable, // or doesn't exist. give up. if (er) { if (er.code === 'ENOENT') return cb() else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') return cb(er) } if (er || !children.length) return chown(p, uid, gid, cb) let len = children.length let errState = null const then = er => { if (errState) return if (er) return cb(errState = er) if (-- len === 0) return chown(p, uid, gid, cb) } children.forEach(child => chownrKid(p, child, uid, gid, then)) }) } const chownrKidSync = (p, child, uid, gid) => { if (typeof child === 'string') { try { const stats = fs.lstatSync(path.resolve(p, child)) stats.name = child child = stats } catch (er) { if (er.code === 'ENOENT') return else throw er } } if (child.isDirectory()) chownrSync(path.resolve(p, child.name), uid, gid) handleEISDirSync(path.resolve(p, child.name), uid, gid) } const chownrSync = (p, uid, gid) => { let children try { children = readdirSync(p, { withFileTypes: true }) } catch (er) { if (er.code === 'ENOENT') return else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') return handleEISDirSync(p, uid, gid) else throw er } if (children && children.length) children.forEach(child => chownrKidSync(p, child, uid, gid)) return handleEISDirSync(p, uid, gid) } module.exports = chownr chownr.sync = chownrSync node_modules/chownr/README.md 0000664 00000000073 15114743311 0012002 0 ustar 00 Like `chown -R`. Takes the same arguments as `fs.chown()` node_modules/fastq/package.json 0000664 00000002536 15114743311 0012635 0 ustar 00 { "name": "fastq", "version": "1.19.1", "description": "Fast, in memory work queue", "main": "queue.js", "scripts": { "lint": "standard --verbose | snazzy", "unit": "nyc --lines 100 --branches 100 --functions 100 --check-coverage --reporter=text tape test/test.js test/promise.js", "coverage": "nyc --reporter=html --reporter=cobertura --reporter=text tape test/test.js test/promise.js", "test:report": "npm run lint && npm run unit:report", "test": "npm run lint && npm run unit", "typescript": "tsc --project ./test/tsconfig.json", "legacy": "tape test/test.js" }, "pre-commit": [ "test", "typescript" ], "repository": { "type": "git", "url": "git+https://github.com/mcollina/fastq.git" }, "keywords": [ "fast", "queue", "async", "worker" ], "author": "Matteo Collina <hello@matteocollina.com>", "license": "ISC", "bugs": { "url": "https://github.com/mcollina/fastq/issues" }, "homepage": "https://github.com/mcollina/fastq#readme", "devDependencies": { "async": "^3.1.0", "neo-async": "^2.6.1", "nyc": "^17.0.0", "pre-commit": "^1.2.2", "snazzy": "^9.0.0", "standard": "^16.0.0", "tape": "^5.0.0", "typescript": "^5.0.4" }, "dependencies": { "reusify": "^1.0.4" }, "standard": { "ignore": [ "example.mjs" ] } } node_modules/fastq/LICENSE 0000664 00000001375 15114743311 0011354 0 ustar 00 Copyright (c) 2015-2020, Matteo Collina <matteo.collina@gmail.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node_modules/fastq/index.d.ts 0000664 00000006661 15114743311 0012253 0 ustar 00 declare function fastq<C, T = any, R = any>(context: C, worker: fastq.worker<C, T, R>, concurrency: number): fastq.queue<T, R> declare function fastq<C, T = any, R = any>(worker: fastq.worker<C, T, R>, concurrency: number): fastq.queue<T, R> declare namespace fastq { type worker<C, T = any, R = any> = (this: C, task: T, cb: fastq.done<R>) => void type asyncWorker<C, T = any, R = any> = (this: C, task: T) => Promise<R> type done<R = any> = (err: Error | null, result?: R) => void type errorHandler<T = any> = (err: Error, task: T) => void interface queue<T = any, R = any> { /** Add a task at the end of the queue. `done(err, result)` will be called when the task was processed. */ push(task: T, done?: done<R>): void /** Add a task at the beginning of the queue. `done(err, result)` will be called when the task was processed. */ unshift(task: T, done?: done<R>): void /** Pause the processing of tasks. Currently worked tasks are not stopped. */ pause(): any /** Resume the processing of tasks. */ resume(): any running(): number /** Returns `false` if there are tasks being processed or waiting to be processed. `true` otherwise. */ idle(): boolean /** Returns the number of tasks waiting to be processed (in the queue). */ length(): number /** Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks */ getQueue(): T[] /** Removes all tasks waiting to be processed, and reset `drain` to an empty function. */ kill(): any /** Same than `kill` but the `drain` function will be called before reset to empty. */ killAndDrain(): any /** Set a global error handler. `handler(err, task)` will be called each time a task is completed, `err` will be not null if the task has thrown an error. */ error(handler: errorHandler<T>): void /** Property that returns the number of concurrent tasks that could be executed in parallel. It can be altered at runtime. */ concurrency: number /** Property (Read-Only) that returns `true` when the queue is in a paused state. */ readonly paused: boolean /** Function that will be called when the last item from the queue has been processed by a worker. It can be altered at runtime. */ drain(): any /** Function that will be called when the last item from the queue has been assigned to a worker. It can be altered at runtime. */ empty: () => void /** Function that will be called when the queue hits the concurrency limit. It can be altered at runtime. */ saturated: () => void } interface queueAsPromised<T = any, R = any> extends queue<T, R> { /** Add a task at the end of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). */ push(task: T): Promise<R> /** Add a task at the beginning of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). */ unshift(task: T): Promise<R> /** Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker. */ drained(): Promise<void> } function promise<C, T = any, R = any>(context: C, worker: fastq.asyncWorker<C, T, R>, concurrency: number): fastq.queueAsPromised<T, R> function promise<C, T = any, R = any>(worker: fastq.asyncWorker<C, T, R>, concurrency: number): fastq.queueAsPromised<T, R> } export = fastq node_modules/fastq/bench.js 0000664 00000002253 15114743311 0011760 0 ustar 00 'use strict' const max = 1000000 const fastqueue = require('./')(worker, 1) const { promisify } = require('util') const immediate = promisify(setImmediate) const qPromise = require('./').promise(immediate, 1) const async = require('async') const neo = require('neo-async') const asyncqueue = async.queue(worker, 1) const neoqueue = neo.queue(worker, 1) function bench (func, done) { const key = max + '*' + func.name let count = -1 console.time(key) end() function end () { if (++count < max) { func(end) } else { console.timeEnd(key) if (done) { done() } } } } function benchFastQ (done) { fastqueue.push(42, done) } function benchAsyncQueue (done) { asyncqueue.push(42, done) } function benchNeoQueue (done) { neoqueue.push(42, done) } function worker (arg, cb) { setImmediate(cb) } function benchSetImmediate (cb) { worker(42, cb) } function benchFastQPromise (done) { qPromise.push(42).then(function () { done() }, done) } function runBench (done) { async.eachSeries([ benchSetImmediate, benchFastQ, benchNeoQueue, benchAsyncQueue, benchFastQPromise ], bench, done) } runBench(runBench) node_modules/fastq/SECURITY.md 0000664 00000000707 15114743311 0012136 0 ustar 00 # Security Policy ## Supported Versions Use this section to tell people about which versions of your project are currently being supported with security updates. | Version | Supported | | ------- | ------------------ | | 1.x | :white_check_mark: | | < 1.0 | :x: | ## Reporting a Vulnerability Please report all vulnerabilities at [https://github.com/mcollina/fastq/security](https://github.com/mcollina/fastq/security). node_modules/fastq/queue.js 0000664 00000014144 15114743311 0012027 0 ustar 00 'use strict' /* eslint-disable no-var */ var reusify = require('reusify') function fastqueue (context, worker, _concurrency) { if (typeof context === 'function') { _concurrency = worker worker = context context = null } if (!(_concurrency >= 1)) { throw new Error('fastqueue concurrency must be equal to or greater than 1') } var cache = reusify(Task) var queueHead = null var queueTail = null var _running = 0 var errorHandler = null var self = { push: push, drain: noop, saturated: noop, pause: pause, paused: false, get concurrency () { return _concurrency }, set concurrency (value) { if (!(value >= 1)) { throw new Error('fastqueue concurrency must be equal to or greater than 1') } _concurrency = value if (self.paused) return for (; queueHead && _running < _concurrency;) { _running++ release() } }, running: running, resume: resume, idle: idle, length: length, getQueue: getQueue, unshift: unshift, empty: noop, kill: kill, killAndDrain: killAndDrain, error: error } return self function running () { return _running } function pause () { self.paused = true } function length () { var current = queueHead var counter = 0 while (current) { current = current.next counter++ } return counter } function getQueue () { var current = queueHead var tasks = [] while (current) { tasks.push(current.value) current = current.next } return tasks } function resume () { if (!self.paused) return self.paused = false if (queueHead === null) { _running++ release() return } for (; queueHead && _running < _concurrency;) { _running++ release() } } function idle () { return _running === 0 && self.length() === 0 } function push (value, done) { var current = cache.get() current.context = context current.release = release current.value = value current.callback = done || noop current.errorHandler = errorHandler if (_running >= _concurrency || self.paused) { if (queueTail) { queueTail.next = current queueTail = current } else { queueHead = current queueTail = current self.saturated() } } else { _running++ worker.call(context, current.value, current.worked) } } function unshift (value, done) { var current = cache.get() current.context = context current.release = release current.value = value current.callback = done || noop current.errorHandler = errorHandler if (_running >= _concurrency || self.paused) { if (queueHead) { current.next = queueHead queueHead = current } else { queueHead = current queueTail = current self.saturated() } } else { _running++ worker.call(context, current.value, current.worked) } } function release (holder) { if (holder) { cache.release(holder) } var next = queueHead if (next && _running <= _concurrency) { if (!self.paused) { if (queueTail === queueHead) { queueTail = null } queueHead = next.next next.next = null worker.call(context, next.value, next.worked) if (queueTail === null) { self.empty() } } else { _running-- } } else if (--_running === 0) { self.drain() } } function kill () { queueHead = null queueTail = null self.drain = noop } function killAndDrain () { queueHead = null queueTail = null self.drain() self.drain = noop } function error (handler) { errorHandler = handler } } function noop () {} function Task () { this.value = null this.callback = noop this.next = null this.release = noop this.context = null this.errorHandler = null var self = this this.worked = function worked (err, result) { var callback = self.callback var errorHandler = self.errorHandler var val = self.value self.value = null self.callback = noop if (self.errorHandler) { errorHandler(err, val) } callback.call(self.context, err, result) self.release(self) } } function queueAsPromised (context, worker, _concurrency) { if (typeof context === 'function') { _concurrency = worker worker = context context = null } function asyncWrapper (arg, cb) { worker.call(this, arg) .then(function (res) { cb(null, res) }, cb) } var queue = fastqueue(context, asyncWrapper, _concurrency) var pushCb = queue.push var unshiftCb = queue.unshift queue.push = push queue.unshift = unshift queue.drained = drained return queue function push (value) { var p = new Promise(function (resolve, reject) { pushCb(value, function (err, result) { if (err) { reject(err) return } resolve(result) }) }) // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop) return p } function unshift (value) { var p = new Promise(function (resolve, reject) { unshiftCb(value, function (err, result) { if (err) { reject(err) return } resolve(result) }) }) // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop) return p } function drained () { var p = new Promise(function (resolve) { process.nextTick(function () { if (queue.idle()) { resolve() } else { var previousDrain = queue.drain queue.drain = function () { if (typeof previousDrain === 'function') previousDrain() resolve() queue.drain = previousDrain } } }) }) return p } } module.exports = fastqueue module.exports.promise = queueAsPromised node_modules/fastq/test/example.ts 0000664 00000002666 15114743311 0013335 0 ustar 00 import * as fastq from '../' import { promise as queueAsPromised } from '../' // Basic example const queue = fastq(worker, 1) queue.push('world', (err, result) => { if (err) throw err console.log('the result is', result) }) queue.push('push without cb') queue.concurrency queue.drain() queue.empty = () => undefined console.log('the queue tasks are', queue.getQueue()) queue.idle() queue.kill() queue.killAndDrain() queue.length queue.pause() queue.resume() queue.running() queue.saturated = () => undefined queue.unshift('world', (err, result) => { if (err) throw err console.log('the result is', result) }) queue.unshift('unshift without cb') function worker(task: any, cb: fastq.done) { cb(null, 'hello ' + task) } // Generics example interface GenericsContext { base: number; } const genericsQueue = fastq<GenericsContext, number, string>({ base: 6 }, genericsWorker, 1) genericsQueue.push(7, (err, done) => { if (err) throw err console.log('the result is', done) }) genericsQueue.unshift(7, (err, done) => { if (err) throw err console.log('the result is', done) }) function genericsWorker(this: GenericsContext, task: number, cb: fastq.done<string>) { cb(null, 'the meaning of life is ' + (this.base * task)) } const queue2 = queueAsPromised(asyncWorker, 1) async function asyncWorker(task: any) { return 'hello ' + task } async function run () { await queue.push(42) await queue.unshift(42) } run() node_modules/fastq/test/promise.js 0000664 00000014357 15114743311 0013346 0 ustar 00 'use strict' const test = require('tape') const buildQueue = require('../').promise const { promisify } = require('util') const sleep = promisify(setTimeout) const immediate = promisify(setImmediate) test('concurrency', function (t) { t.plan(2) t.throws(buildQueue.bind(null, worker, 0)) t.doesNotThrow(buildQueue.bind(null, worker, 1)) async function worker (arg) { return true } }) test('worker execution', async function (t) { const queue = buildQueue(worker, 1) const result = await queue.push(42) t.equal(result, true, 'result matches') async function worker (arg) { t.equal(arg, 42) return true } }) test('limit', async function (t) { const queue = buildQueue(worker, 1) const [res1, res2] = await Promise.all([queue.push(10), queue.push(0)]) t.equal(res1, 10, 'the result matches') t.equal(res2, 0, 'the result matches') async function worker (arg) { await sleep(arg) return arg } }) test('multiple executions', async function (t) { const queue = buildQueue(worker, 1) const toExec = [1, 2, 3, 4, 5] const expected = ['a', 'b', 'c', 'd', 'e'] let count = 0 await Promise.all(toExec.map(async function (task, i) { const result = await queue.push(task) t.equal(result, expected[i], 'the result matches') })) async function worker (arg) { t.equal(arg, toExec[count], 'arg matches') return expected[count++] } }) test('drained', async function (t) { const queue = buildQueue(worker, 2) const toExec = new Array(10).fill(10) let count = 0 async function worker (arg) { await sleep(arg) count++ } toExec.forEach(function (i) { queue.push(i) }) await queue.drained() t.equal(count, toExec.length) toExec.forEach(function (i) { queue.push(i) }) await queue.drained() t.equal(count, toExec.length * 2) }) test('drained with exception should not throw', async function (t) { const queue = buildQueue(worker, 2) const toExec = new Array(10).fill(10) async function worker () { throw new Error('foo') } toExec.forEach(function (i) { queue.push(i) }) await queue.drained() }) test('drained with drain function', async function (t) { let drainCalled = false const queue = buildQueue(worker, 2) queue.drain = function () { drainCalled = true } const toExec = new Array(10).fill(10) let count = 0 async function worker (arg) { await sleep(arg) count++ } toExec.forEach(function () { queue.push() }) await queue.drained() t.equal(count, toExec.length) t.equal(drainCalled, true) }) test('drained while idle should resolve', async function (t) { const queue = buildQueue(worker, 2) async function worker (arg) { await sleep(arg) } await queue.drained() }) test('drained while idle should not call the drain function', async function (t) { let drainCalled = false const queue = buildQueue(worker, 2) queue.drain = function () { drainCalled = true } async function worker (arg) { await sleep(arg) } await queue.drained() t.equal(drainCalled, false) }) test('set this', async function (t) { t.plan(1) const that = {} const queue = buildQueue(that, worker, 1) await queue.push(42) async function worker (arg) { t.equal(this, that, 'this matches') } }) test('unshift', async function (t) { const queue = buildQueue(worker, 1) const expected = [1, 2, 3, 4] await Promise.all([ queue.push(1), queue.push(4), queue.unshift(3), queue.unshift(2) ]) t.is(expected.length, 0) async function worker (arg) { t.equal(expected.shift(), arg, 'tasks come in order') } }) test('push with worker throwing error', async function (t) { t.plan(5) const q = buildQueue(async function (task, cb) { throw new Error('test error') }, 1) q.error(function (err, task) { t.ok(err instanceof Error, 'global error handler should catch the error') t.match(err.message, /test error/, 'error message should be "test error"') t.equal(task, 42, 'The task executed should be passed') }) try { await q.push(42) } catch (err) { t.ok(err instanceof Error, 'push callback should catch the error') t.match(err.message, /test error/, 'error message should be "test error"') } }) test('unshift with worker throwing error', async function (t) { t.plan(2) const q = buildQueue(async function (task, cb) { throw new Error('test error') }, 1) try { await q.unshift(42) } catch (err) { t.ok(err instanceof Error, 'push callback should catch the error') t.match(err.message, /test error/, 'error message should be "test error"') } }) test('no unhandledRejection (push)', async function (t) { function handleRejection () { t.fail('unhandledRejection') } process.once('unhandledRejection', handleRejection) const q = buildQueue(async function (task, cb) { throw new Error('test error') }, 1) q.push(42) await immediate() process.removeListener('unhandledRejection', handleRejection) }) test('no unhandledRejection (unshift)', async function (t) { function handleRejection () { t.fail('unhandledRejection') } process.once('unhandledRejection', handleRejection) const q = buildQueue(async function (task, cb) { throw new Error('test error') }, 1) q.unshift(42) await immediate() process.removeListener('unhandledRejection', handleRejection) }) test('drained should resolve after async tasks complete', async function (t) { const logs = [] async function processTask () { await new Promise(resolve => setTimeout(resolve, 0)) logs.push('processed') } const queue = buildQueue(processTask, 1) queue.drain = () => logs.push('called drain') queue.drained().then(() => logs.push('drained promise resolved')) await Promise.all([ queue.push(), queue.push(), queue.push() ]) t.deepEqual(logs, [ 'processed', 'processed', 'processed', 'called drain', 'drained promise resolved' ], 'events happened in correct order') }) test('drained should handle undefined drain function', async function (t) { const queue = buildQueue(worker, 1) async function worker (arg) { await sleep(10) return arg } queue.drain = undefined queue.push(1) await queue.drained() t.pass('drained resolved successfully with undefined drain') }) node_modules/fastq/test/test.js 0000664 00000033237 15114743311 0012645 0 ustar 00 'use strict' /* eslint-disable no-var */ var test = require('tape') var buildQueue = require('../') test('concurrency', function (t) { t.plan(6) t.throws(buildQueue.bind(null, worker, 0)) t.throws(buildQueue.bind(null, worker, NaN)) t.doesNotThrow(buildQueue.bind(null, worker, 1)) var queue = buildQueue(worker, 1) t.throws(function () { queue.concurrency = 0 }) t.throws(function () { queue.concurrency = NaN }) t.doesNotThrow(function () { queue.concurrency = 2 }) function worker (arg, cb) { cb(null, true) } }) test('worker execution', function (t) { t.plan(3) var queue = buildQueue(worker, 1) queue.push(42, function (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') }) function worker (arg, cb) { t.equal(arg, 42) cb(null, true) } }) test('limit', function (t) { t.plan(4) var expected = [10, 0] var queue = buildQueue(worker, 1) queue.push(10, result) queue.push(0, result) function result (err, arg) { t.error(err, 'no error') t.equal(arg, expected.shift(), 'the result matches') } function worker (arg, cb) { setTimeout(cb, arg, null, arg) } }) test('multiple executions', function (t) { t.plan(15) var queue = buildQueue(worker, 1) var toExec = [1, 2, 3, 4, 5] var count = 0 toExec.forEach(function (task) { queue.push(task, done) }) function done (err, result) { t.error(err, 'no error') t.equal(result, toExec[count - 1], 'the result matches') } function worker (arg, cb) { t.equal(arg, toExec[count], 'arg matches') count++ setImmediate(cb, null, arg) } }) test('multiple executions, one after another', function (t) { t.plan(15) var queue = buildQueue(worker, 1) var toExec = [1, 2, 3, 4, 5] var count = 0 queue.push(toExec[0], done) function done (err, result) { t.error(err, 'no error') t.equal(result, toExec[count - 1], 'the result matches') if (count < toExec.length) { queue.push(toExec[count], done) } } function worker (arg, cb) { t.equal(arg, toExec[count], 'arg matches') count++ setImmediate(cb, null, arg) } }) test('set this', function (t) { t.plan(3) var that = {} var queue = buildQueue(that, worker, 1) queue.push(42, function (err, result) { t.error(err, 'no error') t.equal(this, that, 'this matches') }) function worker (arg, cb) { t.equal(this, that, 'this matches') cb(null, true) } }) test('drain', function (t) { t.plan(4) var queue = buildQueue(worker, 1) var worked = false queue.push(42, function (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') }) queue.drain = function () { t.equal(true, worked, 'drained') } function worker (arg, cb) { t.equal(arg, 42) worked = true setImmediate(cb, null, true) } }) test('pause && resume', function (t) { t.plan(13) var queue = buildQueue(worker, 1) var worked = false var expected = [42, 24] t.notOk(queue.paused, 'it should not be paused') queue.pause() queue.push(42, function (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') }) queue.push(24, function (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') }) t.notOk(worked, 'it should be paused') t.ok(queue.paused, 'it should be paused') queue.resume() queue.pause() queue.resume() queue.resume() // second resume is a no-op function worker (arg, cb) { t.notOk(queue.paused, 'it should not be paused') t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') t.equal(arg, expected.shift()) worked = true process.nextTick(function () { cb(null, true) }) } }) test('pause in flight && resume', function (t) { t.plan(16) var queue = buildQueue(worker, 1) var expected = [42, 24, 12] t.notOk(queue.paused, 'it should not be paused') queue.push(42, function (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') t.ok(queue.paused, 'it should be paused') process.nextTick(function () { queue.resume() queue.pause() queue.resume() }) }) queue.push(24, function (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') t.notOk(queue.paused, 'it should not be paused') }) queue.push(12, function (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') t.notOk(queue.paused, 'it should not be paused') }) queue.pause() function worker (arg, cb) { t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') t.equal(arg, expected.shift()) process.nextTick(function () { cb(null, true) }) } }) test('altering concurrency', function (t) { t.plan(24) var queue = buildQueue(worker, 1) queue.push(24, workDone) queue.push(24, workDone) queue.push(24, workDone) queue.pause() queue.concurrency = 3 // concurrency changes are ignored while paused queue.concurrency = 2 queue.resume() t.equal(queue.running(), 2, '2 jobs running') queue.concurrency = 3 t.equal(queue.running(), 3, '3 jobs running') queue.concurrency = 1 t.equal(queue.running(), 3, '3 jobs running') // running jobs can't be killed queue.push(24, workDone) queue.push(24, workDone) queue.push(24, workDone) queue.push(24, workDone) function workDone (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') } function worker (arg, cb) { t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') setImmediate(function () { cb(null, true) }) } }) test('idle()', function (t) { t.plan(12) var queue = buildQueue(worker, 1) t.ok(queue.idle(), 'queue is idle') queue.push(42, function (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') t.notOk(queue.idle(), 'queue is not idle') }) queue.push(42, function (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') // it will go idle after executing this function setImmediate(function () { t.ok(queue.idle(), 'queue is now idle') }) }) t.notOk(queue.idle(), 'queue is not idle') function worker (arg, cb) { t.notOk(queue.idle(), 'queue is not idle') t.equal(arg, 42) setImmediate(cb, null, true) } }) test('saturated', function (t) { t.plan(9) var queue = buildQueue(worker, 1) var preworked = 0 var worked = 0 queue.saturated = function () { t.pass('saturated') t.equal(preworked, 1, 'started 1 task') t.equal(worked, 0, 'worked zero task') } queue.push(42, done) queue.push(42, done) function done (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') } function worker (arg, cb) { t.equal(arg, 42) preworked++ setImmediate(function () { worked++ cb(null, true) }) } }) test('length', function (t) { t.plan(7) var queue = buildQueue(worker, 1) t.equal(queue.length(), 0, 'nothing waiting') queue.push(42, done) t.equal(queue.length(), 0, 'nothing waiting') queue.push(42, done) t.equal(queue.length(), 1, 'one task waiting') queue.push(42, done) t.equal(queue.length(), 2, 'two tasks waiting') function done (err, result) { t.error(err, 'no error') } function worker (arg, cb) { setImmediate(function () { cb(null, true) }) } }) test('getQueue', function (t) { t.plan(10) var queue = buildQueue(worker, 1) t.equal(queue.getQueue().length, 0, 'nothing waiting') queue.push(42, done) t.equal(queue.getQueue().length, 0, 'nothing waiting') queue.push(42, done) t.equal(queue.getQueue().length, 1, 'one task waiting') t.equal(queue.getQueue()[0], 42, 'should be equal') queue.push(43, done) t.equal(queue.getQueue().length, 2, 'two tasks waiting') t.equal(queue.getQueue()[0], 42, 'should be equal') t.equal(queue.getQueue()[1], 43, 'should be equal') function done (err, result) { t.error(err, 'no error') } function worker (arg, cb) { setImmediate(function () { cb(null, true) }) } }) test('unshift', function (t) { t.plan(8) var queue = buildQueue(worker, 1) var expected = [1, 2, 3, 4] queue.push(1, done) queue.push(4, done) queue.unshift(3, done) queue.unshift(2, done) function done (err, result) { t.error(err, 'no error') } function worker (arg, cb) { t.equal(expected.shift(), arg, 'tasks come in order') setImmediate(function () { cb(null, true) }) } }) test('unshift && empty', function (t) { t.plan(2) var queue = buildQueue(worker, 1) var completed = false queue.pause() queue.empty = function () { t.notOk(completed, 'the task has not completed yet') } queue.unshift(1, done) queue.resume() function done (err, result) { completed = true t.error(err, 'no error') } function worker (arg, cb) { setImmediate(function () { cb(null, true) }) } }) test('push && empty', function (t) { t.plan(2) var queue = buildQueue(worker, 1) var completed = false queue.pause() queue.empty = function () { t.notOk(completed, 'the task has not completed yet') } queue.push(1, done) queue.resume() function done (err, result) { completed = true t.error(err, 'no error') } function worker (arg, cb) { setImmediate(function () { cb(null, true) }) } }) test('kill', function (t) { t.plan(5) var queue = buildQueue(worker, 1) var expected = [1] var predrain = queue.drain queue.drain = function drain () { t.fail('drain should never be called') } queue.push(1, done) queue.push(4, done) queue.unshift(3, done) queue.unshift(2, done) queue.kill() function done (err, result) { t.error(err, 'no error') setImmediate(function () { t.equal(queue.length(), 0, 'no queued tasks') t.equal(queue.running(), 0, 'no running tasks') t.equal(queue.drain, predrain, 'drain is back to default') }) } function worker (arg, cb) { t.equal(expected.shift(), arg, 'tasks come in order') setImmediate(function () { cb(null, true) }) } }) test('killAndDrain', function (t) { t.plan(6) var queue = buildQueue(worker, 1) var expected = [1] var predrain = queue.drain queue.drain = function drain () { t.pass('drain has been called') } queue.push(1, done) queue.push(4, done) queue.unshift(3, done) queue.unshift(2, done) queue.killAndDrain() function done (err, result) { t.error(err, 'no error') setImmediate(function () { t.equal(queue.length(), 0, 'no queued tasks') t.equal(queue.running(), 0, 'no running tasks') t.equal(queue.drain, predrain, 'drain is back to default') }) } function worker (arg, cb) { t.equal(expected.shift(), arg, 'tasks come in order') setImmediate(function () { cb(null, true) }) } }) test('pause && idle', function (t) { t.plan(11) var queue = buildQueue(worker, 1) var worked = false t.notOk(queue.paused, 'it should not be paused') t.ok(queue.idle(), 'should be idle') queue.pause() queue.push(42, function (err, result) { t.error(err, 'no error') t.equal(result, true, 'result matches') }) t.notOk(worked, 'it should be paused') t.ok(queue.paused, 'it should be paused') t.notOk(queue.idle(), 'should not be idle') queue.resume() t.notOk(queue.paused, 'it should not be paused') t.notOk(queue.idle(), 'it should not be idle') function worker (arg, cb) { t.equal(arg, 42) worked = true process.nextTick(cb.bind(null, null, true)) process.nextTick(function () { t.ok(queue.idle(), 'is should be idle') }) } }) test('push without cb', function (t) { t.plan(1) var queue = buildQueue(worker, 1) queue.push(42) function worker (arg, cb) { t.equal(arg, 42) cb() } }) test('unshift without cb', function (t) { t.plan(1) var queue = buildQueue(worker, 1) queue.unshift(42) function worker (arg, cb) { t.equal(arg, 42) cb() } }) test('push with worker throwing error', function (t) { t.plan(5) var q = buildQueue(function (task, cb) { cb(new Error('test error'), null) }, 1) q.error(function (err, task) { t.ok(err instanceof Error, 'global error handler should catch the error') t.match(err.message, /test error/, 'error message should be "test error"') t.equal(task, 42, 'The task executed should be passed') }) q.push(42, function (err) { t.ok(err instanceof Error, 'push callback should catch the error') t.match(err.message, /test error/, 'error message should be "test error"') }) }) test('unshift with worker throwing error', function (t) { t.plan(5) var q = buildQueue(function (task, cb) { cb(new Error('test error'), null) }, 1) q.error(function (err, task) { t.ok(err instanceof Error, 'global error handler should catch the error') t.match(err.message, /test error/, 'error message should be "test error"') t.equal(task, 42, 'The task executed should be passed') }) q.unshift(42, function (err) { t.ok(err instanceof Error, 'unshift callback should catch the error') t.match(err.message, /test error/, 'error message should be "test error"') }) }) test('pause/resume should trigger drain event', function (t) { t.plan(1) var queue = buildQueue(worker, 1) queue.pause() queue.drain = function () { t.pass('drain should be called') } function worker (arg, cb) { cb(null, true) } queue.resume() }) test('paused flag', function (t) { t.plan(2) var queue = buildQueue(function (arg, cb) { cb(null) }, 1) t.equal(queue.paused, false) queue.pause() t.equal(queue.paused, true) }) node_modules/fastq/test/tsconfig.json 0000664 00000000232 15114743311 0014024 0 ustar 00 { "compilerOptions": { "target": "es6", "module": "commonjs", "noEmit": true, "strict": true }, "files": [ "./example.ts" ] } node_modules/fastq/example.mjs 0000664 00000000335 15114743311 0012510 0 ustar 00 import { promise as queueAsPromised } from './queue.js' /* eslint-disable */ const queue = queueAsPromised(worker, 1) console.log('the result is', await queue.push(42)) async function worker (arg) { return 42 * 2 } node_modules/fastq/example.js 0000664 00000000356 15114743311 0012336 0 ustar 00 'use strict' /* eslint-disable no-var */ var queue = require('./')(worker, 1) queue.push(42, function (err, result) { if (err) { throw err } console.log('the result is', result) }) function worker (arg, cb) { cb(null, 42 * 2) } node_modules/fastq/.github/dependabot.yml 0000664 00000000300 15114743311 0014522 0 ustar 00 version: 2 updates: - package-ecosystem: npm directory: "/" schedule: interval: daily open-pull-requests-limit: 10 ignore: - dependency-name: standard versions: - 16.0.3 node_modules/fastq/.github/workflows/ci.yml 0000664 00000002600 15114743311 0015052 0 ustar 00 name: ci on: [push, pull_request] jobs: legacy: runs-on: ubuntu-latest strategy: matrix: node-version: ['0.10', '0.12', 4.x, 6.x, 8.x, 10.x, 12.x, 13.x, 14.x, 15.x, 16.x] steps: - uses: actions/checkout@v3 with: persist-credentials: false - name: Use Node.js uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} - name: Install run: | npm install --production && npm install tape - name: Run tests run: | npm run legacy test: runs-on: ubuntu-latest strategy: matrix: node-version: [18.x, 20.x, 22.x] steps: - uses: actions/checkout@v3 with: persist-credentials: false - name: Use Node.js uses: actions/setup-node@v3 with: node-version: ${{ matrix.node-version }} - name: Install run: | npm install - name: Run tests run: | npm run test types: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: persist-credentials: false - name: Use Node.js uses: actions/setup-node@v3 with: node-version: 16 - name: Install run: | npm install - name: Run types tests run: | npm run typescript node_modules/fastq/README.md 0000664 00000020227 15114743311 0011623 0 ustar 00 # fastq ![ci][ci-url] [![npm version][npm-badge]][npm-url] Fast, in memory work queue. Benchmarks (1 million tasks): * setImmediate: 812ms * fastq: 854ms * async.queue: 1298ms * neoAsync.queue: 1249ms Obtained on node 12.16.1, on a dedicated server. If you need zero-overhead series function call, check out [fastseries](http://npm.im/fastseries). For zero-overhead parallel function call, check out [fastparallel](http://npm.im/fastparallel). [](https://github.com/feross/standard) * <a href="#install">Installation</a> * <a href="#usage">Usage</a> * <a href="#api">API</a> * <a href="#license">Licence & copyright</a> ## Install `npm i fastq --save` ## Usage (callback API) ```js 'use strict' const queue = require('fastq')(worker, 1) queue.push(42, function (err, result) { if (err) { throw err } console.log('the result is', result) }) function worker (arg, cb) { cb(null, arg * 2) } ``` ## Usage (promise API) ```js const queue = require('fastq').promise(worker, 1) async function worker (arg) { return arg * 2 } async function run () { const result = await queue.push(42) console.log('the result is', result) } run() ``` ### Setting "this" ```js 'use strict' const that = { hello: 'world' } const queue = require('fastq')(that, worker, 1) queue.push(42, function (err, result) { if (err) { throw err } console.log(this) console.log('the result is', result) }) function worker (arg, cb) { console.log(this) cb(null, arg * 2) } ``` ### Using with TypeScript (callback API) ```ts 'use strict' import * as fastq from "fastq"; import type { queue, done } from "fastq"; type Task = { id: number } const q: queue<Task> = fastq(worker, 1) q.push({ id: 42}) function worker (arg: Task, cb: done) { console.log(arg.id) cb(null) } ``` ### Using with TypeScript (promise API) ```ts 'use strict' import * as fastq from "fastq"; import type { queueAsPromised } from "fastq"; type Task = { id: number } const q: queueAsPromised<Task> = fastq.promise(asyncWorker, 1) q.push({ id: 42}).catch((err) => console.error(err)) async function asyncWorker (arg: Task): Promise<void> { // No need for a try-catch block, fastq handles errors automatically console.log(arg.id) } ``` ## API * <a href="#fastqueue"><code>fastqueue()</code></a> * <a href="#push"><code>queue#<b>push()</b></code></a> * <a href="#unshift"><code>queue#<b>unshift()</b></code></a> * <a href="#pause"><code>queue#<b>pause()</b></code></a> * <a href="#resume"><code>queue#<b>resume()</b></code></a> * <a href="#idle"><code>queue#<b>idle()</b></code></a> * <a href="#length"><code>queue#<b>length()</b></code></a> * <a href="#getQueue"><code>queue#<b>getQueue()</b></code></a> * <a href="#kill"><code>queue#<b>kill()</b></code></a> * <a href="#killAndDrain"><code>queue#<b>killAndDrain()</b></code></a> * <a href="#error"><code>queue#<b>error()</b></code></a> * <a href="#concurrency"><code>queue#<b>concurrency</b></code></a> * <a href="#drain"><code>queue#<b>drain</b></code></a> * <a href="#empty"><code>queue#<b>empty</b></code></a> * <a href="#saturated"><code>queue#<b>saturated</b></code></a> * <a href="#promise"><code>fastqueue.promise()</code></a> ------------------------------------------------------- <a name="fastqueue"></a> ### fastqueue([that], worker, concurrency) Creates a new queue. Arguments: * `that`, optional context of the `worker` function. * `worker`, worker function, it would be called with `that` as `this`, if that is specified. * `concurrency`, number of concurrent tasks that could be executed in parallel. ------------------------------------------------------- <a name="push"></a> ### queue.push(task, done) Add a task at the end of the queue. `done(err, result)` will be called when the task was processed. ------------------------------------------------------- <a name="unshift"></a> ### queue.unshift(task, done) Add a task at the beginning of the queue. `done(err, result)` will be called when the task was processed. ------------------------------------------------------- <a name="pause"></a> ### queue.pause() Pause the processing of tasks. Currently worked tasks are not stopped. ------------------------------------------------------- <a name="resume"></a> ### queue.resume() Resume the processing of tasks. ------------------------------------------------------- <a name="idle"></a> ### queue.idle() Returns `false` if there are tasks being processed or waiting to be processed. `true` otherwise. ------------------------------------------------------- <a name="length"></a> ### queue.length() Returns the number of tasks waiting to be processed (in the queue). ------------------------------------------------------- <a name="getQueue"></a> ### queue.getQueue() Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks ------------------------------------------------------- <a name="kill"></a> ### queue.kill() Removes all tasks waiting to be processed, and reset `drain` to an empty function. ------------------------------------------------------- <a name="killAndDrain"></a> ### queue.killAndDrain() Same than `kill` but the `drain` function will be called before reset to empty. ------------------------------------------------------- <a name="error"></a> ### queue.error(handler) Set a global error handler. `handler(err, task)` will be called each time a task is completed, `err` will be not null if the task has thrown an error. ------------------------------------------------------- <a name="concurrency"></a> ### queue.concurrency Property that returns the number of concurrent tasks that could be executed in parallel. It can be altered at runtime. ------------------------------------------------------- <a name="paused"></a> ### queue.paused Property (Read-Only) that returns `true` when the queue is in a paused state. ------------------------------------------------------- <a name="drain"></a> ### queue.drain Function that will be called when the last item from the queue has been processed by a worker. It can be altered at runtime. ------------------------------------------------------- <a name="empty"></a> ### queue.empty Function that will be called when the last item from the queue has been assigned to a worker. It can be altered at runtime. ------------------------------------------------------- <a name="saturated"></a> ### queue.saturated Function that will be called when the queue hits the concurrency limit. It can be altered at runtime. ------------------------------------------------------- <a name="promise"></a> ### fastqueue.promise([that], worker(arg), concurrency) Creates a new queue with `Promise` apis. It also offers all the methods and properties of the object returned by [`fastqueue`](#fastqueue) with the modified [`push`](#pushPromise) and [`unshift`](#unshiftPromise) methods. Node v10+ is required to use the promisified version. Arguments: * `that`, optional context of the `worker` function. * `worker`, worker function, it would be called with `that` as `this`, if that is specified. It MUST return a `Promise`. * `concurrency`, number of concurrent tasks that could be executed in parallel. <a name="pushPromise"></a> #### queue.push(task) => Promise Add a task at the end of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). This promise could be ignored as it will not lead to a `'unhandledRejection'`. <a name="unshiftPromise"></a> #### queue.unshift(task) => Promise Add a task at the beginning of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). This promise could be ignored as it will not lead to a `'unhandledRejection'`. <a name="drained"></a> #### queue.drained() => Promise Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker. This promise could be ignored as it will not lead to a `'unhandledRejection'`. ## License ISC [ci-url]: https://github.com/mcollina/fastq/workflows/ci/badge.svg [npm-badge]: https://badge.fury.io/js/fastq.svg [npm-url]: https://badge.fury.io/js/fastq node_modules/is-glob/package.json 0000664 00000003324 15114743311 0013047 0 ustar 00 { "name": "is-glob", "description": "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience.", "version": "4.0.3", "homepage": "https://github.com/micromatch/is-glob", "author": "Jon Schlinkert (https://github.com/jonschlinkert)", "contributors": [ "Brian Woodward (https://twitter.com/doowb)", "Daniel Perez (https://tuvistavie.com)", "Jon Schlinkert (http://twitter.com/jonschlinkert)" ], "repository": "micromatch/is-glob", "bugs": { "url": "https://github.com/micromatch/is-glob/issues" }, "license": "MIT", "files": [ "index.js" ], "main": "index.js", "engines": { "node": ">=0.10.0" }, "scripts": { "test": "mocha && node benchmark.js" }, "dependencies": { "is-extglob": "^2.1.1" }, "devDependencies": { "gulp-format-md": "^0.1.10", "mocha": "^3.0.2" }, "keywords": [ "bash", "braces", "check", "exec", "expression", "extglob", "glob", "globbing", "globstar", "is", "match", "matches", "pattern", "regex", "regular", "string", "test" ], "verb": { "layout": "default", "plugins": [ "gulp-format-md" ], "related": { "list": [ "assemble", "base", "update", "verb" ] }, "reflinks": [ "assemble", "bach", "base", "composer", "gulp", "has-glob", "is-valid-glob", "micromatch", "npm", "scaffold", "verb", "vinyl" ] } } node_modules/is-glob/LICENSE 0000664 00000002100 15114743311 0011555 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2017, Jon Schlinkert. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/is-glob/index.js 0000664 00000007054 15114743311 0012232 0 ustar 00 /*! * is-glob <https://github.com/jonschlinkert/is-glob> * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ var isExtglob = require('is-extglob'); var chars = { '{': '}', '(': ')', '[': ']'}; var strictCheck = function(str) { if (str[0] === '!') { return true; } var index = 0; var pipeIndex = -2; var closeSquareIndex = -2; var closeCurlyIndex = -2; var closeParenIndex = -2; var backSlashIndex = -2; while (index < str.length) { if (str[index] === '*') { return true; } if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) { return true; } if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') { if (closeSquareIndex < index) { closeSquareIndex = str.indexOf(']', index); } if (closeSquareIndex > index) { if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } } } if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { closeCurlyIndex = str.indexOf('}', index); if (closeCurlyIndex > index) { backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { return true; } } } if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { closeParenIndex = str.indexOf(')', index); if (closeParenIndex > index) { backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { if (pipeIndex < index) { pipeIndex = str.indexOf('|', index); } if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { closeParenIndex = str.indexOf(')', pipeIndex); if (closeParenIndex > pipeIndex) { backSlashIndex = str.indexOf('\\', pipeIndex); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } } if (str[index] === '\\') { var open = str[index + 1]; index += 2; var close = chars[open]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === '!') { return true; } } else { index++; } } return false; }; var relaxedCheck = function(str) { if (str[0] === '!') { return true; } var index = 0; while (index < str.length) { if (/[*?{}()[\]]/.test(str[index])) { return true; } if (str[index] === '\\') { var open = str[index + 1]; index += 2; var close = chars[open]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === '!') { return true; } } else { index++; } } return false; }; module.exports = function isGlob(str, options) { if (typeof str !== 'string' || str === '') { return false; } if (isExtglob(str)) { return true; } var check = strictCheck; // optionally relax check if (options && options.strict === false) { check = relaxedCheck; } return check(str); }; node_modules/is-glob/README.md 0000664 00000015751 15114743311 0012047 0 ustar 00 # is-glob [](https://www.npmjs.com/package/is-glob) [](https://npmjs.org/package/is-glob) [](https://npmjs.org/package/is-glob) [](https://github.com/micromatch/is-glob/actions) > Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-glob ``` You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). ## Usage ```js var isGlob = require('is-glob'); ``` ### Default behavior **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js'); isGlob('*.js'); isGlob('**/abc.js'); isGlob('abc/*.js'); isGlob('abc/(aaa|bbb).js'); isGlob('abc/[a-z].js'); isGlob('abc/{a,b}.js'); //=> true ``` Extglobs ```js isGlob('abc/@(a).js'); isGlob('abc/!(a).js'); isGlob('abc/+(a).js'); isGlob('abc/*(a).js'); isGlob('abc/?(a).js'); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('abc/\\@(a).js'); isGlob('abc/\\!(a).js'); isGlob('abc/\\+(a).js'); isGlob('abc/\\*(a).js'); isGlob('abc/\\?(a).js'); isGlob('\\!foo.js'); isGlob('\\*.js'); isGlob('\\*\\*/abc.js'); isGlob('abc/\\*.js'); isGlob('abc/\\(aaa|bbb).js'); isGlob('abc/\\[a-z].js'); isGlob('abc/\\{a,b}.js'); //=> false ``` Patterns that do not have glob patterns return `false`: ```js isGlob('abc.js'); isGlob('abc/def/ghi.js'); isGlob('foo.js'); isGlob('abc/@.js'); isGlob('abc/+.js'); isGlob('abc/?.js'); isGlob(); isGlob(null); //=> false ``` Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): ```js isGlob(['**/*.js']); isGlob(['foo.js']); //=> false ``` ### Option strict When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js', {strict: false}); isGlob('*.js', {strict: false}); isGlob('**/abc.js', {strict: false}); isGlob('abc/*.js', {strict: false}); isGlob('abc/(aaa|bbb).js', {strict: false}); isGlob('abc/[a-z].js', {strict: false}); isGlob('abc/{a,b}.js', {strict: false}); //=> true ``` Extglobs ```js isGlob('abc/@(a).js', {strict: false}); isGlob('abc/!(a).js', {strict: false}); isGlob('abc/+(a).js', {strict: false}); isGlob('abc/*(a).js', {strict: false}); isGlob('abc/?(a).js', {strict: false}); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('\\!foo.js', {strict: false}); isGlob('\\*.js', {strict: false}); isGlob('\\*\\*/abc.js', {strict: false}); isGlob('abc/\\*.js', {strict: false}); isGlob('abc/\\(aaa|bbb).js', {strict: false}); isGlob('abc/\\[a-z].js', {strict: false}); isGlob('abc/\\{a,b}.js', {strict: false}); //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") * [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") * [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 47 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [doowb](https://github.com/doowb) | | 1 | [phated](https://github.com/phated) | | 1 | [danhper](https://github.com/danhper) | | 1 | [paulmillr](https://github.com/paulmillr) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ node_modules/@nodelib/fs.walk/out/settings.d.ts 0000664 00000002227 15114743311 0015550 0 ustar 00 import * as fsScandir from '@nodelib/fs.scandir'; import type { Entry, Errno } from './types'; export declare type FilterFunction<T> = (value: T) => boolean; export declare type DeepFilterFunction = FilterFunction<Entry>; export declare type EntryFilterFunction = FilterFunction<Entry>; export declare type ErrorFilterFunction = FilterFunction<Errno>; export interface Options { basePath?: string; concurrency?: number; deepFilter?: DeepFilterFunction; entryFilter?: EntryFilterFunction; errorFilter?: ErrorFilterFunction; followSymbolicLinks?: boolean; fs?: Partial<fsScandir.FileSystemAdapter>; pathSegmentSeparator?: string; stats?: boolean; throwErrorOnBrokenSymbolicLink?: boolean; } export default class Settings { private readonly _options; readonly basePath?: string; readonly concurrency: number; readonly deepFilter: DeepFilterFunction | null; readonly entryFilter: EntryFilterFunction | null; readonly errorFilter: ErrorFilterFunction | null; readonly pathSegmentSeparator: string; readonly fsScandirSettings: fsScandir.Settings; constructor(_options?: Options); private _getValue; } node_modules/@nodelib/fs.walk/out/settings.js 0000664 00000002342 15114743311 0015312 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const path = require("path"); const fsScandir = require("@nodelib/fs.scandir"); class Settings { constructor(_options = {}) { this._options = _options; this.basePath = this._getValue(this._options.basePath, undefined); this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); this.deepFilter = this._getValue(this._options.deepFilter, null); this.entryFilter = this._getValue(this._options.entryFilter, null); this.errorFilter = this._getValue(this._options.errorFilter, null); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); this.fsScandirSettings = new fsScandir.Settings({ followSymbolicLinks: this._options.followSymbolicLinks, fs: this._options.fs, pathSegmentSeparator: this._options.pathSegmentSeparator, stats: this._options.stats, throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } exports.default = Settings; node_modules/@nodelib/fs.walk/out/index.d.ts 0000664 00000001773 15114743311 0015024 0 ustar 00 /// <reference types="node" /> import type { Readable } from 'stream'; import type { Dirent, FileSystemAdapter } from '@nodelib/fs.scandir'; import { AsyncCallback } from './providers/async'; import Settings, { DeepFilterFunction, EntryFilterFunction, ErrorFilterFunction, Options } from './settings'; import type { Entry } from './types'; declare function walk(directory: string, callback: AsyncCallback): void; declare function walk(directory: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; declare namespace walk { function __promisify__(directory: string, optionsOrSettings?: Options | Settings): Promise<Entry[]>; } declare function walkSync(directory: string, optionsOrSettings?: Options | Settings): Entry[]; declare function walkStream(directory: string, optionsOrSettings?: Options | Settings): Readable; export { walk, walkSync, walkStream, Settings, AsyncCallback, Dirent, Entry, FileSystemAdapter, Options, DeepFilterFunction, EntryFilterFunction, ErrorFilterFunction }; node_modules/@nodelib/fs.walk/out/types/index.d.ts 0000664 00000000373 15114743311 0016163 0 ustar 00 /// <reference types="node" /> import type * as scandir from '@nodelib/fs.scandir'; export declare type Entry = scandir.Entry; export declare type Errno = NodeJS.ErrnoException; export interface QueueItem { directory: string; base?: string; } node_modules/@nodelib/fs.walk/out/types/index.js 0000664 00000000115 15114743311 0015721 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); node_modules/@nodelib/fs.walk/out/providers/index.d.ts 0000664 00000000247 15114743311 0017034 0 ustar 00 import AsyncProvider from './async'; import StreamProvider from './stream'; import SyncProvider from './sync'; export { AsyncProvider, StreamProvider, SyncProvider }; node_modules/@nodelib/fs.walk/out/providers/stream.d.ts 0000664 00000000635 15114743311 0017221 0 ustar 00 /// <reference types="node" /> import { Readable } from 'stream'; import AsyncReader from '../readers/async'; import type Settings from '../settings'; export default class StreamProvider { private readonly _root; private readonly _settings; protected readonly _reader: AsyncReader; protected readonly _stream: Readable; constructor(_root: string, _settings: Settings); read(): Readable; } node_modules/@nodelib/fs.walk/out/providers/stream.js 0000664 00000001775 15114743311 0016773 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const stream_1 = require("stream"); const async_1 = require("../readers/async"); class StreamProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1.default(this._root, this._settings); this._stream = new stream_1.Readable({ objectMode: true, read: () => { }, destroy: () => { if (!this._reader.isDestroyed) { this._reader.destroy(); } } }); } read() { this._reader.onError((error) => { this._stream.emit('error', error); }); this._reader.onEntry((entry) => { this._stream.push(entry); }); this._reader.onEnd(() => { this._stream.push(null); }); this._reader.read(); return this._stream; } } exports.default = StreamProvider; node_modules/@nodelib/fs.walk/out/providers/sync.d.ts 0000664 00000000522 15114743311 0016675 0 ustar 00 import SyncReader from '../readers/sync'; import type Settings from '../settings'; import type { Entry } from '../types'; export default class SyncProvider { private readonly _root; private readonly _settings; protected readonly _reader: SyncReader; constructor(_root: string, _settings: Settings); read(): Entry[]; } node_modules/@nodelib/fs.walk/out/providers/index.js 0000664 00000000604 15114743311 0016575 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SyncProvider = exports.StreamProvider = exports.AsyncProvider = void 0; const async_1 = require("./async"); exports.AsyncProvider = async_1.default; const stream_1 = require("./stream"); exports.StreamProvider = stream_1.default; const sync_1 = require("./sync"); exports.SyncProvider = sync_1.default; node_modules/@nodelib/fs.walk/out/providers/sync.js 0000664 00000000627 15114743311 0016447 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const sync_1 = require("../readers/sync"); class SyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new sync_1.default(this._root, this._settings); } read() { return this._reader.read(); } } exports.default = SyncProvider; node_modules/@nodelib/fs.walk/out/providers/async.d.ts 0000664 00000000736 15114743311 0017045 0 ustar 00 import AsyncReader from '../readers/async'; import type Settings from '../settings'; import type { Entry, Errno } from '../types'; export declare type AsyncCallback = (error: Errno, entries: Entry[]) => void; export default class AsyncProvider { private readonly _root; private readonly _settings; protected readonly _reader: AsyncReader; private readonly _storage; constructor(_root: string, _settings: Settings); read(callback: AsyncCallback): void; } node_modules/@nodelib/fs.walk/out/providers/async.js 0000664 00000001577 15114743311 0016615 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const async_1 = require("../readers/async"); class AsyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1.default(this._root, this._settings); this._storage = []; } read(callback) { this._reader.onError((error) => { callFailureCallback(callback, error); }); this._reader.onEntry((entry) => { this._storage.push(entry); }); this._reader.onEnd(() => { callSuccessCallback(callback, this._storage); }); this._reader.read(); } } exports.default = AsyncProvider; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, entries) { callback(null, entries); } node_modules/@nodelib/fs.walk/out/index.js 0000664 00000002556 15114743311 0014570 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0; const async_1 = require("./providers/async"); const stream_1 = require("./providers/stream"); const sync_1 = require("./providers/sync"); const settings_1 = require("./settings"); exports.Settings = settings_1.default; function walk(directory, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); return; } new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); } exports.walk = walk; function walkSync(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new sync_1.default(directory, settings); return provider.read(); } exports.walkSync = walkSync; function walkStream(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new stream_1.default(directory, settings); return provider.read(); } exports.walkStream = walkStream; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; } return new settings_1.default(settingsOrOptions); } node_modules/@nodelib/fs.walk/out/readers/reader.js 0000664 00000000546 15114743311 0016345 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const common = require("./common"); class Reader { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); } } exports.default = Reader; node_modules/@nodelib/fs.walk/out/readers/reader.d.ts 0000664 00000000320 15114743311 0016567 0 ustar 00 import type Settings from '../settings'; export default class Reader { protected readonly _root: string; protected readonly _settings: Settings; constructor(_root: string, _settings: Settings); } node_modules/@nodelib/fs.walk/out/readers/common.js 0000664 00000002034 15114743311 0016365 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = void 0; function isFatalError(settings, error) { if (settings.errorFilter === null) { return true; } return !settings.errorFilter(error); } exports.isFatalError = isFatalError; function isAppliedFilter(filter, value) { return filter === null || filter(value); } exports.isAppliedFilter = isAppliedFilter; function replacePathSegmentSeparator(filepath, separator) { return filepath.split(/[/\\]/).join(separator); } exports.replacePathSegmentSeparator = replacePathSegmentSeparator; function joinPathSegments(a, b, separator) { if (a === '') { return b; } /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } exports.joinPathSegments = joinPathSegments; node_modules/@nodelib/fs.walk/out/readers/sync.d.ts 0000664 00000000735 15114743311 0016313 0 ustar 00 import * as fsScandir from '@nodelib/fs.scandir'; import type { Entry } from '../types'; import Reader from './reader'; export default class SyncReader extends Reader { protected readonly _scandir: typeof fsScandir.scandirSync; private readonly _storage; private readonly _queue; read(): Entry[]; private _pushToQueue; private _handleQueue; private _handleDirectory; private _handleError; private _handleEntry; private _pushToStorage; } node_modules/@nodelib/fs.walk/out/readers/common.d.ts 0000664 00000000762 15114743311 0016627 0 ustar 00 import type { FilterFunction } from '../settings'; import type Settings from '../settings'; import type { Errno } from '../types'; export declare function isFatalError(settings: Settings, error: Errno): boolean; export declare function isAppliedFilter<T>(filter: FilterFunction<T> | null, value: T): boolean; export declare function replacePathSegmentSeparator(filepath: string, separator: string): string; export declare function joinPathSegments(a: string, b: string, separator: string): string; node_modules/@nodelib/fs.walk/out/readers/sync.js 0000664 00000003567 15114743311 0016065 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const fsScandir = require("@nodelib/fs.scandir"); const common = require("./common"); const reader_1 = require("./reader"); class SyncReader extends reader_1.default { constructor() { super(...arguments); this._scandir = fsScandir.scandirSync; this._storage = []; this._queue = new Set(); } read() { this._pushToQueue(this._root, this._settings.basePath); this._handleQueue(); return this._storage; } _pushToQueue(directory, base) { this._queue.add({ directory, base }); } _handleQueue() { for (const item of this._queue.values()) { this._handleDirectory(item.directory, item.base); } } _handleDirectory(directory, base) { try { const entries = this._scandir(directory, this._settings.fsScandirSettings); for (const entry of entries) { this._handleEntry(entry, base); } } catch (error) { this._handleError(error); } } _handleError(error) { if (!common.isFatalError(this._settings, error)) { return; } throw error; } _handleEntry(entry, base) { const fullpath = entry.path; if (base !== undefined) { entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common.isAppliedFilter(this._settings.entryFilter, entry)) { this._pushToStorage(entry); } if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _pushToStorage(entry) { this._storage.push(entry); } } exports.default = SyncReader; node_modules/@nodelib/fs.walk/out/readers/async.d.ts 0000664 00000002103 15114743311 0016443 0 ustar 00 /// <reference types="node" /> import { EventEmitter } from 'events'; import * as fsScandir from '@nodelib/fs.scandir'; import type Settings from '../settings'; import type { Entry, Errno } from '../types'; import Reader from './reader'; declare type EntryEventCallback = (entry: Entry) => void; declare type ErrorEventCallback = (error: Errno) => void; declare type EndEventCallback = () => void; export default class AsyncReader extends Reader { protected readonly _settings: Settings; protected readonly _scandir: typeof fsScandir.scandir; protected readonly _emitter: EventEmitter; private readonly _queue; private _isFatalError; private _isDestroyed; constructor(_root: string, _settings: Settings); read(): EventEmitter; get isDestroyed(): boolean; destroy(): void; onEntry(callback: EntryEventCallback): void; onError(callback: ErrorEventCallback): void; onEnd(callback: EndEventCallback): void; private _pushToQueue; private _worker; private _handleError; private _handleEntry; private _emitEntry; } export {}; node_modules/@nodelib/fs.walk/out/readers/async.js 0000664 00000006125 15114743311 0016217 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const events_1 = require("events"); const fsScandir = require("@nodelib/fs.scandir"); const fastq = require("fastq"); const common = require("./common"); const reader_1 = require("./reader"); class AsyncReader extends reader_1.default { constructor(_root, _settings) { super(_root, _settings); this._settings = _settings; this._scandir = fsScandir.scandir; this._emitter = new events_1.EventEmitter(); this._queue = fastq(this._worker.bind(this), this._settings.concurrency); this._isFatalError = false; this._isDestroyed = false; this._queue.drain = () => { if (!this._isFatalError) { this._emitter.emit('end'); } }; } read() { this._isFatalError = false; this._isDestroyed = false; setImmediate(() => { this._pushToQueue(this._root, this._settings.basePath); }); return this._emitter; } get isDestroyed() { return this._isDestroyed; } destroy() { if (this._isDestroyed) { throw new Error('The reader is already destroyed'); } this._isDestroyed = true; this._queue.killAndDrain(); } onEntry(callback) { this._emitter.on('entry', callback); } onError(callback) { this._emitter.once('error', callback); } onEnd(callback) { this._emitter.once('end', callback); } _pushToQueue(directory, base) { const queueItem = { directory, base }; this._queue.push(queueItem, (error) => { if (error !== null) { this._handleError(error); } }); } _worker(item, done) { this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { if (error !== null) { done(error, undefined); return; } for (const entry of entries) { this._handleEntry(entry, item.base); } done(null, undefined); }); } _handleError(error) { if (this._isDestroyed || !common.isFatalError(this._settings, error)) { return; } this._isFatalError = true; this._isDestroyed = true; this._emitter.emit('error', error); } _handleEntry(entry, base) { if (this._isDestroyed || this._isFatalError) { return; } const fullpath = entry.path; if (base !== undefined) { entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common.isAppliedFilter(this._settings.entryFilter, entry)) { this._emitEntry(entry); } if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _emitEntry(entry) { this._emitter.emit('entry', entry); } } exports.default = AsyncReader; node_modules/@nodelib/fs.walk/package.json 0000664 00000002162 15114743311 0014573 0 ustar 00 { "name": "@nodelib/fs.walk", "version": "1.2.8", "description": "A library for efficiently walking a directory recursively", "license": "MIT", "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.walk", "keywords": [ "NodeLib", "fs", "FileSystem", "file system", "walk", "scanner", "crawler" ], "engines": { "node": ">= 8" }, "files": [ "out/**", "!out/**/*.map", "!out/**/*.spec.*", "!out/**/tests/**" ], "main": "out/index.js", "typings": "out/index.d.ts", "scripts": { "clean": "rimraf {tsconfig.tsbuildinfo,out}", "lint": "eslint \"src/**/*.ts\" --cache", "compile": "tsc -b .", "compile:watch": "tsc -p . --watch --sourceMap", "test": "mocha \"out/**/*.spec.js\" -s 0", "build": "npm run clean && npm run compile && npm run lint && npm test", "watch": "npm run clean && npm run compile:watch" }, "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" }, "devDependencies": { "@nodelib/fs.macchiato": "1.0.4" }, "gitHead": "1e5bad48565da2b06b8600e744324ea240bf49d8" } node_modules/@nodelib/fs.walk/LICENSE 0000664 00000002067 15114743311 0013316 0 ustar 00 The MIT License (MIT) Copyright (c) Denis Malinochkin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/@nodelib/fs.walk/README.md 0000664 00000013773 15114743311 0013576 0 ustar 00 # @nodelib/fs.walk > A library for efficiently walking a directory recursively. ## :bulb: Highlights * :moneybag: Returns useful information: `name`, `path`, `dirent` and `stats` (optional). * :rocket: On Node.js 10.10+ uses the mechanism without additional calls to determine the entry type for performance reasons. See [`old` and `modern` mode](https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode). * :gear: Built-in directories/files and error filtering system. * :link: Can safely work with broken symbolic links. ## Install ```console npm install @nodelib/fs.walk ``` ## Usage ```ts import * as fsWalk from '@nodelib/fs.walk'; fsWalk.walk('path', (error, entries) => { /* … */ }); ``` ## API ### .walk(path, [optionsOrSettings], callback) Reads the directory recursively and asynchronously. Requires a callback function. > :book: If you want to use the Promise API, use `util.promisify`. ```ts fsWalk.walk('path', (error, entries) => { /* … */ }); fsWalk.walk('path', {}, (error, entries) => { /* … */ }); fsWalk.walk('path', new fsWalk.Settings(), (error, entries) => { /* … */ }); ``` ### .walkStream(path, [optionsOrSettings]) Reads the directory recursively and asynchronously. [Readable Stream](https://nodejs.org/dist/latest-v12.x/docs/api/stream.html#stream_readable_streams) is used as a provider. ```ts const stream = fsWalk.walkStream('path'); const stream = fsWalk.walkStream('path', {}); const stream = fsWalk.walkStream('path', new fsWalk.Settings()); ``` ### .walkSync(path, [optionsOrSettings]) Reads the directory recursively and synchronously. Returns an array of entries. ```ts const entries = fsWalk.walkSync('path'); const entries = fsWalk.walkSync('path', {}); const entries = fsWalk.walkSync('path', new fsWalk.Settings()); ``` #### path * Required: `true` * Type: `string | Buffer | URL` A path to a file. If a URL is provided, it must use the `file:` protocol. #### optionsOrSettings * Required: `false` * Type: `Options | Settings` * Default: An instance of `Settings` class An [`Options`](#options) object or an instance of [`Settings`](#settings) class. > :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. ### Settings([options]) A class of full settings of the package. ```ts const settings = new fsWalk.Settings({ followSymbolicLinks: true }); const entries = fsWalk.walkSync('path', settings); ``` ## Entry * `name` — The name of the entry (`unknown.txt`). * `path` — The path of the entry relative to call directory (`root/unknown.txt`). * `dirent` — An instance of [`fs.Dirent`](./src/types/index.ts) class. * [`stats`] — An instance of `fs.Stats` class. ## Options ### basePath * Type: `string` * Default: `undefined` By default, all paths are built relative to the root path. You can use this option to set custom root path. In the example below we read the files from the `root` directory, but in the results the root path will be `custom`. ```ts fsWalk.walkSync('root'); // → ['root/file.txt'] fsWalk.walkSync('root', { basePath: 'custom' }); // → ['custom/file.txt'] ``` ### concurrency * Type: `number` * Default: `Infinity` The maximum number of concurrent calls to `fs.readdir`. > :book: The higher the number, the higher performance and the load on the File System. If you want to read in quiet mode, set the value to `4 * os.cpus().length` (4 is default size of [thread pool work scheduling](http://docs.libuv.org/en/v1.x/threadpool.html#thread-pool-work-scheduling)). ### deepFilter * Type: [`DeepFilterFunction`](./src/settings.ts) * Default: `undefined` A function that indicates whether the directory will be read deep or not. ```ts // Skip all directories that starts with `node_modules` const filter: DeepFilterFunction = (entry) => !entry.path.startsWith('node_modules'); ``` ### entryFilter * Type: [`EntryFilterFunction`](./src/settings.ts) * Default: `undefined` A function that indicates whether the entry will be included to results or not. ```ts // Exclude all `.js` files from results const filter: EntryFilterFunction = (entry) => !entry.name.endsWith('.js'); ``` ### errorFilter * Type: [`ErrorFilterFunction`](./src/settings.ts) * Default: `undefined` A function that allows you to skip errors that occur when reading directories. For example, you can skip `ENOENT` errors if required: ```ts // Skip all ENOENT errors const filter: ErrorFilterFunction = (error) => error.code == 'ENOENT'; ``` ### stats * Type: `boolean` * Default: `false` Adds an instance of `fs.Stats` class to the [`Entry`](#entry). > :book: Always use `fs.readdir` with additional `fs.lstat/fs.stat` calls to determine the entry type. ### followSymbolicLinks * Type: `boolean` * Default: `false` Follow symbolic links or not. Call `fs.stat` on symbolic link if `true`. ### `throwErrorOnBrokenSymbolicLink` * Type: `boolean` * Default: `true` Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. ### `pathSegmentSeparator` * Type: `string` * Default: `path.sep` By default, this package uses the correct path separator for your OS (`\` on Windows, `/` on Unix-like systems). But you can set this option to any separator character(s) that you want to use instead. ### `fs` * Type: `FileSystemAdapter` * Default: A default FS methods By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. ```ts interface FileSystemAdapter { lstat: typeof fs.lstat; stat: typeof fs.stat; lstatSync: typeof fs.lstatSync; statSync: typeof fs.statSync; readdir: typeof fs.readdir; readdirSync: typeof fs.readdirSync; } const settings = new fsWalk.Settings({ fs: { lstat: fakeLstat } }); ``` ## Changelog See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. ## License This software is released under the terms of the MIT license. node_modules/@nodelib/fs.stat/out/settings.d.ts 0000664 00000001006 15114743311 0015557 0 ustar 00 import * as fs from './adapters/fs'; export interface Options { followSymbolicLink?: boolean; fs?: Partial<fs.FileSystemAdapter>; markSymbolicLink?: boolean; throwErrorOnBrokenSymbolicLink?: boolean; } export default class Settings { private readonly _options; readonly followSymbolicLink: boolean; readonly fs: fs.FileSystemAdapter; readonly markSymbolicLink: boolean; readonly throwErrorOnBrokenSymbolicLink: boolean; constructor(_options?: Options); private _getValue; } node_modules/@nodelib/fs.stat/out/settings.js 0000664 00000001270 15114743311 0015326 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const fs = require("./adapters/fs"); class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); this.fs = fs.createFileSystemAdapter(this._options.fs); this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } exports.default = Settings; node_modules/@nodelib/fs.stat/out/index.d.ts 0000664 00000001445 15114743311 0015035 0 ustar 00 import type { FileSystemAdapter, StatAsynchronousMethod, StatSynchronousMethod } from './adapters/fs'; import * as async from './providers/async'; import Settings, { Options } from './settings'; import type { Stats } from './types'; declare type AsyncCallback = async.AsyncCallback; declare function stat(path: string, callback: AsyncCallback): void; declare function stat(path: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; declare namespace stat { function __promisify__(path: string, optionsOrSettings?: Options | Settings): Promise<Stats>; } declare function statSync(path: string, optionsOrSettings?: Options | Settings): Stats; export { Settings, stat, statSync, AsyncCallback, FileSystemAdapter, StatAsynchronousMethod, StatSynchronousMethod, Options, Stats }; node_modules/@nodelib/fs.stat/out/adapters/fs.js 0000664 00000001106 15114743311 0015677 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = require("fs"); exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; node_modules/@nodelib/fs.stat/out/adapters/fs.d.ts 0000664 00000001231 15114743311 0016132 0 ustar 00 /// <reference types="node" /> import * as fs from 'fs'; import type { ErrnoException } from '../types'; export declare type StatAsynchronousMethod = (path: string, callback: (error: ErrnoException | null, stats: fs.Stats) => void) => void; export declare type StatSynchronousMethod = (path: string) => fs.Stats; export interface FileSystemAdapter { lstat: StatAsynchronousMethod; stat: StatAsynchronousMethod; lstatSync: StatSynchronousMethod; statSync: StatSynchronousMethod; } export declare const FILE_SYSTEM_ADAPTER: FileSystemAdapter; export declare function createFileSystemAdapter(fsMethods?: Partial<FileSystemAdapter>): FileSystemAdapter; node_modules/@nodelib/fs.stat/out/types/index.d.ts 0000664 00000000240 15114743311 0016171 0 ustar 00 /// <reference types="node" /> import type * as fs from 'fs'; export declare type Stats = fs.Stats; export declare type ErrnoException = NodeJS.ErrnoException; node_modules/@nodelib/fs.stat/out/types/index.js 0000664 00000000115 15114743311 0015736 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); node_modules/@nodelib/fs.stat/out/providers/sync.d.ts 0000664 00000000227 15114743311 0016714 0 ustar 00 import type Settings from '../settings'; import type { Stats } from '../types'; export declare function read(path: string, settings: Settings): Stats; node_modules/@nodelib/fs.stat/out/providers/sync.js 0000664 00000001153 15114743311 0016457 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.read = void 0; function read(path, settings) { const lstat = settings.fs.lstatSync(path); if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { return lstat; } try { const stat = settings.fs.statSync(path); if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } return stat; } catch (error) { if (!settings.throwErrorOnBrokenSymbolicLink) { return lstat; } throw error; } } exports.read = read; node_modules/@nodelib/fs.stat/out/providers/async.d.ts 0000664 00000000422 15114743311 0017052 0 ustar 00 import type Settings from '../settings'; import type { ErrnoException, Stats } from '../types'; export declare type AsyncCallback = (error: ErrnoException, stats: Stats) => void; export declare function read(path: string, settings: Settings, callback: AsyncCallback): void; node_modules/@nodelib/fs.stat/out/providers/async.js 0000664 00000002224 15114743311 0016620 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.read = void 0; function read(path, settings, callback) { settings.fs.lstat(path, (lstatError, lstat) => { if (lstatError !== null) { callFailureCallback(callback, lstatError); return; } if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { callSuccessCallback(callback, lstat); return; } settings.fs.stat(path, (statError, stat) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { callFailureCallback(callback, statError); return; } callSuccessCallback(callback, lstat); return; } if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } callSuccessCallback(callback, stat); }); }); } exports.read = read; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, result) { callback(null, result); } node_modules/@nodelib/fs.stat/out/index.js 0000664 00000001731 15114743311 0014577 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.statSync = exports.stat = exports.Settings = void 0; const async = require("./providers/async"); const sync = require("./providers/sync"); const settings_1 = require("./settings"); exports.Settings = settings_1.default; function stat(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async.read(path, getSettings(), optionsOrSettingsOrCallback); return; } async.read(path, getSettings(optionsOrSettingsOrCallback), callback); } exports.stat = stat; function statSync(path, optionsOrSettings) { const settings = getSettings(optionsOrSettings); return sync.read(path, settings); } exports.statSync = statSync; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; } return new settings_1.default(settingsOrOptions); } node_modules/@nodelib/fs.stat/package.json 0000664 00000001733 15114743311 0014613 0 ustar 00 { "name": "@nodelib/fs.stat", "version": "2.0.5", "description": "Get the status of a file with some features", "license": "MIT", "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.stat", "keywords": [ "NodeLib", "fs", "FileSystem", "file system", "stat" ], "engines": { "node": ">= 8" }, "files": [ "out/**", "!out/**/*.map", "!out/**/*.spec.*" ], "main": "out/index.js", "typings": "out/index.d.ts", "scripts": { "clean": "rimraf {tsconfig.tsbuildinfo,out}", "lint": "eslint \"src/**/*.ts\" --cache", "compile": "tsc -b .", "compile:watch": "tsc -p . --watch --sourceMap", "test": "mocha \"out/**/*.spec.js\" -s 0", "build": "npm run clean && npm run compile && npm run lint && npm test", "watch": "npm run clean && npm run compile:watch" }, "devDependencies": { "@nodelib/fs.macchiato": "1.0.4" }, "gitHead": "d6a7960d5281d3dd5f8e2efba49bb552d090f562" } node_modules/@nodelib/fs.stat/LICENSE 0000664 00000002067 15114743311 0013333 0 ustar 00 The MIT License (MIT) Copyright (c) Denis Malinochkin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/@nodelib/fs.stat/README.md 0000664 00000006003 15114743311 0013577 0 ustar 00 # @nodelib/fs.stat > Get the status of a file with some features. ## :bulb: Highlights Wrapper around standard method `fs.lstat` and `fs.stat` with some features. * :beginner: Normally follows symbolic link. * :gear: Can safely work with broken symbolic link. ## Install ```console npm install @nodelib/fs.stat ``` ## Usage ```ts import * as fsStat from '@nodelib/fs.stat'; fsStat.stat('path', (error, stats) => { /* … */ }); ``` ## API ### .stat(path, [optionsOrSettings], callback) Returns an instance of `fs.Stats` class for provided path with standard callback-style. ```ts fsStat.stat('path', (error, stats) => { /* … */ }); fsStat.stat('path', {}, (error, stats) => { /* … */ }); fsStat.stat('path', new fsStat.Settings(), (error, stats) => { /* … */ }); ``` ### .statSync(path, [optionsOrSettings]) Returns an instance of `fs.Stats` class for provided path. ```ts const stats = fsStat.stat('path'); const stats = fsStat.stat('path', {}); const stats = fsStat.stat('path', new fsStat.Settings()); ``` #### path * Required: `true` * Type: `string | Buffer | URL` A path to a file. If a URL is provided, it must use the `file:` protocol. #### optionsOrSettings * Required: `false` * Type: `Options | Settings` * Default: An instance of `Settings` class An [`Options`](#options) object or an instance of [`Settings`](#settings) class. > :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. ### Settings([options]) A class of full settings of the package. ```ts const settings = new fsStat.Settings({ followSymbolicLink: false }); const stats = fsStat.stat('path', settings); ``` ## Options ### `followSymbolicLink` * Type: `boolean` * Default: `true` Follow symbolic link or not. Call `fs.stat` on symbolic link if `true`. ### `markSymbolicLink` * Type: `boolean` * Default: `false` Mark symbolic link by setting the return value of `isSymbolicLink` function to always `true` (even after `fs.stat`). > :book: Can be used if you want to know what is hidden behind a symbolic link, but still continue to know that it is a symbolic link. ### `throwErrorOnBrokenSymbolicLink` * Type: `boolean` * Default: `true` Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. ### `fs` * Type: [`FileSystemAdapter`](./src/adapters/fs.ts) * Default: A default FS methods By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. ```ts interface FileSystemAdapter { lstat?: typeof fs.lstat; stat?: typeof fs.stat; lstatSync?: typeof fs.lstatSync; statSync?: typeof fs.statSync; } const settings = new fsStat.Settings({ fs: { lstat: fakeLstat } }); ``` ## Changelog See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. ## License This software is released under the terms of the MIT license. node_modules/@nodelib/fs.scandir/out/utils/fs.js 0000664 00000001364 15114743311 0015712 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createDirentFromStats = void 0; class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } } function createDirentFromStats(name, stats) { return new DirentFromStats(name, stats); } exports.createDirentFromStats = createDirentFromStats; node_modules/@nodelib/fs.scandir/out/utils/index.d.ts 0000664 00000000053 15114743311 0016637 0 ustar 00 import * as fs from './fs'; export { fs }; node_modules/@nodelib/fs.scandir/out/utils/index.js 0000664 00000000217 15114743311 0016405 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fs = void 0; const fs = require("./fs"); exports.fs = fs; node_modules/@nodelib/fs.scandir/out/utils/fs.d.ts 0000664 00000000202 15114743311 0016134 0 ustar 00 import type { Dirent, Stats } from '../types'; export declare function createDirentFromStats(name: string, stats: Stats): Dirent; node_modules/@nodelib/fs.scandir/out/settings.d.ts 0000664 00000001232 15114743311 0016230 0 ustar 00 import * as fsStat from '@nodelib/fs.stat'; import * as fs from './adapters/fs'; export interface Options { followSymbolicLinks?: boolean; fs?: Partial<fs.FileSystemAdapter>; pathSegmentSeparator?: string; stats?: boolean; throwErrorOnBrokenSymbolicLink?: boolean; } export default class Settings { private readonly _options; readonly followSymbolicLinks: boolean; readonly fs: fs.FileSystemAdapter; readonly pathSegmentSeparator: string; readonly stats: boolean; readonly throwErrorOnBrokenSymbolicLink: boolean; readonly fsStatSettings: fsStat.Settings; constructor(_options?: Options); private _getValue; } node_modules/@nodelib/fs.scandir/out/settings.js 0000664 00000002064 15114743311 0016000 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const path = require("path"); const fsStat = require("@nodelib/fs.stat"); const fs = require("./adapters/fs"); class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); this.fs = fs.createFileSystemAdapter(this._options.fs); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); this.stats = this._getValue(this._options.stats, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); this.fsStatSettings = new fsStat.Settings({ followSymbolicLink: this.followSymbolicLinks, fs: this.fs, throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } exports.default = Settings; node_modules/@nodelib/fs.scandir/out/index.d.ts 0000664 00000001527 15114743311 0015506 0 ustar 00 import type { FileSystemAdapter, ReaddirAsynchronousMethod, ReaddirSynchronousMethod } from './adapters/fs'; import * as async from './providers/async'; import Settings, { Options } from './settings'; import type { Dirent, Entry } from './types'; declare type AsyncCallback = async.AsyncCallback; declare function scandir(path: string, callback: AsyncCallback): void; declare function scandir(path: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; declare namespace scandir { function __promisify__(path: string, optionsOrSettings?: Options | Settings): Promise<Entry[]>; } declare function scandirSync(path: string, optionsOrSettings?: Options | Settings): Entry[]; export { scandir, scandirSync, Settings, AsyncCallback, Dirent, Entry, FileSystemAdapter, ReaddirAsynchronousMethod, ReaddirSynchronousMethod, Options }; node_modules/@nodelib/fs.scandir/out/adapters/fs.js 0000664 00000001200 15114743311 0016342 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = require("fs"); exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts 0000664 00000001556 15114743311 0016614 0 ustar 00 import type * as fsStat from '@nodelib/fs.stat'; import type { Dirent, ErrnoException } from '../types'; export interface ReaddirAsynchronousMethod { (filepath: string, options: { withFileTypes: true; }, callback: (error: ErrnoException | null, files: Dirent[]) => void): void; (filepath: string, callback: (error: ErrnoException | null, files: string[]) => void): void; } export interface ReaddirSynchronousMethod { (filepath: string, options: { withFileTypes: true; }): Dirent[]; (filepath: string): string[]; } export declare type FileSystemAdapter = fsStat.FileSystemAdapter & { readdir: ReaddirAsynchronousMethod; readdirSync: ReaddirSynchronousMethod; }; export declare const FILE_SYSTEM_ADAPTER: FileSystemAdapter; export declare function createFileSystemAdapter(fsMethods?: Partial<FileSystemAdapter>): FileSystemAdapter; node_modules/@nodelib/fs.scandir/out/constants.js 0000664 00000001736 15114743311 0016161 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); } const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); const SUPPORTED_MAJOR_VERSION = 10; const SUPPORTED_MINOR_VERSION = 10; const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; /** * IS `true` for Node.js 10.10 and greater. */ exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; node_modules/@nodelib/fs.scandir/out/types/index.d.ts 0000664 00000001022 15114743311 0016640 0 ustar 00 /// <reference types="node" /> import type * as fs from 'fs'; export interface Entry { dirent: Dirent; name: string; path: string; stats?: Stats; } export declare type Stats = fs.Stats; export declare type ErrnoException = NodeJS.ErrnoException; export interface Dirent { isBlockDevice: () => boolean; isCharacterDevice: () => boolean; isDirectory: () => boolean; isFIFO: () => boolean; isFile: () => boolean; isSocket: () => boolean; isSymbolicLink: () => boolean; name: string; } node_modules/@nodelib/fs.scandir/out/types/index.js 0000664 00000000115 15114743311 0016406 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); node_modules/@nodelib/fs.scandir/out/providers/common.js 0000664 00000000643 15114743311 0017446 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.joinPathSegments = void 0; function joinPathSegments(a, b, separator) { /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } exports.joinPathSegments = joinPathSegments; node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts 0000664 00000000515 15114743311 0017364 0 ustar 00 import type Settings from '../settings'; import type { Entry } from '../types'; export declare function read(directory: string, settings: Settings): Entry[]; export declare function readdirWithFileTypes(directory: string, settings: Settings): Entry[]; export declare function readdir(directory: string, settings: Settings): Entry[]; node_modules/@nodelib/fs.scandir/out/providers/common.d.ts 0000664 00000000133 15114743311 0017674 0 ustar 00 export declare function joinPathSegments(a: string, b: string, separator: string): string; node_modules/@nodelib/fs.scandir/out/providers/sync.js 0000664 00000003706 15114743311 0017135 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; const fsStat = require("@nodelib/fs.stat"); const constants_1 = require("../constants"); const utils = require("../utils"); const common = require("./common"); function read(directory, settings) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { return readdirWithFileTypes(directory, settings); } return readdir(directory, settings); } exports.read = read; function readdirWithFileTypes(directory, settings) { const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); return dirents.map((dirent) => { const entry = { dirent, name: dirent.name, path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) }; if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { try { const stats = settings.fs.statSync(entry.path); entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); } catch (error) { if (settings.throwErrorOnBrokenSymbolicLink) { throw error; } } } return entry; }); } exports.readdirWithFileTypes = readdirWithFileTypes; function readdir(directory, settings) { const names = settings.fs.readdirSync(directory); return names.map((name) => { const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); const stats = fsStat.statSync(entryPath, settings.fsStatSettings); const entry = { name, path: entryPath, dirent: utils.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } return entry; }); } exports.readdir = readdir; node_modules/@nodelib/fs.scandir/out/providers/async.d.ts 0000664 00000001014 15114743311 0017520 0 ustar 00 /// <reference types="node" /> import type Settings from '../settings'; import type { Entry } from '../types'; export declare type AsyncCallback = (error: NodeJS.ErrnoException, entries: Entry[]) => void; export declare function read(directory: string, settings: Settings, callback: AsyncCallback): void; export declare function readdirWithFileTypes(directory: string, settings: Settings, callback: AsyncCallback): void; export declare function readdir(directory: string, settings: Settings, callback: AsyncCallback): void; node_modules/@nodelib/fs.scandir/out/providers/async.js 0000664 00000007146 15114743311 0017300 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; const fsStat = require("@nodelib/fs.stat"); const rpl = require("run-parallel"); const constants_1 = require("../constants"); const utils = require("../utils"); const common = require("./common"); function read(directory, settings, callback) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { readdirWithFileTypes(directory, settings, callback); return; } readdir(directory, settings, callback); } exports.read = read; function readdirWithFileTypes(directory, settings, callback) { settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { if (readdirError !== null) { callFailureCallback(callback, readdirError); return; } const entries = dirents.map((dirent) => ({ dirent, name: dirent.name, path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) })); if (!settings.followSymbolicLinks) { callSuccessCallback(callback, entries); return; } const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); rpl(tasks, (rplError, rplEntries) => { if (rplError !== null) { callFailureCallback(callback, rplError); return; } callSuccessCallback(callback, rplEntries); }); }); } exports.readdirWithFileTypes = readdirWithFileTypes; function makeRplTaskEntry(entry, settings) { return (done) => { if (!entry.dirent.isSymbolicLink()) { done(null, entry); return; } settings.fs.stat(entry.path, (statError, stats) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { done(statError); return; } done(null, entry); return; } entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); done(null, entry); }); }; } function readdir(directory, settings, callback) { settings.fs.readdir(directory, (readdirError, names) => { if (readdirError !== null) { callFailureCallback(callback, readdirError); return; } const tasks = names.map((name) => { const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); return (done) => { fsStat.stat(path, settings.fsStatSettings, (error, stats) => { if (error !== null) { done(error); return; } const entry = { name, path, dirent: utils.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } done(null, entry); }); }; }); rpl(tasks, (rplError, entries) => { if (rplError !== null) { callFailureCallback(callback, rplError); return; } callSuccessCallback(callback, entries); }); }); } exports.readdir = readdir; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, result) { callback(null, result); } node_modules/@nodelib/fs.scandir/out/constants.d.ts 0000664 00000000166 15114743311 0016411 0 ustar 00 /** * IS `true` for Node.js 10.10 and greater. */ export declare const IS_SUPPORT_READDIR_WITH_FILE_TYPES: boolean; node_modules/@nodelib/fs.scandir/out/index.js 0000664 00000001761 15114743311 0015252 0 ustar 00 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Settings = exports.scandirSync = exports.scandir = void 0; const async = require("./providers/async"); const sync = require("./providers/sync"); const settings_1 = require("./settings"); exports.Settings = settings_1.default; function scandir(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async.read(path, getSettings(), optionsOrSettingsOrCallback); return; } async.read(path, getSettings(optionsOrSettingsOrCallback), callback); } exports.scandir = scandir; function scandirSync(path, optionsOrSettings) { const settings = getSettings(optionsOrSettings); return sync.read(path, settings); } exports.scandirSync = scandirSync; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; } return new settings_1.default(settingsOrOptions); } node_modules/@nodelib/fs.scandir/package.json 0000664 00000002213 15114743311 0015255 0 ustar 00 { "name": "@nodelib/fs.scandir", "version": "2.1.5", "description": "List files and directories inside the specified directory", "license": "MIT", "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.scandir", "keywords": [ "NodeLib", "fs", "FileSystem", "file system", "scandir", "readdir", "dirent" ], "engines": { "node": ">= 8" }, "files": [ "out/**", "!out/**/*.map", "!out/**/*.spec.*" ], "main": "out/index.js", "typings": "out/index.d.ts", "scripts": { "clean": "rimraf {tsconfig.tsbuildinfo,out}", "lint": "eslint \"src/**/*.ts\" --cache", "compile": "tsc -b .", "compile:watch": "tsc -p . --watch --sourceMap", "test": "mocha \"out/**/*.spec.js\" -s 0", "build": "npm run clean && npm run compile && npm run lint && npm test", "watch": "npm run clean && npm run compile:watch" }, "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" }, "devDependencies": { "@nodelib/fs.macchiato": "1.0.4", "@types/run-parallel": "^1.1.0" }, "gitHead": "d6a7960d5281d3dd5f8e2efba49bb552d090f562" } node_modules/@nodelib/fs.scandir/LICENSE 0000664 00000002067 15114743311 0014003 0 ustar 00 The MIT License (MIT) Copyright (c) Denis Malinochkin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/@nodelib/fs.scandir/README.md 0000664 00000011537 15114743311 0014257 0 ustar 00 # @nodelib/fs.scandir > List files and directories inside the specified directory. ## :bulb: Highlights The package is aimed at obtaining information about entries in the directory. * :moneybag: Returns useful information: `name`, `path`, `dirent` and `stats` (optional). * :gear: On Node.js 10.10+ uses the mechanism without additional calls to determine the entry type. See [`old` and `modern` mode](#old-and-modern-mode). * :link: Can safely work with broken symbolic links. ## Install ```console npm install @nodelib/fs.scandir ``` ## Usage ```ts import * as fsScandir from '@nodelib/fs.scandir'; fsScandir.scandir('path', (error, stats) => { /* … */ }); ``` ## API ### .scandir(path, [optionsOrSettings], callback) Returns an array of plain objects ([`Entry`](#entry)) with information about entry for provided path with standard callback-style. ```ts fsScandir.scandir('path', (error, entries) => { /* … */ }); fsScandir.scandir('path', {}, (error, entries) => { /* … */ }); fsScandir.scandir('path', new fsScandir.Settings(), (error, entries) => { /* … */ }); ``` ### .scandirSync(path, [optionsOrSettings]) Returns an array of plain objects ([`Entry`](#entry)) with information about entry for provided path. ```ts const entries = fsScandir.scandirSync('path'); const entries = fsScandir.scandirSync('path', {}); const entries = fsScandir.scandirSync(('path', new fsScandir.Settings()); ``` #### path * Required: `true` * Type: `string | Buffer | URL` A path to a file. If a URL is provided, it must use the `file:` protocol. #### optionsOrSettings * Required: `false` * Type: `Options | Settings` * Default: An instance of `Settings` class An [`Options`](#options) object or an instance of [`Settings`](#settingsoptions) class. > :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. ### Settings([options]) A class of full settings of the package. ```ts const settings = new fsScandir.Settings({ followSymbolicLinks: false }); const entries = fsScandir.scandirSync('path', settings); ``` ## Entry * `name` — The name of the entry (`unknown.txt`). * `path` — The path of the entry relative to call directory (`root/unknown.txt`). * `dirent` — An instance of [`fs.Dirent`](./src/types/index.ts) class. On Node.js below 10.10 will be emulated by [`DirentFromStats`](./src/utils/fs.ts) class. * `stats` (optional) — An instance of `fs.Stats` class. For example, the `scandir` call for `tools` directory with one directory inside: ```ts { dirent: Dirent { name: 'typedoc', /* … */ }, name: 'typedoc', path: 'tools/typedoc' } ``` ## Options ### stats * Type: `boolean` * Default: `false` Adds an instance of `fs.Stats` class to the [`Entry`](#entry). > :book: Always use `fs.readdir` without the `withFileTypes` option. ??TODO?? ### followSymbolicLinks * Type: `boolean` * Default: `false` Follow symbolic links or not. Call `fs.stat` on symbolic link if `true`. ### `throwErrorOnBrokenSymbolicLink` * Type: `boolean` * Default: `true` Throw an error when symbolic link is broken if `true` or safely use `lstat` call if `false`. ### `pathSegmentSeparator` * Type: `string` * Default: `path.sep` By default, this package uses the correct path separator for your OS (`\` on Windows, `/` on Unix-like systems). But you can set this option to any separator character(s) that you want to use instead. ### `fs` * Type: [`FileSystemAdapter`](./src/adapters/fs.ts) * Default: A default FS methods By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. ```ts interface FileSystemAdapter { lstat?: typeof fs.lstat; stat?: typeof fs.stat; lstatSync?: typeof fs.lstatSync; statSync?: typeof fs.statSync; readdir?: typeof fs.readdir; readdirSync?: typeof fs.readdirSync; } const settings = new fsScandir.Settings({ fs: { lstat: fakeLstat } }); ``` ## `old` and `modern` mode This package has two modes that are used depending on the environment and parameters of use. ### old * Node.js below `10.10` or when the `stats` option is enabled When working in the old mode, the directory is read first (`fs.readdir`), then the type of entries is determined (`fs.lstat` and/or `fs.stat` for symbolic links). ### modern * Node.js 10.10+ and the `stats` option is disabled In the modern mode, reading the directory (`fs.readdir` with the `withFileTypes` option) is combined with obtaining information about its entries. An additional call for symbolic links (`fs.stat`) is still present. This mode makes fewer calls to the file system. It's faster. ## Changelog See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. ## License This software is released under the terms of the MIT license. node_modules/yallist/package.json 0000664 00000001214 15114743311 0013170 0 ustar 00 { "name": "yallist", "version": "4.0.0", "description": "Yet Another Linked List", "main": "yallist.js", "directories": { "test": "test" }, "files": [ "yallist.js", "iterator.js" ], "dependencies": {}, "devDependencies": { "tap": "^12.1.0" }, "scripts": { "test": "tap test/*.js --100", "preversion": "npm test", "postversion": "npm publish", "postpublish": "git push origin --all; git push origin --tags" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/yallist.git" }, "author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)", "license": "ISC" } node_modules/yallist/iterator.js 0000664 00000000317 15114743311 0013074 0 ustar 00 'use strict' module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } node_modules/yallist/LICENSE 0000664 00000001375 15114743311 0011717 0 ustar 00 The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node_modules/yallist/yallist.js 0000664 00000020333 15114743311 0012724 0 ustar 00 'use strict' module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present require('./iterator.js')(Yallist) } catch (er) {} node_modules/yallist/README.md 0000664 00000011155 15114743311 0012166 0 ustar 00 # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [](https://travis-ci.org/isaacs/yallist) [](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) node_modules/picocolors/package.json 0000664 00000001050 15114743311 0013661 0 ustar 00 { "name": "picocolors", "version": "1.1.1", "main": "./picocolors.js", "types": "./picocolors.d.ts", "browser": { "./picocolors.js": "./picocolors.browser.js" }, "sideEffects": false, "description": "The tiniest and the fastest library for terminal output formatting with ANSI colors", "files": [ "picocolors.*", "types.d.ts" ], "keywords": [ "terminal", "colors", "formatting", "cli", "console" ], "author": "Alexey Raspopov", "repository": "alexeyraspopov/picocolors", "license": "ISC" } node_modules/picocolors/picocolors.js 0000664 00000005147 15114743311 0014120 0 ustar 00 let p = process || {}, argv = p.argv || [], env = p.env || {} let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI) let formatter = (open, close, replace = open) => input => { let string = "" + input, index = string.indexOf(close, open.length) return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close } let replaceClose = (string, close, replace, index) => { let result = "", cursor = 0 do { result += string.substring(cursor, index) + replace cursor = index + close.length index = string.indexOf(close, cursor) } while (~index) return result + string.substring(cursor) } let createColors = (enabled = isColorSupported) => { let f = enabled ? formatter : () => String return { isColorSupported: enabled, reset: f("\x1b[0m", "\x1b[0m"), bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), italic: f("\x1b[3m", "\x1b[23m"), underline: f("\x1b[4m", "\x1b[24m"), inverse: f("\x1b[7m", "\x1b[27m"), hidden: f("\x1b[8m", "\x1b[28m"), strikethrough: f("\x1b[9m", "\x1b[29m"), black: f("\x1b[30m", "\x1b[39m"), red: f("\x1b[31m", "\x1b[39m"), green: f("\x1b[32m", "\x1b[39m"), yellow: f("\x1b[33m", "\x1b[39m"), blue: f("\x1b[34m", "\x1b[39m"), magenta: f("\x1b[35m", "\x1b[39m"), cyan: f("\x1b[36m", "\x1b[39m"), white: f("\x1b[37m", "\x1b[39m"), gray: f("\x1b[90m", "\x1b[39m"), bgBlack: f("\x1b[40m", "\x1b[49m"), bgRed: f("\x1b[41m", "\x1b[49m"), bgGreen: f("\x1b[42m", "\x1b[49m"), bgYellow: f("\x1b[43m", "\x1b[49m"), bgBlue: f("\x1b[44m", "\x1b[49m"), bgMagenta: f("\x1b[45m", "\x1b[49m"), bgCyan: f("\x1b[46m", "\x1b[49m"), bgWhite: f("\x1b[47m", "\x1b[49m"), blackBright: f("\x1b[90m", "\x1b[39m"), redBright: f("\x1b[91m", "\x1b[39m"), greenBright: f("\x1b[92m", "\x1b[39m"), yellowBright: f("\x1b[93m", "\x1b[39m"), blueBright: f("\x1b[94m", "\x1b[39m"), magentaBright: f("\x1b[95m", "\x1b[39m"), cyanBright: f("\x1b[96m", "\x1b[39m"), whiteBright: f("\x1b[97m", "\x1b[39m"), bgBlackBright: f("\x1b[100m", "\x1b[49m"), bgRedBright: f("\x1b[101m", "\x1b[49m"), bgGreenBright: f("\x1b[102m", "\x1b[49m"), bgYellowBright: f("\x1b[103m", "\x1b[49m"), bgBlueBright: f("\x1b[104m", "\x1b[49m"), bgMagentaBright: f("\x1b[105m", "\x1b[49m"), bgCyanBright: f("\x1b[106m", "\x1b[49m"), bgWhiteBright: f("\x1b[107m", "\x1b[49m"), } } module.exports = createColors() module.exports.createColors = createColors node_modules/picocolors/LICENSE 0000664 00000001423 15114743311 0012404 0 ustar 00 ISC License Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node_modules/picocolors/picocolors.browser.js 0000664 00000001126 15114743311 0015573 0 ustar 00 var x=String; var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}}; module.exports=create(); module.exports.createColors = create; node_modules/picocolors/types.d.ts 0000664 00000001765 15114743311 0013346 0 ustar 00 export type Formatter = (input: string | number | null | undefined) => string export interface Colors { isColorSupported: boolean reset: Formatter bold: Formatter dim: Formatter italic: Formatter underline: Formatter inverse: Formatter hidden: Formatter strikethrough: Formatter black: Formatter red: Formatter green: Formatter yellow: Formatter blue: Formatter magenta: Formatter cyan: Formatter white: Formatter gray: Formatter bgBlack: Formatter bgRed: Formatter bgGreen: Formatter bgYellow: Formatter bgBlue: Formatter bgMagenta: Formatter bgCyan: Formatter bgWhite: Formatter blackBright: Formatter redBright: Formatter greenBright: Formatter yellowBright: Formatter blueBright: Formatter magentaBright: Formatter cyanBright: Formatter whiteBright: Formatter bgBlackBright: Formatter bgRedBright: Formatter bgGreenBright: Formatter bgYellowBright: Formatter bgBlueBright: Formatter bgMagentaBright: Formatter bgCyanBright: Formatter bgWhiteBright: Formatter } node_modules/picocolors/picocolors.d.ts 0000664 00000000212 15114743311 0014340 0 ustar 00 import { Colors } from "./types" declare const picocolors: Colors & { createColors: (enabled?: boolean) => Colors } export = picocolors node_modules/picocolors/README.md 0000664 00000001156 15114743311 0012661 0 ustar 00 # picocolors The tiniest and the fastest library for terminal output formatting with ANSI colors. ```javascript import pc from "picocolors" console.log( pc.green(`How are ${pc.italic(`you`)} doing?`) ) ``` - **No dependencies.** - **14 times** smaller and **2 times** faster than chalk. - Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist. - Node.js v6+ & browsers support. Support for both CJS and ESM projects. - TypeScript type declarations included. - [`NO_COLOR`](https://no-color.org/) friendly. ## Docs Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub. node_modules/glob-parent/package.json 0000664 00000002121 15114743311 0013717 0 ustar 00 { "name": "glob-parent", "version": "5.1.2", "description": "Extract the non-magic parent path from a glob string.", "author": "Gulp Team <team@gulpjs.com> (https://gulpjs.com/)", "contributors": [ "Elan Shanker (https://github.com/es128)", "Blaine Bublitz <blaine.bublitz@gmail.com>" ], "repository": "gulpjs/glob-parent", "license": "ISC", "engines": { "node": ">= 6" }, "main": "index.js", "files": [ "LICENSE", "index.js" ], "scripts": { "lint": "eslint .", "pretest": "npm run lint", "test": "nyc mocha --async-only", "azure-pipelines": "nyc mocha --async-only --reporter xunit -O output=test.xunit", "coveralls": "nyc report --reporter=text-lcov | coveralls" }, "dependencies": { "is-glob": "^4.0.1" }, "devDependencies": { "coveralls": "^3.0.11", "eslint": "^2.13.1", "eslint-config-gulp": "^3.0.1", "expect": "^1.20.2", "mocha": "^6.0.2", "nyc": "^13.3.0" }, "keywords": [ "glob", "parent", "strip", "path", "dirname", "directory", "base", "wildcard" ] } node_modules/glob-parent/LICENSE 0000664 00000001361 15114743311 0012443 0 ustar 00 The ISC License Copyright (c) 2015, 2019 Elan Shanker Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node_modules/glob-parent/index.js 0000664 00000002140 15114743311 0013077 0 ustar 00 'use strict'; var isGlob = require('is-glob'); var pathPosixDirname = require('path').posix.dirname; var isWin32 = require('os').platform() === 'win32'; var slash = '/'; var backslash = /\\/g; var enclosure = /[\{\[].*[\}\]]$/; var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; /** * @param {string} str * @param {Object} opts * @param {boolean} [opts.flipBackslashes=true] * @returns {string} */ module.exports = function globParent(str, opts) { var options = Object.assign({ flipBackslashes: true }, opts); // flip windows path separators if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { str = str.replace(backslash, slash); } // special case for strings ending in enclosure containing path separator if (enclosure.test(str)) { str += slash; } // preserves full path in case of trailing path separator str += 'a'; // remove path parts that are globby do { str = pathPosixDirname(str); } while (isGlob(str) || globby.test(str)); // remove escape chars and return result return str.replace(escaped, '$1'); }; node_modules/glob-parent/CHANGELOG.md 0000664 00000010636 15114743311 0013254 0 ustar 00 ### [5.1.2](https://github.com/gulpjs/glob-parent/compare/v5.1.1...v5.1.2) (2021-03-06) ### Bug Fixes * eliminate ReDoS ([#36](https://github.com/gulpjs/glob-parent/issues/36)) ([f923116](https://github.com/gulpjs/glob-parent/commit/f9231168b0041fea3f8f954b3cceb56269fc6366)) ### [5.1.1](https://github.com/gulpjs/glob-parent/compare/v5.1.0...v5.1.1) (2021-01-27) ### Bug Fixes * unescape exclamation mark ([#26](https://github.com/gulpjs/glob-parent/issues/26)) ([a98874f](https://github.com/gulpjs/glob-parent/commit/a98874f1a59e407f4fb1beb0db4efa8392da60bb)) ## [5.1.0](https://github.com/gulpjs/glob-parent/compare/v5.0.0...v5.1.0) (2021-01-27) ### Features * add `flipBackslashes` option to disable auto conversion of slashes (closes [#24](https://github.com/gulpjs/glob-parent/issues/24)) ([#25](https://github.com/gulpjs/glob-parent/issues/25)) ([eecf91d](https://github.com/gulpjs/glob-parent/commit/eecf91d5e3834ed78aee39c4eaaae654d76b87b3)) ## [5.0.0](https://github.com/gulpjs/glob-parent/compare/v4.0.0...v5.0.0) (2021-01-27) ### ⚠ BREAKING CHANGES * Drop support for node <6 & bump dependencies ### Miscellaneous Chores * Drop support for node <6 & bump dependencies ([896c0c0](https://github.com/gulpjs/glob-parent/commit/896c0c00b4e7362f60b96e7fc295ae929245255a)) ## [4.0.0](https://github.com/gulpjs/glob-parent/compare/v3.1.0...v4.0.0) (2021-01-27) ### ⚠ BREAKING CHANGES * question marks are valid path characters on Windows so avoid flagging as a glob when alone * Update is-glob dependency ### Features * hoist regexps and strings for performance gains ([4a80667](https://github.com/gulpjs/glob-parent/commit/4a80667c69355c76a572a5892b0f133c8e1f457e)) * question marks are valid path characters on Windows so avoid flagging as a glob when alone ([2a551dd](https://github.com/gulpjs/glob-parent/commit/2a551dd0dc3235e78bf3c94843d4107072d17841)) * Update is-glob dependency ([e41fcd8](https://github.com/gulpjs/glob-parent/commit/e41fcd895d1f7bc617dba45c9d935a7949b9c281)) ## [3.1.0](https://github.com/gulpjs/glob-parent/compare/v3.0.1...v3.1.0) (2021-01-27) ### Features * allow basic win32 backslash use ([272afa5](https://github.com/gulpjs/glob-parent/commit/272afa5fd070fc0f796386a5993d4ee4a846988b)) * handle extglobs (parentheses) containing separators ([7db1bdb](https://github.com/gulpjs/glob-parent/commit/7db1bdb0756e55fd14619e8ce31aa31b17b117fd)) * new approach to braces/brackets handling ([8269bd8](https://github.com/gulpjs/glob-parent/commit/8269bd89290d99fac9395a354fb56fdcdb80f0be)) * pre-process braces/brackets sections ([9ef8a87](https://github.com/gulpjs/glob-parent/commit/9ef8a87f66b1a43d0591e7a8e4fc5a18415ee388)) * preserve escaped brace/bracket at end of string ([8cfb0ba](https://github.com/gulpjs/glob-parent/commit/8cfb0ba84202d51571340dcbaf61b79d16a26c76)) ### Bug Fixes * trailing escaped square brackets ([99ec9fe](https://github.com/gulpjs/glob-parent/commit/99ec9fecc60ee488ded20a94dd4f18b4f55c4ccf)) ### [3.0.1](https://github.com/gulpjs/glob-parent/compare/v3.0.0...v3.0.1) (2021-01-27) ### Features * use path-dirname ponyfill ([cdbea5f](https://github.com/gulpjs/glob-parent/commit/cdbea5f32a58a54e001a75ddd7c0fccd4776aacc)) ### Bug Fixes * unescape glob-escaped dirnames on output ([598c533](https://github.com/gulpjs/glob-parent/commit/598c533bdf49c1428bc063aa9b8db40c5a86b030)) ## [3.0.0](https://github.com/gulpjs/glob-parent/compare/v2.0.0...v3.0.0) (2021-01-27) ### ⚠ BREAKING CHANGES * update is-glob dependency ### Features * update is-glob dependency ([5c5f8ef](https://github.com/gulpjs/glob-parent/commit/5c5f8efcee362a8e7638cf8220666acd8784f6bd)) ## [2.0.0](https://github.com/gulpjs/glob-parent/compare/v1.3.0...v2.0.0) (2021-01-27) ### Features * move up to dirname regardless of glob characters ([f97fb83](https://github.com/gulpjs/glob-parent/commit/f97fb83be2e0a9fc8d3b760e789d2ecadd6aa0c2)) ## [1.3.0](https://github.com/gulpjs/glob-parent/compare/v1.2.0...v1.3.0) (2021-01-27) ## [1.2.0](https://github.com/gulpjs/glob-parent/compare/v1.1.0...v1.2.0) (2021-01-27) ### Reverts * feat: make regex test strings smaller ([dc80fa9](https://github.com/gulpjs/glob-parent/commit/dc80fa9658dca20549cfeba44bbd37d5246fcce0)) ## [1.1.0](https://github.com/gulpjs/glob-parent/compare/v1.0.0...v1.1.0) (2021-01-27) ### Features * make regex test strings smaller ([cd83220](https://github.com/gulpjs/glob-parent/commit/cd832208638f45169f986d80fcf66e401f35d233)) ## 1.0.0 (2021-01-27) node_modules/glob-parent/README.md 0000664 00000011046 15114743311 0012716 0 ustar 00 <p align="center"> <a href="https://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # glob-parent [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Azure Pipelines Build Status][azure-pipelines-image]][azure-pipelines-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] Extract the non-magic parent path from a glob string. ## Usage ```js var globParent = require('glob-parent'); globParent('path/to/*.js'); // 'path/to' globParent('/root/path/to/*.js'); // '/root/path/to' globParent('/*.js'); // '/' globParent('*.js'); // '.' globParent('**/*.js'); // '.' globParent('path/{to,from}'); // 'path' globParent('path/!(to|from)'); // 'path' globParent('path/?(to|from)'); // 'path' globParent('path/+(to|from)'); // 'path' globParent('path/*(to|from)'); // 'path' globParent('path/@(to|from)'); // 'path' globParent('path/**/*'); // 'path' // if provided a non-glob path, returns the nearest dir globParent('path/foo/bar.js'); // 'path/foo' globParent('path/foo/'); // 'path/foo' globParent('path/foo'); // 'path' (see issue #3 for details) ``` ## API ### `globParent(maybeGlobString, [options])` Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. #### options ```js { // Disables the automatic conversion of slashes for Windows flipBackslashes: true } ``` ## Escaping The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: - `?` (question mark) unless used as a path segment alone - `*` (asterisk) - `|` (pipe) - `(` (opening parenthesis) - `)` (closing parenthesis) - `{` (opening curly brace) - `}` (closing curly brace) - `[` (opening bracket) - `]` (closing bracket) **Example** ```js globParent('foo/[bar]/') // 'foo' globParent('foo/\\[bar]/') // 'foo/[bar]' ``` ## Limitations ### Braces & Brackets This library attempts a quick and imperfect method of determining which path parts have glob magic without fully parsing/lexing the pattern. There are some advanced use cases that can trip it up, such as nested braces where the outer pair is escaped and the inner one contains a path separator. If you find yourself in the unlikely circumstance of being affected by this or need to ensure higher-fidelity glob handling in your library, it is recommended that you pre-process your input with [expand-braces] and/or [expand-brackets]. ### Windows Backslashes are not valid path separators for globs. If a path with backslashes is provided anyway, for simple cases, glob-parent will replace the path separator for you and return the non-glob parent path (now with forward-slashes, which are still valid as Windows path separators). This cannot be used in conjunction with escape characters. ```js // BAD globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' // GOOD globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' ``` If you are using escape characters for a pattern without path parts (i.e. relative to `cwd`), prefix with `./` to avoid confusing glob-parent. ```js // BAD globParent('foo \\[bar]') // 'foo ' globParent('foo \\[bar]*') // 'foo ' // GOOD globParent('./foo \\[bar]') // 'foo [bar]' globParent('./foo \\[bar]*') // '.' ``` ## License ISC [expand-braces]: https://github.com/jonschlinkert/expand-braces [expand-brackets]: https://github.com/jonschlinkert/expand-brackets [downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg [npm-url]: https://www.npmjs.com/package/glob-parent [npm-image]: https://img.shields.io/npm/v/glob-parent.svg [azure-pipelines-url]: https://dev.azure.com/gulpjs/gulp/_build/latest?definitionId=2&branchName=master [azure-pipelines-image]: https://dev.azure.com/gulpjs/gulp/_apis/build/status/glob-parent?branchName=master [travis-url]: https://travis-ci.org/gulpjs/glob-parent [travis-image]: https://img.shields.io/travis/gulpjs/glob-parent.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/glob-parent [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/glob-parent.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent [coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg node_modules/onetime/license 0000664 00000002135 15114743311 0012231 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/onetime/package.json 0000664 00000001313 15114743311 0013147 0 ustar 00 { "name": "onetime", "version": "5.1.2", "description": "Ensure a function is only called once", "license": "MIT", "repository": "sindresorhus/onetime", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "engines": { "node": ">=6" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "once", "function", "one", "onetime", "func", "fn", "single", "call", "called", "prevent" ], "dependencies": { "mimic-fn": "^2.1.0" }, "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.1", "xo": "^0.24.0" } } node_modules/onetime/readme.md 0000664 00000003652 15114743311 0012450 0 ustar 00 # onetime [](https://travis-ci.com/github/sindresorhus/onetime) > Ensure a function is only called once When called multiple times it will return the return value from the first call. *Unlike the module [once](https://github.com/isaacs/once), this one isn't naughty and extending `Function.prototype`.* ## Install ``` $ npm install onetime ``` ## Usage ```js const onetime = require('onetime'); let i = 0; const foo = onetime(() => ++i); foo(); //=> 1 foo(); //=> 1 foo(); //=> 1 onetime.callCount(foo); //=> 3 ``` ```js const onetime = require('onetime'); const foo = onetime(() => {}, {throw: true}); foo(); foo(); //=> Error: Function `foo` can only be called once ``` ## API ### onetime(fn, options?) Returns a function that only calls `fn` once. #### fn Type: `Function` Function that should only be called once. #### options Type: `object` ##### throw Type: `boolean`\ Default: `false` Throw an error when called more than once. ### onetime.callCount(fn) Returns a number representing how many times `fn` has been called. Note: It throws an error if you pass in a function that is not wrapped by `onetime`. ```js const onetime = require('onetime'); const foo = onetime(() => {}); foo(); foo(); foo(); console.log(onetime.callCount(foo)); //=> 3 ``` #### fn Type: `Function` Function to get call count from. ## onetime for enterprise Available as part of the Tidelift Subscription. The maintainers of onetime and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-onetime?utm_source=npm-onetime&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) node_modules/onetime/index.d.ts 0000664 00000002353 15114743311 0012567 0 ustar 00 declare namespace onetime { interface Options { /** Throw an error when called more than once. @default false */ throw?: boolean; } } declare const onetime: { /** Ensure a function is only called once. When called multiple times it will return the return value from the first call. @param fn - Function that should only be called once. @returns A function that only calls `fn` once. @example ``` import onetime = require('onetime'); let i = 0; const foo = onetime(() => ++i); foo(); //=> 1 foo(); //=> 1 foo(); //=> 1 onetime.callCount(foo); //=> 3 ``` */ <ArgumentsType extends unknown[], ReturnType>( fn: (...arguments: ArgumentsType) => ReturnType, options?: onetime.Options ): (...arguments: ArgumentsType) => ReturnType; /** Get the number of times `fn` has been called. @param fn - Function to get call count from. @returns A number representing how many times `fn` has been called. @example ``` import onetime = require('onetime'); const foo = onetime(() => {}); foo(); foo(); foo(); console.log(onetime.callCount(foo)); //=> 3 ``` */ callCount(fn: (...arguments: any[]) => unknown): number; // TODO: Remove this for the next major release default: typeof onetime; }; export = onetime; node_modules/onetime/index.js 0000664 00000002140 15114743311 0012325 0 ustar 00 'use strict'; const mimicFn = require('mimic-fn'); const calledFunctions = new WeakMap(); const onetime = (function_, options = {}) => { if (typeof function_ !== 'function') { throw new TypeError('Expected a function'); } let returnValue; let callCount = 0; const functionName = function_.displayName || function_.name || '<anonymous>'; const onetime = function (...arguments_) { calledFunctions.set(onetime, ++callCount); if (callCount === 1) { returnValue = function_.apply(this, arguments_); function_ = null; } else if (options.throw === true) { throw new Error(`Function \`${functionName}\` can only be called once`); } return returnValue; }; mimicFn(onetime, function_); calledFunctions.set(onetime, callCount); return onetime; }; module.exports = onetime; // TODO: Remove this for the next major release module.exports.default = onetime; module.exports.callCount = function_ => { if (!calledFunctions.has(function_)) { throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); } return calledFunctions.get(function_); }; node_modules/stdin-discarder/license 0000664 00000002135 15114743311 0013650 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/stdin-discarder/package.json 0000664 00000001373 15114743311 0014574 0 ustar 00 { "name": "stdin-discarder", "version": "0.2.2", "description": "Discard stdin input except for Ctrl+C", "license": "MIT", "repository": "sindresorhus/stdin-discarder", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "default": "./index.js" }, "sideEffects": false, "engines": { "node": ">=18" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "stdin", "process", "standard", "discard", "ignore", "input" ], "devDependencies": { "ava": "^6.0.1", "tsd": "^0.29.0", "xo": "^0.56.0" } } node_modules/stdin-discarder/readme.md 0000664 00000001632 15114743311 0014063 0 ustar 00 # stdin-discarder > Discard stdin input except for Ctrl+C This can be useful to prevent stdin input from interfering with stdout output. For example, you are showing a spinner, and if the user presses a key, it would interfere with the spinner, causing visual glitches. This package prevents such problems. This has no effect on Windows as there is no good way to implement discarding stdin properly there. This package is used by [`ora`](https://github.com/sindresorhus/ora) for its [`discardStdin`](https://github.com/sindresorhus/ora#discardstdin) option. ## Install ```sh npm install stdin-discarder ``` ## Usage ```js import stdinDiscarder from 'stdin-discarder'; stdinDiscarder.start(); ``` ## API ### stdinDiscarder.start() Start discarding stdin. ### stdinDiscarder.stop() Stop discarding stdin. ## Related - [hook-std](https://github.com/sindresorhus/hook-std) - Hook and modify stdout and stderr node_modules/stdin-discarder/index.d.ts 0000664 00000000246 15114743311 0014205 0 ustar 00 declare const stdinDiscarder: { /** Start discarding stdin. */ start(): void; /** Stop discarding stdin. */ stop(): void; }; export default stdinDiscarder; node_modules/stdin-discarder/index.js 0000664 00000002061 15114743311 0013746 0 ustar 00 import process from 'node:process'; const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code class StdinDiscarder { #activeCount = 0; start() { this.#activeCount++; if (this.#activeCount === 1) { this.#realStart(); } } stop() { if (this.#activeCount <= 0) { throw new Error('`stop` called more times than `start`'); } this.#activeCount--; if (this.#activeCount === 0) { this.#realStop(); } } #realStart() { // No known way to make it work reliably on Windows. if (process.platform === 'win32' || !process.stdin.isTTY) { return; } process.stdin.setRawMode(true); process.stdin.on('data', this.#handleInput); process.stdin.resume(); } #realStop() { if (!process.stdin.isTTY) { return; } process.stdin.off('data', this.#handleInput); process.stdin.pause(); process.stdin.setRawMode(false); } #handleInput(chunk) { // Allow Ctrl+C to gracefully exit. if (chunk[0] === ASCII_ETX_CODE) { process.emit('SIGINT'); } } } const stdinDiscarder = new StdinDiscarder(); export default stdinDiscarder; node_modules/.package-lock.json 0000664 00000072667 15114743311 0012537 0 ustar 00 { "name": "81b3c76afcd2c892", "lockfileVersion": 3, "requires": true, "packages": { "node_modules/@clack/core": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/@clack/core/-/core-0.3.5.tgz", "integrity": "sha512-5cfhQNH+1VQ2xLQlmzXMqUoiaH0lRBq9/CLW9lTyMbuKLC3+xEK01tHVvyut++mLOn5urSHmkm6I0Lg9MaJSTQ==", "dependencies": { "picocolors": "^1.0.0", "sisteransi": "^1.0.5" } }, "node_modules/@clack/prompts": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-0.7.0.tgz", "integrity": "sha512-0MhX9/B4iL6Re04jPrttDm+BsP8y6mS7byuv0BvXgdXhbV5PdlsHt55dvNsuBCPZ7xq1oTAOOuotR9NFbQyMSA==", "bundleDependencies": [ "is-unicode-supported" ], "dependencies": { "@clack/core": "^0.3.3", "is-unicode-supported": "*", "picocolors": "^1.0.0", "sisteransi": "^1.0.5" } }, "node_modules/@clack/prompts/node_modules/is-unicode-supported": { "version": "1.3.0", "inBundle": true, "license": "MIT", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" }, "engines": { "node": ">= 8" } }, "node_modules/@nodelib/fs.stat": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", "engines": { "node": ">= 8" } }, "node_modules/@nodelib/fs.walk": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" }, "engines": { "node": ">= 8" } }, "node_modules/@types/tinycolor2": { "version": "1.4.6", "resolved": "https://registry.npmjs.org/@types/tinycolor2/-/tinycolor2-1.4.6.tgz", "integrity": "sha512-iEN8J0BoMnsWBqjVbWH/c0G0Hh7O21lpR2/+PrvAVgWdzL7eexIFm4JN/Wn10PTcmNdtS6U67r499mlWMXOxNw==" }, "node_modules/@winches/prompts": { "version": "0.0.7", "resolved": "https://registry.npmjs.org/@winches/prompts/-/prompts-0.0.7.tgz", "integrity": "sha512-H/UlFlm83C6zkYn3CK4GF2VMpAlyjO3o623yamOyHwSaehhnj7oAJmklvr73UVMqu6Q+rl4Bzs3PBmxGB8cJVg==", "dependencies": { "kleur": "^4.0.1", "sisteransi": "^1.0.5" }, "engines": { "node": ">= 14" } }, "node_modules/ansi-regex": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, "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==", "dependencies": { "color-convert": "^2.0.1" }, "engines": { "node": ">=8" }, "funding": { "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, "node_modules/async-retry": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/async-retry/-/async-retry-1.3.3.tgz", "integrity": "sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw==", "dependencies": { "retry": "0.13.1" } }, "node_modules/braces": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "dependencies": { "fill-range": "^7.1.1" }, "engines": { "node": ">=8" } }, "node_modules/chalk": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", "engines": { "node": "^12.17.0 || ^14.13 || >=16.0.0" }, "funding": { "url": "https://github.com/chalk/chalk?sponsor=1" } }, "node_modules/chownr": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", "engines": { "node": ">=10" } }, "node_modules/cli-cursor": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", "dependencies": { "restore-cursor": "^4.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/cli-spinners": { "version": "2.9.2", "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", "engines": { "node": ">=6" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "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==", "dependencies": { "color-name": "~1.1.4" }, "engines": { "node": ">=7.0.0" } }, "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==" }, "node_modules/commander": { "version": "11.0.0", "resolved": "https://registry.npmjs.org/commander/-/commander-11.0.0.tgz", "integrity": "sha512-9HMlXtt/BNoYr8ooyjjNRdIilOTkVJXB+GhxMTtOKwk0R4j4lS4NpjuqmRxroBfnfTSHQIHQB7wryHhXarNjmQ==", "engines": { "node": ">=16" } }, "node_modules/compare-versions": { "version": "6.1.1", "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz", "integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==" }, "node_modules/emoji-regex": { "version": "10.4.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.4.0.tgz", "integrity": "sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw==" }, "node_modules/fast-glob": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.4" }, "engines": { "node": ">=8.6.0" } }, "node_modules/fastq": { "version": "1.19.1", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", "dependencies": { "reusify": "^1.0.4" } }, "node_modules/fill-range": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "dependencies": { "to-regex-range": "^5.0.1" }, "engines": { "node": ">=8" } }, "node_modules/find-up": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-7.0.0.tgz", "integrity": "sha512-YyZM99iHrqLKjmt4LJDj58KI+fYyufRLBSYcqycxf//KpBk9FoewoGX0450m9nB44qrZnovzC2oeP5hUibxc/g==", "dependencies": { "locate-path": "^7.2.0", "path-exists": "^5.0.0", "unicorn-magic": "^0.1.0" }, "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/fs-minipass": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", "dependencies": { "minipass": "^3.0.0" }, "engines": { "node": ">= 8" } }, "node_modules/fs-minipass/node_modules/minipass": { "version": "3.3.6", "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", "dependencies": { "yallist": "^4.0.0" }, "engines": { "node": ">=8" } }, "node_modules/get-east-asian-width": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.3.0.tgz", "integrity": "sha512-vpeMIQKxczTD/0s2CdEWHcb0eeJe6TFjxb+J5xgX7hScxqrGuyjmv4c1D4A/gelKfyox0gJJwIHF+fLjeaM8kQ==", "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/glob-parent": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dependencies": { "is-glob": "^4.0.1" }, "engines": { "node": ">= 6" } }, "node_modules/gradient-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/gradient-string/-/gradient-string-2.0.2.tgz", "integrity": "sha512-rEDCuqUQ4tbD78TpzsMtt5OIf0cBCSDWSJtUDaF6JsAh+k0v9r++NzxNEG87oDZx9ZwGhD8DaezR2L/yrw0Jdw==", "dependencies": { "chalk": "^4.1.2", "tinygradient": "^1.1.5" }, "engines": { "node": ">=10" } }, "node_modules/gradient-string/node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "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/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "engines": { "node": ">=8" } }, "node_modules/heroui-cli": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/heroui-cli/-/heroui-cli-1.2.3.tgz", "integrity": "sha512-q5Cs+jjogTI5LQLKatQtp1XAn/rpgB30G+IUvVtzwEX4NTl3mNM2RCZzlRvf3mNqltGtiyBq2hoBZyLr/XMl1g==", "dependencies": { "@clack/prompts": "0.7.0", "@winches/prompts": "0.0.7", "async-retry": "1.3.3", "chalk": "5.3.0", "commander": "11.0.0", "compare-versions": "6.1.1", "fast-glob": "3.3.2", "find-up": "7.0.0", "gradient-string": "2.0.2", "ora": "8.0.1", "pathe": "1.1.2", "tar": "6.2.1" }, "bin": { "heroui": "dist/index.js" }, "engines": { "pnpm": ">=9.x" } }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", "engines": { "node": ">=0.10.0" } }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dependencies": { "is-extglob": "^2.1.1" }, "engines": { "node": ">=0.10.0" } }, "node_modules/is-interactive": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "engines": { "node": ">=0.12.0" } }, "node_modules/is-unicode-supported": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/kleur": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", "engines": { "node": ">=6" } }, "node_modules/locate-path": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-7.2.0.tgz", "integrity": "sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==", "dependencies": { "p-locate": "^6.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/log-symbols": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-6.0.0.tgz", "integrity": "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw==", "dependencies": { "chalk": "^5.3.0", "is-unicode-supported": "^1.3.0" }, "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/log-symbols/node_modules/is-unicode-supported": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", "engines": { "node": ">= 8" } }, "node_modules/micromatch": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" }, "engines": { "node": ">=8.6" } }, "node_modules/mimic-fn": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", "engines": { "node": ">=6" } }, "node_modules/minipass": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", "engines": { "node": ">=8" } }, "node_modules/minizlib": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", "dependencies": { "minipass": "^3.0.0", "yallist": "^4.0.0" }, "engines": { "node": ">= 8" } }, "node_modules/minizlib/node_modules/minipass": { "version": "3.3.6", "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", "dependencies": { "yallist": "^4.0.0" }, "engines": { "node": ">=8" } }, "node_modules/mkdirp": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", "bin": { "mkdirp": "bin/cmd.js" }, "engines": { "node": ">=10" } }, "node_modules/onetime": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", "dependencies": { "mimic-fn": "^2.1.0" }, "engines": { "node": ">=6" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/ora": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/ora/-/ora-8.0.1.tgz", "integrity": "sha512-ANIvzobt1rls2BDny5fWZ3ZVKyD6nscLvfFRpQgfWsythlcsVUC9kL0zq6j2Z5z9wwp1kd7wpsD/T9qNPVLCaQ==", "dependencies": { "chalk": "^5.3.0", "cli-cursor": "^4.0.0", "cli-spinners": "^2.9.2", "is-interactive": "^2.0.0", "is-unicode-supported": "^2.0.0", "log-symbols": "^6.0.0", "stdin-discarder": "^0.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" }, "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/p-limit": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-4.0.0.tgz", "integrity": "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==", "dependencies": { "yocto-queue": "^1.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/p-locate": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-6.0.0.tgz", "integrity": "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==", "dependencies": { "p-limit": "^4.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/path-exists": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-5.0.0.tgz", "integrity": "sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } }, "node_modules/pathe": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz", "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==" }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "engines": { "node": ">=8.6" }, "funding": { "url": "https://github.com/sponsors/jonschlinkert" } }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ] }, "node_modules/restore-cursor": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/retry": { "version": "0.13.1", "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", "engines": { "node": ">= 4" } }, "node_modules/reusify": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", "engines": { "iojs": ">=1.0.0", "node": ">=0.10.0" } }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ], "dependencies": { "queue-microtask": "^1.2.2" } }, "node_modules/signal-exit": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" }, "node_modules/sisteransi": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==" }, "node_modules/stdin-discarder": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.2.2.tgz", "integrity": "sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==", "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/string-width": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" }, "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/strip-ansi": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", "dependencies": { "ansi-regex": "^6.0.1" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, "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==", "dependencies": { "has-flag": "^4.0.0" }, "engines": { "node": ">=8" } }, "node_modules/tar": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", "dependencies": { "chownr": "^2.0.0", "fs-minipass": "^2.0.0", "minipass": "^5.0.0", "minizlib": "^2.1.1", "mkdirp": "^1.0.3", "yallist": "^4.0.0" }, "engines": { "node": ">=10" } }, "node_modules/tinycolor2": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz", "integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==" }, "node_modules/tinygradient": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/tinygradient/-/tinygradient-1.1.5.tgz", "integrity": "sha512-8nIfc2vgQ4TeLnk2lFj4tRLvvJwEfQuabdsmvDdQPT0xlk9TaNtpGd6nNRxXoK6vQhN6RSzj+Cnp5tTQmpxmbw==", "dependencies": { "@types/tinycolor2": "^1.4.0", "tinycolor2": "^1.0.0" } }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dependencies": { "is-number": "^7.0.0" }, "engines": { "node": ">=8.0" } }, "node_modules/unicorn-magic": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.1.0.tgz", "integrity": "sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ==", "engines": { "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "node_modules/yocto-queue": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.1.tgz", "integrity": "sha512-AyeEbWOu/TAXdxlV9wmGcR0+yh2j3vYPGOECcIj2S7MkrLyC7ne+oye2BKTItt0ii2PHk4cDy+95+LshzbXnGg==", "engines": { "node": ">=12.20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } } } } node_modules/locate-path/license 0000664 00000002135 15114743311 0012772 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/locate-path/package.json 0000664 00000001534 15114743311 0013715 0 ustar 00 { "name": "locate-path", "version": "7.2.0", "description": "Get the first path that exists on disk of multiple paths", "license": "MIT", "repository": "sindresorhus/locate-path", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "locate", "path", "paths", "file", "files", "exists", "find", "finder", "search", "searcher", "array", "iterable", "iterator" ], "dependencies": { "p-locate": "^6.0.0" }, "devDependencies": { "ava": "^3.15.0", "tsd": "^0.17.0", "xo": "^0.44.0" } } node_modules/locate-path/readme.md 0000664 00000004015 15114743311 0013203 0 ustar 00 # locate-path > Get the first path that exists on disk of multiple paths ## Install ``` $ npm install locate-path ``` ## Usage Here we find the first file that exists on disk, in array order. ```js import {locatePath} from 'locate-path'; const files = [ 'unicorn.png', 'rainbow.png', // Only this one actually exists on disk 'pony.png' ]; console(await locatePath(files)); //=> 'rainbow' ``` ## API ### locatePath(paths, options?) Returns a `Promise<string>` for the first path that exists or `undefined` if none exists. #### paths Type: `Iterable<string>` The paths to check. #### options Type: `object` ##### concurrency Type: `number`\ Default: `Infinity`\ Minimum: `1` The number of concurrently pending promises. ##### preserveOrder Type: `boolean`\ Default: `true` Preserve `paths` order when searching. Disable this to improve performance if you don't care about the order. ##### cwd Type: `URL | string`\ Default: `process.cwd()` The current working directory. ##### type Type: `string`\ Default: `'file'`\ Values: `'file' | 'directory'` The type of paths that can match. ##### allowSymlinks Type: `boolean`\ Default: `true` Allow symbolic links to match if they point to the chosen path type. ### locatePathSync(paths, options?) Returns the first path that exists or `undefined` if none exists. #### paths Type: `Iterable<string>` The paths to check. #### options Type: `object` ##### cwd Same as above. ##### type Same as above. ##### allowSymlinks Same as above. ## Related - [path-exists](https://github.com/sindresorhus/path-exists) - Check if a path exists --- <div align="center"> <b> <a href="https://tidelift.com/subscription/pkg/npm-locate-path?utm_source=npm-locate-path&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> </b> <br> <sub> Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. </sub> </div> node_modules/locate-path/index.d.ts 0000664 00000003233 15114743311 0013326 0 ustar 00 export interface Options { /** The current working directory. @default process.cwd() */ readonly cwd?: URL | string; /** The type of path to match. @default 'file' */ readonly type?: 'file' | 'directory'; /** Allow symbolic links to match if they point to the requested path type. @default true */ readonly allowSymlinks?: boolean; } export interface AsyncOptions extends Options { /** The number of concurrently pending promises. Minimum: `1` @default Infinity */ readonly concurrency?: number; /** Preserve `paths` order when searching. Disable this to improve performance if you don't care about the order. @default true */ readonly preserveOrder?: boolean; } /** Get the first path that exists on disk of multiple paths. @param paths - The paths to check. @returns The first path that exists or `undefined` if none exists. @example ``` import {locatePath} from 'locate-path'; const files = [ 'unicorn.png', 'rainbow.png', // Only this one actually exists on disk 'pony.png' ]; console(await locatePath(files)); //=> 'rainbow' ``` */ export function locatePath( paths: Iterable<string>, options?: AsyncOptions ): Promise<string | undefined>; /** Synchronously get the first path that exists on disk of multiple paths. @param paths - The paths to check. @returns The first path that exists or `undefined` if none exists. @example ``` import {locatePathSync} from 'locate-path'; const files = [ 'unicorn.png', 'rainbow.png', // Only this one actually exists on disk 'pony.png' ]; console(locatePathSync(files)); //=> 'rainbow' ``` */ export function locatePathSync( paths: Iterable<string>, options?: Options ): string | undefined; node_modules/locate-path/index.js 0000664 00000002756 15114743311 0013103 0 ustar 00 import process from 'node:process'; import path from 'node:path'; import fs, {promises as fsPromises} from 'node:fs'; import {fileURLToPath} from 'node:url'; import pLocate from 'p-locate'; const typeMappings = { directory: 'isDirectory', file: 'isFile', }; function checkType(type) { if (Object.hasOwnProperty.call(typeMappings, type)) { return; } throw new Error(`Invalid type specified: ${type}`); } const matchType = (type, stat) => stat[typeMappings[type]](); const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath; export async function locatePath( paths, { cwd = process.cwd(), type = 'file', allowSymlinks = true, concurrency, preserveOrder, } = {}, ) { checkType(type); cwd = toPath(cwd); const statFunction = allowSymlinks ? fsPromises.stat : fsPromises.lstat; return pLocate(paths, async path_ => { try { const stat = await statFunction(path.resolve(cwd, path_)); return matchType(type, stat); } catch { return false; } }, {concurrency, preserveOrder}); } export function locatePathSync( paths, { cwd = process.cwd(), type = 'file', allowSymlinks = true, } = {}, ) { checkType(type); cwd = toPath(cwd); const statFunction = allowSymlinks ? fs.statSync : fs.lstatSync; for (const path_ of paths) { try { const stat = statFunction(path.resolve(cwd, path_), { throwIfNoEntry: false, }); if (!stat) { continue; } if (matchType(type, stat)) { return path_; } } catch {} } } node_modules/retry/License 0000664 00000002163 15114743311 0011677 0 ustar 00 Copyright (c) 2011: Tim Koschützki (tim@debuggable.com) Felix Geisendörfer (felix@debuggable.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/retry/example/stop.js 0000664 00000001570 15114743311 0013351 0 ustar 00 var retry = require('../lib/retry'); function attemptAsyncOperation(someInput, cb) { var opts = { retries: 2, factor: 2, minTimeout: 1 * 1000, maxTimeout: 2 * 1000, randomize: true }; var operation = retry.operation(opts); operation.attempt(function(currentAttempt) { failingAsyncOperation(someInput, function(err, result) { if (err && err.message === 'A fatal error') { operation.stop(); return cb(err); } if (operation.retry(err)) { return; } cb(operation.mainError(), operation.errors(), result); }); }); } attemptAsyncOperation('test input', function(err, errors, result) { console.warn('err:'); console.log(err); console.warn('result:'); console.log(result); }); function failingAsyncOperation(input, cb) { return setImmediate(cb.bind(null, new Error('A fatal error'))); } node_modules/retry/example/dns.js 0000664 00000001257 15114743311 0013152 0 ustar 00 var dns = require('dns'); var retry = require('../lib/retry'); function faultTolerantResolve(address, cb) { var opts = { retries: 2, factor: 2, minTimeout: 1 * 1000, maxTimeout: 2 * 1000, randomize: true }; var operation = retry.operation(opts); operation.attempt(function(currentAttempt) { dns.resolve(address, function(err, addresses) { if (operation.retry(err)) { return; } cb(operation.mainError(), operation.errors(), addresses); }); }); } faultTolerantResolve('nodejs.org', function(err, errors, addresses) { console.warn('err:'); console.log(err); console.warn('addresses:'); console.log(addresses); }); node_modules/retry/package.json 0000664 00000002054 15114743311 0012657 0 ustar 00 { "author": "Tim Koschützki <tim@debuggable.com> (http://debuggable.com/)", "name": "retry", "description": "Abstraction for exponential and custom retry strategies for failed operations.", "license": "MIT", "version": "0.13.1", "homepage": "https://github.com/tim-kos/node-retry", "repository": { "type": "git", "url": "git://github.com/tim-kos/node-retry.git" }, "files": [ "lib", "example" ], "directories": { "lib": "./lib" }, "main": "index.js", "engines": { "node": ">= 4" }, "dependencies": {}, "devDependencies": { "fake": "0.2.0", "istanbul": "^0.4.5", "tape": "^4.8.0" }, "scripts": { "test": "./node_modules/.bin/istanbul cover ./node_modules/tape/bin/tape ./test/integration/*.js", "release:major": "env SEMANTIC=major npm run release", "release:minor": "env SEMANTIC=minor npm run release", "release:patch": "env SEMANTIC=patch npm run release", "release": "npm version ${SEMANTIC:-patch} -m \"Release %s\" && git push && git push --tags && npm publish" } } node_modules/retry/lib/retry.js 0000664 00000004451 15114743311 0012645 0 ustar 00 var RetryOperation = require('./retry_operation'); exports.operation = function(options) { var timeouts = exports.timeouts(options); return new RetryOperation(timeouts, { forever: options && (options.forever || options.retries === Infinity), unref: options && options.unref, maxRetryTime: options && options.maxRetryTime }); }; exports.timeouts = function(options) { if (options instanceof Array) { return [].concat(options); } var opts = { retries: 10, factor: 2, minTimeout: 1 * 1000, maxTimeout: Infinity, randomize: false }; for (var key in options) { opts[key] = options[key]; } if (opts.minTimeout > opts.maxTimeout) { throw new Error('minTimeout is greater than maxTimeout'); } var timeouts = []; for (var i = 0; i < opts.retries; i++) { timeouts.push(this.createTimeout(i, opts)); } if (options && options.forever && !timeouts.length) { timeouts.push(this.createTimeout(i, opts)); } // sort the array numerically ascending timeouts.sort(function(a,b) { return a - b; }); return timeouts; }; exports.createTimeout = function(attempt, opts) { var random = (opts.randomize) ? (Math.random() + 1) : 1; var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); timeout = Math.min(timeout, opts.maxTimeout); return timeout; }; exports.wrap = function(obj, options, methods) { if (options instanceof Array) { methods = options; options = null; } if (!methods) { methods = []; for (var key in obj) { if (typeof obj[key] === 'function') { methods.push(key); } } } for (var i = 0; i < methods.length; i++) { var method = methods[i]; var original = obj[method]; obj[method] = function retryWrapper(original) { var op = exports.operation(options); var args = Array.prototype.slice.call(arguments, 1); var callback = args.pop(); args.push(function(err) { if (op.retry(err)) { return; } if (err) { arguments[0] = op.mainError(); } callback.apply(this, arguments); }); op.attempt(function() { original.apply(obj, args); }); }.bind(obj, original); obj[method].options = options; } }; node_modules/retry/lib/retry_operation.js 0000664 00000007204 15114743311 0014724 0 ustar 00 function RetryOperation(timeouts, options) { // Compatibility for the old (timeouts, retryForever) signature if (typeof options === 'boolean') { options = { forever: options }; } this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); this._timeouts = timeouts; this._options = options || {}; this._maxRetryTime = options && options.maxRetryTime || Infinity; this._fn = null; this._errors = []; this._attempts = 1; this._operationTimeout = null; this._operationTimeoutCb = null; this._timeout = null; this._operationStart = null; this._timer = null; if (this._options.forever) { this._cachedTimeouts = this._timeouts.slice(0); } } module.exports = RetryOperation; RetryOperation.prototype.reset = function() { this._attempts = 1; this._timeouts = this._originalTimeouts.slice(0); } RetryOperation.prototype.stop = function() { if (this._timeout) { clearTimeout(this._timeout); } if (this._timer) { clearTimeout(this._timer); } this._timeouts = []; this._cachedTimeouts = null; }; RetryOperation.prototype.retry = function(err) { if (this._timeout) { clearTimeout(this._timeout); } if (!err) { return false; } var currentTime = new Date().getTime(); if (err && currentTime - this._operationStart >= this._maxRetryTime) { this._errors.push(err); this._errors.unshift(new Error('RetryOperation timeout occurred')); return false; } this._errors.push(err); var timeout = this._timeouts.shift(); if (timeout === undefined) { if (this._cachedTimeouts) { // retry forever, only keep last error this._errors.splice(0, this._errors.length - 1); timeout = this._cachedTimeouts.slice(-1); } else { return false; } } var self = this; this._timer = setTimeout(function() { self._attempts++; if (self._operationTimeoutCb) { self._timeout = setTimeout(function() { self._operationTimeoutCb(self._attempts); }, self._operationTimeout); if (self._options.unref) { self._timeout.unref(); } } self._fn(self._attempts); }, timeout); if (this._options.unref) { this._timer.unref(); } return true; }; RetryOperation.prototype.attempt = function(fn, timeoutOps) { this._fn = fn; if (timeoutOps) { if (timeoutOps.timeout) { this._operationTimeout = timeoutOps.timeout; } if (timeoutOps.cb) { this._operationTimeoutCb = timeoutOps.cb; } } var self = this; if (this._operationTimeoutCb) { this._timeout = setTimeout(function() { self._operationTimeoutCb(); }, self._operationTimeout); } this._operationStart = new Date().getTime(); this._fn(this._attempts); }; RetryOperation.prototype.try = function(fn) { console.log('Using RetryOperation.try() is deprecated'); this.attempt(fn); }; RetryOperation.prototype.start = function(fn) { console.log('Using RetryOperation.start() is deprecated'); this.attempt(fn); }; RetryOperation.prototype.start = RetryOperation.prototype.try; RetryOperation.prototype.errors = function() { return this._errors; }; RetryOperation.prototype.attempts = function() { return this._attempts; }; RetryOperation.prototype.mainError = function() { if (this._errors.length === 0) { return null; } var counts = {}; var mainError = null; var mainErrorCount = 0; for (var i = 0; i < this._errors.length; i++) { var error = this._errors[i]; var message = error.message; var count = (counts[message] || 0) + 1; counts[message] = count; if (count >= mainErrorCount) { mainError = error; mainErrorCount = count; } } return mainError; }; node_modules/retry/index.js 0000664 00000000050 15114743311 0012030 0 ustar 00 module.exports = require('./lib/retry'); node_modules/retry/README.md 0000664 00000021411 15114743311 0011646 0 ustar 00 <!-- badges/ --> [](http://travis-ci.org/tim-kos/node-retry "Check this project's build status on TravisCI") [](https://codecov.io/gh/tim-kos/node-retry) <!-- /badges --> # retry Abstraction for exponential and custom retry strategies for failed operations. ## Installation npm install retry ## Current Status This module has been tested and is ready to be used. ## Tutorial The example below will retry a potentially failing `dns.resolve` operation `10` times using an exponential backoff strategy. With the default settings, this means the last attempt is made after `17 minutes and 3 seconds`. ``` javascript var dns = require('dns'); var retry = require('retry'); function faultTolerantResolve(address, cb) { var operation = retry.operation(); operation.attempt(function(currentAttempt) { dns.resolve(address, function(err, addresses) { if (operation.retry(err)) { return; } cb(err ? operation.mainError() : null, addresses); }); }); } faultTolerantResolve('nodejs.org', function(err, addresses) { console.log(err, addresses); }); ``` Of course you can also configure the factors that go into the exponential backoff. See the API documentation below for all available settings. currentAttempt is an int representing the number of attempts so far. ``` javascript var operation = retry.operation({ retries: 5, factor: 3, minTimeout: 1 * 1000, maxTimeout: 60 * 1000, randomize: true, }); ``` ## API ### retry.operation([options]) Creates a new `RetryOperation` object. `options` is the same as `retry.timeouts()`'s `options`, with three additions: * `forever`: Whether to retry forever, defaults to `false`. * `unref`: Whether to [unref](https://nodejs.org/api/timers.html#timers_unref) the setTimeout's, defaults to `false`. * `maxRetryTime`: The maximum time (in milliseconds) that the retried operation is allowed to run. Default is `Infinity`. ### retry.timeouts([options]) Returns an array of timeouts. All time `options` and return values are in milliseconds. If `options` is an array, a copy of that array is returned. `options` is a JS object that can contain any of the following keys: * `retries`: The maximum amount of times to retry the operation. Default is `10`. Seting this to `1` means `do it once, then retry it once`. * `factor`: The exponential factor to use. Default is `2`. * `minTimeout`: The number of milliseconds before starting the first retry. Default is `1000`. * `maxTimeout`: The maximum number of milliseconds between two retries. Default is `Infinity`. * `randomize`: Randomizes the timeouts by multiplying with a factor between `1` to `2`. Default is `false`. The formula used to calculate the individual timeouts is: ``` Math.min(random * minTimeout * Math.pow(factor, attempt), maxTimeout) ``` Have a look at [this article][article] for a better explanation of approach. If you want to tune your `factor` / `times` settings to attempt the last retry after a certain amount of time, you can use wolfram alpha. For example in order to tune for `10` attempts in `5 minutes`, you can use this equation:  Explaining the various values from left to right: * `k = 0 ... 9`: The `retries` value (10) * `1000`: The `minTimeout` value in ms (1000) * `x^k`: No need to change this, `x` will be your resulting factor * `5 * 60 * 1000`: The desired total amount of time for retrying in ms (5 minutes) To make this a little easier for you, use wolfram alpha to do the calculations: <http://www.wolframalpha.com/input/?i=Sum%5B1000*x^k%2C+{k%2C+0%2C+9}%5D+%3D+5+*+60+*+1000> [article]: http://dthain.blogspot.com/2009/02/exponential-backoff-in-distributed.html ### retry.createTimeout(attempt, opts) Returns a new `timeout` (integer in milliseconds) based on the given parameters. `attempt` is an integer representing for which retry the timeout should be calculated. If your retry operation was executed 4 times you had one attempt and 3 retries. If you then want to calculate a new timeout, you should set `attempt` to 4 (attempts are zero-indexed). `opts` can include `factor`, `minTimeout`, `randomize` (boolean) and `maxTimeout`. They are documented above. `retry.createTimeout()` is used internally by `retry.timeouts()` and is public for you to be able to create your own timeouts for reinserting an item, see [issue #13](https://github.com/tim-kos/node-retry/issues/13). ### retry.wrap(obj, [options], [methodNames]) Wrap all functions of the `obj` with retry. Optionally you can pass operation options and an array of method names which need to be wrapped. ``` retry.wrap(obj) retry.wrap(obj, ['method1', 'method2']) retry.wrap(obj, {retries: 3}) retry.wrap(obj, {retries: 3}, ['method1', 'method2']) ``` The `options` object can take any options that the usual call to `retry.operation` can take. ### new RetryOperation(timeouts, [options]) Creates a new `RetryOperation` where `timeouts` is an array where each value is a timeout given in milliseconds. Available options: * `forever`: Whether to retry forever, defaults to `false`. * `unref`: Wether to [unref](https://nodejs.org/api/timers.html#timers_unref) the setTimeout's, defaults to `false`. If `forever` is true, the following changes happen: * `RetryOperation.errors()` will only output an array of one item: the last error. * `RetryOperation` will repeatedly use the `timeouts` array. Once all of its timeouts have been used up, it restarts with the first timeout, then uses the second and so on. #### retryOperation.errors() Returns an array of all errors that have been passed to `retryOperation.retry()` so far. The returning array has the errors ordered chronologically based on when they were passed to `retryOperation.retry()`, which means the first passed error is at index zero and the last is at the last index. #### retryOperation.mainError() A reference to the error object that occured most frequently. Errors are compared using the `error.message` property. If multiple error messages occured the same amount of time, the last error object with that message is returned. If no errors occured so far, the value is `null`. #### retryOperation.attempt(fn, timeoutOps) Defines the function `fn` that is to be retried and executes it for the first time right away. The `fn` function can receive an optional `currentAttempt` callback that represents the number of attempts to execute `fn` so far. Optionally defines `timeoutOps` which is an object having a property `timeout` in miliseconds and a property `cb` callback function. Whenever your retry operation takes longer than `timeout` to execute, the timeout callback function `cb` is called. #### retryOperation.try(fn) This is an alias for `retryOperation.attempt(fn)`. This is deprecated. Please use `retryOperation.attempt(fn)` instead. #### retryOperation.start(fn) This is an alias for `retryOperation.attempt(fn)`. This is deprecated. Please use `retryOperation.attempt(fn)` instead. #### retryOperation.retry(error) Returns `false` when no `error` value is given, or the maximum amount of retries has been reached. Otherwise it returns `true`, and retries the operation after the timeout for the current attempt number. #### retryOperation.stop() Allows you to stop the operation being retried. Useful for aborting the operation on a fatal error etc. #### retryOperation.reset() Resets the internal state of the operation object, so that you can call `attempt()` again as if this was a new operation object. #### retryOperation.attempts() Returns an int representing the number of attempts it took to call `fn` before it was successful. ## License retry is licensed under the MIT license. # Changelog 0.10.0 Adding `stop` functionality, thanks to @maxnachlinger. 0.9.0 Adding `unref` functionality, thanks to @satazor. 0.8.0 Implementing retry.wrap. 0.7.0 Some bug fixes and made retry.createTimeout() public. Fixed issues [#10](https://github.com/tim-kos/node-retry/issues/10), [#12](https://github.com/tim-kos/node-retry/issues/12), and [#13](https://github.com/tim-kos/node-retry/issues/13). 0.6.0 Introduced optional timeOps parameter for the attempt() function which is an object having a property timeout in milliseconds and a property cb callback function. Whenever your retry operation takes longer than timeout to execute, the timeout callback function cb is called. 0.5.0 Some minor refactoring. 0.4.0 Changed retryOperation.try() to retryOperation.attempt(). Deprecated the aliases start() and try() for it. 0.3.0 Added retryOperation.start() which is an alias for retryOperation.try(). 0.2.0 Added attempts() function and parameter to retryOperation.try() representing the number of attempts it took to call fn(). node_modules/fs-minipass/package.json 0000664 00000001541 15114743311 0013743 0 ustar 00 { "name": "fs-minipass", "version": "2.1.0", "main": "index.js", "scripts": { "test": "tap", "preversion": "npm test", "postversion": "npm publish", "postpublish": "git push origin --follow-tags" }, "keywords": [], "author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)", "license": "ISC", "repository": { "type": "git", "url": "git+https://github.com/npm/fs-minipass.git" }, "bugs": { "url": "https://github.com/npm/fs-minipass/issues" }, "homepage": "https://github.com/npm/fs-minipass#readme", "description": "fs read and write streams based on minipass", "dependencies": { "minipass": "^3.0.0" }, "devDependencies": { "mutate-fs": "^2.0.1", "tap": "^14.6.4" }, "files": [ "index.js" ], "tap": { "check-coverage": true }, "engines": { "node": ">= 8" } } node_modules/fs-minipass/LICENSE 0000664 00000001375 15114743311 0012467 0 ustar 00 The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node_modules/fs-minipass/index.js 0000664 00000023406 15114743311 0013126 0 ustar 00 'use strict' const MiniPass = require('minipass') const EE = require('events').EventEmitter const fs = require('fs') let writev = fs.writev /* istanbul ignore next */ if (!writev) { // This entire block can be removed if support for earlier than Node.js // 12.9.0 is not needed. const binding = process.binding('fs') const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback writev = (fd, iovec, pos, cb) => { const done = (er, bw) => cb(er, bw, iovec) const req = new FSReqWrap() req.oncomplete = done binding.writeBuffers(fd, iovec, pos, req) } } const _autoClose = Symbol('_autoClose') const _close = Symbol('_close') const _ended = Symbol('_ended') const _fd = Symbol('_fd') const _finished = Symbol('_finished') const _flags = Symbol('_flags') const _flush = Symbol('_flush') const _handleChunk = Symbol('_handleChunk') const _makeBuf = Symbol('_makeBuf') const _mode = Symbol('_mode') const _needDrain = Symbol('_needDrain') const _onerror = Symbol('_onerror') const _onopen = Symbol('_onopen') const _onread = Symbol('_onread') const _onwrite = Symbol('_onwrite') const _open = Symbol('_open') const _path = Symbol('_path') const _pos = Symbol('_pos') const _queue = Symbol('_queue') const _read = Symbol('_read') const _readSize = Symbol('_readSize') const _reading = Symbol('_reading') const _remain = Symbol('_remain') const _size = Symbol('_size') const _write = Symbol('_write') const _writing = Symbol('_writing') const _defaultFlag = Symbol('_defaultFlag') const _errored = Symbol('_errored') class ReadStream extends MiniPass { constructor (path, opt) { opt = opt || {} super(opt) this.readable = true this.writable = false if (typeof path !== 'string') throw new TypeError('path must be a string') this[_errored] = false this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_path] = path this[_readSize] = opt.readSize || 16*1024*1024 this[_reading] = false this[_size] = typeof opt.size === 'number' ? opt.size : Infinity this[_remain] = this[_size] this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true if (typeof this[_fd] === 'number') this[_read]() else this[_open]() } get fd () { return this[_fd] } get path () { return this[_path] } write () { throw new TypeError('this is a readable stream') } end () { throw new TypeError('this is a readable stream') } [_open] () { fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_read]() } } [_makeBuf] () { return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) } [_read] () { if (!this[_reading]) { this[_reading] = true const buf = this[_makeBuf]() /* istanbul ignore if */ if (buf.length === 0) return process.nextTick(() => this[_onread](null, 0, buf)) fs.read(this[_fd], buf, 0, buf.length, null, (er, br, buf) => this[_onread](er, br, buf)) } } [_onread] (er, br, buf) { this[_reading] = false if (er) this[_onerror](er) else if (this[_handleChunk](br, buf)) this[_read]() } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } [_onerror] (er) { this[_reading] = true this[_close]() this.emit('error', er) } [_handleChunk] (br, buf) { let ret = false // no effect if infinite this[_remain] -= br if (br > 0) ret = super.write(br < buf.length ? buf.slice(0, br) : buf) if (br === 0 || this[_remain] <= 0) { ret = false this[_close]() super.end() } return ret } emit (ev, data) { switch (ev) { case 'prefinish': case 'finish': break case 'drain': if (typeof this[_fd] === 'number') this[_read]() break case 'error': if (this[_errored]) return this[_errored] = true return super.emit(ev, data) default: return super.emit(ev, data) } } } class ReadStreamSync extends ReadStream { [_open] () { let threw = true try { this[_onopen](null, fs.openSync(this[_path], 'r')) threw = false } finally { if (threw) this[_close]() } } [_read] () { let threw = true try { if (!this[_reading]) { this[_reading] = true do { const buf = this[_makeBuf]() /* istanbul ignore next */ const br = buf.length === 0 ? 0 : fs.readSync(this[_fd], buf, 0, buf.length, null) if (!this[_handleChunk](br, buf)) break } while (true) this[_reading] = false } threw = false } finally { if (threw) this[_close]() } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } } class WriteStream extends EE { constructor (path, opt) { opt = opt || {} super(opt) this.readable = false this.writable = true this[_errored] = false this[_writing] = false this[_ended] = false this[_needDrain] = false this[_queue] = [] this[_path] = path this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_mode] = opt.mode === undefined ? 0o666 : opt.mode this[_pos] = typeof opt.start === 'number' ? opt.start : null this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true // truncating makes no sense when writing into the middle const defaultFlag = this[_pos] !== null ? 'r+' : 'w' this[_defaultFlag] = opt.flags === undefined this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags if (this[_fd] === null) this[_open]() } emit (ev, data) { if (ev === 'error') { if (this[_errored]) return this[_errored] = true } return super.emit(ev, data) } get fd () { return this[_fd] } get path () { return this[_path] } [_onerror] (er) { this[_close]() this[_writing] = true this.emit('error', er) } [_open] () { fs.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (this[_defaultFlag] && this[_flags] === 'r+' && er && er.code === 'ENOENT') { this[_flags] = 'w' this[_open]() } else if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_flush]() } } end (buf, enc) { if (buf) this.write(buf, enc) this[_ended] = true // synthetic after-write logic, where drain/finish live if (!this[_writing] && !this[_queue].length && typeof this[_fd] === 'number') this[_onwrite](null, 0) return this } write (buf, enc) { if (typeof buf === 'string') buf = Buffer.from(buf, enc) if (this[_ended]) { this.emit('error', new Error('write() after end()')) return false } if (this[_fd] === null || this[_writing] || this[_queue].length) { this[_queue].push(buf) this[_needDrain] = true return false } this[_writing] = true this[_write](buf) return true } [_write] (buf) { fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw)) } [_onwrite] (er, bw) { if (er) this[_onerror](er) else { if (this[_pos] !== null) this[_pos] += bw if (this[_queue].length) this[_flush]() else { this[_writing] = false if (this[_ended] && !this[_finished]) { this[_finished] = true this[_close]() this.emit('finish') } else if (this[_needDrain]) { this[_needDrain] = false this.emit('drain') } } } } [_flush] () { if (this[_queue].length === 0) { if (this[_ended]) this[_onwrite](null, 0) } else if (this[_queue].length === 1) this[_write](this[_queue].pop()) else { const iovec = this[_queue] this[_queue] = [] writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw)) } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } } class WriteStreamSync extends WriteStream { [_open] () { let fd // only wrap in a try{} block if we know we'll retry, to avoid // the rethrow obscuring the error's source frame in most cases. if (this[_defaultFlag] && this[_flags] === 'r+') { try { fd = fs.openSync(this[_path], this[_flags], this[_mode]) } catch (er) { if (er.code === 'ENOENT') { this[_flags] = 'w' return this[_open]() } else throw er } } else fd = fs.openSync(this[_path], this[_flags], this[_mode]) this[_onopen](null, fd) } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } [_write] (buf) { // throw the original, but try to close if it fails let threw = true try { this[_onwrite](null, fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) threw = false } finally { if (threw) try { this[_close]() } catch (_) {} } } } exports.ReadStream = ReadStream exports.ReadStreamSync = ReadStreamSync exports.WriteStream = WriteStream exports.WriteStreamSync = WriteStreamSync node_modules/fs-minipass/node_modules/minipass/package.json 0000664 00000002243 15114743311 0020243 0 ustar 00 { "name": "minipass", "version": "3.3.6", "description": "minimal implementation of a PassThrough stream", "main": "index.js", "types": "index.d.ts", "dependencies": { "yallist": "^4.0.0" }, "devDependencies": { "@types/node": "^17.0.41", "end-of-stream": "^1.4.0", "prettier": "^2.6.2", "tap": "^16.2.0", "through2": "^2.0.3", "ts-node": "^10.8.1", "typescript": "^4.7.3" }, "scripts": { "test": "tap", "preversion": "npm test", "postversion": "npm publish", "postpublish": "git push origin --follow-tags" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass.git" }, "keywords": [ "passthrough", "stream" ], "author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)", "license": "ISC", "files": [ "index.d.ts", "index.js" ], "tap": { "check-coverage": true }, "engines": { "node": ">=8" }, "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" } } node_modules/fs-minipass/node_modules/minipass/LICENSE 0000664 00000001423 15114743311 0016761 0 ustar 00 The ISC License Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node_modules/fs-minipass/node_modules/minipass/index.d.ts 0000664 00000010200 15114743311 0017646 0 ustar 00 /// <reference types="node" /> import { EventEmitter } from 'events' import { Stream } from 'stream' declare namespace Minipass { type Encoding = BufferEncoding | 'buffer' | null interface Writable extends EventEmitter { end(): any write(chunk: any, ...args: any[]): any } interface Readable extends EventEmitter { pause(): any resume(): any pipe(): any } interface Pipe<R, W> { src: Minipass<R, W> dest: Writable opts: PipeOptions } type DualIterable<T> = Iterable<T> & AsyncIterable<T> type ContiguousData = Buffer | ArrayBufferLike | ArrayBufferView | string type BufferOrString = Buffer | string interface StringOptions { encoding: BufferEncoding objectMode?: boolean async?: boolean } interface BufferOptions { encoding?: null | 'buffer' objectMode?: boolean async?: boolean } interface ObjectModeOptions { objectMode: true async?: boolean } interface PipeOptions { end?: boolean proxyErrors?: boolean } type Options<T> = T extends string ? StringOptions : T extends Buffer ? BufferOptions : ObjectModeOptions } declare class Minipass< RType extends any = Buffer, WType extends any = RType extends Minipass.BufferOrString ? Minipass.ContiguousData : RType > extends Stream implements Minipass.DualIterable<RType> { static isStream(stream: any): stream is Minipass.Readable | Minipass.Writable readonly bufferLength: number readonly flowing: boolean readonly writable: boolean readonly readable: boolean readonly paused: boolean readonly emittedEnd: boolean readonly destroyed: boolean /** * Not technically private or readonly, but not safe to mutate. */ private readonly buffer: RType[] private readonly pipes: Minipass.Pipe<RType, WType>[] /** * Technically writable, but mutating it can change the type, * so is not safe to do in TypeScript. */ readonly objectMode: boolean async: boolean /** * Note: encoding is not actually read-only, and setEncoding(enc) * exists. However, this type definition will insist that TypeScript * programs declare the type of a Minipass stream up front, and if * that type is string, then an encoding MUST be set in the ctor. If * the type is Buffer, then the encoding must be missing, or set to * 'buffer' or null. If the type is anything else, then objectMode * must be set in the constructor options. So there is effectively * no allowed way that a TS program can set the encoding after * construction, as doing so will destroy any hope of type safety. * TypeScript does not provide many options for changing the type of * an object at run-time, which is what changing the encoding does. */ readonly encoding: Minipass.Encoding // setEncoding(encoding: Encoding): void // Options required if not reading buffers constructor( ...args: RType extends Buffer ? [] | [Minipass.Options<RType>] : [Minipass.Options<RType>] ) write(chunk: WType, cb?: () => void): boolean write(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): boolean read(size?: number): RType end(cb?: () => void): this end(chunk: any, cb?: () => void): this end(chunk: any, encoding?: Minipass.Encoding, cb?: () => void): this pause(): void resume(): void promise(): Promise<void> collect(): Promise<RType[]> concat(): RType extends Minipass.BufferOrString ? Promise<RType> : never destroy(er?: any): void pipe<W extends Minipass.Writable>(dest: W, opts?: Minipass.PipeOptions): W unpipe<W extends Minipass.Writable>(dest: W): void /** * alias for on() */ addEventHandler(event: string, listener: (...args: any[]) => any): this on(event: string, listener: (...args: any[]) => any): this on(event: 'data', listener: (chunk: RType) => any): this on(event: 'error', listener: (error: any) => any): this on( event: | 'readable' | 'drain' | 'resume' | 'end' | 'prefinish' | 'finish' | 'close', listener: () => any ): this [Symbol.iterator](): Iterator<RType> [Symbol.asyncIterator](): AsyncIterator<RType> } export = Minipass node_modules/fs-minipass/node_modules/minipass/index.js 0000664 00000040367 15114743311 0017433 0 ustar 00 'use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = require('events') const Stream = require('stream') const SD = require('string_decoder').StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') const DESTROYED = Symbol('destroyed') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol('asyncIterator not implemented') const ITERATOR = doIter && Symbol.iterator || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor (src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe () { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors () {} end () { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe () { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor (src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } module.exports = class Minipass extends Stream { constructor (options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this.pipes = [] this.buffer = [] this[OBJECTMODE] = options && options.objectMode || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = options && options.encoding || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = options && !!options.async || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false } get bufferLength () { return this[BUFFERLENGTH] } get encoding () { return this[ENCODING] } set encoding (enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if (this[ENCODING] && enc !== this[ENCODING] && (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this.buffer.length) this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding (enc) { this.encoding = enc } get objectMode () { return this[OBJECTMODE] } set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async'] () { return this[ASYNC] } set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } write (chunk, encoding, cb) { if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit('error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } )) return true } if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read (n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this.buffer.length > 1 && !this[OBJECTMODE]) { if (this.encoding) this.buffer = [this.buffer.join('')] else this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] } const ret = this[READ](n || null, this.buffer[0]) this[MAYBE_EMIT_END]() return ret } [READ] (n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this.buffer[0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this.buffer.length && !this[EOF]) this.emit('drain') return chunk } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME] () { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this.buffer.length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume () { return this[RESUME]() } pause () { this[FLOWING] = false this[PAUSED] = true } get destroyed () { return this[DESTROYED] } get flowing () { return this[FLOWING] } get paused () { return this[PAUSED] } [BUFFERPUSH] (chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this.buffer.push(chunk) } [BUFFERSHIFT] () { if (this.buffer.length) { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this.buffer[0].length } return this.buffer.shift() } [FLUSH] (noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) if (!noDrain && !this.buffer.length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK] (chunk) { return chunk ? (this.emit('data', chunk), this.flowing) : false } pipe (dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts)) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe (dest) { const p = this.pipes.find(p => p.dest === dest) if (p) { this.pipes.splice(this.pipes.indexOf(p), 1) p.unpipe() } } addListener (ev, fn) { return this.on(ev, fn) } on (ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this.pipes.length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd () { return this[EMITTED_END] } [MAYBE_EMIT_END] () { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this.buffer.length === 0 && this[EOF]) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit (ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data const ret = super.emit('error', data) this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA] (data) { for (const p of this.pipes) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND] () { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2] () { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this.pipes) { p.dest.write(data) } super.emit('data', data) } } for (const p of this.pipes) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect () { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat () { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) } // stream.promise().then(() => done, er => emitted error) promise () { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR] () { const next = () => { const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return Promise.resolve({ done: true }) let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next } } // for (let chunk of stream) [ITERATOR] () { const next = () => { const value = this.read() const done = value === null return { value, done } } return { next } } destroy (er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this.buffer.length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) else // if no error to emit, still reject pending promises this.emit(DESTROYED) return this } static isStream (s) { return !!s && (s instanceof Minipass || s instanceof Stream || s instanceof EE && ( typeof s.pipe === 'function' || // readable (typeof s.write === 'function' && typeof s.end === 'function') // writable )) } } node_modules/fs-minipass/node_modules/minipass/README.md 0000664 00000061255 15114743311 0017244 0 ustar 00 # minipass A _very_ minimal implementation of a [PassThrough stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) [It's very fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0) for objects, strings, and buffers. Supports `pipe()`ing (including multi-`pipe()` and backpressure transmission), buffering data until either a `data` event handler or `pipe()` is added (so you don't lose the first chunk), and most other cases where PassThrough is a good idea. There is a `read()` method, but it's much more efficient to consume data from this stream via `'data'` events or by calling `pipe()` into some other stream. Calling `read()` requires the buffer to be flattened in some cases, which requires copying memory. If you set `objectMode: true` in the options, then whatever is written will be emitted. Otherwise, it'll do a minimal amount of Buffer copying to ensure proper Streams semantics when `read(n)` is called. `objectMode` can also be set by doing `stream.objectMode = true`, or by writing any non-string/non-buffer data. `objectMode` cannot be set to false once it is set. This is not a `through` or `through2` stream. It doesn't transform the data, it just passes it right through. If you want to transform the data, extend the class, and override the `write()` method. Once you're done transforming the data however you want, call `super.write()` with the transform output. For some examples of streams that extend Minipass in various ways, check out: - [minizlib](http://npm.im/minizlib) - [fs-minipass](http://npm.im/fs-minipass) - [tar](http://npm.im/tar) - [minipass-collect](http://npm.im/minipass-collect) - [minipass-flush](http://npm.im/minipass-flush) - [minipass-pipeline](http://npm.im/minipass-pipeline) - [tap](http://npm.im/tap) - [tap-parser](http://npm.im/tap-parser) - [treport](http://npm.im/treport) - [minipass-fetch](http://npm.im/minipass-fetch) - [pacote](http://npm.im/pacote) - [make-fetch-happen](http://npm.im/make-fetch-happen) - [cacache](http://npm.im/cacache) - [ssri](http://npm.im/ssri) - [npm-registry-fetch](http://npm.im/npm-registry-fetch) - [minipass-json-stream](http://npm.im/minipass-json-stream) - [minipass-sized](http://npm.im/minipass-sized) ## Differences from Node.js Streams There are several things that make Minipass streams different from (and in some ways superior to) Node.js core streams. Please read these caveats if you are familiar with node-core streams and intend to use Minipass streams in your programs. You can avoid most of these differences entirely (for a very small performance penalty) by setting `{async: true}` in the constructor options. ### Timing Minipass streams are designed to support synchronous use-cases. Thus, data is emitted as soon as it is available, always. It is buffered until read, but no longer. Another way to look at it is that Minipass streams are exactly as synchronous as the logic that writes into them. This can be surprising if your code relies on `PassThrough.write()` always providing data on the next tick rather than the current one, or being able to call `resume()` and not have the entire buffer disappear immediately. However, without this synchronicity guarantee, there would be no way for Minipass to achieve the speeds it does, or support the synchronous use cases that it does. Simply put, waiting takes time. This non-deferring approach makes Minipass streams much easier to reason about, especially in the context of Promises and other flow-control mechanisms. Example: ```js const Minipass = require('minipass') const stream = new Minipass({ async: true }) stream.on('data', () => console.log('data event')) console.log('before write') stream.write('hello') console.log('after write') // output: // before write // data event // after write ``` ### Exception: Async Opt-In If you wish to have a Minipass stream with behavior that more closely mimics Node.js core streams, you can set the stream in async mode either by setting `async: true` in the constructor options, or by setting `stream.async = true` later on. ```js const Minipass = require('minipass') const asyncStream = new Minipass({ async: true }) asyncStream.on('data', () => console.log('data event')) console.log('before write') asyncStream.write('hello') console.log('after write') // output: // before write // after write // data event <-- this is deferred until the next tick ``` Switching _out_ of async mode is unsafe, as it could cause data corruption, and so is not enabled. Example: ```js const Minipass = require('minipass') const stream = new Minipass({ encoding: 'utf8' }) stream.on('data', chunk => console.log(chunk)) stream.async = true console.log('before writes') stream.write('hello') setStreamSyncAgainSomehow(stream) // <-- this doesn't actually exist! stream.write('world') console.log('after writes') // hypothetical output would be: // before writes // world // after writes // hello // NOT GOOD! ``` To avoid this problem, once set into async mode, any attempt to make the stream sync again will be ignored. ```js const Minipass = require('minipass') const stream = new Minipass({ encoding: 'utf8' }) stream.on('data', chunk => console.log(chunk)) stream.async = true console.log('before writes') stream.write('hello') stream.async = false // <-- no-op, stream already async stream.write('world') console.log('after writes') // actual output: // before writes // after writes // hello // world ``` ### No High/Low Water Marks Node.js core streams will optimistically fill up a buffer, returning `true` on all writes until the limit is hit, even if the data has nowhere to go. Then, they will not attempt to draw more data in until the buffer size dips below a minimum value. Minipass streams are much simpler. The `write()` method will return `true` if the data has somewhere to go (which is to say, given the timing guarantees, that the data is already there by the time `write()` returns). If the data has nowhere to go, then `write()` returns false, and the data sits in a buffer, to be drained out immediately as soon as anyone consumes it. Since nothing is ever buffered unnecessarily, there is much less copying data, and less bookkeeping about buffer capacity levels. ### Hazards of Buffering (or: Why Minipass Is So Fast) Since data written to a Minipass stream is immediately written all the way through the pipeline, and `write()` always returns true/false based on whether the data was fully flushed, backpressure is communicated immediately to the upstream caller. This minimizes buffering. Consider this case: ```js const {PassThrough} = require('stream') const p1 = new PassThrough({ highWaterMark: 1024 }) const p2 = new PassThrough({ highWaterMark: 1024 }) const p3 = new PassThrough({ highWaterMark: 1024 }) const p4 = new PassThrough({ highWaterMark: 1024 }) p1.pipe(p2).pipe(p3).pipe(p4) p4.on('data', () => console.log('made it through')) // this returns false and buffers, then writes to p2 on next tick (1) // p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) // p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) // p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' // on next tick (4) // p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and // 'drain' on next tick (5) // p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) // p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next // tick (7) p1.write(Buffer.alloc(2048)) // returns false ``` Along the way, the data was buffered and deferred at each stage, and multiple event deferrals happened, for an unblocked pipeline where it was perfectly safe to write all the way through! Furthermore, setting a `highWaterMark` of `1024` might lead someone reading the code to think an advisory maximum of 1KiB is being set for the pipeline. However, the actual advisory buffering level is the _sum_ of `highWaterMark` values, since each one has its own bucket. Consider the Minipass case: ```js const m1 = new Minipass() const m2 = new Minipass() const m3 = new Minipass() const m4 = new Minipass() m1.pipe(m2).pipe(m3).pipe(m4) m4.on('data', () => console.log('made it through')) // m1 is flowing, so it writes the data to m2 immediately // m2 is flowing, so it writes the data to m3 immediately // m3 is flowing, so it writes the data to m4 immediately // m4 is flowing, so it fires the 'data' event immediately, returns true // m4's write returned true, so m3 is still flowing, returns true // m3's write returned true, so m2 is still flowing, returns true // m2's write returned true, so m1 is still flowing, returns true // No event deferrals or buffering along the way! m1.write(Buffer.alloc(2048)) // returns true ``` It is extremely unlikely that you _don't_ want to buffer any data written, or _ever_ buffer data that can be flushed all the way through. Neither node-core streams nor Minipass ever fail to buffer written data, but node-core streams do a lot of unnecessary buffering and pausing. As always, the faster implementation is the one that does less stuff and waits less time to do it. ### Immediately emit `end` for empty streams (when not paused) If a stream is not paused, and `end()` is called before writing any data into it, then it will emit `end` immediately. If you have logic that occurs on the `end` event which you don't want to potentially happen immediately (for example, closing file descriptors, moving on to the next entry in an archive parse stream, etc.) then be sure to call `stream.pause()` on creation, and then `stream.resume()` once you are ready to respond to the `end` event. However, this is _usually_ not a problem because: ### Emit `end` When Asked One hazard of immediately emitting `'end'` is that you may not yet have had a chance to add a listener. In order to avoid this hazard, Minipass streams safely re-emit the `'end'` event if a new listener is added after `'end'` has been emitted. Ie, if you do `stream.on('end', someFunction)`, and the stream has already emitted `end`, then it will call the handler right away. (You can think of this somewhat like attaching a new `.then(fn)` to a previously-resolved Promise.) To prevent calling handlers multiple times who would not expect multiple ends to occur, all listeners are removed from the `'end'` event whenever it is emitted. ### Emit `error` When Asked The most recent error object passed to the `'error'` event is stored on the stream. If a new `'error'` event handler is added, and an error was previously emitted, then the event handler will be called immediately (or on `process.nextTick` in the case of async streams). This makes it much more difficult to end up trying to interact with a broken stream, if the error handler is added after an error was previously emitted. ### Impact of "immediate flow" on Tee-streams A "tee stream" is a stream piping to multiple destinations: ```js const tee = new Minipass() t.pipe(dest1) t.pipe(dest2) t.write('foo') // goes to both destinations ``` Since Minipass streams _immediately_ process any pending data through the pipeline when a new pipe destination is added, this can have surprising effects, especially when a stream comes in from some other function and may or may not have data in its buffer. ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone src.pipe(dest2) // gets nothing! ``` One solution is to create a dedicated tee-stream junction that pipes to both locations, and then pipe to _that_ instead. ```js // Safe example: tee to both places const src = new Minipass() src.write('foo') const tee = new Minipass() tee.pipe(dest1) tee.pipe(dest2) src.pipe(tee) // tee gets 'foo', pipes to both locations ``` The same caveat applies to `on('data')` event listeners. The first one added will _immediately_ receive all of the data, leaving nothing for the second: ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.on('data', handler1) // receives 'foo' right away src.on('data', handler2) // nothing to see here! ``` Using a dedicated tee-stream can be used in this case as well: ```js // Safe example: tee to both data handlers const src = new Minipass() src.write('foo') const tee = new Minipass() tee.on('data', handler1) tee.on('data', handler2) src.pipe(tee) ``` All of the hazards in this section are avoided by setting `{ async: true }` in the Minipass constructor, or by setting `stream.async = true` afterwards. Note that this does add some overhead, so should only be done in cases where you are willing to lose a bit of performance in order to avoid having to refactor program logic. ## USAGE It's a stream! Use it like a stream and it'll most likely do what you want. ```js const Minipass = require('minipass') const mp = new Minipass(options) // optional: { encoding, objectMode } mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` ### OPTIONS * `encoding` How would you like the data coming _out_ of the stream to be encoded? Accepts any values that can be passed to `Buffer.toString()`. * `objectMode` Emit data exactly as it comes in. This will be flipped on by default if you write() something other than a string or Buffer at any point. Setting `objectMode: true` will prevent setting any encoding value. * `async` Defaults to `false`. Set to `true` to defer data emission until next tick. This reduces performance slightly, but makes Minipass streams use timing behavior closer to Node core streams. See [Timing](#timing) for more details. ### API Implements the user-facing portions of Node.js's `Readable` and `Writable` streams. ### Methods * `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the base Minipass class, the same data will come out.) Returns `false` if the stream will buffer the next write, or true if it's still in "flowing" mode. * `end([chunk, [encoding]], [callback])` - Signal that you have no more data to write. This will queue an `end` event to be fired when all the data has been consumed. * `setEncoding(encoding)` - Set the encoding for data coming of the stream. This can only be done once. * `pause()` - No more data for a while, please. This also prevents `end` from being emitted for empty streams until the stream is resumed. * `resume()` - Resume the stream. If there's data in the buffer, it is all discarded. Any buffered events are immediately emitted. * `pipe(dest)` - Send all output to the stream provided. When data is emitted, it is immediately written to any and all pipe destinations. (Or written on next tick in `async` mode.) * `unpipe(dest)` - Stop piping to the destination stream. This is immediate, meaning that any asynchronously queued data will _not_ make it to the destination when running in `async` mode. * `options.end` - Boolean, end the destination stream when the source stream ends. Default `true`. * `options.proxyErrors` - Boolean, proxy `error` events from the source stream to the destination stream. Note that errors are _not_ proxied after the pipeline terminates, either due to the source emitting `'end'` or manually unpiping with `src.unpipe(dest)`. Default `false`. * `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some events are given special treatment, however. (See below under "events".) * `promise()` - Returns a Promise that resolves when the stream emits `end`, or rejects if the stream emits `error`. * `collect()` - Return a Promise that resolves on `end` with an array containing each chunk of data that was emitted, or rejects if the stream emits `error`. Note that this consumes the stream data. * `concat()` - Same as `collect()`, but concatenates the data into a single Buffer object. Will reject the returned promise if the stream is in objectMode, or if it goes into objectMode by the end of the data. * `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not provided, then consume all of it. If `n` bytes are not available, then it returns null. **Note** consuming streams in this way is less efficient, and can lead to unnecessary Buffer copying. * `destroy([er])` - Destroy the stream. If an error is provided, then an `'error'` event is emitted. If the stream has a `close()` method, and has not emitted a `'close'` event yet, then `stream.close()` will be called. Any Promises returned by `.promise()`, `.collect()` or `.concat()` will be rejected. After being destroyed, writing to the stream will emit an error. No more data will be emitted if the stream is destroyed, even if it was previously buffered. ### Properties * `bufferLength` Read-only. Total number of bytes buffered, or in the case of objectMode, the total number of objects. * `encoding` The encoding that has been set. (Setting this is equivalent to calling `setEncoding(enc)` and has the same prohibition against setting multiple times.) * `flowing` Read-only. Boolean indicating whether a chunk written to the stream will be immediately emitted. * `emittedEnd` Read-only. Boolean indicating whether the end-ish events (ie, `end`, `prefinish`, `finish`) have been emitted. Note that listening on any end-ish event will immediateyl re-emit it if it has already been emitted. * `writable` Whether the stream is writable. Default `true`. Set to `false` when `end()` * `readable` Whether the stream is readable. Default `true`. * `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written to the stream that have not yet been emitted. (It's probably a bad idea to mess with this.) * `pipes` A [yallist](http://npm.im/yallist) linked list of streams that this stream is piping into. (It's probably a bad idea to mess with this.) * `destroyed` A getter that indicates whether the stream was destroyed. * `paused` True if the stream has been explicitly paused, otherwise false. * `objectMode` Indicates whether the stream is in `objectMode`. Once set to `true`, it cannot be set to `false`. ### Events * `data` Emitted when there's data to read. Argument is the data to read. This is never emitted while not flowing. If a listener is attached, that will resume the stream. * `end` Emitted when there's no more data to read. This will be emitted immediately for empty streams when `end()` is called. If a listener is attached, and `end` was already emitted, then it will be emitted again. All listeners are removed when `end` is emitted. * `prefinish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'end'`. * `finish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'prefinish'`. * `close` An indication that an underlying resource has been released. Minipass does not emit this event, but will defer it until after `end` has been emitted, since it throws off some stream libraries otherwise. * `drain` Emitted when the internal buffer empties, and it is again suitable to `write()` into the stream. * `readable` Emitted when data is buffered and ready to be read by a consumer. * `resume` Emitted when stream changes state from buffering to flowing mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event listener is added.) ### Static Methods * `Minipass.isStream(stream)` Returns `true` if the argument is a stream, and false otherwise. To be considered a stream, the object must be either an instance of Minipass, or an EventEmitter that has either a `pipe()` method, or both `write()` and `end()` methods. (Pretty much any stream in node-land will return `true` for this.) ## EXAMPLES Here are some examples of things you can do with Minipass streams. ### simple "are you done yet" promise ```js mp.promise().then(() => { // stream is finished }, er => { // stream emitted an error }) ``` ### collecting ```js mp.collect().then(all => { // all is an array of all the data emitted // encoding is supported in this case, so // so the result will be a collection of strings if // an encoding is specified, or buffers/objects if not. // // In an async function, you may do // const data = await stream.collect() }) ``` ### collecting into a single blob This is a bit slower because it concatenates the data into one chunk for you, but if you're going to do it yourself anyway, it's convenient this way: ```js mp.concat().then(onebigchunk => { // onebigchunk is a string if the stream // had an encoding set, or a buffer otherwise. }) ``` ### iteration You can iterate over streams synchronously or asynchronously in platforms that support it. Synchronous iteration will end when the currently available data is consumed, even if the `end` event has not been reached. In string and buffer mode, the data is concatenated, so unless multiple writes are occurring in the same tick as the `read()`, sync iteration loops will generally only have a single iteration. To consume chunks in this way exactly as they have been written, with no flattening, create the stream with the `{ objectMode: true }` option. ```js const mp = new Minipass({ objectMode: true }) mp.write('a') mp.write('b') for (let letter of mp) { console.log(letter) // a, b } mp.write('c') mp.write('d') for (let letter of mp) { console.log(letter) // c, d } mp.write('e') mp.end() for (let letter of mp) { console.log(letter) // e } for (let letter of mp) { console.log(letter) // nothing } ``` Asynchronous iteration will continue until the end event is reached, consuming all of the data. ```js const mp = new Minipass({ encoding: 'utf8' }) // some source of some data let i = 5 const inter = setInterval(() => { if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // consume the data with asynchronous iteration async function consume () { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // logs `foo\n` 5 times, and then `ok` ``` ### subclass that `console.log()`s everything written into it ```js class Logger extends Minipass { write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } } someSource.pipe(new Logger()).pipe(someDest) ``` ### same thing, but using an inline anonymous class ```js // js classes are fun someSource .pipe(new (class extends Minipass { emit (ev, ...data) { // let's also log events, because debugging some weird thing console.log('EMIT', ev) return super.emit(ev, ...data) } write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } })) .pipe(someDest) ``` ### subclass that defers 'end' for some reason ```js class SlowEnd extends Minipass { emit (ev, ...args) { if (ev === 'end') { console.log('going to end, hold on a sec') setTimeout(() => { console.log('ok, ready to end now') super.emit('end', ...args) }, 100) } else { return super.emit(ev, ...args) } } } ``` ### transform that creates newline-delimited JSON ```js class NDJSONEncode extends Minipass { write (obj, cb) { try { // JSON.stringify can throw, emit an error on that return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) } catch (er) { this.emit('error', er) } } end (obj, cb) { if (typeof obj === 'function') { cb = obj obj = undefined } if (obj !== undefined) { this.write(obj) } return super.end(cb) } } ``` ### transform that parses newline-delimited JSON ```js class NDJSONDecode extends Minipass { constructor (options) { // always be in object mode, as far as Minipass is concerned super({ objectMode: true }) this._jsonBuffer = '' } write (chunk, encoding, cb) { if (typeof chunk === 'string' && typeof encoding === 'string' && encoding !== 'utf8') { chunk = Buffer.from(chunk, encoding).toString() } else if (Buffer.isBuffer(chunk)) chunk = chunk.toString() } if (typeof encoding === 'function') { cb = encoding } const jsonData = (this._jsonBuffer + chunk).split('\n') this._jsonBuffer = jsonData.pop() for (let i = 0; i < jsonData.length; i++) { try { // JSON.parse can throw, emit an error on that super.write(JSON.parse(jsonData[i])) } catch (er) { this.emit('error', er) continue } } if (cb) cb() } } ``` node_modules/fs-minipass/README.md 0000664 00000004645 15114743311 0012744 0 ustar 00 # fs-minipass Filesystem streams based on [minipass](http://npm.im/minipass). 4 classes are exported: - ReadStream - ReadStreamSync - WriteStream - WriteStreamSync When using `ReadStreamSync`, all of the data is made available immediately upon consuming the stream. Nothing is buffered in memory when the stream is constructed. If the stream is piped to a writer, then it will synchronously `read()` and emit data into the writer as fast as the writer can consume it. (That is, it will respect backpressure.) If you call `stream.read()` then it will read the entire file and return the contents. When using `WriteStreamSync`, every write is flushed to the file synchronously. If your writes all come in a single tick, then it'll write it all out in a single tick. It's as synchronous as you are. The async versions work much like their node builtin counterparts, with the exception of introducing significantly less Stream machinery overhead. ## USAGE It's just streams, you pipe them or read() them or write() to them. ```js const fsm = require('fs-minipass') const readStream = new fsm.ReadStream('file.txt') const writeStream = new fsm.WriteStream('output.txt') writeStream.write('some file header or whatever\n') readStream.pipe(writeStream) ``` ## ReadStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `readSize` The size of reads to do, defaults to 16MB - `size` The size of the file, if known. Prevents zero-byte read() call at the end. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the file is done being read. ## WriteStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `mode` The mode to create the file with. Defaults to `0o666`. - `start` The position in the file to start reading. If not specified, then the file will start writing at position zero, and be truncated by default. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the stream is ended. - `flags` Flags to use when opening the file. Irrelevant if `fd` is passed in, since file won't be opened in that case. Defaults to `'a'` if a `pos` is specified, or `'w'` otherwise. node_modules/find-up/license 0000664 00000002135 15114743311 0012133 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/find-up/package.json 0000664 00000002043 15114743311 0013052 0 ustar 00 { "name": "find-up", "version": "7.0.0", "description": "Find a file or directory by walking up parent directories", "license": "MIT", "repository": "sindresorhus/find-up", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "default": "./index.js" }, "sideEffects": false, "engines": { "node": ">=18" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "find", "up", "find-up", "findup", "look-up", "look", "file", "search", "match", "package", "resolve", "parent", "parents", "folder", "directory", "walk", "walking", "path" ], "dependencies": { "locate-path": "^7.2.0", "path-exists": "^5.0.0", "unicorn-magic": "^0.1.0" }, "devDependencies": { "ava": "^5.3.1", "is-path-inside": "^4.0.0", "tempy": "^3.1.0", "tsd": "^0.29.0", "xo": "^0.56.0" } } node_modules/find-up/readme.md 0000664 00000010247 15114743311 0012350 0 ustar 00 # find-up > Find a file or directory by walking up parent directories ## Install ```sh npm install find-up ``` ## Usage ``` / └── Users └── sindresorhus ├── unicorn.png └── foo └── bar ├── baz └── example.js ``` `example.js` ```js import path from 'node:path'; import {findUp, pathExists} from 'find-up'; console.log(await findUp('unicorn.png')); //=> '/Users/sindresorhus/unicorn.png' console.log(await findUp(['rainbow.png', 'unicorn.png'])); //=> '/Users/sindresorhus/unicorn.png' console.log(await findUp(async directory => { const hasUnicorns = await pathExists(path.join(directory, 'unicorn.png')); return hasUnicorns && directory; }, {type: 'directory'})); //=> '/Users/sindresorhus' ``` ## API ### findUp(name, options?) ### findUp(matcher, options?) Returns a `Promise` for either the path or `undefined` if it could not be found. ### findUp([...name], options?) Returns a `Promise` for either the first path found (by respecting the order of the array) or `undefined` if none could be found. ### findUpMultiple(name, options?) ### findUpMultiple(matcher, options?) Returns a `Promise` for either an array of paths or an empty array if none could be found. ### findUpMultiple([...name], options?) Returns a `Promise` for either an array of the first paths found (by respecting the order of the array) or an empty array if none could be found. ### findUpSync(name, options?) ### findUpSync(matcher, options?) Returns a path or `undefined` if it could not be found. ### findUpSync([...name], options?) Returns the first path found (by respecting the order of the array) or `undefined` if none could be found. ### findUpMultipleSync(name, options?) ### findUpMultipleSync(matcher, options?) Returns an array of paths or an empty array if none could be found. ### findUpMultipleSync([...name], options?) Returns an array of the first paths found (by respecting the order of the array) or an empty array if none could be found. #### name Type: `string` The name of the file or directory to find. #### matcher Type: `Function` A function that will be called with each directory until it returns a `string` with the path, which stops the search, or the root directory has been reached and nothing was found. Useful if you want to match files with certain patterns, set of permissions, or other advanced use-cases. When using async mode, the `matcher` may optionally be an async or promise-returning function that returns the path. #### options Type: `object` ##### cwd Type: `URL | string`\ Default: `process.cwd()` The directory to start from. ##### type Type: `string`\ Default: `'file'`\ Values: `'file' | 'directory'` The type of path to match. ##### allowSymlinks Type: `boolean`\ Default: `true` Allow symbolic links to match if they point to the chosen path type. ##### stopAt Type: `URL | string`\ Default: Root directory A directory path where the search halts if no matches are found before reaching this point. ### pathExists(path) Returns a `Promise<boolean>` of whether the path exists. ### pathExistsSync(path) Returns a `boolean` of whether the path exists. #### path Type: `string` The path to a file or directory. ### findUpStop A [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) that can be returned by a `matcher` function to stop the search and cause `findUp` to immediately return `undefined`. Useful as a performance optimization in case the current working directory is deeply nested in the filesystem. ```js import path from 'node:path'; import {findUp, findUpStop} from 'find-up'; await findUp(directory => { return path.basename(directory) === 'work' ? findUpStop : 'logo.png'; }); ``` ## Related - [find-up-cli](https://github.com/sindresorhus/find-up-cli) - CLI for this module - [package-up](https://github.com/sindresorhus/package-up) - Find the closest package.json file - [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package - [resolve-from](https://github.com/sindresorhus/resolve-from) - Resolve the path of a module like `require.resolve()` but from a given path node_modules/find-up/index.d.ts 0000664 00000016401 15114743311 0012470 0 ustar 00 import {type Options as LocatePathOptions} from 'locate-path'; /** Return this in a `matcher` function to stop the search and force `findUp` to immediately return `undefined`. */ export const findUpStop: unique symbol; export type Match = string | typeof findUpStop | undefined; export type Options = { /** A directory path where the search halts if no matches are found before reaching this point. Default: Root directory */ readonly stopAt?: string; } & LocatePathOptions; /** Find a file or directory by walking up parent directories. @param name - The name of the file or directory to find. Can be multiple. @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. @example ``` // / // └── Users // └── sindresorhus // ├── unicorn.png // └── foo // └── bar // ├── baz // └── example.js // example.js import {findUp} from 'find-up'; console.log(await findUp('unicorn.png')); //=> '/Users/sindresorhus/unicorn.png' console.log(await findUp(['rainbow.png', 'unicorn.png'])); //=> '/Users/sindresorhus/unicorn.png' ``` */ export function findUp(name: string | readonly string[], options?: Options): Promise<string | undefined>; /** Find a file or directory by walking up parent directories. @param matcher - Called for each directory in the search. Return a path or `findUpStop` to stop the search. @returns The first path found or `undefined` if none could be found. @example ``` import path from 'node:path'; import {findUp, pathExists} from 'find-up'; console.log(await findUp(async directory => { const hasUnicorns = await pathExists(path.join(directory, 'unicorn.png')); return hasUnicorns && directory; }, {type: 'directory'})); //=> '/Users/sindresorhus' ``` */ export function findUp(matcher: (directory: string) => (Match | Promise<Match>), options?: Options): Promise<string | undefined>; /** Synchronously find a file or directory by walking up parent directories. @param name - The name of the file or directory to find. Can be multiple. @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. @example ``` // / // └── Users // └── sindresorhus // ├── unicorn.png // └── foo // └── bar // ├── baz // └── example.js // example.js import {findUpSync} from 'find-up'; console.log(findUpSync('unicorn.png')); //=> '/Users/sindresorhus/unicorn.png' console.log(findUpSync(['rainbow.png', 'unicorn.png'])); //=> '/Users/sindresorhus/unicorn.png' ``` */ export function findUpSync(name: string | readonly string[], options?: Options): string | undefined; /** Synchronously find a file or directory by walking up parent directories. @param matcher - Called for each directory in the search. Return a path or `findUpStop` to stop the search. @returns The first path found or `undefined` if none could be found. @example ``` import path from 'node:path'; import {findUpSync, pathExistsSync} from 'find-up'; console.log(findUpSync(directory => { const hasUnicorns = pathExistsSync(path.join(directory, 'unicorn.png')); return hasUnicorns && directory; }, {type: 'directory'})); //=> '/Users/sindresorhus' ``` */ export function findUpSync(matcher: (directory: string) => Match, options?: Options): string | undefined; /** Find files or directories by walking up parent directories. @param name - The name of the file or directory to find. Can be multiple. @returns All paths found (by respecting the order of `name`s) or an empty array if none could be found. @example ``` // / // └── Users // └── sindresorhus // ├── unicorn.png // └── foo // ├── unicorn.png // └── bar // ├── baz // └── example.js // example.js import {findUpMultiple} from 'find-up'; console.log(await findUpMultiple('unicorn.png')); //=> ['/Users/sindresorhus/foo/unicorn.png', '/Users/sindresorhus/unicorn.png'] console.log(await findUpMultiple(['rainbow.png', 'unicorn.png'])); //=> ['/Users/sindresorhus/foo/unicorn.png', '/Users/sindresorhus/unicorn.png'] ``` */ export function findUpMultiple(name: string | readonly string[], options?: Options): Promise<string[]>; /** Find files or directories by walking up parent directories. @param matcher - Called for each directory in the search. Return a path or `findUpStop` to stop the search. @returns All paths found or an empty array if none could be found. @example ``` import path from 'node:path'; import {findUpMultiple, pathExists} from 'find-up'; console.log(await findUpMultiple(async directory => { const hasUnicorns = await pathExists(path.join(directory, 'unicorn.png')); return hasUnicorns && directory; }, {type: 'directory'})); //=> ['/Users/sindresorhus/foo', '/Users/sindresorhus'] ``` */ export function findUpMultiple(matcher: (directory: string) => (Match | Promise<Match>), options?: Options): Promise<string[]>; /** Synchronously find files or directories by walking up parent directories. @param name - The name of the file or directory to find. Can be multiple. @returns All paths found (by respecting the order of `name`s) or an empty array if none could be found. @example ``` // / // └── Users // └── sindresorhus // ├── unicorn.png // └── foo // ├── unicorn.png // └── bar // ├── baz // └── example.js // example.js import {findUpMultipleSync} from 'find-up'; console.log(findUpMultipleSync('unicorn.png')); //=> ['/Users/sindresorhus/foo/unicorn.png', '/Users/sindresorhus/unicorn.png'] console.log(findUpMultipleSync(['rainbow.png', 'unicorn.png'])); //=> ['/Users/sindresorhus/foo/unicorn.png', '/Users/sindresorhus/unicorn.png'] ``` */ export function findUpMultipleSync(name: string | readonly string[], options?: Options): string[]; /** Synchronously find files or directories by walking up parent directories. @param matcher - Called for each directory in the search. Return a path or `findUpStop` to stop the search. @returns All paths found or an empty array if none could be found. @example ``` import path from 'node:path'; import {findUpMultipleSync, pathExistsSync} from 'find-up'; console.log(findUpMultipleSync(directory => { const hasUnicorns = pathExistsSync(path.join(directory, 'unicorn.png')); return hasUnicorns && directory; }, {type: 'directory'})); //=> ['/Users/sindresorhus/foo', '/Users/sindresorhus'] ``` */ export function findUpMultipleSync(matcher: (directory: string) => Match, options?: Options): string[]; /** Check if a path exists. @param path - The path to a file or directory. @returns Whether the path exists. @example ``` import {pathExists} from 'find-up'; console.log(await pathExists('/Users/sindresorhus/unicorn.png')); //=> true ``` */ export function pathExists(path: string): Promise<boolean>; /** Synchronously check if a path exists. @param path - Path to the file or directory. @returns Whether the path exists. @example ``` import {pathExistsSync} from 'find-up'; console.log(pathExistsSync('/Users/sindresorhus/unicorn.png')); //=> true ``` */ export function pathExistsSync(path: string): boolean; node_modules/find-up/index.js 0000664 00000005100 15114743311 0012226 0 ustar 00 import path from 'node:path'; import {locatePath, locatePathSync} from 'locate-path'; import {toPath} from 'unicorn-magic'; export const findUpStop = Symbol('findUpStop'); export async function findUpMultiple(name, options = {}) { let directory = path.resolve(toPath(options.cwd) ?? ''); const {root} = path.parse(directory); const stopAt = path.resolve(directory, toPath(options.stopAt ?? root)); const limit = options.limit ?? Number.POSITIVE_INFINITY; const paths = [name].flat(); const runMatcher = async locateOptions => { if (typeof name !== 'function') { return locatePath(paths, locateOptions); } const foundPath = await name(locateOptions.cwd); if (typeof foundPath === 'string') { return locatePath([foundPath], locateOptions); } return foundPath; }; const matches = []; // eslint-disable-next-line no-constant-condition while (true) { // eslint-disable-next-line no-await-in-loop const foundPath = await runMatcher({...options, cwd: directory}); if (foundPath === findUpStop) { break; } if (foundPath) { matches.push(path.resolve(directory, foundPath)); } if (directory === stopAt || matches.length >= limit) { break; } directory = path.dirname(directory); } return matches; } export function findUpMultipleSync(name, options = {}) { let directory = path.resolve(toPath(options.cwd) ?? ''); const {root} = path.parse(directory); const stopAt = path.resolve(directory, toPath(options.stopAt) ?? root); const limit = options.limit ?? Number.POSITIVE_INFINITY; const paths = [name].flat(); const runMatcher = locateOptions => { if (typeof name !== 'function') { return locatePathSync(paths, locateOptions); } const foundPath = name(locateOptions.cwd); if (typeof foundPath === 'string') { return locatePathSync([foundPath], locateOptions); } return foundPath; }; const matches = []; // eslint-disable-next-line no-constant-condition while (true) { const foundPath = runMatcher({...options, cwd: directory}); if (foundPath === findUpStop) { break; } if (foundPath) { matches.push(path.resolve(directory, foundPath)); } if (directory === stopAt || matches.length >= limit) { break; } directory = path.dirname(directory); } return matches; } export async function findUp(name, options = {}) { const matches = await findUpMultiple(name, {...options, limit: 1}); return matches[0]; } export function findUpSync(name, options = {}) { const matches = findUpMultipleSync(name, {...options, limit: 1}); return matches[0]; } export { pathExists, pathExistsSync, } from 'path-exists'; node_modules/p-locate/license 0000664 00000002135 15114743311 0012275 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/p-locate/package.json 0000664 00000001770 15114743311 0013222 0 ustar 00 { "name": "p-locate", "version": "6.0.0", "description": "Get the first fulfilled promise that satisfies the provided testing function", "license": "MIT", "repository": "sindresorhus/p-locate", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "promise", "locate", "find", "finder", "search", "searcher", "test", "array", "collection", "iterable", "iterator", "race", "fulfilled", "fastest", "async", "await", "promises", "bluebird" ], "dependencies": { "p-limit": "^4.0.0" }, "devDependencies": { "ava": "^3.15.0", "delay": "^5.0.0", "in-range": "^3.0.0", "time-span": "^5.0.0", "tsd": "^0.17.0", "xo": "^0.44.0" } } node_modules/p-locate/readme.md 0000664 00000004534 15114743311 0012514 0 ustar 00 # p-locate > Get the first fulfilled promise that satisfies the provided testing function Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find). ## Install ``` $ npm install p-locate ``` ## Usage Here we find the first file that exists on disk, in array order. ```js import {pathExists} from 'path-exists'; import pLocate from 'p-locate'; const files = [ 'unicorn.png', 'rainbow.png', // Only this one actually exists on disk 'pony.png' ]; const foundPath = await pLocate(files, file => pathExists(file)); console.log(foundPath); //=> 'rainbow' ``` *The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.* ## API ### pLocate(input, tester, options?) Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. #### input Type: `Iterable<Promise | unknown>` An iterable of promises/values to test. #### tester(element) Type: `Function` This function will receive resolved values from `input` and is expected to return a `Promise<boolean>` or `boolean`. #### options Type: `object` ##### concurrency Type: `number`\ Default: `Infinity`\ Minimum: `1` The number of concurrently pending promises returned by `tester`. ##### preserveOrder Type: `boolean`\ Default: `true` Preserve `input` order when searching. Disable this to improve performance if you don't care about the order. ## Related - [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently - [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently - [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled - [More…](https://github.com/sindresorhus/promise-fun) --- <div align="center"> <b> <a href="https://tidelift.com/subscription/pkg/npm-p-locate?utm_source=npm-p-locate&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> </b> <br> <sub> Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. </sub> </div> node_modules/p-locate/index.d.ts 0000664 00000002546 15114743311 0012637 0 ustar 00 export interface Options { /** The number of concurrently pending promises returned by `tester`. Minimum: `1` @default Infinity */ readonly concurrency?: number; /** Preserve `input` order when searching. Disable this to improve performance if you don't care about the order. @default true */ readonly preserveOrder?: boolean; } /** Get the first fulfilled promise that satisfies the provided testing function. @param input - An iterable of promises/values to test. @param tester - This function will receive resolved values from `input` and is expected to return a `Promise<boolean>` or `boolean`. @returns A `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. @example ``` import {pathExists} from 'path-exists'; import pLocate from 'p-locate'; const files = [ 'unicorn.png', 'rainbow.png', // Only this one actually exists on disk 'pony.png' ]; const foundPath = await pLocate(files, file => pathExists(file)); console.log(foundPath); //=> 'rainbow' ``` */ export default function pLocate<ValueType>( input: Iterable<PromiseLike<ValueType> | ValueType>, tester: (element: ValueType) => PromiseLike<boolean> | boolean, options?: Options ): Promise<ValueType | undefined>; node_modules/p-locate/index.js 0000664 00000002141 15114743311 0012372 0 ustar 00 import pLimit from 'p-limit'; class EndError extends Error { constructor(value) { super(); this.value = value; } } // The input can also be a promise, so we await it. const testElement = async (element, tester) => tester(await element); // The input can also be a promise, so we `Promise.all()` them both. const finder = async element => { const values = await Promise.all(element); if (values[1] === true) { throw new EndError(values[0]); } return false; }; export default async function pLocate( iterable, tester, { concurrency = Number.POSITIVE_INFINITY, preserveOrder = true, } = {}, ) { const limit = pLimit(concurrency); // Start all the promises concurrently with optional limit. const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); // Check the promises either serially or concurrently. const checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY); try { await Promise.all(items.map(element => checkLimit(finder, element))); } catch (error) { if (error instanceof EndError) { return error.value; } throw error; } } node_modules/tar/package.json 0000664 00000002632 15114743311 0012302 0 ustar 00 { "author": "GitHub Inc.", "name": "tar", "description": "tar for node", "version": "6.2.1", "repository": { "type": "git", "url": "https://github.com/isaacs/node-tar.git" }, "scripts": { "genparse": "node scripts/generate-parse-fixtures.js", "snap": "tap", "test": "tap" }, "dependencies": { "chownr": "^2.0.0", "fs-minipass": "^2.0.0", "minipass": "^5.0.0", "minizlib": "^2.1.1", "mkdirp": "^1.0.3", "yallist": "^4.0.0" }, "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.11.0", "chmodr": "^1.2.0", "end-of-stream": "^1.4.3", "events-to-array": "^2.0.3", "mutate-fs": "^2.1.1", "nock": "^13.2.9", "rimraf": "^3.0.2", "tap": "^16.0.1" }, "license": "ISC", "engines": { "node": ">=10" }, "files": [ "bin/", "lib/", "index.js" ], "tap": { "coverage-map": "map.js", "timeout": 0, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.11.0", "content": "scripts/template-oss", "engines": ">=10", "distPaths": [ "index.js" ], "allowPaths": [ "/index.js" ], "ciVersions": [ "10.x", "12.x", "14.x", "16.x", "18.x" ] } } node_modules/tar/LICENSE 0000664 00000001375 15114743311 0011024 0 ustar 00 The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node_modules/tar/lib/strip-trailing-slashes.js 0000664 00000000612 15114743311 0015524 0 ustar 00 // warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. module.exports = str => { let i = str.length - 1 let slashesStart = -1 while (i > -1 && str.charAt(i) === '/') { slashesStart = i i-- } return slashesStart === -1 ? str : str.slice(0, slashesStart) } node_modules/tar/lib/pack.js 0000664 00000023445 15114743311 0012043 0 ustar 00 'use strict' // A readable tar stream creator // Technically, this is a transform stream that you write paths into, // and tar format comes out of. // The `add()` method is like `write()` but returns this, // and end() return `this` as well, so you can // do `new Pack(opt).add('files').add('dir').end().pipe(output) // You could also do something like: // streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar')) class PackJob { constructor (path, absolute) { this.path = path || './' this.absolute = absolute this.entry = null this.stat = null this.readdir = null this.pending = false this.ignore = false this.piped = false } } const { Minipass } = require('minipass') const zlib = require('minizlib') const ReadEntry = require('./read-entry.js') const WriteEntry = require('./write-entry.js') const WriteEntrySync = WriteEntry.Sync const WriteEntryTar = WriteEntry.Tar const Yallist = require('yallist') const EOF = Buffer.alloc(1024) const ONSTAT = Symbol('onStat') const ENDED = Symbol('ended') const QUEUE = Symbol('queue') const CURRENT = Symbol('current') const PROCESS = Symbol('process') const PROCESSING = Symbol('processing') const PROCESSJOB = Symbol('processJob') const JOBS = Symbol('jobs') const JOBDONE = Symbol('jobDone') const ADDFSENTRY = Symbol('addFSEntry') const ADDTARENTRY = Symbol('addTarEntry') const STAT = Symbol('stat') const READDIR = Symbol('readdir') const ONREADDIR = Symbol('onreaddir') const PIPE = Symbol('pipe') const ENTRY = Symbol('entry') const ENTRYOPT = Symbol('entryOpt') const WRITEENTRYCLASS = Symbol('writeEntryClass') const WRITE = Symbol('write') const ONDRAIN = Symbol('ondrain') const fs = require('fs') const path = require('path') const warner = require('./warn-mixin.js') const normPath = require('./normalize-windows-path.js') const Pack = warner(class Pack extends Minipass { constructor (opt) { super(opt) opt = opt || Object.create(null) this.opt = opt this.file = opt.file || '' this.cwd = opt.cwd || process.cwd() this.maxReadSize = opt.maxReadSize this.preservePaths = !!opt.preservePaths this.strict = !!opt.strict this.noPax = !!opt.noPax this.prefix = normPath(opt.prefix || '') this.linkCache = opt.linkCache || new Map() this.statCache = opt.statCache || new Map() this.readdirCache = opt.readdirCache || new Map() this[WRITEENTRYCLASS] = WriteEntry if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } this.portable = !!opt.portable this.zip = null if (opt.gzip || opt.brotli) { if (opt.gzip && opt.brotli) { throw new TypeError('gzip and brotli are mutually exclusive') } if (opt.gzip) { if (typeof opt.gzip !== 'object') { opt.gzip = {} } if (this.portable) { opt.gzip.portable = true } this.zip = new zlib.Gzip(opt.gzip) } if (opt.brotli) { if (typeof opt.brotli !== 'object') { opt.brotli = {} } this.zip = new zlib.BrotliCompress(opt.brotli) } this.zip.on('data', chunk => super.write(chunk)) this.zip.on('end', _ => super.end()) this.zip.on('drain', _ => this[ONDRAIN]()) this.on('resume', _ => this.zip.resume()) } else { this.on('drain', this[ONDRAIN]) } this.noDirRecurse = !!opt.noDirRecurse this.follow = !!opt.follow this.noMtime = !!opt.noMtime this.mtime = opt.mtime || null this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true this[QUEUE] = new Yallist() this[JOBS] = 0 this.jobs = +opt.jobs || 4 this[PROCESSING] = false this[ENDED] = false } [WRITE] (chunk) { return super.write(chunk) } add (path) { this.write(path) return this } end (path) { if (path) { this.write(path) } this[ENDED] = true this[PROCESS]() return this } write (path) { if (this[ENDED]) { throw new Error('write after end') } if (path instanceof ReadEntry) { this[ADDTARENTRY](path) } else { this[ADDFSENTRY](path) } return this.flowing } [ADDTARENTRY] (p) { const absolute = normPath(path.resolve(this.cwd, p.path)) // in this case, we don't have to wait for the stat if (!this.filter(p.path, p)) { p.resume() } else { const job = new PackJob(p.path, absolute, false) job.entry = new WriteEntryTar(p, this[ENTRYOPT](job)) job.entry.on('end', _ => this[JOBDONE](job)) this[JOBS] += 1 this[QUEUE].push(job) } this[PROCESS]() } [ADDFSENTRY] (p) { const absolute = normPath(path.resolve(this.cwd, p)) this[QUEUE].push(new PackJob(p, absolute)) this[PROCESS]() } [STAT] (job) { job.pending = true this[JOBS] += 1 const stat = this.follow ? 'stat' : 'lstat' fs[stat](job.absolute, (er, stat) => { job.pending = false this[JOBS] -= 1 if (er) { this.emit('error', er) } else { this[ONSTAT](job, stat) } }) } [ONSTAT] (job, stat) { this.statCache.set(job.absolute, stat) job.stat = stat // now we have the stat, we can filter it. if (!this.filter(job.path, stat)) { job.ignore = true } this[PROCESS]() } [READDIR] (job) { job.pending = true this[JOBS] += 1 fs.readdir(job.absolute, (er, entries) => { job.pending = false this[JOBS] -= 1 if (er) { return this.emit('error', er) } this[ONREADDIR](job, entries) }) } [ONREADDIR] (job, entries) { this.readdirCache.set(job.absolute, entries) job.readdir = entries this[PROCESS]() } [PROCESS] () { if (this[PROCESSING]) { return } this[PROCESSING] = true for (let w = this[QUEUE].head; w !== null && this[JOBS] < this.jobs; w = w.next) { this[PROCESSJOB](w.value) if (w.value.ignore) { const p = w.next this[QUEUE].removeNode(w) w.next = p } } this[PROCESSING] = false if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { if (this.zip) { this.zip.end(EOF) } else { super.write(EOF) super.end() } } } get [CURRENT] () { return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value } [JOBDONE] (job) { this[QUEUE].shift() this[JOBS] -= 1 this[PROCESS]() } [PROCESSJOB] (job) { if (job.pending) { return } if (job.entry) { if (job === this[CURRENT] && !job.piped) { this[PIPE](job) } return } if (!job.stat) { if (this.statCache.has(job.absolute)) { this[ONSTAT](job, this.statCache.get(job.absolute)) } else { this[STAT](job) } } if (!job.stat) { return } // filtered out! if (job.ignore) { return } if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { if (this.readdirCache.has(job.absolute)) { this[ONREADDIR](job, this.readdirCache.get(job.absolute)) } else { this[READDIR](job) } if (!job.readdir) { return } } // we know it doesn't have an entry, because that got checked above job.entry = this[ENTRY](job) if (!job.entry) { job.ignore = true return } if (job === this[CURRENT] && !job.piped) { this[PIPE](job) } } [ENTRYOPT] (job) { return { onwarn: (code, msg, data) => this.warn(code, msg, data), noPax: this.noPax, cwd: this.cwd, absolute: job.absolute, preservePaths: this.preservePaths, maxReadSize: this.maxReadSize, strict: this.strict, portable: this.portable, linkCache: this.linkCache, statCache: this.statCache, noMtime: this.noMtime, mtime: this.mtime, prefix: this.prefix, } } [ENTRY] (job) { this[JOBS] += 1 try { return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)) .on('end', () => this[JOBDONE](job)) .on('error', er => this.emit('error', er)) } catch (er) { this.emit('error', er) } } [ONDRAIN] () { if (this[CURRENT] && this[CURRENT].entry) { this[CURRENT].entry.resume() } } // like .pipe() but using super, because our write() is special [PIPE] (job) { job.piped = true if (job.readdir) { job.readdir.forEach(entry => { const p = job.path const base = p === './' ? '' : p.replace(/\/*$/, '/') this[ADDFSENTRY](base + entry) }) } const source = job.entry const zip = this.zip if (zip) { source.on('data', chunk => { if (!zip.write(chunk)) { source.pause() } }) } else { source.on('data', chunk => { if (!super.write(chunk)) { source.pause() } }) } } pause () { if (this.zip) { this.zip.pause() } return super.pause() } }) class PackSync extends Pack { constructor (opt) { super(opt) this[WRITEENTRYCLASS] = WriteEntrySync } // pause/resume are no-ops in sync streams. pause () {} resume () {} [STAT] (job) { const stat = this.follow ? 'statSync' : 'lstatSync' this[ONSTAT](job, fs[stat](job.absolute)) } [READDIR] (job, stat) { this[ONREADDIR](job, fs.readdirSync(job.absolute)) } // gotta get it all in this tick [PIPE] (job) { const source = job.entry const zip = this.zip if (job.readdir) { job.readdir.forEach(entry => { const p = job.path const base = p === './' ? '' : p.replace(/\/*$/, '/') this[ADDFSENTRY](base + entry) }) } if (zip) { source.on('data', chunk => { zip.write(chunk) }) } else { source.on('data', chunk => { super[WRITE](chunk) }) } } } Pack.Sync = PackSync module.exports = Pack node_modules/tar/lib/pax.js 0000664 00000007744 15114743311 0011721 0 ustar 00 'use strict' const Header = require('./header.js') const path = require('path') class Pax { constructor (obj, global) { this.atime = obj.atime || null this.charset = obj.charset || null this.comment = obj.comment || null this.ctime = obj.ctime || null this.gid = obj.gid || null this.gname = obj.gname || null this.linkpath = obj.linkpath || null this.mtime = obj.mtime || null this.path = obj.path || null this.size = obj.size || null this.uid = obj.uid || null this.uname = obj.uname || null this.dev = obj.dev || null this.ino = obj.ino || null this.nlink = obj.nlink || null this.global = global || false } encode () { const body = this.encodeBody() if (body === '') { return null } const bodyLen = Buffer.byteLength(body) // round up to 512 bytes // add 512 for header const bufLen = 512 * Math.ceil(1 + bodyLen / 512) const buf = Buffer.allocUnsafe(bufLen) // 0-fill the header section, it might not hit every field for (let i = 0; i < 512; i++) { buf[i] = 0 } new Header({ // XXX split the path // then the path should be PaxHeader + basename, but less than 99, // prepend with the dirname path: ('PaxHeader/' + path.basename(this.path)).slice(0, 99), mode: this.mode || 0o644, uid: this.uid || null, gid: this.gid || null, size: bodyLen, mtime: this.mtime || null, type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader', linkpath: '', uname: this.uname || '', gname: this.gname || '', devmaj: 0, devmin: 0, atime: this.atime || null, ctime: this.ctime || null, }).encode(buf) buf.write(body, 512, bodyLen, 'utf8') // null pad after the body for (let i = bodyLen + 512; i < buf.length; i++) { buf[i] = 0 } return buf } encodeBody () { return ( this.encodeField('path') + this.encodeField('ctime') + this.encodeField('atime') + this.encodeField('dev') + this.encodeField('ino') + this.encodeField('nlink') + this.encodeField('charset') + this.encodeField('comment') + this.encodeField('gid') + this.encodeField('gname') + this.encodeField('linkpath') + this.encodeField('mtime') + this.encodeField('size') + this.encodeField('uid') + this.encodeField('uname') ) } encodeField (field) { if (this[field] === null || this[field] === undefined) { return '' } const v = this[field] instanceof Date ? this[field].getTime() / 1000 : this[field] const s = ' ' + (field === 'dev' || field === 'ino' || field === 'nlink' ? 'SCHILY.' : '') + field + '=' + v + '\n' const byteLen = Buffer.byteLength(s) // the digits includes the length of the digits in ascii base-10 // so if it's 9 characters, then adding 1 for the 9 makes it 10 // which makes it 11 chars. let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1 if (byteLen + digits >= Math.pow(10, digits)) { digits += 1 } const len = digits + byteLen return len + s } } Pax.parse = (string, ex, g) => new Pax(merge(parseKV(string), ex), g) const merge = (a, b) => b ? Object.keys(a).reduce((s, k) => (s[k] = a[k], s), b) : a const parseKV = string => string .replace(/\n$/, '') .split('\n') .reduce(parseKVLine, Object.create(null)) const parseKVLine = (set, line) => { const n = parseInt(line, 10) // XXX Values with \n in them will fail this. // Refactor to not be a naive line-by-line parse. if (n !== Buffer.byteLength(line) + 1) { return set } line = line.slice((n + ' ').length) const kv = line.split('=') const k = kv.shift().replace(/^SCHILY\.(dev|ino|nlink)/, '$1') if (!k) { return set } const v = kv.join('=') set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) ? new Date(v * 1000) : /^[0-9]+$/.test(v) ? +v : v return set } module.exports = Pax node_modules/tar/lib/warn-mixin.js 0000664 00000001325 15114743311 0013207 0 ustar 00 'use strict' module.exports = Base => class extends Base { warn (code, message, data = {}) { if (this.file) { data.file = this.file } if (this.cwd) { data.cwd = this.cwd } data.code = message instanceof Error && message.code || code data.tarCode = code if (!this.strict && data.recoverable !== false) { if (message instanceof Error) { data = Object.assign(message, data) message = message.message } this.emit('warn', data.tarCode, message, data) } else if (message instanceof Error) { this.emit('error', Object.assign(message, data)) } else { this.emit('error', Object.assign(new Error(`${code}: ${message}`), data)) } } } node_modules/tar/lib/types.js 0000664 00000002110 15114743311 0012253 0 ustar 00 'use strict' // map types from key to human-friendly name exports.name = new Map([ ['0', 'File'], // same as File ['', 'OldFile'], ['1', 'Link'], ['2', 'SymbolicLink'], // Devices and FIFOs aren't fully supported // they are parsed, but skipped when unpacking ['3', 'CharacterDevice'], ['4', 'BlockDevice'], ['5', 'Directory'], ['6', 'FIFO'], // same as File ['7', 'ContiguousFile'], // pax headers ['g', 'GlobalExtendedHeader'], ['x', 'ExtendedHeader'], // vendor-specific stuff // skip ['A', 'SolarisACL'], // like 5, but with data, which should be skipped ['D', 'GNUDumpDir'], // metadata only, skip ['I', 'Inode'], // data = link path of next file ['K', 'NextFileHasLongLinkpath'], // data = path of next file ['L', 'NextFileHasLongPath'], // skip ['M', 'ContinuationFile'], // like L ['N', 'OldGnuLongPath'], // skip ['S', 'SparseFile'], // skip ['V', 'TapeVolumeHeader'], // like x ['X', 'OldExtendedHeader'], ]) // map the other direction exports.code = new Map(Array.from(exports.name).map(kv => [kv[1], kv[0]])) node_modules/tar/lib/mode-fix.js 0000664 00000001211 15114743311 0012620 0 ustar 00 'use strict' module.exports = (mode, isDir, portable) => { mode &= 0o7777 // in portable mode, use the minimum reasonable umask // if this system creates files with 0o664 by default // (as some linux distros do), then we'll write the // archive with 0o644 instead. Also, don't ever create // a file that is not readable/writable by the owner. if (portable) { mode = (mode | 0o600) & ~0o22 } // if dirs are readable, then they should be listable if (isDir) { if (mode & 0o400) { mode |= 0o100 } if (mode & 0o40) { mode |= 0o10 } if (mode & 0o4) { mode |= 0o1 } } return mode } node_modules/tar/lib/parse.js 0000664 00000037702 15114743311 0012240 0 ustar 00 'use strict' // this[BUFFER] is the remainder of a chunk if we're waiting for // the full 512 bytes of a header to come in. We will Buffer.concat() // it to the next write(), which is a mem copy, but a small one. // // this[QUEUE] is a Yallist of entries that haven't been emitted // yet this can only get filled up if the user keeps write()ing after // a write() returns false, or does a write() with more than one entry // // We don't buffer chunks, we always parse them and either create an // entry, or push it into the active entry. The ReadEntry class knows // to throw data away if .ignore=true // // Shift entry off the buffer when it emits 'end', and emit 'entry' for // the next one in the list. // // At any time, we're pushing body chunks into the entry at WRITEENTRY, // and waiting for 'end' on the entry at READENTRY // // ignored entries get .resume() called on them straight away const warner = require('./warn-mixin.js') const Header = require('./header.js') const EE = require('events') const Yallist = require('yallist') const maxMetaEntrySize = 1024 * 1024 const Entry = require('./read-entry.js') const Pax = require('./pax.js') const zlib = require('minizlib') const { nextTick } = require('process') const gzipHeader = Buffer.from([0x1f, 0x8b]) const STATE = Symbol('state') const WRITEENTRY = Symbol('writeEntry') const READENTRY = Symbol('readEntry') const NEXTENTRY = Symbol('nextEntry') const PROCESSENTRY = Symbol('processEntry') const EX = Symbol('extendedHeader') const GEX = Symbol('globalExtendedHeader') const META = Symbol('meta') const EMITMETA = Symbol('emitMeta') const BUFFER = Symbol('buffer') const QUEUE = Symbol('queue') const ENDED = Symbol('ended') const EMITTEDEND = Symbol('emittedEnd') const EMIT = Symbol('emit') const UNZIP = Symbol('unzip') const CONSUMECHUNK = Symbol('consumeChunk') const CONSUMECHUNKSUB = Symbol('consumeChunkSub') const CONSUMEBODY = Symbol('consumeBody') const CONSUMEMETA = Symbol('consumeMeta') const CONSUMEHEADER = Symbol('consumeHeader') const CONSUMING = Symbol('consuming') const BUFFERCONCAT = Symbol('bufferConcat') const MAYBEEND = Symbol('maybeEnd') const WRITING = Symbol('writing') const ABORTED = Symbol('aborted') const DONE = Symbol('onDone') const SAW_VALID_ENTRY = Symbol('sawValidEntry') const SAW_NULL_BLOCK = Symbol('sawNullBlock') const SAW_EOF = Symbol('sawEOF') const CLOSESTREAM = Symbol('closeStream') const noop = _ => true module.exports = warner(class Parser extends EE { constructor (opt) { opt = opt || {} super(opt) this.file = opt.file || '' // set to boolean false when an entry starts. 1024 bytes of \0 // is technically a valid tarball, albeit a boring one. this[SAW_VALID_ENTRY] = null // these BADARCHIVE errors can't be detected early. listen on DONE. this.on(DONE, _ => { if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) { // either less than 1 block of data, or all entries were invalid. // Either way, probably not even a tarball. this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format') } }) if (opt.ondone) { this.on(DONE, opt.ondone) } else { this.on(DONE, _ => { this.emit('prefinish') this.emit('finish') this.emit('end') }) } this.strict = !!opt.strict this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize this.filter = typeof opt.filter === 'function' ? opt.filter : noop // Unlike gzip, brotli doesn't have any magic bytes to identify it // Users need to explicitly tell us they're extracting a brotli file // Or we infer from the file extension const isTBR = (opt.file && ( opt.file.endsWith('.tar.br') || opt.file.endsWith('.tbr'))) // if it's a tbr file it MIGHT be brotli, but we don't know until // we look at it and verify it's not a valid tar file. this.brotli = !opt.gzip && opt.brotli !== undefined ? opt.brotli : isTBR ? undefined : false // have to set this so that streams are ok piping into it this.writable = true this.readable = false this[QUEUE] = new Yallist() this[BUFFER] = null this[READENTRY] = null this[WRITEENTRY] = null this[STATE] = 'begin' this[META] = '' this[EX] = null this[GEX] = null this[ENDED] = false this[UNZIP] = null this[ABORTED] = false this[SAW_NULL_BLOCK] = false this[SAW_EOF] = false this.on('end', () => this[CLOSESTREAM]()) if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } if (typeof opt.onentry === 'function') { this.on('entry', opt.onentry) } } [CONSUMEHEADER] (chunk, position) { if (this[SAW_VALID_ENTRY] === null) { this[SAW_VALID_ENTRY] = false } let header try { header = new Header(chunk, position, this[EX], this[GEX]) } catch (er) { return this.warn('TAR_ENTRY_INVALID', er) } if (header.nullBlock) { if (this[SAW_NULL_BLOCK]) { this[SAW_EOF] = true // ending an archive with no entries. pointless, but legal. if (this[STATE] === 'begin') { this[STATE] = 'header' } this[EMIT]('eof') } else { this[SAW_NULL_BLOCK] = true this[EMIT]('nullBlock') } } else { this[SAW_NULL_BLOCK] = false if (!header.cksumValid) { this.warn('TAR_ENTRY_INVALID', 'checksum failure', { header }) } else if (!header.path) { this.warn('TAR_ENTRY_INVALID', 'path is required', { header }) } else { const type = header.type if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) { this.warn('TAR_ENTRY_INVALID', 'linkpath required', { header }) } else if (!/^(Symbolic)?Link$/.test(type) && header.linkpath) { this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', { header }) } else { const entry = this[WRITEENTRY] = new Entry(header, this[EX], this[GEX]) // we do this for meta & ignored entries as well, because they // are still valid tar, or else we wouldn't know to ignore them if (!this[SAW_VALID_ENTRY]) { if (entry.remain) { // this might be the one! const onend = () => { if (!entry.invalid) { this[SAW_VALID_ENTRY] = true } } entry.on('end', onend) } else { this[SAW_VALID_ENTRY] = true } } if (entry.meta) { if (entry.size > this.maxMetaEntrySize) { entry.ignore = true this[EMIT]('ignoredEntry', entry) this[STATE] = 'ignore' entry.resume() } else if (entry.size > 0) { this[META] = '' entry.on('data', c => this[META] += c) this[STATE] = 'meta' } } else { this[EX] = null entry.ignore = entry.ignore || !this.filter(entry.path, entry) if (entry.ignore) { // probably valid, just not something we care about this[EMIT]('ignoredEntry', entry) this[STATE] = entry.remain ? 'ignore' : 'header' entry.resume() } else { if (entry.remain) { this[STATE] = 'body' } else { this[STATE] = 'header' entry.end() } if (!this[READENTRY]) { this[QUEUE].push(entry) this[NEXTENTRY]() } else { this[QUEUE].push(entry) } } } } } } } [CLOSESTREAM] () { nextTick(() => this.emit('close')) } [PROCESSENTRY] (entry) { let go = true if (!entry) { this[READENTRY] = null go = false } else if (Array.isArray(entry)) { this.emit.apply(this, entry) } else { this[READENTRY] = entry this.emit('entry', entry) if (!entry.emittedEnd) { entry.on('end', _ => this[NEXTENTRY]()) go = false } } return go } [NEXTENTRY] () { do {} while (this[PROCESSENTRY](this[QUEUE].shift())) if (!this[QUEUE].length) { // At this point, there's nothing in the queue, but we may have an // entry which is being consumed (readEntry). // If we don't, then we definitely can handle more data. // If we do, and either it's flowing, or it has never had any data // written to it, then it needs more. // The only other possibility is that it has returned false from a // write() call, so we wait for the next drain to continue. const re = this[READENTRY] const drainNow = !re || re.flowing || re.size === re.remain if (drainNow) { if (!this[WRITING]) { this.emit('drain') } } else { re.once('drain', _ => this.emit('drain')) } } } [CONSUMEBODY] (chunk, position) { // write up to but no more than writeEntry.blockRemain const entry = this[WRITEENTRY] const br = entry.blockRemain const c = (br >= chunk.length && position === 0) ? chunk : chunk.slice(position, position + br) entry.write(c) if (!entry.blockRemain) { this[STATE] = 'header' this[WRITEENTRY] = null entry.end() } return c.length } [CONSUMEMETA] (chunk, position) { const entry = this[WRITEENTRY] const ret = this[CONSUMEBODY](chunk, position) // if we finished, then the entry is reset if (!this[WRITEENTRY]) { this[EMITMETA](entry) } return ret } [EMIT] (ev, data, extra) { if (!this[QUEUE].length && !this[READENTRY]) { this.emit(ev, data, extra) } else { this[QUEUE].push([ev, data, extra]) } } [EMITMETA] (entry) { this[EMIT]('meta', this[META]) switch (entry.type) { case 'ExtendedHeader': case 'OldExtendedHeader': this[EX] = Pax.parse(this[META], this[EX], false) break case 'GlobalExtendedHeader': this[GEX] = Pax.parse(this[META], this[GEX], true) break case 'NextFileHasLongPath': case 'OldGnuLongPath': this[EX] = this[EX] || Object.create(null) this[EX].path = this[META].replace(/\0.*/, '') break case 'NextFileHasLongLinkpath': this[EX] = this[EX] || Object.create(null) this[EX].linkpath = this[META].replace(/\0.*/, '') break /* istanbul ignore next */ default: throw new Error('unknown meta: ' + entry.type) } } abort (error) { this[ABORTED] = true this.emit('abort', error) // always throws, even in non-strict mode this.warn('TAR_ABORT', error, { recoverable: false }) } write (chunk) { if (this[ABORTED]) { return } // first write, might be gzipped const needSniff = this[UNZIP] === null || this.brotli === undefined && this[UNZIP] === false if (needSniff && chunk) { if (this[BUFFER]) { chunk = Buffer.concat([this[BUFFER], chunk]) this[BUFFER] = null } if (chunk.length < gzipHeader.length) { this[BUFFER] = chunk return true } // look for gzip header for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) { if (chunk[i] !== gzipHeader[i]) { this[UNZIP] = false } } const maybeBrotli = this.brotli === undefined if (this[UNZIP] === false && maybeBrotli) { // read the first header to see if it's a valid tar file. If so, // we can safely assume that it's not actually brotli, despite the // .tbr or .tar.br file extension. // if we ended before getting a full chunk, yes, def brotli if (chunk.length < 512) { if (this[ENDED]) { this.brotli = true } else { this[BUFFER] = chunk return true } } else { // if it's tar, it's pretty reliably not brotli, chances of // that happening are astronomical. try { new Header(chunk.slice(0, 512)) this.brotli = false } catch (_) { this.brotli = true } } } if (this[UNZIP] === null || (this[UNZIP] === false && this.brotli)) { const ended = this[ENDED] this[ENDED] = false this[UNZIP] = this[UNZIP] === null ? new zlib.Unzip() : new zlib.BrotliDecompress() this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk)) this[UNZIP].on('error', er => this.abort(er)) this[UNZIP].on('end', _ => { this[ENDED] = true this[CONSUMECHUNK]() }) this[WRITING] = true const ret = this[UNZIP][ended ? 'end' : 'write'](chunk) this[WRITING] = false return ret } } this[WRITING] = true if (this[UNZIP]) { this[UNZIP].write(chunk) } else { this[CONSUMECHUNK](chunk) } this[WRITING] = false // return false if there's a queue, or if the current entry isn't flowing const ret = this[QUEUE].length ? false : this[READENTRY] ? this[READENTRY].flowing : true // if we have no queue, then that means a clogged READENTRY if (!ret && !this[QUEUE].length) { this[READENTRY].once('drain', _ => this.emit('drain')) } return ret } [BUFFERCONCAT] (c) { if (c && !this[ABORTED]) { this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c } } [MAYBEEND] () { if (this[ENDED] && !this[EMITTEDEND] && !this[ABORTED] && !this[CONSUMING]) { this[EMITTEDEND] = true const entry = this[WRITEENTRY] if (entry && entry.blockRemain) { // truncated, likely a damaged file const have = this[BUFFER] ? this[BUFFER].length : 0 this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${ entry.blockRemain} more bytes, only ${have} available)`, { entry }) if (this[BUFFER]) { entry.write(this[BUFFER]) } entry.end() } this[EMIT](DONE) } } [CONSUMECHUNK] (chunk) { if (this[CONSUMING]) { this[BUFFERCONCAT](chunk) } else if (!chunk && !this[BUFFER]) { this[MAYBEEND]() } else { this[CONSUMING] = true if (this[BUFFER]) { this[BUFFERCONCAT](chunk) const c = this[BUFFER] this[BUFFER] = null this[CONSUMECHUNKSUB](c) } else { this[CONSUMECHUNKSUB](chunk) } while (this[BUFFER] && this[BUFFER].length >= 512 && !this[ABORTED] && !this[SAW_EOF]) { const c = this[BUFFER] this[BUFFER] = null this[CONSUMECHUNKSUB](c) } this[CONSUMING] = false } if (!this[BUFFER] || this[ENDED]) { this[MAYBEEND]() } } [CONSUMECHUNKSUB] (chunk) { // we know that we are in CONSUMING mode, so anything written goes into // the buffer. Advance the position and put any remainder in the buffer. let position = 0 const length = chunk.length while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) { switch (this[STATE]) { case 'begin': case 'header': this[CONSUMEHEADER](chunk, position) position += 512 break case 'ignore': case 'body': position += this[CONSUMEBODY](chunk, position) break case 'meta': position += this[CONSUMEMETA](chunk, position) break /* istanbul ignore next */ default: throw new Error('invalid state: ' + this[STATE]) } } if (position < length) { if (this[BUFFER]) { this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]]) } else { this[BUFFER] = chunk.slice(position) } } } end (chunk) { if (!this[ABORTED]) { if (this[UNZIP]) { this[UNZIP].end(chunk) } else { this[ENDED] = true if (this.brotli === undefined) chunk = chunk || Buffer.alloc(0) this.write(chunk) } } } }) node_modules/tar/lib/high-level-opt.js 0000664 00000001370 15114743311 0013742 0 ustar 00 'use strict' // turn tar(1) style args like `C` into the more verbose things like `cwd` const argmap = new Map([ ['C', 'cwd'], ['f', 'file'], ['z', 'gzip'], ['P', 'preservePaths'], ['U', 'unlink'], ['strip-components', 'strip'], ['stripComponents', 'strip'], ['keep-newer', 'newer'], ['keepNewer', 'newer'], ['keep-newer-files', 'newer'], ['keepNewerFiles', 'newer'], ['k', 'keep'], ['keep-existing', 'keep'], ['keepExisting', 'keep'], ['m', 'noMtime'], ['no-mtime', 'noMtime'], ['p', 'preserveOwner'], ['L', 'follow'], ['h', 'follow'], ]) module.exports = opt => opt ? Object.keys(opt).map(k => [ argmap.has(k) ? argmap.get(k) : k, opt[k], ]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {} node_modules/tar/lib/update.js 0000664 00000001651 15114743311 0012402 0 ustar 00 'use strict' // tar -u const hlo = require('./high-level-opt.js') const r = require('./replace.js') // just call tar.r with the filter and mtimeCache module.exports = (opt_, files, cb) => { const opt = hlo(opt_) if (!opt.file) { throw new TypeError('file is required') } if (opt.gzip || opt.brotli || opt.file.endsWith('.br') || opt.file.endsWith('.tbr')) { throw new TypeError('cannot append to compressed archives') } if (!files || !Array.isArray(files) || !files.length) { throw new TypeError('no files or directories specified') } files = Array.from(files) mtimeFilter(opt) return r(opt, files, cb) } const mtimeFilter = opt => { const filter = opt.filter if (!opt.mtimeCache) { opt.mtimeCache = new Map() } opt.filter = filter ? (path, stat) => filter(path, stat) && !(opt.mtimeCache.get(path) > stat.mtime) : (path, stat) => !(opt.mtimeCache.get(path) > stat.mtime) } node_modules/tar/lib/replace.js 0000664 00000013220 15114743311 0012526 0 ustar 00 'use strict' // tar -r const hlo = require('./high-level-opt.js') const Pack = require('./pack.js') const fs = require('fs') const fsm = require('fs-minipass') const t = require('./list.js') const path = require('path') // starting at the head of the file, read a Header // If the checksum is invalid, that's our position to start writing // If it is, jump forward by the specified size (round up to 512) // and try again. // Write the new Pack stream starting there. const Header = require('./header.js') module.exports = (opt_, files, cb) => { const opt = hlo(opt_) if (!opt.file) { throw new TypeError('file is required') } if (opt.gzip || opt.brotli || opt.file.endsWith('.br') || opt.file.endsWith('.tbr')) { throw new TypeError('cannot append to compressed archives') } if (!files || !Array.isArray(files) || !files.length) { throw new TypeError('no files or directories specified') } files = Array.from(files) return opt.sync ? replaceSync(opt, files) : replace(opt, files, cb) } const replaceSync = (opt, files) => { const p = new Pack.Sync(opt) let threw = true let fd let position try { try { fd = fs.openSync(opt.file, 'r+') } catch (er) { if (er.code === 'ENOENT') { fd = fs.openSync(opt.file, 'w+') } else { throw er } } const st = fs.fstatSync(fd) const headBuf = Buffer.alloc(512) POSITION: for (position = 0; position < st.size; position += 512) { for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) { bytes = fs.readSync( fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos ) if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) { throw new Error('cannot append to compressed archives') } if (!bytes) { break POSITION } } const h = new Header(headBuf) if (!h.cksumValid) { break } const entryBlockSize = 512 * Math.ceil(h.size / 512) if (position + entryBlockSize + 512 > st.size) { break } // the 512 for the header we just parsed will be added as well // also jump ahead all the blocks for the body position += entryBlockSize if (opt.mtimeCache) { opt.mtimeCache.set(h.path, h.mtime) } } threw = false streamSync(opt, p, position, fd, files) } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } } } const streamSync = (opt, p, position, fd, files) => { const stream = new fsm.WriteStreamSync(opt.file, { fd: fd, start: position, }) p.pipe(stream) addFilesSync(p, files) } const replace = (opt, files, cb) => { files = Array.from(files) const p = new Pack(opt) const getPos = (fd, size, cb_) => { const cb = (er, pos) => { if (er) { fs.close(fd, _ => cb_(er)) } else { cb_(null, pos) } } let position = 0 if (size === 0) { return cb(null, 0) } let bufPos = 0 const headBuf = Buffer.alloc(512) const onread = (er, bytes) => { if (er) { return cb(er) } bufPos += bytes if (bufPos < 512 && bytes) { return fs.read( fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos, onread ) } if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) { return cb(new Error('cannot append to compressed archives')) } // truncated header if (bufPos < 512) { return cb(null, position) } const h = new Header(headBuf) if (!h.cksumValid) { return cb(null, position) } const entryBlockSize = 512 * Math.ceil(h.size / 512) if (position + entryBlockSize + 512 > size) { return cb(null, position) } position += entryBlockSize + 512 if (position >= size) { return cb(null, position) } if (opt.mtimeCache) { opt.mtimeCache.set(h.path, h.mtime) } bufPos = 0 fs.read(fd, headBuf, 0, 512, position, onread) } fs.read(fd, headBuf, 0, 512, position, onread) } const promise = new Promise((resolve, reject) => { p.on('error', reject) let flag = 'r+' const onopen = (er, fd) => { if (er && er.code === 'ENOENT' && flag === 'r+') { flag = 'w+' return fs.open(opt.file, flag, onopen) } if (er) { return reject(er) } fs.fstat(fd, (er, st) => { if (er) { return fs.close(fd, () => reject(er)) } getPos(fd, st.size, (er, position) => { if (er) { return reject(er) } const stream = new fsm.WriteStream(opt.file, { fd: fd, start: position, }) p.pipe(stream) stream.on('error', reject) stream.on('close', resolve) addFilesAsync(p, files) }) }) } fs.open(opt.file, flag, onopen) }) return cb ? promise.then(cb, cb) : promise } const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { t({ file: path.resolve(p.cwd, file.slice(1)), sync: true, noResume: true, onentry: entry => p.add(entry), }) } else { p.add(file) } }) p.end() } const addFilesAsync = (p, files) => { while (files.length) { const file = files.shift() if (file.charAt(0) === '@') { return t({ file: path.resolve(p.cwd, file.slice(1)), noResume: true, onentry: entry => p.add(entry), }).then(_ => addFilesAsync(p, files)) } else { p.add(file) } } p.end() } node_modules/tar/lib/write-entry.js 0000664 00000035704 15114743311 0013417 0 ustar 00 'use strict' const { Minipass } = require('minipass') const Pax = require('./pax.js') const Header = require('./header.js') const fs = require('fs') const path = require('path') const normPath = require('./normalize-windows-path.js') const stripSlash = require('./strip-trailing-slashes.js') const prefixPath = (path, prefix) => { if (!prefix) { return normPath(path) } path = normPath(path).replace(/^\.(\/|$)/, '') return stripSlash(prefix) + '/' + path } const maxReadSize = 16 * 1024 * 1024 const PROCESS = Symbol('process') const FILE = Symbol('file') const DIRECTORY = Symbol('directory') const SYMLINK = Symbol('symlink') const HARDLINK = Symbol('hardlink') const HEADER = Symbol('header') const READ = Symbol('read') const LSTAT = Symbol('lstat') const ONLSTAT = Symbol('onlstat') const ONREAD = Symbol('onread') const ONREADLINK = Symbol('onreadlink') const OPENFILE = Symbol('openfile') const ONOPENFILE = Symbol('onopenfile') const CLOSE = Symbol('close') const MODE = Symbol('mode') const AWAITDRAIN = Symbol('awaitDrain') const ONDRAIN = Symbol('ondrain') const PREFIX = Symbol('prefix') const HAD_ERROR = Symbol('hadError') const warner = require('./warn-mixin.js') const winchars = require('./winchars.js') const stripAbsolutePath = require('./strip-absolute-path.js') const modeFix = require('./mode-fix.js') const WriteEntry = warner(class WriteEntry extends Minipass { constructor (p, opt) { opt = opt || {} super(opt) if (typeof p !== 'string') { throw new TypeError('path is required') } this.path = normPath(p) // suppress atime, ctime, uid, gid, uname, gname this.portable = !!opt.portable // until node has builtin pwnam functions, this'll have to do this.myuid = process.getuid && process.getuid() || 0 this.myuser = process.env.USER || '' this.maxReadSize = opt.maxReadSize || maxReadSize this.linkCache = opt.linkCache || new Map() this.statCache = opt.statCache || new Map() this.preservePaths = !!opt.preservePaths this.cwd = normPath(opt.cwd || process.cwd()) this.strict = !!opt.strict this.noPax = !!opt.noPax this.noMtime = !!opt.noMtime this.mtime = opt.mtime || null this.prefix = opt.prefix ? normPath(opt.prefix) : null this.fd = null this.blockLen = null this.blockRemain = null this.buf = null this.offset = null this.length = null this.pos = null this.remain = null if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } let pathWarn = false if (!this.preservePaths) { const [root, stripped] = stripAbsolutePath(this.path) if (root) { this.path = stripped pathWarn = root } } this.win32 = !!opt.win32 || process.platform === 'win32' if (this.win32) { // force the \ to / normalization, since we might not *actually* // be on windows, but want \ to be considered a path separator. this.path = winchars.decode(this.path.replace(/\\/g, '/')) p = p.replace(/\\/g, '/') } this.absolute = normPath(opt.absolute || path.resolve(this.cwd, p)) if (this.path === '') { this.path = './' } if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }) } if (this.statCache.has(this.absolute)) { this[ONLSTAT](this.statCache.get(this.absolute)) } else { this[LSTAT]() } } emit (ev, ...data) { if (ev === 'error') { this[HAD_ERROR] = true } return super.emit(ev, ...data) } [LSTAT] () { fs.lstat(this.absolute, (er, stat) => { if (er) { return this.emit('error', er) } this[ONLSTAT](stat) }) } [ONLSTAT] (stat) { this.statCache.set(this.absolute, stat) this.stat = stat if (!stat.isFile()) { stat.size = 0 } this.type = getType(stat) this.emit('stat', stat) this[PROCESS]() } [PROCESS] () { switch (this.type) { case 'File': return this[FILE]() case 'Directory': return this[DIRECTORY]() case 'SymbolicLink': return this[SYMLINK]() // unsupported types are ignored. default: return this.end() } } [MODE] (mode) { return modeFix(mode, this.type === 'Directory', this.portable) } [PREFIX] (path) { return prefixPath(path, this.prefix) } [HEADER] () { if (this.type === 'Directory' && this.portable) { this.noMtime = true } this.header = new Header({ path: this[PREFIX](this.path), // only apply the prefix to hard links. linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this[MODE](this.stat.mode), uid: this.portable ? null : this.stat.uid, gid: this.portable ? null : this.stat.gid, size: this.stat.size, mtime: this.noMtime ? null : this.mtime || this.stat.mtime, type: this.type, uname: this.portable ? null : this.stat.uid === this.myuid ? this.myuser : '', atime: this.portable ? null : this.stat.atime, ctime: this.portable ? null : this.stat.ctime, }) if (this.header.encode() && !this.noPax) { super.write(new Pax({ atime: this.portable ? null : this.header.atime, ctime: this.portable ? null : this.header.ctime, gid: this.portable ? null : this.header.gid, mtime: this.noMtime ? null : this.mtime || this.header.mtime, path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, size: this.header.size, uid: this.portable ? null : this.header.uid, uname: this.portable ? null : this.header.uname, dev: this.portable ? null : this.stat.dev, ino: this.portable ? null : this.stat.ino, nlink: this.portable ? null : this.stat.nlink, }).encode()) } super.write(this.header.block) } [DIRECTORY] () { if (this.path.slice(-1) !== '/') { this.path += '/' } this.stat.size = 0 this[HEADER]() this.end() } [SYMLINK] () { fs.readlink(this.absolute, (er, linkpath) => { if (er) { return this.emit('error', er) } this[ONREADLINK](linkpath) }) } [ONREADLINK] (linkpath) { this.linkpath = normPath(linkpath) this[HEADER]() this.end() } [HARDLINK] (linkpath) { this.type = 'Link' this.linkpath = normPath(path.relative(this.cwd, linkpath)) this.stat.size = 0 this[HEADER]() this.end() } [FILE] () { if (this.stat.nlink > 1) { const linkKey = this.stat.dev + ':' + this.stat.ino if (this.linkCache.has(linkKey)) { const linkpath = this.linkCache.get(linkKey) if (linkpath.indexOf(this.cwd) === 0) { return this[HARDLINK](linkpath) } } this.linkCache.set(linkKey, this.absolute) } this[HEADER]() if (this.stat.size === 0) { return this.end() } this[OPENFILE]() } [OPENFILE] () { fs.open(this.absolute, 'r', (er, fd) => { if (er) { return this.emit('error', er) } this[ONOPENFILE](fd) }) } [ONOPENFILE] (fd) { this.fd = fd if (this[HAD_ERROR]) { return this[CLOSE]() } this.blockLen = 512 * Math.ceil(this.stat.size / 512) this.blockRemain = this.blockLen const bufLen = Math.min(this.blockLen, this.maxReadSize) this.buf = Buffer.allocUnsafe(bufLen) this.offset = 0 this.pos = 0 this.remain = this.stat.size this.length = this.buf.length this[READ]() } [READ] () { const { fd, buf, offset, length, pos } = this fs.read(fd, buf, offset, length, pos, (er, bytesRead) => { if (er) { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one return this[CLOSE](() => this.emit('error', er)) } this[ONREAD](bytesRead) }) } [CLOSE] (cb) { fs.close(this.fd, cb) } [ONREAD] (bytesRead) { if (bytesRead <= 0 && this.remain > 0) { const er = new Error('encountered unexpected EOF') er.path = this.absolute er.syscall = 'read' er.code = 'EOF' return this[CLOSE](() => this.emit('error', er)) } if (bytesRead > this.remain) { const er = new Error('did not encounter expected EOF') er.path = this.absolute er.syscall = 'read' er.code = 'EOF' return this[CLOSE](() => this.emit('error', er)) } // null out the rest of the buffer, if we could fit the block padding // at the end of this loop, we've incremented bytesRead and this.remain // to be incremented up to the blockRemain level, as if we had expected // to get a null-padded file, and read it until the end. then we will // decrement both remain and blockRemain by bytesRead, and know that we // reached the expected EOF, without any null buffer to append. if (bytesRead === this.remain) { for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) { this.buf[i + this.offset] = 0 bytesRead++ this.remain++ } } const writeBuf = this.offset === 0 && bytesRead === this.buf.length ? this.buf : this.buf.slice(this.offset, this.offset + bytesRead) const flushed = this.write(writeBuf) if (!flushed) { this[AWAITDRAIN](() => this[ONDRAIN]()) } else { this[ONDRAIN]() } } [AWAITDRAIN] (cb) { this.once('drain', cb) } write (writeBuf) { if (this.blockRemain < writeBuf.length) { const er = new Error('writing more data than expected') er.path = this.absolute return this.emit('error', er) } this.remain -= writeBuf.length this.blockRemain -= writeBuf.length this.pos += writeBuf.length this.offset += writeBuf.length return super.write(writeBuf) } [ONDRAIN] () { if (!this.remain) { if (this.blockRemain) { super.write(Buffer.alloc(this.blockRemain)) } return this[CLOSE](er => er ? this.emit('error', er) : this.end()) } if (this.offset >= this.length) { // if we only have a smaller bit left to read, alloc a smaller buffer // otherwise, keep it the same length it was before. this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length)) this.offset = 0 } this.length = this.buf.length - this.offset this[READ]() } }) class WriteEntrySync extends WriteEntry { [LSTAT] () { this[ONLSTAT](fs.lstatSync(this.absolute)) } [SYMLINK] () { this[ONREADLINK](fs.readlinkSync(this.absolute)) } [OPENFILE] () { this[ONOPENFILE](fs.openSync(this.absolute, 'r')) } [READ] () { let threw = true try { const { fd, buf, offset, length, pos } = this const bytesRead = fs.readSync(fd, buf, offset, length, pos) this[ONREAD](bytesRead) threw = false } finally { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one if (threw) { try { this[CLOSE](() => {}) } catch (er) {} } } } [AWAITDRAIN] (cb) { cb() } [CLOSE] (cb) { fs.closeSync(this.fd) cb() } } const WriteEntryTar = warner(class WriteEntryTar extends Minipass { constructor (readEntry, opt) { opt = opt || {} super(opt) this.preservePaths = !!opt.preservePaths this.portable = !!opt.portable this.strict = !!opt.strict this.noPax = !!opt.noPax this.noMtime = !!opt.noMtime this.readEntry = readEntry this.type = readEntry.type if (this.type === 'Directory' && this.portable) { this.noMtime = true } this.prefix = opt.prefix || null this.path = normPath(readEntry.path) this.mode = this[MODE](readEntry.mode) this.uid = this.portable ? null : readEntry.uid this.gid = this.portable ? null : readEntry.gid this.uname = this.portable ? null : readEntry.uname this.gname = this.portable ? null : readEntry.gname this.size = readEntry.size this.mtime = this.noMtime ? null : opt.mtime || readEntry.mtime this.atime = this.portable ? null : readEntry.atime this.ctime = this.portable ? null : readEntry.ctime this.linkpath = normPath(readEntry.linkpath) if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } let pathWarn = false if (!this.preservePaths) { const [root, stripped] = stripAbsolutePath(this.path) if (root) { this.path = stripped pathWarn = root } } this.remain = readEntry.size this.blockRemain = readEntry.startBlockSize this.header = new Header({ path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this.mode, uid: this.portable ? null : this.uid, gid: this.portable ? null : this.gid, size: this.size, mtime: this.noMtime ? null : this.mtime, type: this.type, uname: this.portable ? null : this.uname, atime: this.portable ? null : this.atime, ctime: this.portable ? null : this.ctime, }) if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }) } if (this.header.encode() && !this.noPax) { super.write(new Pax({ atime: this.portable ? null : this.atime, ctime: this.portable ? null : this.ctime, gid: this.portable ? null : this.gid, mtime: this.noMtime ? null : this.mtime, path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, size: this.size, uid: this.portable ? null : this.uid, uname: this.portable ? null : this.uname, dev: this.portable ? null : this.readEntry.dev, ino: this.portable ? null : this.readEntry.ino, nlink: this.portable ? null : this.readEntry.nlink, }).encode()) } super.write(this.header.block) readEntry.pipe(this) } [PREFIX] (path) { return prefixPath(path, this.prefix) } [MODE] (mode) { return modeFix(mode, this.type === 'Directory', this.portable) } write (data) { const writeLen = data.length if (writeLen > this.blockRemain) { throw new Error('writing more to entry than is appropriate') } this.blockRemain -= writeLen return super.write(data) } end () { if (this.blockRemain) { super.write(Buffer.alloc(this.blockRemain)) } return super.end() } }) WriteEntry.Sync = WriteEntrySync WriteEntry.Tar = WriteEntryTar const getType = stat => stat.isFile() ? 'File' : stat.isDirectory() ? 'Directory' : stat.isSymbolicLink() ? 'SymbolicLink' : 'Unsupported' module.exports = WriteEntry node_modules/tar/lib/list.js 0000664 00000006230 15114743311 0012071 0 ustar 00 'use strict' // XXX: This shares a lot in common with extract.js // maybe some DRY opportunity here? // tar -t const hlo = require('./high-level-opt.js') const Parser = require('./parse.js') const fs = require('fs') const fsm = require('fs-minipass') const path = require('path') const stripSlash = require('./strip-trailing-slashes.js') module.exports = (opt_, files, cb) => { if (typeof opt_ === 'function') { cb = opt_, files = null, opt_ = {} } else if (Array.isArray(opt_)) { files = opt_, opt_ = {} } if (typeof files === 'function') { cb = files, files = null } if (!files) { files = [] } else { files = Array.from(files) } const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions') } if (!opt.file && typeof cb === 'function') { throw new TypeError('callback only supported with file option') } if (files.length) { filesFilter(opt, files) } if (!opt.noResume) { onentryFunction(opt) } return opt.file && opt.sync ? listFileSync(opt) : opt.file ? listFile(opt, cb) : list(opt) } const onentryFunction = opt => { const onentry = opt.onentry opt.onentry = onentry ? e => { onentry(e) e.resume() } : e => e.resume() } // construct a filter that limits the file entries listed // include child entries if a dir is included const filesFilter = (opt, files) => { const map = new Map(files.map(f => [stripSlash(f), true])) const filter = opt.filter const mapHas = (file, r) => { const root = r || path.parse(file).root || '.' const ret = file === root ? false : map.has(file) ? map.get(file) : mapHas(path.dirname(file), root) map.set(file, ret) return ret } opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) : file => mapHas(stripSlash(file)) } const listFileSync = opt => { const p = list(opt) const file = opt.file let threw = true let fd try { const stat = fs.statSync(file) const readSize = opt.maxReadSize || 16 * 1024 * 1024 if (stat.size < readSize) { p.end(fs.readFileSync(file)) } else { let pos = 0 const buf = Buffer.allocUnsafe(readSize) fd = fs.openSync(file, 'r') while (pos < stat.size) { const bytesRead = fs.readSync(fd, buf, 0, readSize, pos) pos += bytesRead p.write(buf.slice(0, bytesRead)) } p.end() } threw = false } finally { if (threw && fd) { try { fs.closeSync(fd) } catch (er) {} } } } const listFile = (opt, cb) => { const parse = new Parser(opt) const readSize = opt.maxReadSize || 16 * 1024 * 1024 const file = opt.file const p = new Promise((resolve, reject) => { parse.on('error', reject) parse.on('end', resolve) fs.stat(file, (er, stat) => { if (er) { reject(er) } else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }) stream.on('error', reject) stream.pipe(parse) } }) }) return cb ? p.then(cb, cb) : p } const list = opt => new Parser(opt) node_modules/tar/lib/large-numbers.js 0000664 00000004265 15114743311 0013667 0 ustar 00 'use strict' // Tar can encode large and negative numbers using a leading byte of // 0xff for negative, and 0x80 for positive. const encode = (num, buf) => { if (!Number.isSafeInteger(num)) { // The number is so large that javascript cannot represent it with integer // precision. throw Error('cannot encode number outside of javascript safe integer range') } else if (num < 0) { encodeNegative(num, buf) } else { encodePositive(num, buf) } return buf } const encodePositive = (num, buf) => { buf[0] = 0x80 for (var i = buf.length; i > 1; i--) { buf[i - 1] = num & 0xff num = Math.floor(num / 0x100) } } const encodeNegative = (num, buf) => { buf[0] = 0xff var flipped = false num = num * -1 for (var i = buf.length; i > 1; i--) { var byte = num & 0xff num = Math.floor(num / 0x100) if (flipped) { buf[i - 1] = onesComp(byte) } else if (byte === 0) { buf[i - 1] = 0 } else { flipped = true buf[i - 1] = twosComp(byte) } } } const parse = (buf) => { const pre = buf[0] const value = pre === 0x80 ? pos(buf.slice(1, buf.length)) : pre === 0xff ? twos(buf) : null if (value === null) { throw Error('invalid base256 encoding') } if (!Number.isSafeInteger(value)) { // The number is so large that javascript cannot represent it with integer // precision. throw Error('parsed number outside of javascript safe integer range') } return value } const twos = (buf) => { var len = buf.length var sum = 0 var flipped = false for (var i = len - 1; i > -1; i--) { var byte = buf[i] var f if (flipped) { f = onesComp(byte) } else if (byte === 0) { f = byte } else { flipped = true f = twosComp(byte) } if (f !== 0) { sum -= f * Math.pow(256, len - i - 1) } } return sum } const pos = (buf) => { var len = buf.length var sum = 0 for (var i = len - 1; i > -1; i--) { var byte = buf[i] if (byte !== 0) { sum += byte * Math.pow(256, len - i - 1) } } return sum } const onesComp = byte => (0xff ^ byte) & 0xff const twosComp = byte => ((0xff ^ byte) + 1) & 0xff module.exports = { encode, parse, } node_modules/tar/lib/create.js 0000664 00000004533 15114743311 0012365 0 ustar 00 'use strict' // tar -c const hlo = require('./high-level-opt.js') const Pack = require('./pack.js') const fsm = require('fs-minipass') const t = require('./list.js') const path = require('path') module.exports = (opt_, files, cb) => { if (typeof files === 'function') { cb = files } if (Array.isArray(opt_)) { files = opt_, opt_ = {} } if (!files || !Array.isArray(files) || !files.length) { throw new TypeError('no files or directories specified') } files = Array.from(files) const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions') } if (!opt.file && typeof cb === 'function') { throw new TypeError('callback only supported with file option') } return opt.file && opt.sync ? createFileSync(opt, files) : opt.file ? createFile(opt, files, cb) : opt.sync ? createSync(opt, files) : create(opt, files) } const createFileSync = (opt, files) => { const p = new Pack.Sync(opt) const stream = new fsm.WriteStreamSync(opt.file, { mode: opt.mode || 0o666, }) p.pipe(stream) addFilesSync(p, files) } const createFile = (opt, files, cb) => { const p = new Pack(opt) const stream = new fsm.WriteStream(opt.file, { mode: opt.mode || 0o666, }) p.pipe(stream) const promise = new Promise((res, rej) => { stream.on('error', rej) stream.on('close', res) p.on('error', rej) }) addFilesAsync(p, files) return cb ? promise.then(cb, cb) : promise } const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { t({ file: path.resolve(p.cwd, file.slice(1)), sync: true, noResume: true, onentry: entry => p.add(entry), }) } else { p.add(file) } }) p.end() } const addFilesAsync = (p, files) => { while (files.length) { const file = files.shift() if (file.charAt(0) === '@') { return t({ file: path.resolve(p.cwd, file.slice(1)), noResume: true, onentry: entry => p.add(entry), }).then(_ => addFilesAsync(p, files)) } else { p.add(file) } } p.end() } const createSync = (opt, files) => { const p = new Pack.Sync(opt) addFilesSync(p, files) return p } const create = (opt, files) => { const p = new Pack(opt) addFilesAsync(p, files) return p } node_modules/tar/lib/path-reservations.js 0000664 00000010472 15114743311 0014577 0 ustar 00 // A path exclusive reservation system // reserve([list, of, paths], fn) // When the fn is first in line for all its paths, it // is called with a cb that clears the reservation. // // Used by async unpack to avoid clobbering paths in use, // while still allowing maximal safe parallelization. const assert = require('assert') const normalize = require('./normalize-unicode.js') const stripSlashes = require('./strip-trailing-slashes.js') const { join } = require('path') const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform const isWindows = platform === 'win32' module.exports = () => { // path => [function or Set] // A Set object means a directory reservation // A fn is a direct reservation on that path const queues = new Map() // fn => {paths:[path,...], dirs:[path, ...]} const reservations = new Map() // return a set of parent dirs for a given path // '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d'] const getDirs = path => { const dirs = path.split('/').slice(0, -1).reduce((set, path) => { if (set.length) { path = join(set[set.length - 1], path) } set.push(path || '/') return set }, []) return dirs } // functions currently running const running = new Set() // return the queues for each path the function cares about // fn => {paths, dirs} const getQueues = fn => { const res = reservations.get(fn) /* istanbul ignore if - unpossible */ if (!res) { throw new Error('function does not have any path reservations') } return { paths: res.paths.map(path => queues.get(path)), dirs: [...res.dirs].map(path => queues.get(path)), } } // check if fn is first in line for all its paths, and is // included in the first set for all its dir queues const check = fn => { const { paths, dirs } = getQueues(fn) return paths.every(q => q[0] === fn) && dirs.every(q => q[0] instanceof Set && q[0].has(fn)) } // run the function if it's first in line and not already running const run = fn => { if (running.has(fn) || !check(fn)) { return false } running.add(fn) fn(() => clear(fn)) return true } const clear = fn => { if (!running.has(fn)) { return false } const { paths, dirs } = reservations.get(fn) const next = new Set() paths.forEach(path => { const q = queues.get(path) assert.equal(q[0], fn) if (q.length === 1) { queues.delete(path) } else { q.shift() if (typeof q[0] === 'function') { next.add(q[0]) } else { q[0].forEach(fn => next.add(fn)) } } }) dirs.forEach(dir => { const q = queues.get(dir) assert(q[0] instanceof Set) if (q[0].size === 1 && q.length === 1) { queues.delete(dir) } else if (q[0].size === 1) { q.shift() // must be a function or else the Set would've been reused next.add(q[0]) } else { q[0].delete(fn) } }) running.delete(fn) next.forEach(fn => run(fn)) return true } const reserve = (paths, fn) => { // collide on matches across case and unicode normalization // On windows, thanks to the magic of 8.3 shortnames, it is fundamentally // impossible to determine whether two paths refer to the same thing on // disk, without asking the kernel for a shortname. // So, we just pretend that every path matches every other path here, // effectively removing all parallelization on windows. paths = isWindows ? ['win32 parallelization disabled'] : paths.map(p => { // don't need normPath, because we skip this entirely for windows return stripSlashes(join(normalize(p))).toLowerCase() }) const dirs = new Set( paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)) ) reservations.set(fn, { dirs, paths }) paths.forEach(path => { const q = queues.get(path) if (!q) { queues.set(path, [fn]) } else { q.push(fn) } }) dirs.forEach(dir => { const q = queues.get(dir) if (!q) { queues.set(dir, [new Set([fn])]) } else if (q[q.length - 1] instanceof Set) { q[q.length - 1].add(fn) } else { q.push(new Set([fn])) } }) return run(fn) } return { check, reserve } } node_modules/tar/lib/mkdir.js 0000664 00000012555 15114743311 0012233 0 ustar 00 'use strict' // wrapper around mkdirp for tar's needs. // TODO: This should probably be a class, not functionally // passing around state in a gazillion args. const mkdirp = require('mkdirp') const fs = require('fs') const path = require('path') const chownr = require('chownr') const normPath = require('./normalize-windows-path.js') class SymlinkError extends Error { constructor (symlink, path) { super('Cannot extract through symbolic link') this.path = path this.symlink = symlink } get name () { return 'SylinkError' } } class CwdError extends Error { constructor (path, code) { super(code + ': Cannot cd into \'' + path + '\'') this.path = path this.code = code } get name () { return 'CwdError' } } const cGet = (cache, key) => cache.get(normPath(key)) const cSet = (cache, key, val) => cache.set(normPath(key), val) const checkCwd = (dir, cb) => { fs.stat(dir, (er, st) => { if (er || !st.isDirectory()) { er = new CwdError(dir, er && er.code || 'ENOTDIR') } cb(er) }) } module.exports = (dir, opt, cb) => { dir = normPath(dir) // if there's any overlap between mask and mode, // then we'll need an explicit chmod const umask = opt.umask const mode = opt.mode | 0o0700 const needChmod = (mode & umask) !== 0 const uid = opt.uid const gid = opt.gid const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid) const preserve = opt.preserve const unlink = opt.unlink const cache = opt.cache const cwd = normPath(opt.cwd) const done = (er, created) => { if (er) { cb(er) } else { cSet(cache, dir, true) if (created && doChown) { chownr(created, uid, gid, er => done(er)) } else if (needChmod) { fs.chmod(dir, mode, cb) } else { cb() } } } if (cache && cGet(cache, dir) === true) { return done() } if (dir === cwd) { return checkCwd(dir, done) } if (preserve) { return mkdirp(dir, { mode }).then(made => done(null, made), done) } const sub = normPath(path.relative(cwd, dir)) const parts = sub.split('/') mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done) } const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { if (!parts.length) { return cb(null, created) } const p = parts.shift() const part = normPath(path.resolve(base + '/' + p)) if (cGet(cache, part)) { return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) } fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) } const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => er => { if (er) { fs.lstat(part, (statEr, st) => { if (statEr) { statEr.path = statEr.path && normPath(statEr.path) cb(statEr) } else if (st.isDirectory()) { mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) } else if (unlink) { fs.unlink(part, er => { if (er) { return cb(er) } fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) }) } else if (st.isSymbolicLink()) { return cb(new SymlinkError(part, part + '/' + parts.join('/'))) } else { cb(er) } }) } else { created = created || part mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) } } const checkCwdSync = dir => { let ok = false let code = 'ENOTDIR' try { ok = fs.statSync(dir).isDirectory() } catch (er) { code = er.code } finally { if (!ok) { throw new CwdError(dir, code) } } } module.exports.sync = (dir, opt) => { dir = normPath(dir) // if there's any overlap between mask and mode, // then we'll need an explicit chmod const umask = opt.umask const mode = opt.mode | 0o0700 const needChmod = (mode & umask) !== 0 const uid = opt.uid const gid = opt.gid const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid) const preserve = opt.preserve const unlink = opt.unlink const cache = opt.cache const cwd = normPath(opt.cwd) const done = (created) => { cSet(cache, dir, true) if (created && doChown) { chownr.sync(created, uid, gid) } if (needChmod) { fs.chmodSync(dir, mode) } } if (cache && cGet(cache, dir) === true) { return done() } if (dir === cwd) { checkCwdSync(cwd) return done() } if (preserve) { return done(mkdirp.sync(dir, mode)) } const sub = normPath(path.relative(cwd, dir)) const parts = sub.split('/') let created = null for (let p = parts.shift(), part = cwd; p && (part += '/' + p); p = parts.shift()) { part = normPath(path.resolve(part)) if (cGet(cache, part)) { continue } try { fs.mkdirSync(part, mode) created = created || part cSet(cache, part, true) } catch (er) { const st = fs.lstatSync(part) if (st.isDirectory()) { cSet(cache, part, true) continue } else if (unlink) { fs.unlinkSync(part) fs.mkdirSync(part, mode) created = created || part cSet(cache, part, true) continue } else if (st.isSymbolicLink()) { return new SymlinkError(part, part + '/' + parts.join('/')) } } } return done(created) } node_modules/tar/lib/strip-absolute-path.js 0000664 00000001625 15114743311 0015030 0 ustar 00 // unix absolute paths are also absolute on win32, so we use this for both const { isAbsolute, parse } = require('path').win32 // returns [root, stripped] // Note that windows will think that //x/y/z/a has a "root" of //x/y, and in // those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip / // explicitly if it's the first character. // drive-specific relative paths on Windows get their root stripped off even // though they are not absolute, so `c:../foo` becomes ['c:', '../foo'] module.exports = path => { let r = '' let parsed = parse(path) while (isAbsolute(path) || parsed.root) { // windows will think that //x/y/z has a "root" of //x/y/ // but strip the //?/C:/ off of //?/C:/path const root = path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ? '/' : parsed.root path = path.slice(root.length) r += root parsed = parse(path) } return [r, path] } node_modules/tar/lib/get-write-flag.js 0000664 00000001631 15114743311 0013734 0 ustar 00 // Get the appropriate flag to use for creating files // We use fmap on Windows platforms for files less than // 512kb. This is a fairly low limit, but avoids making // things slower in some cases. Since most of what this // library is used for is extracting tarballs of many // relatively small files in npm packages and the like, // it can be a big boost on Windows platforms. // Only supported in Node v12.9.0 and above. const platform = process.env.__FAKE_PLATFORM__ || process.platform const isWindows = platform === 'win32' const fs = global.__FAKE_TESTING_FS__ || require('fs') /* istanbul ignore next */ const { O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP = 0 } = fs.constants const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP const fMapLimit = 512 * 1024 const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY module.exports = !fMapEnabled ? () => 'w' : size => size < fMapLimit ? fMapFlag : 'w' node_modules/tar/lib/normalize-windows-path.js 0000664 00000000632 15114743311 0015540 0 ustar 00 // on windows, either \ or / are valid directory separators. // on unix, \ is a valid character in filenames. // so, on windows, and only on windows, we replace all \ chars with /, // so that we can use / as our one and only directory separator char. const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform module.exports = platform !== 'win32' ? p => p : p => p && p.replace(/\\/g, '/') node_modules/tar/lib/read-entry.js 0000664 00000005432 15114743311 0013173 0 ustar 00 'use strict' const { Minipass } = require('minipass') const normPath = require('./normalize-windows-path.js') const SLURP = Symbol('slurp') module.exports = class ReadEntry extends Minipass { constructor (header, ex, gex) { super() // read entries always start life paused. this is to avoid the // situation where Minipass's auto-ending empty streams results // in an entry ending before we're ready for it. this.pause() this.extended = ex this.globalExtended = gex this.header = header this.startBlockSize = 512 * Math.ceil(header.size / 512) this.blockRemain = this.startBlockSize this.remain = header.size this.type = header.type this.meta = false this.ignore = false switch (this.type) { case 'File': case 'OldFile': case 'Link': case 'SymbolicLink': case 'CharacterDevice': case 'BlockDevice': case 'Directory': case 'FIFO': case 'ContiguousFile': case 'GNUDumpDir': break case 'NextFileHasLongLinkpath': case 'NextFileHasLongPath': case 'OldGnuLongPath': case 'GlobalExtendedHeader': case 'ExtendedHeader': case 'OldExtendedHeader': this.meta = true break // NOTE: gnutar and bsdtar treat unrecognized types as 'File' // it may be worth doing the same, but with a warning. default: this.ignore = true } this.path = normPath(header.path) this.mode = header.mode if (this.mode) { this.mode = this.mode & 0o7777 } this.uid = header.uid this.gid = header.gid this.uname = header.uname this.gname = header.gname this.size = header.size this.mtime = header.mtime this.atime = header.atime this.ctime = header.ctime this.linkpath = normPath(header.linkpath) this.uname = header.uname this.gname = header.gname if (ex) { this[SLURP](ex) } if (gex) { this[SLURP](gex, true) } } write (data) { const writeLen = data.length if (writeLen > this.blockRemain) { throw new Error('writing more to entry than is appropriate') } const r = this.remain const br = this.blockRemain this.remain = Math.max(0, r - writeLen) this.blockRemain = Math.max(0, br - writeLen) if (this.ignore) { return true } if (r >= writeLen) { return super.write(data) } // r < writeLen return super.write(data.slice(0, r)) } [SLURP] (ex, global) { for (const k in ex) { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. if (ex[k] !== null && ex[k] !== undefined && !(global && k === 'path')) { this[k] = k === 'path' || k === 'linkpath' ? normPath(ex[k]) : ex[k] } } } } node_modules/tar/lib/header.js 0000664 00000021702 15114743311 0012347 0 ustar 00 'use strict' // parse a 512-byte header block to a data object, or vice-versa // encode returns `true` if a pax extended header is needed, because // the data could not be faithfully encoded in a simple header. // (Also, check header.needPax to see if it needs a pax header.) const types = require('./types.js') const pathModule = require('path').posix const large = require('./large-numbers.js') const SLURP = Symbol('slurp') const TYPE = Symbol('type') class Header { constructor (data, off, ex, gex) { this.cksumValid = false this.needPax = false this.nullBlock = false this.block = null this.path = null this.mode = null this.uid = null this.gid = null this.size = null this.mtime = null this.cksum = null this[TYPE] = '0' this.linkpath = null this.uname = null this.gname = null this.devmaj = 0 this.devmin = 0 this.atime = null this.ctime = null if (Buffer.isBuffer(data)) { this.decode(data, off || 0, ex, gex) } else if (data) { this.set(data) } } decode (buf, off, ex, gex) { if (!off) { off = 0 } if (!buf || !(buf.length >= off + 512)) { throw new Error('need 512 bytes for header') } this.path = decString(buf, off, 100) this.mode = decNumber(buf, off + 100, 8) this.uid = decNumber(buf, off + 108, 8) this.gid = decNumber(buf, off + 116, 8) this.size = decNumber(buf, off + 124, 12) this.mtime = decDate(buf, off + 136, 12) this.cksum = decNumber(buf, off + 148, 12) // if we have extended or global extended headers, apply them now // See https://github.com/npm/node-tar/pull/187 this[SLURP](ex) this[SLURP](gex, true) // old tar versions marked dirs as a file with a trailing / this[TYPE] = decString(buf, off + 156, 1) if (this[TYPE] === '') { this[TYPE] = '0' } if (this[TYPE] === '0' && this.path.slice(-1) === '/') { this[TYPE] = '5' } // tar implementations sometimes incorrectly put the stat(dir).size // as the size in the tarball, even though Directory entries are // not able to have any body at all. In the very rare chance that // it actually DOES have a body, we weren't going to do anything with // it anyway, and it'll just be a warning about an invalid header. if (this[TYPE] === '5') { this.size = 0 } this.linkpath = decString(buf, off + 157, 100) if (buf.slice(off + 257, off + 265).toString() === 'ustar\u000000') { this.uname = decString(buf, off + 265, 32) this.gname = decString(buf, off + 297, 32) this.devmaj = decNumber(buf, off + 329, 8) this.devmin = decNumber(buf, off + 337, 8) if (buf[off + 475] !== 0) { // definitely a prefix, definitely >130 chars. const prefix = decString(buf, off + 345, 155) this.path = prefix + '/' + this.path } else { const prefix = decString(buf, off + 345, 130) if (prefix) { this.path = prefix + '/' + this.path } this.atime = decDate(buf, off + 476, 12) this.ctime = decDate(buf, off + 488, 12) } } let sum = 8 * 0x20 for (let i = off; i < off + 148; i++) { sum += buf[i] } for (let i = off + 156; i < off + 512; i++) { sum += buf[i] } this.cksumValid = sum === this.cksum if (this.cksum === null && sum === 8 * 0x20) { this.nullBlock = true } } [SLURP] (ex, global) { for (const k in ex) { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. if (ex[k] !== null && ex[k] !== undefined && !(global && k === 'path')) { this[k] = ex[k] } } } encode (buf, off) { if (!buf) { buf = this.block = Buffer.alloc(512) off = 0 } if (!off) { off = 0 } if (!(buf.length >= off + 512)) { throw new Error('need 512 bytes for header') } const prefixSize = this.ctime || this.atime ? 130 : 155 const split = splitPrefix(this.path || '', prefixSize) const path = split[0] const prefix = split[1] this.needPax = split[2] this.needPax = encString(buf, off, 100, path) || this.needPax this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax buf[off + 156] = this[TYPE].charCodeAt(0) this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax buf.write('ustar\u000000', off + 257, 8) this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax if (buf[off + 475] !== 0) { this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax } else { this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax } let sum = 8 * 0x20 for (let i = off; i < off + 148; i++) { sum += buf[i] } for (let i = off + 156; i < off + 512; i++) { sum += buf[i] } this.cksum = sum encNumber(buf, off + 148, 8, this.cksum) this.cksumValid = true return this.needPax } set (data) { for (const i in data) { if (data[i] !== null && data[i] !== undefined) { this[i] = data[i] } } } get type () { return types.name.get(this[TYPE]) || this[TYPE] } get typeKey () { return this[TYPE] } set type (type) { if (types.code.has(type)) { this[TYPE] = types.code.get(type) } else { this[TYPE] = type } } } const splitPrefix = (p, prefixSize) => { const pathSize = 100 let pp = p let prefix = '' let ret const root = pathModule.parse(p).root || '.' if (Buffer.byteLength(pp) < pathSize) { ret = [pp, prefix, false] } else { // first set prefix to the dir, and path to the base prefix = pathModule.dirname(pp) pp = pathModule.basename(pp) do { if (Buffer.byteLength(pp) <= pathSize && Buffer.byteLength(prefix) <= prefixSize) { // both fit! ret = [pp, prefix, false] } else if (Buffer.byteLength(pp) > pathSize && Buffer.byteLength(prefix) <= prefixSize) { // prefix fits in prefix, but path doesn't fit in path ret = [pp.slice(0, pathSize - 1), prefix, true] } else { // make path take a bit from prefix pp = pathModule.join(pathModule.basename(prefix), pp) prefix = pathModule.dirname(prefix) } } while (prefix !== root && !ret) // at this point, found no resolution, just truncate if (!ret) { ret = [p.slice(0, pathSize - 1), '', true] } } return ret } const decString = (buf, off, size) => buf.slice(off, off + size).toString('utf8').replace(/\0.*/, '') const decDate = (buf, off, size) => numToDate(decNumber(buf, off, size)) const numToDate = num => num === null ? null : new Date(num * 1000) const decNumber = (buf, off, size) => buf[off] & 0x80 ? large.parse(buf.slice(off, off + size)) : decSmallNumber(buf, off, size) const nanNull = value => isNaN(value) ? null : value const decSmallNumber = (buf, off, size) => nanNull(parseInt( buf.slice(off, off + size) .toString('utf8').replace(/\0.*$/, '').trim(), 8)) // the maximum encodable as a null-terminated octal, by field size const MAXNUM = { 12: 0o77777777777, 8: 0o7777777, } const encNumber = (buf, off, size, number) => number === null ? false : number > MAXNUM[size] || number < 0 ? (large.encode(number, buf.slice(off, off + size)), true) : (encSmallNumber(buf, off, size, number), false) const encSmallNumber = (buf, off, size, number) => buf.write(octalString(number, size), off, size, 'ascii') const octalString = (number, size) => padOctal(Math.floor(number).toString(8), size) const padOctal = (string, size) => (string.length === size - 1 ? string : new Array(size - string.length - 1).join('0') + string + ' ') + '\0' const encDate = (buf, off, size, date) => date === null ? false : encNumber(buf, off, size, date.getTime() / 1000) // enough to fill the longest string we've got const NULLS = new Array(156).join('\0') // pad with nulls, return true if it's longer or non-ascii const encString = (buf, off, size, string) => string === null ? false : (buf.write(string + NULLS, off, size, 'utf8'), string.length !== Buffer.byteLength(string) || string.length > size) module.exports = Header node_modules/tar/lib/normalize-unicode.js 0000664 00000000634 15114743311 0014544 0 ustar 00 // warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. const normalizeCache = Object.create(null) const { hasOwnProperty } = Object.prototype module.exports = s => { if (!hasOwnProperty.call(normalizeCache, s)) { normalizeCache[s] = s.normalize('NFD') } return normalizeCache[s] } node_modules/tar/lib/unpack.js 0000664 00000062353 15114743311 0012407 0 ustar 00 'use strict' // the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet. // but the path reservations are required to avoid race conditions where // parallelized unpack ops may mess with one another, due to dependencies // (like a Link depending on its target) or destructive operations (like // clobbering an fs object to create one of a different type.) const assert = require('assert') const Parser = require('./parse.js') const fs = require('fs') const fsm = require('fs-minipass') const path = require('path') const mkdir = require('./mkdir.js') const wc = require('./winchars.js') const pathReservations = require('./path-reservations.js') const stripAbsolutePath = require('./strip-absolute-path.js') const normPath = require('./normalize-windows-path.js') const stripSlash = require('./strip-trailing-slashes.js') const normalize = require('./normalize-unicode.js') const ONENTRY = Symbol('onEntry') const CHECKFS = Symbol('checkFs') const CHECKFS2 = Symbol('checkFs2') const PRUNECACHE = Symbol('pruneCache') const ISREUSABLE = Symbol('isReusable') const MAKEFS = Symbol('makeFs') const FILE = Symbol('file') const DIRECTORY = Symbol('directory') const LINK = Symbol('link') const SYMLINK = Symbol('symlink') const HARDLINK = Symbol('hardlink') const UNSUPPORTED = Symbol('unsupported') const CHECKPATH = Symbol('checkPath') const MKDIR = Symbol('mkdir') const ONERROR = Symbol('onError') const PENDING = Symbol('pending') const PEND = Symbol('pend') const UNPEND = Symbol('unpend') const ENDED = Symbol('ended') const MAYBECLOSE = Symbol('maybeClose') const SKIP = Symbol('skip') const DOCHOWN = Symbol('doChown') const UID = Symbol('uid') const GID = Symbol('gid') const CHECKED_CWD = Symbol('checkedCwd') const crypto = require('crypto') const getFlag = require('./get-write-flag.js') const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform const isWindows = platform === 'win32' const DEFAULT_MAX_DEPTH = 1024 // Unlinks on Windows are not atomic. // // This means that if you have a file entry, followed by another // file entry with an identical name, and you cannot re-use the file // (because it's a hardlink, or because unlink:true is set, or it's // Windows, which does not have useful nlink values), then the unlink // will be committed to the disk AFTER the new file has been written // over the old one, deleting the new file. // // To work around this, on Windows systems, we rename the file and then // delete the renamed file. It's a sloppy kludge, but frankly, I do not // know of a better way to do this, given windows' non-atomic unlink // semantics. // // See: https://github.com/npm/node-tar/issues/183 /* istanbul ignore next */ const unlinkFile = (path, cb) => { if (!isWindows) { return fs.unlink(path, cb) } const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') fs.rename(path, name, er => { if (er) { return cb(er) } fs.unlink(name, cb) }) } /* istanbul ignore next */ const unlinkFileSync = path => { if (!isWindows) { return fs.unlinkSync(path) } const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') fs.renameSync(path, name) fs.unlinkSync(name) } // this.gid, entry.gid, this.processUid const uint32 = (a, b, c) => a === a >>> 0 ? a : b === b >>> 0 ? b : c // clear the cache if it's a case-insensitive unicode-squashing match. // we can't know if the current file system is case-sensitive or supports // unicode fully, so we check for similarity on the maximally compatible // representation. Err on the side of pruning, since all it's doing is // preventing lstats, and it's not the end of the world if we get a false // positive. // Note that on windows, we always drop the entire cache whenever a // symbolic link is encountered, because 8.3 filenames are impossible // to reason about, and collisions are hazards rather than just failures. const cacheKeyNormalize = path => stripSlash(normPath(normalize(path))) .toLowerCase() const pruneCache = (cache, abs) => { abs = cacheKeyNormalize(abs) for (const path of cache.keys()) { const pnorm = cacheKeyNormalize(path) if (pnorm === abs || pnorm.indexOf(abs + '/') === 0) { cache.delete(path) } } } const dropCache = cache => { for (const key of cache.keys()) { cache.delete(key) } } class Unpack extends Parser { constructor (opt) { if (!opt) { opt = {} } opt.ondone = _ => { this[ENDED] = true this[MAYBECLOSE]() } super(opt) this[CHECKED_CWD] = false this.reservations = pathReservations() this.transform = typeof opt.transform === 'function' ? opt.transform : null this.writable = true this.readable = false this[PENDING] = 0 this[ENDED] = false this.dirCache = opt.dirCache || new Map() if (typeof opt.uid === 'number' || typeof opt.gid === 'number') { // need both or neither if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number') { throw new TypeError('cannot set owner without number uid and gid') } if (opt.preserveOwner) { throw new TypeError( 'cannot preserve owner in archive and also set owner explicitly') } this.uid = opt.uid this.gid = opt.gid this.setOwner = true } else { this.uid = null this.gid = null this.setOwner = false } // default true for root if (opt.preserveOwner === undefined && typeof opt.uid !== 'number') { this.preserveOwner = process.getuid && process.getuid() === 0 } else { this.preserveOwner = !!opt.preserveOwner } this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? process.getuid() : null this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? process.getgid() : null // prevent excessively deep nesting of subfolders // set to `Infinity` to remove this restriction this.maxDepth = typeof opt.maxDepth === 'number' ? opt.maxDepth : DEFAULT_MAX_DEPTH // mostly just for testing, but useful in some cases. // Forcibly trigger a chown on every entry, no matter what this.forceChown = opt.forceChown === true // turn ><?| in filenames into 0xf000-higher encoded forms this.win32 = !!opt.win32 || isWindows // do not unpack over files that are newer than what's in the archive this.newer = !!opt.newer // do not unpack over ANY files this.keep = !!opt.keep // do not set mtime/atime of extracted entries this.noMtime = !!opt.noMtime // allow .., absolute path entries, and unpacking through symlinks // without this, warn and skip .., relativize absolutes, and error // on symlinks in extraction path this.preservePaths = !!opt.preservePaths // unlink files and links before writing. This breaks existing hard // links, and removes symlink directories rather than erroring this.unlink = !!opt.unlink this.cwd = normPath(path.resolve(opt.cwd || process.cwd())) this.strip = +opt.strip || 0 // if we're not chmodding, then we don't need the process umask this.processUmask = opt.noChmod ? 0 : process.umask() this.umask = typeof opt.umask === 'number' ? opt.umask : this.processUmask // default mode for dirs created as parents this.dmode = opt.dmode || (0o0777 & (~this.umask)) this.fmode = opt.fmode || (0o0666 & (~this.umask)) this.on('entry', entry => this[ONENTRY](entry)) } // a bad or damaged archive is a warning for Parser, but an error // when extracting. Mark those errors as unrecoverable, because // the Unpack contract cannot be met. warn (code, msg, data = {}) { if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') { data.recoverable = false } return super.warn(code, msg, data) } [MAYBECLOSE] () { if (this[ENDED] && this[PENDING] === 0) { this.emit('prefinish') this.emit('finish') this.emit('end') } } [CHECKPATH] (entry) { const p = normPath(entry.path) const parts = p.split('/') if (this.strip) { if (parts.length < this.strip) { return false } if (entry.type === 'Link') { const linkparts = normPath(entry.linkpath).split('/') if (linkparts.length >= this.strip) { entry.linkpath = linkparts.slice(this.strip).join('/') } else { return false } } parts.splice(0, this.strip) entry.path = parts.join('/') } if (isFinite(this.maxDepth) && parts.length > this.maxDepth) { this.warn('TAR_ENTRY_ERROR', 'path excessively deep', { entry, path: p, depth: parts.length, maxDepth: this.maxDepth, }) return false } if (!this.preservePaths) { if (parts.includes('..') || isWindows && /^[a-z]:\.\.$/i.test(parts[0])) { this.warn('TAR_ENTRY_ERROR', `path contains '..'`, { entry, path: p, }) return false } // strip off the root const [root, stripped] = stripAbsolutePath(p) if (root) { entry.path = stripped this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute path`, { entry, path: p, }) } } if (path.isAbsolute(entry.path)) { entry.absolute = normPath(path.resolve(entry.path)) } else { entry.absolute = normPath(path.resolve(this.cwd, entry.path)) } // if we somehow ended up with a path that escapes the cwd, and we are // not in preservePaths mode, then something is fishy! This should have // been prevented above, so ignore this for coverage. /* istanbul ignore if - defense in depth */ if (!this.preservePaths && entry.absolute.indexOf(this.cwd + '/') !== 0 && entry.absolute !== this.cwd) { this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', { entry, path: normPath(entry.path), resolvedPath: entry.absolute, cwd: this.cwd, }) return false } // an archive can set properties on the extraction directory, but it // may not replace the cwd with a different kind of thing entirely. if (entry.absolute === this.cwd && entry.type !== 'Directory' && entry.type !== 'GNUDumpDir') { return false } // only encode : chars that aren't drive letter indicators if (this.win32) { const { root: aRoot } = path.win32.parse(entry.absolute) entry.absolute = aRoot + wc.encode(entry.absolute.slice(aRoot.length)) const { root: pRoot } = path.win32.parse(entry.path) entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length)) } return true } [ONENTRY] (entry) { if (!this[CHECKPATH](entry)) { return entry.resume() } assert.equal(typeof entry.absolute, 'string') switch (entry.type) { case 'Directory': case 'GNUDumpDir': if (entry.mode) { entry.mode = entry.mode | 0o700 } // eslint-disable-next-line no-fallthrough case 'File': case 'OldFile': case 'ContiguousFile': case 'Link': case 'SymbolicLink': return this[CHECKFS](entry) case 'CharacterDevice': case 'BlockDevice': case 'FIFO': default: return this[UNSUPPORTED](entry) } } [ONERROR] (er, entry) { // Cwd has to exist, or else nothing works. That's serious. // Other errors are warnings, which raise the error in strict // mode, but otherwise continue on. if (er.name === 'CwdError') { this.emit('error', er) } else { this.warn('TAR_ENTRY_ERROR', er, { entry }) this[UNPEND]() entry.resume() } } [MKDIR] (dir, mode, cb) { mkdir(normPath(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, noChmod: this.noChmod, }, cb) } [DOCHOWN] (entry) { // in preserve owner mode, chown if the entry doesn't match process // in set owner mode, chown if setting doesn't match process return this.forceChown || this.preserveOwner && (typeof entry.uid === 'number' && entry.uid !== this.processUid || typeof entry.gid === 'number' && entry.gid !== this.processGid) || (typeof this.uid === 'number' && this.uid !== this.processUid || typeof this.gid === 'number' && this.gid !== this.processGid) } [UID] (entry) { return uint32(this.uid, entry.uid, this.processUid) } [GID] (entry) { return uint32(this.gid, entry.gid, this.processGid) } [FILE] (entry, fullyDone) { const mode = entry.mode & 0o7777 || this.fmode const stream = new fsm.WriteStream(entry.absolute, { flags: getFlag(entry.size), mode: mode, autoClose: false, }) stream.on('error', er => { if (stream.fd) { fs.close(stream.fd, () => {}) } // flush all the data out so that we aren't left hanging // if the error wasn't actually fatal. otherwise the parse // is blocked, and we never proceed. stream.write = () => true this[ONERROR](er, entry) fullyDone() }) let actions = 1 const done = er => { if (er) { /* istanbul ignore else - we should always have a fd by now */ if (stream.fd) { fs.close(stream.fd, () => {}) } this[ONERROR](er, entry) fullyDone() return } if (--actions === 0) { fs.close(stream.fd, er => { if (er) { this[ONERROR](er, entry) } else { this[UNPEND]() } fullyDone() }) } } stream.on('finish', _ => { // if futimes fails, try utimes // if utimes fails, fail with the original error // same for fchown/chown const abs = entry.absolute const fd = stream.fd if (entry.mtime && !this.noMtime) { actions++ const atime = entry.atime || new Date() const mtime = entry.mtime fs.futimes(fd, atime, mtime, er => er ? fs.utimes(abs, atime, mtime, er2 => done(er2 && er)) : done()) } if (this[DOCHOWN](entry)) { actions++ const uid = this[UID](entry) const gid = this[GID](entry) fs.fchown(fd, uid, gid, er => er ? fs.chown(abs, uid, gid, er2 => done(er2 && er)) : done()) } done() }) const tx = this.transform ? this.transform(entry) || entry : entry if (tx !== entry) { tx.on('error', er => { this[ONERROR](er, entry) fullyDone() }) entry.pipe(tx) } tx.pipe(stream) } [DIRECTORY] (entry, fullyDone) { const mode = entry.mode & 0o7777 || this.dmode this[MKDIR](entry.absolute, mode, er => { if (er) { this[ONERROR](er, entry) fullyDone() return } let actions = 1 const done = _ => { if (--actions === 0) { fullyDone() this[UNPEND]() entry.resume() } } if (entry.mtime && !this.noMtime) { actions++ fs.utimes(entry.absolute, entry.atime || new Date(), entry.mtime, done) } if (this[DOCHOWN](entry)) { actions++ fs.chown(entry.absolute, this[UID](entry), this[GID](entry), done) } done() }) } [UNSUPPORTED] (entry) { entry.unsupported = true this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, { entry }) entry.resume() } [SYMLINK] (entry, done) { this[LINK](entry, entry.linkpath, 'symlink', done) } [HARDLINK] (entry, done) { const linkpath = normPath(path.resolve(this.cwd, entry.linkpath)) this[LINK](entry, linkpath, 'link', done) } [PEND] () { this[PENDING]++ } [UNPEND] () { this[PENDING]-- this[MAYBECLOSE]() } [SKIP] (entry) { this[UNPEND]() entry.resume() } // Check if we can reuse an existing filesystem entry safely and // overwrite it, rather than unlinking and recreating // Windows doesn't report a useful nlink, so we just never reuse entries [ISREUSABLE] (entry, st) { return entry.type === 'File' && !this.unlink && st.isFile() && st.nlink <= 1 && !isWindows } // check if a thing is there, and if so, try to clobber it [CHECKFS] (entry) { this[PEND]() const paths = [entry.path] if (entry.linkpath) { paths.push(entry.linkpath) } this.reservations.reserve(paths, done => this[CHECKFS2](entry, done)) } [PRUNECACHE] (entry) { // if we are not creating a directory, and the path is in the dirCache, // then that means we are about to delete the directory we created // previously, and it is no longer going to be a directory, and neither // is any of its children. // If a symbolic link is encountered, all bets are off. There is no // reasonable way to sanitize the cache in such a way we will be able to // avoid having filesystem collisions. If this happens with a non-symlink // entry, it'll just fail to unpack, but a symlink to a directory, using an // 8.3 shortname or certain unicode attacks, can evade detection and lead // to arbitrary writes to anywhere on the system. if (entry.type === 'SymbolicLink') { dropCache(this.dirCache) } else if (entry.type !== 'Directory') { pruneCache(this.dirCache, entry.absolute) } } [CHECKFS2] (entry, fullyDone) { this[PRUNECACHE](entry) const done = er => { this[PRUNECACHE](entry) fullyDone(er) } const checkCwd = () => { this[MKDIR](this.cwd, this.dmode, er => { if (er) { this[ONERROR](er, entry) done() return } this[CHECKED_CWD] = true start() }) } const start = () => { if (entry.absolute !== this.cwd) { const parent = normPath(path.dirname(entry.absolute)) if (parent !== this.cwd) { return this[MKDIR](parent, this.dmode, er => { if (er) { this[ONERROR](er, entry) done() return } afterMakeParent() }) } } afterMakeParent() } const afterMakeParent = () => { fs.lstat(entry.absolute, (lstatEr, st) => { if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { this[SKIP](entry) done() return } if (lstatEr || this[ISREUSABLE](entry, st)) { return this[MAKEFS](null, entry, done) } if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = !this.noChmod && entry.mode && (st.mode & 0o7777) !== entry.mode const afterChmod = er => this[MAKEFS](er, entry, done) if (!needChmod) { return afterChmod() } return fs.chmod(entry.absolute, entry.mode, afterChmod) } // Not a dir entry, have to remove it. // NB: the only way to end up with an entry that is the cwd // itself, in such a way that == does not detect, is a // tricky windows absolute path with UNC or 8.3 parts (and // preservePaths:true, or else it will have been stripped). // In that case, the user has opted out of path protections // explicitly, so if they blow away the cwd, c'est la vie. if (entry.absolute !== this.cwd) { return fs.rmdir(entry.absolute, er => this[MAKEFS](er, entry, done)) } } // not a dir, and not reusable // don't remove if the cwd, we want that error if (entry.absolute === this.cwd) { return this[MAKEFS](null, entry, done) } unlinkFile(entry.absolute, er => this[MAKEFS](er, entry, done)) }) } if (this[CHECKED_CWD]) { start() } else { checkCwd() } } [MAKEFS] (er, entry, done) { if (er) { this[ONERROR](er, entry) done() return } switch (entry.type) { case 'File': case 'OldFile': case 'ContiguousFile': return this[FILE](entry, done) case 'Link': return this[HARDLINK](entry, done) case 'SymbolicLink': return this[SYMLINK](entry, done) case 'Directory': case 'GNUDumpDir': return this[DIRECTORY](entry, done) } } [LINK] (entry, linkpath, link, done) { // XXX: get the type ('symlink' or 'junction') for windows fs[link](linkpath, entry.absolute, er => { if (er) { this[ONERROR](er, entry) } else { this[UNPEND]() entry.resume() } done() }) } } const callSync = fn => { try { return [null, fn()] } catch (er) { return [er, null] } } class UnpackSync extends Unpack { [MAKEFS] (er, entry) { return super[MAKEFS](er, entry, () => {}) } [CHECKFS] (entry) { this[PRUNECACHE](entry) if (!this[CHECKED_CWD]) { const er = this[MKDIR](this.cwd, this.dmode) if (er) { return this[ONERROR](er, entry) } this[CHECKED_CWD] = true } // don't bother to make the parent if the current entry is the cwd, // we've already checked it. if (entry.absolute !== this.cwd) { const parent = normPath(path.dirname(entry.absolute)) if (parent !== this.cwd) { const mkParent = this[MKDIR](parent, this.dmode) if (mkParent) { return this[ONERROR](mkParent, entry) } } } const [lstatEr, st] = callSync(() => fs.lstatSync(entry.absolute)) if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { return this[SKIP](entry) } if (lstatEr || this[ISREUSABLE](entry, st)) { return this[MAKEFS](null, entry) } if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = !this.noChmod && entry.mode && (st.mode & 0o7777) !== entry.mode const [er] = needChmod ? callSync(() => { fs.chmodSync(entry.absolute, entry.mode) }) : [] return this[MAKEFS](er, entry) } // not a dir entry, have to remove it const [er] = callSync(() => fs.rmdirSync(entry.absolute)) this[MAKEFS](er, entry) } // not a dir, and not reusable. // don't remove if it's the cwd, since we want that error. const [er] = entry.absolute === this.cwd ? [] : callSync(() => unlinkFileSync(entry.absolute)) this[MAKEFS](er, entry) } [FILE] (entry, done) { const mode = entry.mode & 0o7777 || this.fmode const oner = er => { let closeError try { fs.closeSync(fd) } catch (e) { closeError = e } if (er || closeError) { this[ONERROR](er || closeError, entry) } done() } let fd try { fd = fs.openSync(entry.absolute, getFlag(entry.size), mode) } catch (er) { return oner(er) } const tx = this.transform ? this.transform(entry) || entry : entry if (tx !== entry) { tx.on('error', er => this[ONERROR](er, entry)) entry.pipe(tx) } tx.on('data', chunk => { try { fs.writeSync(fd, chunk, 0, chunk.length) } catch (er) { oner(er) } }) tx.on('end', _ => { let er = null // try both, falling futimes back to utimes // if either fails, handle the first error if (entry.mtime && !this.noMtime) { const atime = entry.atime || new Date() const mtime = entry.mtime try { fs.futimesSync(fd, atime, mtime) } catch (futimeser) { try { fs.utimesSync(entry.absolute, atime, mtime) } catch (utimeser) { er = futimeser } } } if (this[DOCHOWN](entry)) { const uid = this[UID](entry) const gid = this[GID](entry) try { fs.fchownSync(fd, uid, gid) } catch (fchowner) { try { fs.chownSync(entry.absolute, uid, gid) } catch (chowner) { er = er || fchowner } } } oner(er) }) } [DIRECTORY] (entry, done) { const mode = entry.mode & 0o7777 || this.dmode const er = this[MKDIR](entry.absolute, mode) if (er) { this[ONERROR](er, entry) done() return } if (entry.mtime && !this.noMtime) { try { fs.utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime) } catch (er) {} } if (this[DOCHOWN](entry)) { try { fs.chownSync(entry.absolute, this[UID](entry), this[GID](entry)) } catch (er) {} } done() entry.resume() } [MKDIR] (dir, mode) { try { return mkdir.sync(normPath(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, }) } catch (er) { return er } } [LINK] (entry, linkpath, link, done) { try { fs[link + 'Sync'](linkpath, entry.absolute) done() entry.resume() } catch (er) { return this[ONERROR](er, entry) } } } Unpack.Sync = UnpackSync module.exports = Unpack node_modules/tar/lib/extract.js 0000664 00000005444 15114743311 0012576 0 ustar 00 'use strict' // tar -x const hlo = require('./high-level-opt.js') const Unpack = require('./unpack.js') const fs = require('fs') const fsm = require('fs-minipass') const path = require('path') const stripSlash = require('./strip-trailing-slashes.js') module.exports = (opt_, files, cb) => { if (typeof opt_ === 'function') { cb = opt_, files = null, opt_ = {} } else if (Array.isArray(opt_)) { files = opt_, opt_ = {} } if (typeof files === 'function') { cb = files, files = null } if (!files) { files = [] } else { files = Array.from(files) } const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions') } if (!opt.file && typeof cb === 'function') { throw new TypeError('callback only supported with file option') } if (files.length) { filesFilter(opt, files) } return opt.file && opt.sync ? extractFileSync(opt) : opt.file ? extractFile(opt, cb) : opt.sync ? extractSync(opt) : extract(opt) } // construct a filter that limits the file entries listed // include child entries if a dir is included const filesFilter = (opt, files) => { const map = new Map(files.map(f => [stripSlash(f), true])) const filter = opt.filter const mapHas = (file, r) => { const root = r || path.parse(file).root || '.' const ret = file === root ? false : map.has(file) ? map.get(file) : mapHas(path.dirname(file), root) map.set(file, ret) return ret } opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) : file => mapHas(stripSlash(file)) } const extractFileSync = opt => { const u = new Unpack.Sync(opt) const file = opt.file const stat = fs.statSync(file) // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation const readSize = opt.maxReadSize || 16 * 1024 * 1024 const stream = new fsm.ReadStreamSync(file, { readSize: readSize, size: stat.size, }) stream.pipe(u) } const extractFile = (opt, cb) => { const u = new Unpack(opt) const readSize = opt.maxReadSize || 16 * 1024 * 1024 const file = opt.file const p = new Promise((resolve, reject) => { u.on('error', reject) u.on('close', resolve) // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation fs.stat(file, (er, stat) => { if (er) { reject(er) } else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }) stream.on('error', reject) stream.pipe(u) } }) }) return cb ? p.then(cb, cb) : p } const extractSync = opt => new Unpack.Sync(opt) const extract = opt => new Unpack(opt) node_modules/tar/lib/winchars.js 0000664 00000001027 15114743311 0012733 0 ustar 00 'use strict' // When writing files on Windows, translate the characters to their // 0xf000 higher-encoded versions. const raw = [ '|', '<', '>', '?', ':', ] const win = raw.map(char => String.fromCharCode(0xf000 + char.charCodeAt(0))) const toWin = new Map(raw.map((char, i) => [char, win[i]])) const toRaw = new Map(win.map((char, i) => [char, raw[i]])) module.exports = { encode: s => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s), decode: s => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s), } node_modules/tar/index.js 0000664 00000001253 15114743311 0011457 0 ustar 00 'use strict' // high-level commands exports.c = exports.create = require('./lib/create.js') exports.r = exports.replace = require('./lib/replace.js') exports.t = exports.list = require('./lib/list.js') exports.u = exports.update = require('./lib/update.js') exports.x = exports.extract = require('./lib/extract.js') // classes exports.Pack = require('./lib/pack.js') exports.Unpack = require('./lib/unpack.js') exports.Parse = require('./lib/parse.js') exports.ReadEntry = require('./lib/read-entry.js') exports.WriteEntry = require('./lib/write-entry.js') exports.Header = require('./lib/header.js') exports.Pax = require('./lib/pax.js') exports.types = require('./lib/types.js') node_modules/tar/README.md 0000664 00000131756 15114743311 0011305 0 ustar 00 # node-tar Fast and full-featured Tar for Node.js The API is designed to mimic the behavior of `tar(1)` on unix systems. If you are familiar with how tar works, most of this will hopefully be straightforward for you. If not, then hopefully this module can teach you useful unix skills that may come in handy someday :) ## Background A "tar file" or "tarball" is an archive of file system entries (directories, files, links, etc.) The name comes from "tape archive". If you run `man tar` on almost any Unix command line, you'll learn quite a bit about what it can do, and its history. Tar has 5 main top-level commands: * `c` Create an archive * `r` Replace entries within an archive * `u` Update entries within an archive (ie, replace if they're newer) * `t` List out the contents of an archive * `x` Extract an archive to disk The other flags and options modify how this top level function works. ## High-Level API These 5 functions are the high-level API. All of them have a single-character name (for unix nerds familiar with `tar(1)`) as well as a long name (for everyone else). All the high-level functions take the following arguments, all three of which are optional and may be omitted. 1. `options` - An optional object specifying various options 2. `paths` - An array of paths to add or extract 3. `callback` - Called when the command is completed, if async. (If sync or no file specified, providing a callback throws a `TypeError`.) If the command is sync (ie, if `options.sync=true`), then the callback is not allowed, since the action will be completed immediately. If a `file` argument is specified, and the command is async, then a `Promise` is returned. In this case, if async, a callback may be provided which is called when the command is completed. If a `file` option is not specified, then a stream is returned. For `create`, this is a readable stream of the generated archive. For `list` and `extract` this is a writable stream that an archive should be written into. If a file is not specified, then a callback is not allowed, because you're already getting a stream to work with. `replace` and `update` only work on existing archives, and so require a `file` argument. Sync commands without a file argument return a stream that acts on its input immediately in the same tick. For readable streams, this means that all of the data is immediately available by calling `stream.read()`. For writable streams, it will be acted upon as soon as it is provided, but this can be at any time. ### Warnings and Errors Tar emits warnings and errors for recoverable and unrecoverable situations, respectively. In many cases, a warning only affects a single entry in an archive, or is simply informing you that it's modifying an entry to comply with the settings provided. Unrecoverable warnings will always raise an error (ie, emit `'error'` on streaming actions, throw for non-streaming sync actions, reject the returned Promise for non-streaming async operations, or call a provided callback with an `Error` as the first argument). Recoverable errors will raise an error only if `strict: true` is set in the options. Respond to (recoverable) warnings by listening to the `warn` event. Handlers receive 3 arguments: - `code` String. One of the error codes below. This may not match `data.code`, which preserves the original error code from fs and zlib. - `message` String. More details about the error. - `data` Metadata about the error. An `Error` object for errors raised by fs and zlib. All fields are attached to errors raisd by tar. Typically contains the following fields, as relevant: - `tarCode` The tar error code. - `code` Either the tar error code, or the error code set by the underlying system. - `file` The archive file being read or written. - `cwd` Working directory for creation and extraction operations. - `entry` The entry object (if it could be created) for `TAR_ENTRY_INFO`, `TAR_ENTRY_INVALID`, and `TAR_ENTRY_ERROR` warnings. - `header` The header object (if it could be created, and the entry could not be created) for `TAR_ENTRY_INFO` and `TAR_ENTRY_INVALID` warnings. - `recoverable` Boolean. If `false`, then the warning will emit an `error`, even in non-strict mode. #### Error Codes * `TAR_ENTRY_INFO` An informative error indicating that an entry is being modified, but otherwise processed normally. For example, removing `/` or `C:\` from absolute paths if `preservePaths` is not set. * `TAR_ENTRY_INVALID` An indication that a given entry is not a valid tar archive entry, and will be skipped. This occurs when: - a checksum fails, - a `linkpath` is missing for a link type, or - a `linkpath` is provided for a non-link type. If every entry in a parsed archive raises an `TAR_ENTRY_INVALID` error, then the archive is presumed to be unrecoverably broken, and `TAR_BAD_ARCHIVE` will be raised. * `TAR_ENTRY_ERROR` The entry appears to be a valid tar archive entry, but encountered an error which prevented it from being unpacked. This occurs when: - an unrecoverable fs error happens during unpacking, - an entry is trying to extract into an excessively deep location (by default, limited to 1024 subfolders), - an entry has `..` in the path and `preservePaths` is not set, or - an entry is extracting through a symbolic link, when `preservePaths` is not set. * `TAR_ENTRY_UNSUPPORTED` An indication that a given entry is a valid archive entry, but of a type that is unsupported, and so will be skipped in archive creation or extracting. * `TAR_ABORT` When parsing gzipped-encoded archives, the parser will abort the parse process raise a warning for any zlib errors encountered. Aborts are considered unrecoverable for both parsing and unpacking. * `TAR_BAD_ARCHIVE` The archive file is totally hosed. This can happen for a number of reasons, and always occurs at the end of a parse or extract: - An entry body was truncated before seeing the full number of bytes. - The archive contained only invalid entries, indicating that it is likely not an archive, or at least, not an archive this library can parse. `TAR_BAD_ARCHIVE` is considered informative for parse operations, but unrecoverable for extraction. Note that, if encountered at the end of an extraction, tar WILL still have extracted as much it could from the archive, so there may be some garbage files to clean up. Errors that occur deeper in the system (ie, either the filesystem or zlib) will have their error codes left intact, and a `tarCode` matching one of the above will be added to the warning metadata or the raised error object. Errors generated by tar will have one of the above codes set as the `error.code` field as well, but since errors originating in zlib or fs will have their original codes, it's better to read `error.tarCode` if you wish to see how tar is handling the issue. ### Examples The API mimics the `tar(1)` command line functionality, with aliases for more human-readable option and function names. The goal is that if you know how to use `tar(1)` in Unix, then you know how to use `require('tar')` in JavaScript. To replicate `tar czf my-tarball.tgz files and folders`, you'd do: ```js tar.c( { gzip: <true|gzip options>, file: 'my-tarball.tgz' }, ['some', 'files', 'and', 'folders'] ).then(_ => { .. tarball has been created .. }) ``` To replicate `tar cz files and folders > my-tarball.tgz`, you'd do: ```js tar.c( // or tar.create { gzip: <true|gzip options> }, ['some', 'files', 'and', 'folders'] ).pipe(fs.createWriteStream('my-tarball.tgz')) ``` To replicate `tar xf my-tarball.tgz` you'd do: ```js tar.x( // or tar.extract( { file: 'my-tarball.tgz' } ).then(_=> { .. tarball has been dumped in cwd .. }) ``` To replicate `cat my-tarball.tgz | tar x -C some-dir --strip=1`: ```js fs.createReadStream('my-tarball.tgz').pipe( tar.x({ strip: 1, C: 'some-dir' // alias for cwd:'some-dir', also ok }) ) ``` To replicate `tar tf my-tarball.tgz`, do this: ```js tar.t({ file: 'my-tarball.tgz', onentry: entry => { .. do whatever with it .. } }) ``` For example, to just get the list of filenames from an archive: ```js const getEntryFilenames = async tarballFilename => { const filenames = [] await tar.t({ file: tarballFilename, onentry: entry => filenames.push(entry.path), }) return filenames } ``` To replicate `cat my-tarball.tgz | tar t` do: ```js fs.createReadStream('my-tarball.tgz') .pipe(tar.t()) .on('entry', entry => { .. do whatever with it .. }) ``` To do anything synchronous, add `sync: true` to the options. Note that sync functions don't take a callback and don't return a promise. When the function returns, it's already done. Sync methods without a file argument return a sync stream, which flushes immediately. But, of course, it still won't be done until you `.end()` it. ```js const getEntryFilenamesSync = tarballFilename => { const filenames = [] tar.t({ file: tarballFilename, onentry: entry => filenames.push(entry.path), sync: true, }) return filenames } ``` To filter entries, add `filter: <function>` to the options. Tar-creating methods call the filter with `filter(path, stat)`. Tar-reading methods (including extraction) call the filter with `filter(path, entry)`. The filter is called in the `this`-context of the `Pack` or `Unpack` stream object. The arguments list to `tar t` and `tar x` specify a list of filenames to extract or list, so they're equivalent to a filter that tests if the file is in the list. For those who _aren't_ fans of tar's single-character command names: ``` tar.c === tar.create tar.r === tar.replace (appends to archive, file is required) tar.u === tar.update (appends if newer, file is required) tar.x === tar.extract tar.t === tar.list ``` Keep reading for all the command descriptions and options, as well as the low-level API that they are built on. ### tar.c(options, fileList, callback) [alias: tar.create] Create a tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Write the tarball archive to the specified filename. If this is specified, then the callback will be fired when the file has been written, and a promise will be returned that resolves when the file is written. If a filename is not specified, then a Readable Stream will be returned which will emit the file data. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. If this is set, and a file is not provided, then the resulting stream will already have the data ready to `read` or `emit('data')` as soon as you request it. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `mode` The mode to set on the created file archive - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. ### tar.x(options, fileList, callback) [alias: tar.extract] Extract a tarball archive. The `fileList` is an array of paths to extract from the tarball. If no paths are provided, then all the entries are extracted. If the archive is gzipped, then tar will detect this and unzip it. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. Most extraction errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then the extraction will fail completely. The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. [Alias: `C`] - `file` The archive file to extract. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Create files and directories synchronously. - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. [Alias: `keep-newer`, `keep-newer-files`] - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. [Alias: `k`, `keep-existing`] - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. [Alias: `P`] - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. [Alias: `U`] - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. [Alias: `strip-components`, `stripComponents`] - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. [Alias: `p`] - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. [Alias: `m`, `no-mtime`] - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noChmod` Set to true to omit calling `fs.chmod()` to ensure that the extracted file matches the entry mode. This also suppresses the call to `process.umask()` to determine the default umask value, since tar will extract with whatever mode is provided, and let the process `umask` apply normally. - `maxDepth` The maximum depth of subfolders to extract into. This defaults to 1024. Anything deeper than the limit will raise a warning and skip the entry. Set to `Infinity` to remove the limitation. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync extractions. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### tar.t(options, fileList, callback) [alias: tar.list] List the contents of a tarball archive. The `fileList` is an array of paths to list from the tarball. If no paths are provided, then all the entries are listed. If the archive is gzipped, then tar will detect this and unzip it. If the `file` option is _not_ provided, then returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. However, they don't emit `'data'` or `'end'` events. (If you want to get actual readable entries, use the `tar.Parse` class instead.) If a `file` option _is_ provided, then the return value will be a promise that resolves when the file has been fully traversed in async mode, or `undefined` if `sync: true` is set. Thus, you _must_ specify an `onentry` method in order to do anything useful with the data it parses. The following options are supported: - `file` The archive file to list. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Read the specified file synchronously. (This has no effect when a file option isn't specified, because entries are emitted as fast as they are parsed from the stream anyway.) - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. This is important for when `file` is set, because there is no other way to do anything useful with this method. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noResume` By default, `entry` streams are resumed immediately after the call to `onentry`. Set `noResume: true` to suppress this behavior. Note that by opting into this, the stream will never complete until the entry data is consumed. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") ### tar.u(options, fileList, callback) [alias: tar.update] Add files to an archive if they are newer than the entry already in the tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ### tar.r(options, fileList, callback) [alias: tar.replace] Add files to an existing archive. Because later entries override earlier entries, this effectively replaces any existing entries. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ## Low-Level API ### class tar.Pack A readable tar stream. Has all the standard readable stream interface stuff. `'data'` and `'end'` events, `read()` method, `pause()` and `resume()`, etc. #### constructor(options) The following options are supported: - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. #### add(path) Adds an entry to the archive. Returns the Pack stream. #### write(path) Adds an entry to the archive. Returns true if flushed. #### end() Finishes the archive. ### class tar.Pack.Sync Synchronous version of `tar.Pack`. ### class tar.Unpack A writable stream that unpacks a tar archive onto the file system. All the normal writable stream stuff is supported. `write()` and `end()` methods, `'drain'` events, etc. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. `'close'` is emitted when it's done writing stuff to the file system. Most unpack errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then an error will be emitted. #### constructor(options) - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. - `win32` True if on a windows platform. Causes behavior where filenames containing `<|>?` chars are converted to windows-compatible values while being unpacked. - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `strict` Treat warnings as crash-worthy errors. Default false. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noChmod` Set to true to omit calling `fs.chmod()` to ensure that the extracted file matches the entry mode. This also suppresses the call to `process.umask()` to determine the default umask value, since tar will extract with whatever mode is provided, and let the process `umask` apply normally. - `maxDepth` The maximum depth of subfolders to extract into. This defaults to 1024. Anything deeper than the limit will raise a warning and skip the entry. Set to `Infinity` to remove the limitation. ### class tar.Unpack.Sync Synchronous version of `tar.Unpack`. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync unpack streams. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### class tar.Parse A writable stream that parses a tar archive stream. All the standard writable stream stuff is supported. If the archive is gzipped, then tar will detect this and unzip it. Emits `'entry'` events with `tar.ReadEntry` objects, which are themselves readable streams that you can pipe wherever. Each `entry` will not emit until the one before it is flushed through, so make sure to either consume the data (with `on('data', ...)` or `.pipe(...)`) or throw it away with `.resume()` to keep the stream flowing. #### constructor(options) Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. The following options are supported: - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") #### abort(error) Stop all parsing activities. This is called when there are zlib errors. It also emits an unrecoverable warning with the error provided. ### class tar.ReadEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being read out of a tar archive. It has the following fields: - `extended` The extended metadata object provided to the constructor. - `globalExtended` The global extended metadata object provided to the constructor. - `remain` The number of bytes remaining to be written into the stream. - `blockRemain` The number of 512-byte blocks remaining to be written into the stream. - `ignore` Whether this entry should be ignored. - `meta` True if this represents metadata about the next entry, false if it represents a filesystem object. - All the fields from the header, extended header, and global extended header are added to the ReadEntry object. So it has `path`, `type`, `size`, `mode`, and so on. #### constructor(header, extended, globalExtended) Create a new ReadEntry object with the specified header, extended header, and global extended header values. ### class tar.WriteEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being written from the file system into a tar archive. Emits data for the Header, and for the Pax Extended Header if one is required, as well as any body data. Creating a WriteEntry for a directory does not also create WriteEntry objects for all of the directory contents. It has the following fields: - `path` The path field that will be written to the archive. By default, this is also the path from the cwd to the file system object. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `myuid` If supported, the uid of the user running the current process. - `myuser` The `env.USER` string if set, or `''`. Set as the entry `uname` field if the file's `uid` matches `this.myuid`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/` and filenames containing the windows-compatible forms of `<|>?:` characters are converted to actual `<|>?:` characters in the archive. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. #### constructor(path, options) `path` is the path of the entry as it is written in the archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `umask` Set to restrict the modes on the entries in the archive, somewhat like how umask works on file creation. Defaults to `process.umask()` on unix systems, or `0o22` on Windows. #### warn(message, data) If strict, emit an error with the provided message. Othewise, emit a `'warn'` event with the provided message and data. ### class tar.WriteEntry.Sync Synchronous version of tar.WriteEntry ### class tar.WriteEntry.Tar A version of tar.WriteEntry that gets its data from a tar.ReadEntry instead of from the filesystem. #### constructor(readEntry, options) `readEntry` is the entry being read out of another archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `strict` Treat warnings as crash-worthy errors. Default false. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. ### class tar.Header A class for reading and writing header blocks. It has the following fields: - `nullBlock` True if decoding a block which is entirely composed of `0x00` null bytes. (Useful because tar files are terminated by at least 2 null blocks.) - `cksumValid` True if the checksum in the header is valid, false otherwise. - `needPax` True if the values, as encoded, will require a Pax extended header. - `path` The path of the entry. - `mode` The 4 lowest-order octal digits of the file mode. That is, read/write/execute permissions for world, group, and owner, and the setuid, setgid, and sticky bits. - `uid` Numeric user id of the file owner - `gid` Numeric group id of the file owner - `size` Size of the file in bytes - `mtime` Modified time of the file - `cksum` The checksum of the header. This is generated by adding all the bytes of the header block, treating the checksum field itself as all ascii space characters (that is, `0x20`). - `type` The human-readable name of the type of entry this represents, or the alphanumeric key if unknown. - `typeKey` The alphanumeric key for the type of entry this header represents. - `linkpath` The target of Link and SymbolicLink entries. - `uname` Human-readable user name of the file owner - `gname` Human-readable group name of the file owner - `devmaj` The major portion of the device number. Always `0` for files, directories, and links. - `devmin` The minor portion of the device number. Always `0` for files, directories, and links. - `atime` File access time. - `ctime` File change time. #### constructor(data, [offset=0]) `data` is optional. It is either a Buffer that should be interpreted as a tar Header starting at the specified offset and continuing for 512 bytes, or a data object of keys and values to set on the header object, and eventually encode as a tar Header. #### decode(block, offset) Decode the provided buffer starting at the specified offset. Buffer length must be greater than 512 bytes. #### set(data) Set the fields in the data object. #### encode(buffer, offset) Encode the header fields into the buffer at the specified offset. Returns `this.needPax` to indicate whether a Pax Extended Header is required to properly encode the specified data. ### class tar.Pax An object representing a set of key-value pairs in an Pax extended header entry. It has the following fields. Where the same name is used, they have the same semantics as the tar.Header field of the same name. - `global` True if this represents a global extended header, or false if it is for a single entry. - `atime` - `charset` - `comment` - `ctime` - `gid` - `gname` - `linkpath` - `mtime` - `path` - `size` - `uid` - `uname` - `dev` - `ino` - `nlink` #### constructor(object, global) Set the fields set in the object. `global` is a boolean that defaults to false. #### encode() Return a Buffer containing the header and body for the Pax extended header entry, or `null` if there is nothing to encode. #### encodeBody() Return a string representing the body of the pax extended header entry. #### encodeField(fieldName) Return a string representing the key/value encoding for the specified fieldName, or `''` if the field is unset. ### tar.Pax.parse(string, extended, global) Return a new Pax object created by parsing the contents of the string provided. If the `extended` object is set, then also add the fields from that object. (This is necessary because multiple metadata entries can occur in sequence.) ### tar.types A translation table for the `type` field in tar headers. #### tar.types.name.get(code) Get the human-readable name for a given alphanumeric code. #### tar.types.code.get(name) Get the alphanumeric code for a given human-readable name. node_modules/emoji-regex/LICENSE-MIT.txt 0000664 00000002065 15114743311 0013713 0 ustar 00 Copyright Mathias Bynens <https://mathiasbynens.be/> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/emoji-regex/package.json 0000664 00000002030 15114743311 0013717 0 ustar 00 { "name": "emoji-regex", "version": "10.4.0", "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", "homepage": "https://mths.be/emoji-regex", "main": "index.js", "module": "index.mjs", "types": "index.d.ts", "keywords": [ "unicode", "regex", "regexp", "regular expressions", "code points", "symbols", "characters", "emoji" ], "license": "MIT", "author": { "name": "Mathias Bynens", "url": "https://mathiasbynens.be/" }, "repository": { "type": "git", "url": "https://github.com/mathiasbynens/emoji-regex.git" }, "bugs": "https://github.com/mathiasbynens/emoji-regex/issues", "files": [ "LICENSE-MIT.txt", "index.js", "index.d.ts", "index.mjs" ], "scripts": { "build": "node script/build.js", "test": "mocha", "test:watch": "npm run test -- --watch" }, "devDependencies": { "@unicode/unicode-16.0.0": "^1.0.0", "emoji-test-regex-pattern": "^2.2.0", "mocha": "^10.7.3" } } node_modules/emoji-regex/index.d.ts 0000664 00000000121 15114743311 0013331 0 ustar 00 declare module 'emoji-regex' { export default function emojiRegex(): RegExp; } node_modules/emoji-regex/index.mjs 0000664 00000031110 15114743311 0013254 0 ustar 00 export default () => { // https://mths.be/emoji return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uD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\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; }; node_modules/emoji-regex/index.js 0000664 00000031112 15114743311 0013101 0 ustar 00 module.exports = () => { // https://mths.be/emoji return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uD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|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; }; node_modules/emoji-regex/README.md 0000664 00000007706 15114743311 0012727 0 ustar 00 # emoji-regex [](https://github.com/mathiasbynens/emoji-regex/actions/workflows/main.yml) [](https://www.npmjs.com/package/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols and sequences (including textual representations of emoji) as per the Unicode Standard. It’s based on [_emoji-test-regex-pattern_](https://github.com/mathiasbynens/emoji-test-regex-pattern), which generates (at build time) the regular expression pattern based on the Unicode Standard. As a result, _emoji-regex_ can easily be updated whenever new emoji are added to Unicode. Since each version of _emoji-regex_ is tied to the latest Unicode version at the time of release, results are deterministic. This is important for use cases like image replacement, where you want to guarantee that an image asset is available for every possibly matched emoji. If you don’t need a deterministic regex, a lighter-weight, general emoji pattern is available via the [_emoji-regex-xs_](https://github.com/slevithan/emoji-regex-xs) package that follows the same API. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); for (const match of text.matchAll(regex)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` ## For maintainers ### How to update emoji-regex after new Unicode Standard releases 1. [Update _emoji-test-regex-pattern_ as described in its repository](https://github.com/mathiasbynens/emoji-test-regex-pattern#how-to-update-emoji-test-regex-pattern-after-new-uts51-releases). 1. Bump the _emoji-test-regex-pattern_ dependency to the latest version. 1. Update the Unicode data dependency in `package.json` by running the following commands: ```sh # Example: updating from Unicode v13 to Unicode v14. npm uninstall @unicode/unicode-13.0.0 npm install @unicode/unicode-14.0.0 --save-dev ```` 1. Generate the new output: ```sh npm run build ``` 1. Verify that tests still pass: ```sh npm test ``` ### How to publish a new release 1. On the `main` branch, bump the emoji-regex version number in `package.json`: ```sh npm version patch -m 'Release v%s' ``` Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/). Note that this produces a Git commit + tag. 1. Push the release commit and tag: ```sh git push && git push --tags ``` Our CI then automatically publishes the new release to npm. ## Author | [](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. node_modules/has-flag/license 0000664 00000002125 15114743311 0012252 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/has-flag/package.json 0000664 00000001270 15114743311 0013173 0 ustar 00 { "name": "has-flag", "version": "4.0.0", "description": "Check if argv has a specific flag", "license": "MIT", "repository": "sindresorhus/has-flag", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=8" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "has", "check", "detect", "contains", "find", "flag", "cli", "command-line", "argv", "process", "arg", "args", "argument", "arguments", "getopt", "minimist", "optimist" ], "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.2", "xo": "^0.24.0" } } node_modules/has-flag/readme.md 0000664 00000003100 15114743311 0012456 0 ustar 00 # has-flag [](https://travis-ci.org/sindresorhus/has-flag) > Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag Correctly stops looking after an `--` argument terminator. --- <div align="center"> <b> <a href="https://tidelift.com/subscription/pkg/npm-has-flag?utm_source=npm-has-flag&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> </b> <br> <sub> Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. </sub> </div> --- ## Install ``` $ npm install has-flag ``` ## Usage ```js // foo.js const hasFlag = require('has-flag'); hasFlag('unicorn'); //=> true hasFlag('--unicorn'); //=> true hasFlag('f'); //=> true hasFlag('-f'); //=> true hasFlag('foo=bar'); //=> true hasFlag('foo'); //=> false hasFlag('rainbow'); //=> false ``` ``` $ node foo.js -f --unicorn --foo=bar -- --rainbow ``` ## API ### hasFlag(flag, [argv]) Returns a boolean for whether the flag exists. #### flag Type: `string` CLI flag to look for. The `--` prefix is optional. #### argv Type: `string[]`<br> Default: `process.argv` CLI arguments. ## Security To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## License MIT © [Sindre Sorhus](https://sindresorhus.com) node_modules/has-flag/index.d.ts 0000664 00000001254 15114743311 0012610 0 ustar 00 /** Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag. @param flag - CLI flag to look for. The `--` prefix is optional. @param argv - CLI arguments. Default: `process.argv`. @returns Whether the flag exists. @example ``` // $ ts-node foo.ts -f --unicorn --foo=bar -- --rainbow // foo.ts import hasFlag = require('has-flag'); hasFlag('unicorn'); //=> true hasFlag('--unicorn'); //=> true hasFlag('f'); //=> true hasFlag('-f'); //=> true hasFlag('foo=bar'); //=> true hasFlag('foo'); //=> false hasFlag('rainbow'); //=> false ``` */ declare function hasFlag(flag: string, argv?: string[]): boolean; export = hasFlag; node_modules/has-flag/index.js 0000664 00000000512 15114743311 0012350 0 ustar 00 'use strict'; module.exports = (flag, argv = process.argv) => { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; node_modules/is-extglob/package.json 0000664 00000002304 15114743311 0013565 0 ustar 00 { "name": "is-extglob", "description": "Returns true if a string has an extglob.", "version": "2.1.1", "homepage": "https://github.com/jonschlinkert/is-extglob", "author": "Jon Schlinkert (https://github.com/jonschlinkert)", "repository": "jonschlinkert/is-extglob", "bugs": { "url": "https://github.com/jonschlinkert/is-extglob/issues" }, "license": "MIT", "files": [ "index.js" ], "main": "index.js", "engines": { "node": ">=0.10.0" }, "scripts": { "test": "mocha" }, "devDependencies": { "gulp-format-md": "^0.1.10", "mocha": "^3.0.2" }, "keywords": [ "bash", "braces", "check", "exec", "expression", "extglob", "glob", "globbing", "globstar", "is", "match", "matches", "pattern", "regex", "regular", "string", "test" ], "verb": { "toc": false, "layout": "default", "tasks": [ "readme" ], "plugins": [ "gulp-format-md" ], "related": { "list": [ "has-glob", "is-glob", "micromatch" ] }, "reflinks": [ "verb", "verb-generate-readme" ], "lint": { "reflinks": true } } } node_modules/is-extglob/LICENSE 0000664 00000002077 15114743311 0012313 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2016, Jon Schlinkert Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/is-extglob/index.js 0000664 00000000671 15114743311 0012751 0 ustar 00 /*! * is-extglob <https://github.com/jonschlinkert/is-extglob> * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ module.exports = function isExtglob(str) { if (typeof str !== 'string' || str === '') { return false; } var match; while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { if (match[2]) return true; str = str.slice(match.index + match[0].length); } return false; }; node_modules/is-extglob/README.md 0000664 00000006615 15114743311 0012567 0 ustar 00 # is-extglob [](https://www.npmjs.com/package/is-extglob) [](https://npmjs.org/package/is-extglob) [](https://travis-ci.org/jonschlinkert/is-extglob) > Returns true if a string has an extglob. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-extglob ``` ## Usage ```js var isExtglob = require('is-extglob'); ``` **True** ```js isExtglob('?(abc)'); isExtglob('@(abc)'); isExtglob('!(abc)'); isExtglob('*(abc)'); isExtglob('+(abc)'); ``` **False** Escaped extglobs: ```js isExtglob('\\?(abc)'); isExtglob('\\@(abc)'); isExtglob('\\!(abc)'); isExtglob('\\*(abc)'); isExtglob('\\+(abc)'); ``` Everything else... ```js isExtglob('foo.js'); isExtglob('!foo.js'); isExtglob('*.js'); isExtglob('**/abc.js'); isExtglob('abc/*.js'); isExtglob('abc/(aaa|bbb).js'); isExtglob('abc/[a-z].js'); isExtglob('abc/{a,b}.js'); isExtglob('abc/?.js'); isExtglob('abc.js'); isExtglob('abc/def/ghi.js'); ``` ## History **v2.0** Adds support for escaping. Escaped exglobs no longer return true. ## About ### Related projects * [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ node_modules/is-interactive/license 0000664 00000002135 15114743311 0013517 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/is-interactive/package.json 0000664 00000001352 15114743311 0014440 0 ustar 00 { "name": "is-interactive", "version": "2.0.0", "description": "Check if stdout or stderr is interactive", "license": "MIT", "repository": "sindresorhus/is-interactive", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": ">=12" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "interactive", "stdout", "stderr", "detect", "is", "terminal", "shell", "tty" ], "devDependencies": { "@types/node": "^15.0.1", "ava": "^3.15.0", "tsd": "^0.14.0", "xo": "^0.39.1" } } node_modules/is-interactive/readme.md 0000664 00000004026 15114743311 0013732 0 ustar 00 # is-interactive > Check if stdout or stderr is [interactive](https://unix.stackexchange.com/a/43389/7678) It checks that the stream is [TTY](https://jameshfisher.com/2017/12/09/what-is-a-tty/), not a dumb terminal, and not running in a CI. This can be useful to decide whether to present interactive UI or animations in the terminal. ## Install ``` $ npm install is-interactive ``` ## Usage ```js import isInteractive from 'is-interactive'; isInteractive(); //=> true ``` ## API ### isInteractive(options?) #### options Type: `object` ##### stream Type: [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable)\ Default: [`process.stdout`](https://nodejs.org/api/process.html#process_process_stdout) The stream to check. ## FAQ #### Why are you not using [`ci-info`](https://github.com/watson/ci-info) for the CI check? It's silly to have to detect individual CIs. They should identify themselves with the `CI` environment variable, and most do just that. A manually maintained list of detections will easily get out of date. And if a package using `ci-info` doesn't update to the latest version all the time, they will not support certain CIs. It also creates unpredictability as you might assume a CI is not supported and then suddenly it gets supported and you didn't account for that. In addition, some of the manual detections are loose and might cause false-positives which could create hard-to-debug bugs. #### Why does this even exist? It's just a few lines. It's not about the number of lines, but rather discoverability and documentation. A lot of people wouldn't even know they need this. Feel free to copy-paste the code if you don't want the dependency. You might also want to read [this blog post](https://blog.sindresorhus.com/small-focused-modules-9238d977a92a). ## Related - [is-unicode-supported](https://github.com/sindresorhus/is-unicode-supported) - Detect whether the terminal supports Unicode - [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color node_modules/is-interactive/index.d.ts 0000664 00000001144 15114743311 0014052 0 ustar 00 export interface Options { /** The stream to check. @default process.stdout */ readonly stream?: NodeJS.WritableStream; } /** Check if stdout or stderr is [interactive](https://unix.stackexchange.com/a/43389/7678). It checks that the stream is [TTY](https://jameshfisher.com/2017/12/09/what-is-a-tty/), not a dumb terminal, and not running in a CI. This can be useful to decide whether to present interactive UI or animations in the terminal. @example ``` import isInteractive from 'is-interactive'; isInteractive(); //=> true ``` */ export default function isInteractive(options?: Options): boolean; node_modules/is-interactive/index.js 0000664 00000000265 15114743311 0013621 0 ustar 00 export default function isInteractive({stream = process.stdout} = {}) { return Boolean( stream && stream.isTTY && process.env.TERM !== 'dumb' && !('CI' in process.env) ); } node_modules/chalk/license 0000664 00000002135 15114743311 0011653 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/chalk/package.json 0000664 00000003150 15114743311 0012572 0 ustar 00 { "name": "chalk", "version": "5.3.0", "description": "Terminal string styling done right", "license": "MIT", "repository": "chalk/chalk", "funding": "https://github.com/chalk/chalk?sponsor=1", "type": "module", "main": "./source/index.js", "exports": "./source/index.js", "imports": { "#ansi-styles": "./source/vendor/ansi-styles/index.js", "#supports-color": { "node": "./source/vendor/supports-color/index.js", "default": "./source/vendor/supports-color/browser.js" } }, "types": "./source/index.d.ts", "engines": { "node": "^12.17.0 || ^14.13 || >=16.0.0" }, "scripts": { "test": "xo && c8 ava && tsd", "bench": "matcha benchmark.js" }, "files": [ "source", "!source/index.test-d.ts" ], "keywords": [ "color", "colour", "colors", "terminal", "console", "cli", "string", "ansi", "style", "styles", "tty", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "devDependencies": { "@types/node": "^16.11.10", "ava": "^3.15.0", "c8": "^7.10.0", "color-convert": "^2.0.1", "execa": "^6.0.0", "log-update": "^5.0.0", "matcha": "^0.7.0", "tsd": "^0.19.0", "xo": "^0.53.0", "yoctodelay": "^2.0.0" }, "sideEffects": false, "xo": { "rules": { "unicorn/prefer-string-slice": "off", "@typescript-eslint/consistent-type-imports": "off", "@typescript-eslint/consistent-type-exports": "off", "@typescript-eslint/consistent-type-definitions": "off", "unicorn/expiring-todo-comments": "off" } }, "c8": { "reporter": [ "text", "lcov" ], "exclude": [ "source/vendor" ] } } node_modules/chalk/readme.md 0000664 00000026022 15114743311 0012066 0 ustar 00 <h1 align="center"> <br> <br> <img width="320" src="media/logo.svg" alt="Chalk"> <br> <br> <br> </h1> > Terminal string styling done right [](https://codecov.io/gh/chalk/chalk) [](https://www.npmjs.com/package/chalk?activeTab=dependents) [](https://www.npmjs.com/package/chalk) [](https://repl.it/github/chalk/chalk)  <br> --- <div align="center"> <p> <p> <sup> Sindre Sorhus' open source work is supported by the community on <a href="https://github.com/sponsors/sindresorhus">GitHub Sponsors</a> </sup> </p> <sup>Special thanks to:</sup> <br> <br> <a href="https://standardresume.co/tech"> <img src="https://sindresorhus.com/assets/thanks/standard-resume-logo.svg" width="160"> </a> <br> <br> <a href="https://retool.com/?utm_campaign=sindresorhus"> <img src="https://sindresorhus.com/assets/thanks/retool-logo.svg" width="230"> </a> <br> <br> <a href="https://strapi.io/?ref=sindresorhus"> <div> <img src="https://sindresorhus.com/assets/thanks/strapi-logo-white-bg.png" width="220" alt="Strapi"> </div> <b>Strapi is the leading open-source headless CMS.</b> <div> <sup>It’s 100% JavaScript, fully customizable, and developer-first.</sup> </div> </a> <br> <br> <a href="https://www.stackaid.us/?utm_campaign=sindre"> <div> <img src="https://sindresorhus.com/assets/thanks/stackaid-logo.png" width="230" alt="StackAid"> </div> <b>Fund your open source dependencies</b> </a> <br> <br> </p> </div> --- <br> ## Highlights - Expressive API - Highly performant - No dependencies - Ability to nest styles - [256/Truecolor color support](#256-and-truecolor-color-support) - Auto-detects color support - Doesn't extend `String.prototype` - Clean and focused - Actively maintained - [Used by ~86,000 packages](https://www.npmjs.com/browse/depended/chalk) as of October 4, 2022 ## Install ```sh npm install chalk ``` **IMPORTANT:** Chalk 5 is ESM. If you want to use Chalk with TypeScript or a build tool, you will probably want to use Chalk 4 for now. [Read more.](https://github.com/chalk/chalk/releases/tag/v5.0.0) ## Usage ```js import chalk from 'chalk'; console.log(chalk.blue('Hello world!')); ``` Chalk comes with an easy to use composable API where you just chain and nest the styles you want. ```js import chalk from 'chalk'; const log = console.log; // Combine styled and normal strings log(chalk.blue('Hello') + ' World' + chalk.red('!')); // Compose multiple styles using the chainable API log(chalk.blue.bgRed.bold('Hello world!')); // Pass in multiple arguments log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); // Nest styles log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); // Nest styles of the same type even (color, underline, background) log(chalk.green( 'I am a green line ' + chalk.blue.underline.bold('with a blue substring') + ' that becomes green again!' )); // ES2015 template literal log(` CPU: ${chalk.red('90%')} RAM: ${chalk.green('40%')} DISK: ${chalk.yellow('70%')} `); // Use RGB colors in terminal emulators that support it. log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); log(chalk.hex('#DEADED').bold('Bold gray!')); ``` Easily define your own themes: ```js import chalk from 'chalk'; const error = chalk.bold.red; const warning = chalk.hex('#FFA500'); // Orange color console.log(error('Error!')); console.log(warning('Warning!')); ``` Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): ```js import chalk from 'chalk'; const name = 'Sindre'; console.log(chalk.green('Hello %s'), name); //=> 'Hello Sindre' ``` ## API ### chalk.`<style>[.<style>...](string, [string...])` Example: `chalk.red.bold.underline('Hello', 'world');` Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. Multiple arguments will be separated by space. ### chalk.level Specifies the level of color support. Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers. If you need to change this in a reusable module, create a new instance: ```js import {Chalk} from 'chalk'; const customChalk = new Chalk({level: 0}); ``` | Level | Description | | :---: | :--- | | `0` | All colors disabled | | `1` | Basic color support (16 colors) | | `2` | 256 color support | | `3` | Truecolor support (16 million colors) | ### supportsColor Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience. Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. ### chalkStderr and supportsColorStderr `chalkStderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `supportsColor` apply to this too. `supportsColorStderr` is exposed for convenience. ### modifierNames, foregroundColorNames, backgroundColorNames, and colorNames All supported style strings are exposed as an array of strings for convenience. `colorNames` is the combination of `foregroundColorNames` and `backgroundColorNames`. This can be useful if you wrap Chalk and need to validate input: ```js import {modifierNames, foregroundColorNames} from 'chalk'; console.log(modifierNames.includes('bold')); //=> true console.log(foregroundColorNames.includes('pink')); //=> false ``` ## Styles ### Modifiers - `reset` - Reset the current style. - `bold` - Make the text bold. - `dim` - Make the text have lower opacity. - `italic` - Make the text italic. *(Not widely supported)* - `underline` - Put a horizontal line below the text. *(Not widely supported)* - `overline` - Put a horizontal line above the text. *(Not widely supported)* - `inverse`- Invert background and foreground colors. - `hidden` - Print the text but make it invisible. - `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)* - `visible`- Print the text only when Chalk has a color level above zero. Can be useful for things that are purely cosmetic. ### Colors - `black` - `red` - `green` - `yellow` - `blue` - `magenta` - `cyan` - `white` - `blackBright` (alias: `gray`, `grey`) - `redBright` - `greenBright` - `yellowBright` - `blueBright` - `magentaBright` - `cyanBright` - `whiteBright` ### Background colors - `bgBlack` - `bgRed` - `bgGreen` - `bgYellow` - `bgBlue` - `bgMagenta` - `bgCyan` - `bgWhite` - `bgBlackBright` (alias: `bgGray`, `bgGrey`) - `bgRedBright` - `bgGreenBright` - `bgYellowBright` - `bgBlueBright` - `bgMagentaBright` - `bgCyanBright` - `bgWhiteBright` ## 256 and Truecolor color support Chalk supports 256 colors and [Truecolor](https://github.com/termstandard/colors) (16 million colors) on supported terminal apps. Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red). Examples: - `chalk.hex('#DEADED').underline('Hello, world!')` - `chalk.rgb(15, 100, 204).inverse('Hello!')` Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `hex` for foreground colors and `bgHex` for background colors). - `chalk.bgHex('#DEADED').underline('Hello, world!')` - `chalk.bgRgb(15, 100, 204).inverse('Hello!')` The following color models can be used: - [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')` - [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')` - [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')` ## Browser support Since Chrome 69, ANSI escape codes are natively supported in the developer console. ## Windows If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`. ## Origin story [colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative. ## Related - [chalk-template](https://github.com/chalk/chalk-template) - [Tagged template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) support for this module - [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module - [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal - [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color - [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes - [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream - [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes - [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes - [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes - [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes - [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models - [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal - [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings - [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings - [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) node_modules/chalk/source/utilities.js 0000664 00000001745 15114743311 0014165 0 ustar 00 // TODO: When targeting Node.js 16, use `String.prototype.replaceAll`. export function stringReplaceAll(string, substring, replacer) { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.slice(endIndex, index) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } node_modules/chalk/source/index.d.ts 0000664 00000015377 15114743311 0013523 0 ustar 00 // TODO: Make it this when TS suports that. // import {ModifierName, ForegroundColor, BackgroundColor, ColorName} from '#ansi-styles'; // import {ColorInfo, ColorSupportLevel} from '#supports-color'; import {ModifierName, ForegroundColorName, BackgroundColorName, ColorName} from './vendor/ansi-styles/index.js'; import {ColorInfo, ColorSupportLevel} from './vendor/supports-color/index.js'; export interface Options { /** Specify the color support for Chalk. By default, color support is automatically detected based on the environment. Levels: - `0` - All colors disabled. - `1` - Basic 16 colors support. - `2` - ANSI 256 colors support. - `3` - Truecolor 16 million colors support. */ readonly level?: ColorSupportLevel; } /** Return a new Chalk instance. */ export const Chalk: new (options?: Options) => ChalkInstance; // eslint-disable-line @typescript-eslint/naming-convention export interface ChalkInstance { (...text: unknown[]): string; /** The color support for Chalk. By default, color support is automatically detected based on the environment. Levels: - `0` - All colors disabled. - `1` - Basic 16 colors support. - `2` - ANSI 256 colors support. - `3` - Truecolor 16 million colors support. */ level: ColorSupportLevel; /** Use RGB values to set text color. @example ``` import chalk from 'chalk'; chalk.rgb(222, 173, 237); ``` */ rgb: (red: number, green: number, blue: number) => this; /** Use HEX value to set text color. @param color - Hexadecimal value representing the desired color. @example ``` import chalk from 'chalk'; chalk.hex('#DEADED'); ``` */ hex: (color: string) => this; /** Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. @example ``` import chalk from 'chalk'; chalk.ansi256(201); ``` */ ansi256: (index: number) => this; /** Use RGB values to set background color. @example ``` import chalk from 'chalk'; chalk.bgRgb(222, 173, 237); ``` */ bgRgb: (red: number, green: number, blue: number) => this; /** Use HEX value to set background color. @param color - Hexadecimal value representing the desired color. @example ``` import chalk from 'chalk'; chalk.bgHex('#DEADED'); ``` */ bgHex: (color: string) => this; /** Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color. @example ``` import chalk from 'chalk'; chalk.bgAnsi256(201); ``` */ bgAnsi256: (index: number) => this; /** Modifier: Reset the current style. */ readonly reset: this; /** Modifier: Make the text bold. */ readonly bold: this; /** Modifier: Make the text have lower opacity. */ readonly dim: this; /** Modifier: Make the text italic. *(Not widely supported)* */ readonly italic: this; /** Modifier: Put a horizontal line below the text. *(Not widely supported)* */ readonly underline: this; /** Modifier: Put a horizontal line above the text. *(Not widely supported)* */ readonly overline: this; /** Modifier: Invert background and foreground colors. */ readonly inverse: this; /** Modifier: Print the text but make it invisible. */ readonly hidden: this; /** Modifier: Puts a horizontal line through the center of the text. *(Not widely supported)* */ readonly strikethrough: this; /** Modifier: Print the text only when Chalk has a color level above zero. Can be useful for things that are purely cosmetic. */ readonly visible: this; readonly black: this; readonly red: this; readonly green: this; readonly yellow: this; readonly blue: this; readonly magenta: this; readonly cyan: this; readonly white: this; /* Alias for `blackBright`. */ readonly gray: this; /* Alias for `blackBright`. */ readonly grey: this; readonly blackBright: this; readonly redBright: this; readonly greenBright: this; readonly yellowBright: this; readonly blueBright: this; readonly magentaBright: this; readonly cyanBright: this; readonly whiteBright: this; readonly bgBlack: this; readonly bgRed: this; readonly bgGreen: this; readonly bgYellow: this; readonly bgBlue: this; readonly bgMagenta: this; readonly bgCyan: this; readonly bgWhite: this; /* Alias for `bgBlackBright`. */ readonly bgGray: this; /* Alias for `bgBlackBright`. */ readonly bgGrey: this; readonly bgBlackBright: this; readonly bgRedBright: this; readonly bgGreenBright: this; readonly bgYellowBright: this; readonly bgBlueBright: this; readonly bgMagentaBright: this; readonly bgCyanBright: this; readonly bgWhiteBright: this; } /** Main Chalk object that allows to chain styles together. Call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. */ declare const chalk: ChalkInstance; export const supportsColor: ColorInfo; export const chalkStderr: typeof chalk; export const supportsColorStderr: typeof supportsColor; export { ModifierName, ForegroundColorName, BackgroundColorName, ColorName, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, // } from '#ansi-styles'; } from './vendor/ansi-styles/index.js'; export { ColorInfo, ColorSupport, ColorSupportLevel, // } from '#supports-color'; } from './vendor/supports-color/index.js'; // TODO: Remove these aliases in the next major version /** @deprecated Use `ModifierName` instead. Basic modifier names. */ export type Modifiers = ModifierName; /** @deprecated Use `ForegroundColorName` instead. Basic foreground color names. [More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) */ export type ForegroundColor = ForegroundColorName; /** @deprecated Use `BackgroundColorName` instead. Basic background color names. [More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) */ export type BackgroundColor = BackgroundColorName; /** @deprecated Use `ColorName` instead. Basic color names. The combination of foreground and background color names. [More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) */ export type Color = ColorName; /** @deprecated Use `modifierNames` instead. Basic modifier names. */ export const modifiers: readonly Modifiers[]; /** @deprecated Use `foregroundColorNames` instead. Basic foreground color names. */ export const foregroundColors: readonly ForegroundColor[]; /** @deprecated Use `backgroundColorNames` instead. Basic background color names. */ export const backgroundColors: readonly BackgroundColor[]; /** @deprecated Use `colorNames` instead. Basic color names. The combination of foreground and background color names. */ export const colors: readonly Color[]; export default chalk; node_modules/chalk/source/index.js 0000664 00000013416 15114743311 0013257 0 ustar 00 import ansiStyles from '#ansi-styles'; import supportsColor from '#supports-color'; import { // eslint-disable-line import/order stringReplaceAll, stringEncaseCRLFWithFirstIndex, } from './utilities.js'; const {stdout: stdoutColor, stderr: stderrColor} = supportsColor; const GENERATOR = Symbol('GENERATOR'); const STYLER = Symbol('STYLER'); const IS_EMPTY = Symbol('IS_EMPTY'); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = [ 'ansi', 'ansi', 'ansi256', 'ansi16m', ]; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; export class Chalk { constructor(options) { // eslint-disable-next-line no-constructor-return return chalkFactory(options); } } const chalkFactory = options => { const chalk = (...strings) => strings.join(' '); applyOptions(chalk, options); Object.setPrototypeOf(chalk, createChalk.prototype); return chalk; }; function createChalk(options) { return chalkFactory(options); } Object.setPrototypeOf(createChalk.prototype, Function.prototype); for (const [styleName, style] of Object.entries(ansiStyles)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]); Object.defineProperty(this, styleName, {value: builder}); return builder; }, }; } styles.visible = { get() { const builder = createBuilder(this, this[STYLER], true); Object.defineProperty(this, 'visible', {value: builder}); return builder; }, }; const getModelAnsi = (model, level, type, ...arguments_) => { if (model === 'rgb') { if (level === 'ansi16m') { return ansiStyles[type].ansi16m(...arguments_); } if (level === 'ansi256') { return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_)); } return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_)); } if (model === 'hex') { return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_)); } return ansiStyles[type][model](...arguments_); }; const usedModels = ['rgb', 'hex', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]); return createBuilder(this, styler, this[IS_EMPTY]); }; }, }; const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]); return createBuilder(this, styler, this[IS_EMPTY]); }; }, }; } const proto = Object.defineProperties(() => {}, { ...styles, level: { enumerable: true, get() { return this[GENERATOR].level; }, set(level) { this[GENERATOR].level = level; }, }, }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent, }; }; const createBuilder = (self, _styler, _isEmpty) => { // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion const builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); // We alter the prototype because we must return a function, but there is // no way to create a function with a different prototype Object.setPrototypeOf(builder, proto); builder[GENERATOR] = self; builder[STYLER] = _styler; builder[IS_EMPTY] = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self[IS_EMPTY] ? '' : string; } let styler = self[STYLER]; if (styler === undefined) { return string; } const {openAll, closeAll} = styler; if (string.includes('\u001B')) { while (styler !== undefined) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. string = stringReplaceAll(string, styler.close, styler.open); styler = styler.parent; } } // We can move both next actions out of loop, because remaining actions in loop won't have // any/visible effect on parts we add here. Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; Object.defineProperties(createChalk.prototype, styles); const chalk = createChalk(); export const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0}); export { modifierNames, foregroundColorNames, backgroundColorNames, colorNames, // TODO: Remove these aliases in the next major version modifierNames as modifiers, foregroundColorNames as foregroundColors, backgroundColorNames as backgroundColors, colorNames as colors, } from './vendor/ansi-styles/index.js'; export { stdoutColor as supportsColor, stderrColor as supportsColorStderr, }; export default chalk; node_modules/chalk/source/vendor/supports-color/index.d.ts 0000664 00000001762 15114743311 0020024 0 ustar 00 import type {WriteStream} from 'node:tty'; export type Options = { /** Whether `process.argv` should be sniffed for `--color` and `--no-color` flags. @default true */ readonly sniffFlags?: boolean; }; /** Levels: - `0` - All colors disabled. - `1` - Basic 16 colors support. - `2` - ANSI 256 colors support. - `3` - Truecolor 16 million colors support. */ export type ColorSupportLevel = 0 | 1 | 2 | 3; /** Detect whether the terminal supports color. */ export type ColorSupport = { /** The color level. */ level: ColorSupportLevel; /** Whether basic 16 colors are supported. */ hasBasic: boolean; /** Whether ANSI 256 colors are supported. */ has256: boolean; /** Whether Truecolor 16 million colors are supported. */ has16m: boolean; }; export type ColorInfo = ColorSupport | false; export function createSupportsColor(stream?: WriteStream, options?: Options): ColorInfo; declare const supportsColor: { stdout: ColorInfo; stderr: ColorInfo; }; export default supportsColor; node_modules/chalk/source/vendor/supports-color/browser.d.ts 0000664 00000000044 15114743311 0020370 0 ustar 00 export {default} from './index.js'; node_modules/chalk/source/vendor/supports-color/index.js 0000664 00000007417 15114743311 0017573 0 ustar 00 import process from 'node:process'; import os from 'node:os'; import tty from 'node:tty'; // From: https://github.com/sindresorhus/has-flag/blob/main/index.js /// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) { function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); } const {env} = process; let flagForceColor; if ( hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never') ) { flagForceColor = 0; } else if ( hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always') ) { flagForceColor = 1; } function envForceColor() { if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { return 1; } if (env.FORCE_COLOR === 'false') { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3, }; } function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== undefined) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if (sniffFlags) { if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } } // Check for Azure DevOps pipelines. // Has to be above the `!streamIsTTY` check. if ('TF_BUILD' in env && 'AGENT_NAME' in env) { return 1; } if (haveStream && !streamIsTTY && forceColor === undefined) { return 0; } const min = forceColor || 0; if (env.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10_586 ) { return Number(osRelease[2]) >= 14_931 ? 3 : 2; } return 1; } if ('CI' in env) { if ('GITHUB_ACTIONS' in env || 'GITEA_ACTIONS' in env) { return 3; } if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if (env.TERM === 'xterm-kitty') { return 3; } if ('TERM_PROGRAM' in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': { return version >= 3 ? 3 : 2; } case 'Apple_Terminal': { return 2; } // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } return min; } export function createSupportsColor(stream, options = {}) { const level = _supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options, }); return translateLevel(level); } const supportsColor = { stdout: createSupportsColor({isTTY: tty.isatty(1)}), stderr: createSupportsColor({isTTY: tty.isatty(2)}), }; export default supportsColor; node_modules/chalk/source/vendor/supports-color/browser.js 0000664 00000001024 15114743311 0020133 0 ustar 00 /* eslint-env browser */ const level = (() => { if (navigator.userAgentData) { const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium'); if (brand && brand.version > 93) { return 3; } } if (/\b(Chrome|Chromium)\//.test(navigator.userAgent)) { return 1; } return 0; })(); const colorSupport = level !== 0 && { level, hasBasic: true, has256: level >= 2, has16m: level >= 3, }; const supportsColor = { stdout: colorSupport, stderr: colorSupport, }; export default supportsColor; node_modules/chalk/source/vendor/ansi-styles/index.d.ts 0000664 00000012116 15114743311 0017257 0 ustar 00 export interface CSPair { // eslint-disable-line @typescript-eslint/naming-convention /** The ANSI terminal control sequence for starting this style. */ readonly open: string; /** The ANSI terminal control sequence for ending this style. */ readonly close: string; } export interface ColorBase { /** The ANSI terminal control sequence for ending this color. */ readonly close: string; ansi(code: number): string; ansi256(code: number): string; ansi16m(red: number, green: number, blue: number): string; } export interface Modifier { /** Resets the current color chain. */ readonly reset: CSPair; /** Make text bold. */ readonly bold: CSPair; /** Emitting only a small amount of light. */ readonly dim: CSPair; /** Make text italic. (Not widely supported) */ readonly italic: CSPair; /** Make text underline. (Not widely supported) */ readonly underline: CSPair; /** Make text overline. Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash. */ readonly overline: CSPair; /** Inverse background and foreground colors. */ readonly inverse: CSPair; /** Prints the text, but makes it invisible. */ readonly hidden: CSPair; /** Puts a horizontal line through the center of the text. (Not widely supported) */ readonly strikethrough: CSPair; } export interface ForegroundColor { readonly black: CSPair; readonly red: CSPair; readonly green: CSPair; readonly yellow: CSPair; readonly blue: CSPair; readonly cyan: CSPair; readonly magenta: CSPair; readonly white: CSPair; /** Alias for `blackBright`. */ readonly gray: CSPair; /** Alias for `blackBright`. */ readonly grey: CSPair; readonly blackBright: CSPair; readonly redBright: CSPair; readonly greenBright: CSPair; readonly yellowBright: CSPair; readonly blueBright: CSPair; readonly cyanBright: CSPair; readonly magentaBright: CSPair; readonly whiteBright: CSPair; } export interface BackgroundColor { readonly bgBlack: CSPair; readonly bgRed: CSPair; readonly bgGreen: CSPair; readonly bgYellow: CSPair; readonly bgBlue: CSPair; readonly bgCyan: CSPair; readonly bgMagenta: CSPair; readonly bgWhite: CSPair; /** Alias for `bgBlackBright`. */ readonly bgGray: CSPair; /** Alias for `bgBlackBright`. */ readonly bgGrey: CSPair; readonly bgBlackBright: CSPair; readonly bgRedBright: CSPair; readonly bgGreenBright: CSPair; readonly bgYellowBright: CSPair; readonly bgBlueBright: CSPair; readonly bgCyanBright: CSPair; readonly bgMagentaBright: CSPair; readonly bgWhiteBright: CSPair; } export interface ConvertColor { /** Convert from the RGB color space to the ANSI 256 color space. @param red - (`0...255`) @param green - (`0...255`) @param blue - (`0...255`) */ rgbToAnsi256(red: number, green: number, blue: number): number; /** Convert from the RGB HEX color space to the RGB color space. @param hex - A hexadecimal string containing RGB data. */ hexToRgb(hex: string): [red: number, green: number, blue: number]; /** Convert from the RGB HEX color space to the ANSI 256 color space. @param hex - A hexadecimal string containing RGB data. */ hexToAnsi256(hex: string): number; /** Convert from the ANSI 256 color space to the ANSI 16 color space. @param code - A number representing the ANSI 256 color. */ ansi256ToAnsi(code: number): number; /** Convert from the RGB color space to the ANSI 16 color space. @param red - (`0...255`) @param green - (`0...255`) @param blue - (`0...255`) */ rgbToAnsi(red: number, green: number, blue: number): number; /** Convert from the RGB HEX color space to the ANSI 16 color space. @param hex - A hexadecimal string containing RGB data. */ hexToAnsi(hex: string): number; } /** Basic modifier names. */ export type ModifierName = keyof Modifier; /** Basic foreground color names. [More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) */ export type ForegroundColorName = keyof ForegroundColor; /** Basic background color names. [More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) */ export type BackgroundColorName = keyof BackgroundColor; /** Basic color names. The combination of foreground and background color names. [More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) */ export type ColorName = ForegroundColorName | BackgroundColorName; /** Basic modifier names. */ export const modifierNames: readonly ModifierName[]; /** Basic foreground color names. */ export const foregroundColorNames: readonly ForegroundColorName[]; /** Basic background color names. */ export const backgroundColorNames: readonly BackgroundColorName[]; /* Basic color names. The combination of foreground and background color names. */ export const colorNames: readonly ColorName[]; declare const ansiStyles: { readonly modifier: Modifier; readonly color: ColorBase & ForegroundColor; readonly bgColor: ColorBase & BackgroundColor; readonly codes: ReadonlyMap<number, number>; } & ForegroundColor & BackgroundColor & Modifier & ConvertColor; export default ansiStyles; node_modules/chalk/source/vendor/ansi-styles/index.js 0000664 00000012210 15114743311 0017016 0 ustar 00 const ANSI_BACKGROUND_OFFSET = 10; const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], gray: [90, 39], // Alias of `blackBright` grey: [90, 39], // Alias of `blackBright` redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgGray: [100, 49], // Alias of `bgBlackBright` bgGrey: [100, 49], // Alias of `bgBlackBright` bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], }, }; export const modifierNames = Object.keys(styles.modifier); export const foregroundColorNames = Object.keys(styles.color); export const backgroundColorNames = Object.keys(styles.bgColor); export const colorNames = [...foregroundColorNames, ...backgroundColorNames]; function assembleStyles() { const codes = new Map(); for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m`, }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false, }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false, }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = wrapAnsi16(); styles.color.ansi256 = wrapAnsi256(); styles.color.ansi16m = wrapAnsi16m(); styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js Object.defineProperties(styles, { rgbToAnsi256: { value(red, green, blue) { // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round(((red - 8) / 247) * 24) + 232; } return 16 + (36 * Math.round(red / 255 * 5)) + (6 * Math.round(green / 255 * 5)) + Math.round(blue / 255 * 5); }, enumerable: false, }, hexToRgb: { value(hex) { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map(character => character + character).join(''); } const integer = Number.parseInt(colorString, 16); return [ /* eslint-disable no-bitwise */ (integer >> 16) & 0xFF, (integer >> 8) & 0xFF, integer & 0xFF, /* eslint-enable no-bitwise */ ]; }, enumerable: false, }, hexToAnsi256: { value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), enumerable: false, }, ansi256ToAnsi: { value(code) { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = (((code - 232) * 10) + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = (remainder % 6) / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } // eslint-disable-next-line no-bitwise let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false, }, rgbToAnsi: { value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), enumerable: false, }, hexToAnsi: { value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), enumerable: false, }, }); return styles; } const ansiStyles = assembleStyles(); export default ansiStyles; node_modules/minipass/package.json 0000664 00000003321 15114743311 0013333 0 ustar 00 { "name": "minipass", "version": "5.0.0", "description": "minimal implementation of a PassThrough stream", "main": "./index.js", "module": "./index.mjs", "types": "./index.d.ts", "exports": { ".": { "import": { "types": "./index.d.ts", "default": "./index.mjs" }, "require": { "types": "./index.d.ts", "default": "./index.js" } }, "./package.json": "./package.json" }, "devDependencies": { "@types/node": "^17.0.41", "end-of-stream": "^1.4.0", "node-abort-controller": "^3.1.1", "prettier": "^2.6.2", "tap": "^16.2.0", "through2": "^2.0.3", "ts-node": "^10.8.1", "typedoc": "^0.23.24", "typescript": "^4.7.3" }, "scripts": { "pretest": "npm run prepare", "presnap": "npm run prepare", "prepare": "node ./scripts/transpile-to-esm.js", "snap": "tap", "test": "tap", "preversion": "npm test", "postversion": "npm publish", "postpublish": "git push origin --follow-tags", "typedoc": "typedoc ./index.d.ts", "format": "prettier --write . --loglevel warn" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass.git" }, "keywords": [ "passthrough", "stream" ], "author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)", "license": "ISC", "files": [ "index.d.ts", "index.js", "index.mjs" ], "tap": { "check-coverage": true }, "engines": { "node": ">=8" }, "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" } } node_modules/minipass/LICENSE 0000664 00000001423 15114743311 0012053 0 ustar 00 The ISC License Copyright (c) 2017-2023 npm, Inc., Isaac Z. Schlueter, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node_modules/minipass/index.d.ts 0000664 00000010346 15114743311 0012753 0 ustar 00 /// <reference types="node" /> // Note: marking anything protected or private in the exported // class will limit Minipass's ability to be used as the base // for mixin classes. import { EventEmitter } from 'events' import { Stream } from 'stream' export namespace Minipass { export type Encoding = BufferEncoding | 'buffer' | null export interface Writable extends EventEmitter { end(): any write(chunk: any, ...args: any[]): any } export interface Readable extends EventEmitter { pause(): any resume(): any pipe(): any } export type DualIterable<T> = Iterable<T> & AsyncIterable<T> export type ContiguousData = | Buffer | ArrayBufferLike | ArrayBufferView | string export type BufferOrString = Buffer | string export interface SharedOptions { async?: boolean signal?: AbortSignal } export interface StringOptions extends SharedOptions { encoding: BufferEncoding objectMode?: boolean } export interface BufferOptions extends SharedOptions { encoding?: null | 'buffer' objectMode?: boolean } export interface ObjectModeOptions extends SharedOptions { objectMode: true } export interface PipeOptions { end?: boolean proxyErrors?: boolean } export type Options<T> = T extends string ? StringOptions : T extends Buffer ? BufferOptions : ObjectModeOptions } export class Minipass< RType extends any = Buffer, WType extends any = RType extends Minipass.BufferOrString ? Minipass.ContiguousData : RType > extends Stream implements Minipass.DualIterable<RType> { static isStream(stream: any): stream is Minipass.Readable | Minipass.Writable readonly bufferLength: number readonly flowing: boolean readonly writable: boolean readonly readable: boolean readonly aborted: boolean readonly paused: boolean readonly emittedEnd: boolean readonly destroyed: boolean /** * Technically writable, but mutating it can change the type, * so is not safe to do in TypeScript. */ readonly objectMode: boolean async: boolean /** * Note: encoding is not actually read-only, and setEncoding(enc) * exists. However, this type definition will insist that TypeScript * programs declare the type of a Minipass stream up front, and if * that type is string, then an encoding MUST be set in the ctor. If * the type is Buffer, then the encoding must be missing, or set to * 'buffer' or null. If the type is anything else, then objectMode * must be set in the constructor options. So there is effectively * no allowed way that a TS program can set the encoding after * construction, as doing so will destroy any hope of type safety. * TypeScript does not provide many options for changing the type of * an object at run-time, which is what changing the encoding does. */ readonly encoding: Minipass.Encoding // setEncoding(encoding: Encoding): void // Options required if not reading buffers constructor( ...args: RType extends Buffer ? [] | [Minipass.Options<RType>] : [Minipass.Options<RType>] ) write(chunk: WType, cb?: () => void): boolean write(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): boolean read(size?: number): RType end(cb?: () => void): this end(chunk: any, cb?: () => void): this end(chunk: any, encoding?: Minipass.Encoding, cb?: () => void): this pause(): void resume(): void promise(): Promise<void> collect(): Promise<RType[]> concat(): RType extends Minipass.BufferOrString ? Promise<RType> : never destroy(er?: any): void pipe<W extends Minipass.Writable>(dest: W, opts?: Minipass.PipeOptions): W unpipe<W extends Minipass.Writable>(dest: W): void /** * alias for on() */ addEventHandler(event: string, listener: (...args: any[]) => any): this on(event: string, listener: (...args: any[]) => any): this on(event: 'data', listener: (chunk: RType) => any): this on(event: 'error', listener: (error: any) => any): this on( event: | 'readable' | 'drain' | 'resume' | 'end' | 'prefinish' | 'finish' | 'close', listener: () => any ): this [Symbol.iterator](): Generator<RType, void, void> [Symbol.asyncIterator](): AsyncGenerator<RType, void, void> } node_modules/minipass/index.mjs 0000664 00000044124 15114743311 0012675 0 ustar 00 'use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } import EE from 'events' import Stream from 'stream' import stringdecoder from 'string_decoder' const SD = stringdecoder.StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFER = Symbol('buffer') const PIPES = Symbol('pipes') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') // internal event when stream is destroyed const DESTROYED = Symbol('destroyed') // internal event when stream has an error const ERROR = Symbol('error') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const ABORT = Symbol('abort') const ABORTED = Symbol('aborted') const SIGNAL = Symbol('signal') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = (doIter && Symbol.asyncIterator) || Symbol('asyncIterator not implemented') const ITERATOR = (doIter && Symbol.iterator) || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || (typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0) const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor(src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe() { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors() {} end() { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe() { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor(src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } export class Minipass extends Stream { constructor(options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this[PIPES] = [] this[BUFFER] = [] this[OBJECTMODE] = (options && options.objectMode) || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = (options && options.encoding) || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = (options && !!options.async) || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false if (options && options.debugExposeBuffer === true) { Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] }) } if (options && options.debugExposePipes === true) { Object.defineProperty(this, 'pipes', { get: () => this[PIPES] }) } this[SIGNAL] = options && options.signal this[ABORTED] = false if (this[SIGNAL]) { this[SIGNAL].addEventListener('abort', () => this[ABORT]()) if (this[SIGNAL].aborted) { this[ABORT]() } } } get bufferLength() { return this[BUFFERLENGTH] } get encoding() { return this[ENCODING] } set encoding(enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if ( this[ENCODING] && enc !== this[ENCODING] && ((this[DECODER] && this[DECODER].lastNeed) || this[BUFFERLENGTH]) ) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this[BUFFER].length) this[BUFFER] = this[BUFFER].map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding(enc) { this.encoding = enc } get objectMode() { return this[OBJECTMODE] } set objectMode(om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async']() { return this[ASYNC] } set ['async'](a) { this[ASYNC] = this[ASYNC] || !!a } // drop everything and get out of the flow completely [ABORT]() { this[ABORTED] = true this.emit('abort', this[SIGNAL].reason) this.destroy(this[SIGNAL].reason) } get aborted() { return this[ABORTED] } set aborted(_) {} write(chunk, encoding, cb) { if (this[ABORTED]) return false if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit( 'error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } ) ) return true } if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8') if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if ( typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed) ) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read(n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this[BUFFER].length > 1 && !this[OBJECTMODE]) { if (this.encoding) this[BUFFER] = [this[BUFFER].join('')] else this[BUFFER] = [Buffer.concat(this[BUFFER], this[BUFFERLENGTH])] } const ret = this[READ](n || null, this[BUFFER][0]) this[MAYBE_EMIT_END]() return ret } [READ](n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this[BUFFER][0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this[BUFFER].length && !this[EOF]) this.emit('drain') return chunk } end(chunk, encoding, cb) { if (typeof chunk === 'function') (cb = chunk), (chunk = null) if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8') if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME]() { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this[BUFFER].length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume() { return this[RESUME]() } pause() { this[FLOWING] = false this[PAUSED] = true } get destroyed() { return this[DESTROYED] } get flowing() { return this[FLOWING] } get paused() { return this[PAUSED] } [BUFFERPUSH](chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this[BUFFER].push(chunk) } [BUFFERSHIFT]() { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this[BUFFER][0].length return this[BUFFER].shift() } [FLUSH](noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length) if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK](chunk) { this.emit('data', chunk) return this.flowing } pipe(dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this[PIPES].push( !opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts) ) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe(dest) { const p = this[PIPES].find(p => p.dest === dest) if (p) { this[PIPES].splice(this[PIPES].indexOf(p), 1) p.unpipe() } } addListener(ev, fn) { return this.on(ev, fn) } on(ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this[PIPES].length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd() { return this[EMITTED_END] } [MAYBE_EMIT_END]() { if ( !this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF] ) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit(ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data super.emit(ERROR, data) const ret = !this[SIGNAL] || this.listeners('error').length ? super.emit('error', data) : false this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA](data) { for (const p of this[PIPES]) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND]() { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2]() { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this[PIPES]) { p.dest.write(data) } super.emit('data', data) } } for (const p of this[PIPES]) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect() { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat() { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength) ) } // stream.promise().then(() => done, er => emitted error) promise() { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR]() { let stopped = false const stop = () => { this.pause() stopped = true return Promise.resolve({ done: true }) } const next = () => { if (stopped) return stop() const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return stop() let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) this.removeListener(DESTROYED, ondestroy) stop() reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.removeListener(DESTROYED, ondestroy) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) this.removeListener(DESTROYED, ondestroy) stop() resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next, throw: stop, return: stop, [ASYNCITERATOR]() { return this }, } } // for (let chunk of stream) [ITERATOR]() { let stopped = false const stop = () => { this.pause() this.removeListener(ERROR, stop) this.removeListener(DESTROYED, stop) this.removeListener('end', stop) stopped = true return { done: true } } const next = () => { if (stopped) return stop() const value = this.read() return value === null ? stop() : { value } } this.once('end', stop) this.once(ERROR, stop) this.once(DESTROYED, stop) return { next, throw: stop, return: stop, [ITERATOR]() { return this }, } } destroy(er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this[BUFFER].length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) // if no error to emit, still reject pending promises else this.emit(DESTROYED) return this } static isStream(s) { return ( !!s && (s instanceof Minipass || s instanceof Stream || (s instanceof EE && // readable (typeof s.pipe === 'function' || // writable (typeof s.write === 'function' && typeof s.end === 'function')))) ) } } node_modules/minipass/index.js 0000664 00000044167 15114743311 0012527 0 ustar 00 'use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = require('events') const Stream = require('stream') const stringdecoder = require('string_decoder') const SD = stringdecoder.StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFER = Symbol('buffer') const PIPES = Symbol('pipes') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') // internal event when stream is destroyed const DESTROYED = Symbol('destroyed') // internal event when stream has an error const ERROR = Symbol('error') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const ABORT = Symbol('abort') const ABORTED = Symbol('aborted') const SIGNAL = Symbol('signal') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = (doIter && Symbol.asyncIterator) || Symbol('asyncIterator not implemented') const ITERATOR = (doIter && Symbol.iterator) || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || (typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0) const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor(src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe() { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors() {} end() { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe() { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor(src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } class Minipass extends Stream { constructor(options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this[PIPES] = [] this[BUFFER] = [] this[OBJECTMODE] = (options && options.objectMode) || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = (options && options.encoding) || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = (options && !!options.async) || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false if (options && options.debugExposeBuffer === true) { Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] }) } if (options && options.debugExposePipes === true) { Object.defineProperty(this, 'pipes', { get: () => this[PIPES] }) } this[SIGNAL] = options && options.signal this[ABORTED] = false if (this[SIGNAL]) { this[SIGNAL].addEventListener('abort', () => this[ABORT]()) if (this[SIGNAL].aborted) { this[ABORT]() } } } get bufferLength() { return this[BUFFERLENGTH] } get encoding() { return this[ENCODING] } set encoding(enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if ( this[ENCODING] && enc !== this[ENCODING] && ((this[DECODER] && this[DECODER].lastNeed) || this[BUFFERLENGTH]) ) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this[BUFFER].length) this[BUFFER] = this[BUFFER].map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding(enc) { this.encoding = enc } get objectMode() { return this[OBJECTMODE] } set objectMode(om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async']() { return this[ASYNC] } set ['async'](a) { this[ASYNC] = this[ASYNC] || !!a } // drop everything and get out of the flow completely [ABORT]() { this[ABORTED] = true this.emit('abort', this[SIGNAL].reason) this.destroy(this[SIGNAL].reason) } get aborted() { return this[ABORTED] } set aborted(_) {} write(chunk, encoding, cb) { if (this[ABORTED]) return false if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit( 'error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } ) ) return true } if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8') if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if ( typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed) ) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read(n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this[BUFFER].length > 1 && !this[OBJECTMODE]) { if (this.encoding) this[BUFFER] = [this[BUFFER].join('')] else this[BUFFER] = [Buffer.concat(this[BUFFER], this[BUFFERLENGTH])] } const ret = this[READ](n || null, this[BUFFER][0]) this[MAYBE_EMIT_END]() return ret } [READ](n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this[BUFFER][0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this[BUFFER].length && !this[EOF]) this.emit('drain') return chunk } end(chunk, encoding, cb) { if (typeof chunk === 'function') (cb = chunk), (chunk = null) if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8') if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME]() { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this[BUFFER].length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume() { return this[RESUME]() } pause() { this[FLOWING] = false this[PAUSED] = true } get destroyed() { return this[DESTROYED] } get flowing() { return this[FLOWING] } get paused() { return this[PAUSED] } [BUFFERPUSH](chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this[BUFFER].push(chunk) } [BUFFERSHIFT]() { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this[BUFFER][0].length return this[BUFFER].shift() } [FLUSH](noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length) if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK](chunk) { this.emit('data', chunk) return this.flowing } pipe(dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this[PIPES].push( !opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts) ) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe(dest) { const p = this[PIPES].find(p => p.dest === dest) if (p) { this[PIPES].splice(this[PIPES].indexOf(p), 1) p.unpipe() } } addListener(ev, fn) { return this.on(ev, fn) } on(ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this[PIPES].length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd() { return this[EMITTED_END] } [MAYBE_EMIT_END]() { if ( !this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF] ) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit(ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data super.emit(ERROR, data) const ret = !this[SIGNAL] || this.listeners('error').length ? super.emit('error', data) : false this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA](data) { for (const p of this[PIPES]) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND]() { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2]() { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this[PIPES]) { p.dest.write(data) } super.emit('data', data) } } for (const p of this[PIPES]) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect() { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat() { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength) ) } // stream.promise().then(() => done, er => emitted error) promise() { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR]() { let stopped = false const stop = () => { this.pause() stopped = true return Promise.resolve({ done: true }) } const next = () => { if (stopped) return stop() const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return stop() let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) this.removeListener(DESTROYED, ondestroy) stop() reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.removeListener(DESTROYED, ondestroy) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) this.removeListener(DESTROYED, ondestroy) stop() resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next, throw: stop, return: stop, [ASYNCITERATOR]() { return this }, } } // for (let chunk of stream) [ITERATOR]() { let stopped = false const stop = () => { this.pause() this.removeListener(ERROR, stop) this.removeListener(DESTROYED, stop) this.removeListener('end', stop) stopped = true return { done: true } } const next = () => { if (stopped) return stop() const value = this.read() return value === null ? stop() : { value } } this.once('end', stop) this.once(ERROR, stop) this.once(DESTROYED, stop) return { next, throw: stop, return: stop, [ITERATOR]() { return this }, } } destroy(er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this[BUFFER].length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) // if no error to emit, still reject pending promises else this.emit(DESTROYED) return this } static isStream(s) { return ( !!s && (s instanceof Minipass || s instanceof Stream || (s instanceof EE && // readable (typeof s.pipe === 'function' || // writable (typeof s.write === 'function' && typeof s.end === 'function')))) ) } } exports.Minipass = Minipass node_modules/minipass/README.md 0000664 00000061716 15114743311 0012340 0 ustar 00 # minipass A _very_ minimal implementation of a [PassThrough stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) [It's very fast](https://docs.google.com/spreadsheets/d/1K_HR5oh3r80b8WVMWCPPjfuWXUgfkmhlX7FGI6JJ8tY/edit?usp=sharing) for objects, strings, and buffers. Supports `pipe()`ing (including multi-`pipe()` and backpressure transmission), buffering data until either a `data` event handler or `pipe()` is added (so you don't lose the first chunk), and most other cases where PassThrough is a good idea. There is a `read()` method, but it's much more efficient to consume data from this stream via `'data'` events or by calling `pipe()` into some other stream. Calling `read()` requires the buffer to be flattened in some cases, which requires copying memory. If you set `objectMode: true` in the options, then whatever is written will be emitted. Otherwise, it'll do a minimal amount of Buffer copying to ensure proper Streams semantics when `read(n)` is called. `objectMode` can also be set by doing `stream.objectMode = true`, or by writing any non-string/non-buffer data. `objectMode` cannot be set to false once it is set. This is not a `through` or `through2` stream. It doesn't transform the data, it just passes it right through. If you want to transform the data, extend the class, and override the `write()` method. Once you're done transforming the data however you want, call `super.write()` with the transform output. For some examples of streams that extend Minipass in various ways, check out: - [minizlib](http://npm.im/minizlib) - [fs-minipass](http://npm.im/fs-minipass) - [tar](http://npm.im/tar) - [minipass-collect](http://npm.im/minipass-collect) - [minipass-flush](http://npm.im/minipass-flush) - [minipass-pipeline](http://npm.im/minipass-pipeline) - [tap](http://npm.im/tap) - [tap-parser](http://npm.im/tap-parser) - [treport](http://npm.im/treport) - [minipass-fetch](http://npm.im/minipass-fetch) - [pacote](http://npm.im/pacote) - [make-fetch-happen](http://npm.im/make-fetch-happen) - [cacache](http://npm.im/cacache) - [ssri](http://npm.im/ssri) - [npm-registry-fetch](http://npm.im/npm-registry-fetch) - [minipass-json-stream](http://npm.im/minipass-json-stream) - [minipass-sized](http://npm.im/minipass-sized) ## Differences from Node.js Streams There are several things that make Minipass streams different from (and in some ways superior to) Node.js core streams. Please read these caveats if you are familiar with node-core streams and intend to use Minipass streams in your programs. You can avoid most of these differences entirely (for a very small performance penalty) by setting `{async: true}` in the constructor options. ### Timing Minipass streams are designed to support synchronous use-cases. Thus, data is emitted as soon as it is available, always. It is buffered until read, but no longer. Another way to look at it is that Minipass streams are exactly as synchronous as the logic that writes into them. This can be surprising if your code relies on `PassThrough.write()` always providing data on the next tick rather than the current one, or being able to call `resume()` and not have the entire buffer disappear immediately. However, without this synchronicity guarantee, there would be no way for Minipass to achieve the speeds it does, or support the synchronous use cases that it does. Simply put, waiting takes time. This non-deferring approach makes Minipass streams much easier to reason about, especially in the context of Promises and other flow-control mechanisms. Example: ```js // hybrid module, either works import { Minipass } from 'minipass' // or: const { Minipass } = require('minipass') const stream = new Minipass() stream.on('data', () => console.log('data event')) console.log('before write') stream.write('hello') console.log('after write') // output: // before write // data event // after write ``` ### Exception: Async Opt-In If you wish to have a Minipass stream with behavior that more closely mimics Node.js core streams, you can set the stream in async mode either by setting `async: true` in the constructor options, or by setting `stream.async = true` later on. ```js // hybrid module, either works import { Minipass } from 'minipass' // or: const { Minipass } = require('minipass') const asyncStream = new Minipass({ async: true }) asyncStream.on('data', () => console.log('data event')) console.log('before write') asyncStream.write('hello') console.log('after write') // output: // before write // after write // data event <-- this is deferred until the next tick ``` Switching _out_ of async mode is unsafe, as it could cause data corruption, and so is not enabled. Example: ```js import { Minipass } from 'minipass' const stream = new Minipass({ encoding: 'utf8' }) stream.on('data', chunk => console.log(chunk)) stream.async = true console.log('before writes') stream.write('hello') setStreamSyncAgainSomehow(stream) // <-- this doesn't actually exist! stream.write('world') console.log('after writes') // hypothetical output would be: // before writes // world // after writes // hello // NOT GOOD! ``` To avoid this problem, once set into async mode, any attempt to make the stream sync again will be ignored. ```js const { Minipass } = require('minipass') const stream = new Minipass({ encoding: 'utf8' }) stream.on('data', chunk => console.log(chunk)) stream.async = true console.log('before writes') stream.write('hello') stream.async = false // <-- no-op, stream already async stream.write('world') console.log('after writes') // actual output: // before writes // after writes // hello // world ``` ### No High/Low Water Marks Node.js core streams will optimistically fill up a buffer, returning `true` on all writes until the limit is hit, even if the data has nowhere to go. Then, they will not attempt to draw more data in until the buffer size dips below a minimum value. Minipass streams are much simpler. The `write()` method will return `true` if the data has somewhere to go (which is to say, given the timing guarantees, that the data is already there by the time `write()` returns). If the data has nowhere to go, then `write()` returns false, and the data sits in a buffer, to be drained out immediately as soon as anyone consumes it. Since nothing is ever buffered unnecessarily, there is much less copying data, and less bookkeeping about buffer capacity levels. ### Hazards of Buffering (or: Why Minipass Is So Fast) Since data written to a Minipass stream is immediately written all the way through the pipeline, and `write()` always returns true/false based on whether the data was fully flushed, backpressure is communicated immediately to the upstream caller. This minimizes buffering. Consider this case: ```js const { PassThrough } = require('stream') const p1 = new PassThrough({ highWaterMark: 1024 }) const p2 = new PassThrough({ highWaterMark: 1024 }) const p3 = new PassThrough({ highWaterMark: 1024 }) const p4 = new PassThrough({ highWaterMark: 1024 }) p1.pipe(p2).pipe(p3).pipe(p4) p4.on('data', () => console.log('made it through')) // this returns false and buffers, then writes to p2 on next tick (1) // p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) // p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) // p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' // on next tick (4) // p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and // 'drain' on next tick (5) // p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) // p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next // tick (7) p1.write(Buffer.alloc(2048)) // returns false ``` Along the way, the data was buffered and deferred at each stage, and multiple event deferrals happened, for an unblocked pipeline where it was perfectly safe to write all the way through! Furthermore, setting a `highWaterMark` of `1024` might lead someone reading the code to think an advisory maximum of 1KiB is being set for the pipeline. However, the actual advisory buffering level is the _sum_ of `highWaterMark` values, since each one has its own bucket. Consider the Minipass case: ```js const m1 = new Minipass() const m2 = new Minipass() const m3 = new Minipass() const m4 = new Minipass() m1.pipe(m2).pipe(m3).pipe(m4) m4.on('data', () => console.log('made it through')) // m1 is flowing, so it writes the data to m2 immediately // m2 is flowing, so it writes the data to m3 immediately // m3 is flowing, so it writes the data to m4 immediately // m4 is flowing, so it fires the 'data' event immediately, returns true // m4's write returned true, so m3 is still flowing, returns true // m3's write returned true, so m2 is still flowing, returns true // m2's write returned true, so m1 is still flowing, returns true // No event deferrals or buffering along the way! m1.write(Buffer.alloc(2048)) // returns true ``` It is extremely unlikely that you _don't_ want to buffer any data written, or _ever_ buffer data that can be flushed all the way through. Neither node-core streams nor Minipass ever fail to buffer written data, but node-core streams do a lot of unnecessary buffering and pausing. As always, the faster implementation is the one that does less stuff and waits less time to do it. ### Immediately emit `end` for empty streams (when not paused) If a stream is not paused, and `end()` is called before writing any data into it, then it will emit `end` immediately. If you have logic that occurs on the `end` event which you don't want to potentially happen immediately (for example, closing file descriptors, moving on to the next entry in an archive parse stream, etc.) then be sure to call `stream.pause()` on creation, and then `stream.resume()` once you are ready to respond to the `end` event. However, this is _usually_ not a problem because: ### Emit `end` When Asked One hazard of immediately emitting `'end'` is that you may not yet have had a chance to add a listener. In order to avoid this hazard, Minipass streams safely re-emit the `'end'` event if a new listener is added after `'end'` has been emitted. Ie, if you do `stream.on('end', someFunction)`, and the stream has already emitted `end`, then it will call the handler right away. (You can think of this somewhat like attaching a new `.then(fn)` to a previously-resolved Promise.) To prevent calling handlers multiple times who would not expect multiple ends to occur, all listeners are removed from the `'end'` event whenever it is emitted. ### Emit `error` When Asked The most recent error object passed to the `'error'` event is stored on the stream. If a new `'error'` event handler is added, and an error was previously emitted, then the event handler will be called immediately (or on `process.nextTick` in the case of async streams). This makes it much more difficult to end up trying to interact with a broken stream, if the error handler is added after an error was previously emitted. ### Impact of "immediate flow" on Tee-streams A "tee stream" is a stream piping to multiple destinations: ```js const tee = new Minipass() t.pipe(dest1) t.pipe(dest2) t.write('foo') // goes to both destinations ``` Since Minipass streams _immediately_ process any pending data through the pipeline when a new pipe destination is added, this can have surprising effects, especially when a stream comes in from some other function and may or may not have data in its buffer. ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone src.pipe(dest2) // gets nothing! ``` One solution is to create a dedicated tee-stream junction that pipes to both locations, and then pipe to _that_ instead. ```js // Safe example: tee to both places const src = new Minipass() src.write('foo') const tee = new Minipass() tee.pipe(dest1) tee.pipe(dest2) src.pipe(tee) // tee gets 'foo', pipes to both locations ``` The same caveat applies to `on('data')` event listeners. The first one added will _immediately_ receive all of the data, leaving nothing for the second: ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.on('data', handler1) // receives 'foo' right away src.on('data', handler2) // nothing to see here! ``` Using a dedicated tee-stream can be used in this case as well: ```js // Safe example: tee to both data handlers const src = new Minipass() src.write('foo') const tee = new Minipass() tee.on('data', handler1) tee.on('data', handler2) src.pipe(tee) ``` All of the hazards in this section are avoided by setting `{ async: true }` in the Minipass constructor, or by setting `stream.async = true` afterwards. Note that this does add some overhead, so should only be done in cases where you are willing to lose a bit of performance in order to avoid having to refactor program logic. ## USAGE It's a stream! Use it like a stream and it'll most likely do what you want. ```js import { Minipass } from 'minipass' const mp = new Minipass(options) // optional: { encoding, objectMode } mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` ### OPTIONS - `encoding` How would you like the data coming _out_ of the stream to be encoded? Accepts any values that can be passed to `Buffer.toString()`. - `objectMode` Emit data exactly as it comes in. This will be flipped on by default if you write() something other than a string or Buffer at any point. Setting `objectMode: true` will prevent setting any encoding value. - `async` Defaults to `false`. Set to `true` to defer data emission until next tick. This reduces performance slightly, but makes Minipass streams use timing behavior closer to Node core streams. See [Timing](#timing) for more details. - `signal` An `AbortSignal` that will cause the stream to unhook itself from everything and become as inert as possible. Note that providing a `signal` parameter will make `'error'` events no longer throw if they are unhandled, but they will still be emitted to handlers if any are attached. ### API Implements the user-facing portions of Node.js's `Readable` and `Writable` streams. ### Methods - `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the base Minipass class, the same data will come out.) Returns `false` if the stream will buffer the next write, or true if it's still in "flowing" mode. - `end([chunk, [encoding]], [callback])` - Signal that you have no more data to write. This will queue an `end` event to be fired when all the data has been consumed. - `setEncoding(encoding)` - Set the encoding for data coming of the stream. This can only be done once. - `pause()` - No more data for a while, please. This also prevents `end` from being emitted for empty streams until the stream is resumed. - `resume()` - Resume the stream. If there's data in the buffer, it is all discarded. Any buffered events are immediately emitted. - `pipe(dest)` - Send all output to the stream provided. When data is emitted, it is immediately written to any and all pipe destinations. (Or written on next tick in `async` mode.) - `unpipe(dest)` - Stop piping to the destination stream. This is immediate, meaning that any asynchronously queued data will _not_ make it to the destination when running in `async` mode. - `options.end` - Boolean, end the destination stream when the source stream ends. Default `true`. - `options.proxyErrors` - Boolean, proxy `error` events from the source stream to the destination stream. Note that errors are _not_ proxied after the pipeline terminates, either due to the source emitting `'end'` or manually unpiping with `src.unpipe(dest)`. Default `false`. - `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some events are given special treatment, however. (See below under "events".) - `promise()` - Returns a Promise that resolves when the stream emits `end`, or rejects if the stream emits `error`. - `collect()` - Return a Promise that resolves on `end` with an array containing each chunk of data that was emitted, or rejects if the stream emits `error`. Note that this consumes the stream data. - `concat()` - Same as `collect()`, but concatenates the data into a single Buffer object. Will reject the returned promise if the stream is in objectMode, or if it goes into objectMode by the end of the data. - `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not provided, then consume all of it. If `n` bytes are not available, then it returns null. **Note** consuming streams in this way is less efficient, and can lead to unnecessary Buffer copying. - `destroy([er])` - Destroy the stream. If an error is provided, then an `'error'` event is emitted. If the stream has a `close()` method, and has not emitted a `'close'` event yet, then `stream.close()` will be called. Any Promises returned by `.promise()`, `.collect()` or `.concat()` will be rejected. After being destroyed, writing to the stream will emit an error. No more data will be emitted if the stream is destroyed, even if it was previously buffered. ### Properties - `bufferLength` Read-only. Total number of bytes buffered, or in the case of objectMode, the total number of objects. - `encoding` The encoding that has been set. (Setting this is equivalent to calling `setEncoding(enc)` and has the same prohibition against setting multiple times.) - `flowing` Read-only. Boolean indicating whether a chunk written to the stream will be immediately emitted. - `emittedEnd` Read-only. Boolean indicating whether the end-ish events (ie, `end`, `prefinish`, `finish`) have been emitted. Note that listening on any end-ish event will immediateyl re-emit it if it has already been emitted. - `writable` Whether the stream is writable. Default `true`. Set to `false` when `end()` - `readable` Whether the stream is readable. Default `true`. - `pipes` An array of Pipe objects referencing streams that this stream is piping into. - `destroyed` A getter that indicates whether the stream was destroyed. - `paused` True if the stream has been explicitly paused, otherwise false. - `objectMode` Indicates whether the stream is in `objectMode`. Once set to `true`, it cannot be set to `false`. - `aborted` Readonly property set when the `AbortSignal` dispatches an `abort` event. ### Events - `data` Emitted when there's data to read. Argument is the data to read. This is never emitted while not flowing. If a listener is attached, that will resume the stream. - `end` Emitted when there's no more data to read. This will be emitted immediately for empty streams when `end()` is called. If a listener is attached, and `end` was already emitted, then it will be emitted again. All listeners are removed when `end` is emitted. - `prefinish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'end'`. - `finish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'prefinish'`. - `close` An indication that an underlying resource has been released. Minipass does not emit this event, but will defer it until after `end` has been emitted, since it throws off some stream libraries otherwise. - `drain` Emitted when the internal buffer empties, and it is again suitable to `write()` into the stream. - `readable` Emitted when data is buffered and ready to be read by a consumer. - `resume` Emitted when stream changes state from buffering to flowing mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event listener is added.) ### Static Methods - `Minipass.isStream(stream)` Returns `true` if the argument is a stream, and false otherwise. To be considered a stream, the object must be either an instance of Minipass, or an EventEmitter that has either a `pipe()` method, or both `write()` and `end()` methods. (Pretty much any stream in node-land will return `true` for this.) ## EXAMPLES Here are some examples of things you can do with Minipass streams. ### simple "are you done yet" promise ```js mp.promise().then( () => { // stream is finished }, er => { // stream emitted an error } ) ``` ### collecting ```js mp.collect().then(all => { // all is an array of all the data emitted // encoding is supported in this case, so // so the result will be a collection of strings if // an encoding is specified, or buffers/objects if not. // // In an async function, you may do // const data = await stream.collect() }) ``` ### collecting into a single blob This is a bit slower because it concatenates the data into one chunk for you, but if you're going to do it yourself anyway, it's convenient this way: ```js mp.concat().then(onebigchunk => { // onebigchunk is a string if the stream // had an encoding set, or a buffer otherwise. }) ``` ### iteration You can iterate over streams synchronously or asynchronously in platforms that support it. Synchronous iteration will end when the currently available data is consumed, even if the `end` event has not been reached. In string and buffer mode, the data is concatenated, so unless multiple writes are occurring in the same tick as the `read()`, sync iteration loops will generally only have a single iteration. To consume chunks in this way exactly as they have been written, with no flattening, create the stream with the `{ objectMode: true }` option. ```js const mp = new Minipass({ objectMode: true }) mp.write('a') mp.write('b') for (let letter of mp) { console.log(letter) // a, b } mp.write('c') mp.write('d') for (let letter of mp) { console.log(letter) // c, d } mp.write('e') mp.end() for (let letter of mp) { console.log(letter) // e } for (let letter of mp) { console.log(letter) // nothing } ``` Asynchronous iteration will continue until the end event is reached, consuming all of the data. ```js const mp = new Minipass({ encoding: 'utf8' }) // some source of some data let i = 5 const inter = setInterval(() => { if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // consume the data with asynchronous iteration async function consume() { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // logs `foo\n` 5 times, and then `ok` ``` ### subclass that `console.log()`s everything written into it ```js class Logger extends Minipass { write(chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end(chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } } someSource.pipe(new Logger()).pipe(someDest) ``` ### same thing, but using an inline anonymous class ```js // js classes are fun someSource .pipe( new (class extends Minipass { emit(ev, ...data) { // let's also log events, because debugging some weird thing console.log('EMIT', ev) return super.emit(ev, ...data) } write(chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end(chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } })() ) .pipe(someDest) ``` ### subclass that defers 'end' for some reason ```js class SlowEnd extends Minipass { emit(ev, ...args) { if (ev === 'end') { console.log('going to end, hold on a sec') setTimeout(() => { console.log('ok, ready to end now') super.emit('end', ...args) }, 100) } else { return super.emit(ev, ...args) } } } ``` ### transform that creates newline-delimited JSON ```js class NDJSONEncode extends Minipass { write(obj, cb) { try { // JSON.stringify can throw, emit an error on that return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) } catch (er) { this.emit('error', er) } } end(obj, cb) { if (typeof obj === 'function') { cb = obj obj = undefined } if (obj !== undefined) { this.write(obj) } return super.end(cb) } } ``` ### transform that parses newline-delimited JSON ```js class NDJSONDecode extends Minipass { constructor (options) { // always be in object mode, as far as Minipass is concerned super({ objectMode: true }) this._jsonBuffer = '' } write (chunk, encoding, cb) { if (typeof chunk === 'string' && typeof encoding === 'string' && encoding !== 'utf8') { chunk = Buffer.from(chunk, encoding).toString() } else if (Buffer.isBuffer(chunk)) { chunk = chunk.toString() } if (typeof encoding === 'function') { cb = encoding } const jsonData = (this._jsonBuffer + chunk).split('\n') this._jsonBuffer = jsonData.pop() for (let i = 0; i < jsonData.length; i++) { try { // JSON.parse can throw, emit an error on that super.write(JSON.parse(jsonData[i])) } catch (er) { this.emit('error', er) continue } } if (cb) cb() } } ``` node_modules/ansi-styles/license 0000664 00000002125 15114743311 0013043 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/ansi-styles/package.json 0000664 00000002036 15114743311 0013765 0 ustar 00 { "name": "ansi-styles", "version": "4.3.0", "description": "ANSI escape codes for styling strings in the terminal", "license": "MIT", "repository": "chalk/ansi-styles", "funding": "https://github.com/chalk/ansi-styles?sponsor=1", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=8" }, "scripts": { "test": "xo && ava && tsd", "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "dependencies": { "color-convert": "^2.0.1" }, "devDependencies": { "@types/color-convert": "^1.9.0", "ava": "^2.3.0", "svg-term-cli": "^2.1.1", "tsd": "^0.11.0", "xo": "^0.25.3" } } node_modules/ansi-styles/readme.md 0000664 00000010347 15114743311 0013262 0 ustar 00 # ansi-styles [](https://travis-ci.org/chalk/ansi-styles) > [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. <img src="screenshot.svg" width="900"> ## Install ``` $ npm install ansi-styles ``` ## Usage ```js const style = require('ansi-styles'); console.log(`${style.green.open}Hello world!${style.green.close}`); // Color conversion between 16/256/truecolor // NOTE: If conversion goes to 16 colors or 256 colors, the original color // may be degraded to fit that color palette. This means terminals // that do not support 16 million colors will best-match the // original color. console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close); ``` ## API Each style has an `open` and `close` property. ## Styles ### Modifiers - `reset` - `bold` - `dim` - `italic` *(Not widely supported)* - `underline` - `inverse` - `hidden` - `strikethrough` *(Not widely supported)* ### Colors - `black` - `red` - `green` - `yellow` - `blue` - `magenta` - `cyan` - `white` - `blackBright` (alias: `gray`, `grey`) - `redBright` - `greenBright` - `yellowBright` - `blueBright` - `magentaBright` - `cyanBright` - `whiteBright` ### Background colors - `bgBlack` - `bgRed` - `bgGreen` - `bgYellow` - `bgBlue` - `bgMagenta` - `bgCyan` - `bgWhite` - `bgBlackBright` (alias: `bgGray`, `bgGrey`) - `bgRedBright` - `bgGreenBright` - `bgYellowBright` - `bgBlueBright` - `bgMagentaBright` - `bgCyanBright` - `bgWhiteBright` ## Advanced usage By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. - `style.modifier` - `style.color` - `style.bgColor` ###### Example ```js console.log(style.color.green.open); ``` Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. ###### Example ```js console.log(style.codes.get(36)); //=> 39 ``` ## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) `ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. The following color spaces from `color-convert` are supported: - `rgb` - `hex` - `keyword` - `hsl` - `hsv` - `hwb` - `ansi` - `ansi256` To use these, call the associated conversion function with the intended output, for example: ```js style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code ``` ## Related - [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) ## For enterprise Available as part of the Tidelift Subscription. The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) node_modules/ansi-styles/index.d.ts 0000664 00000014315 15114743311 0013403 0 ustar 00 declare type CSSColor = | 'aliceblue' | 'antiquewhite' | 'aqua' | 'aquamarine' | 'azure' | 'beige' | 'bisque' | 'black' | 'blanchedalmond' | 'blue' | 'blueviolet' | 'brown' | 'burlywood' | 'cadetblue' | 'chartreuse' | 'chocolate' | 'coral' | 'cornflowerblue' | 'cornsilk' | 'crimson' | 'cyan' | 'darkblue' | 'darkcyan' | 'darkgoldenrod' | 'darkgray' | 'darkgreen' | 'darkgrey' | 'darkkhaki' | 'darkmagenta' | 'darkolivegreen' | 'darkorange' | 'darkorchid' | 'darkred' | 'darksalmon' | 'darkseagreen' | 'darkslateblue' | 'darkslategray' | 'darkslategrey' | 'darkturquoise' | 'darkviolet' | 'deeppink' | 'deepskyblue' | 'dimgray' | 'dimgrey' | 'dodgerblue' | 'firebrick' | 'floralwhite' | 'forestgreen' | 'fuchsia' | 'gainsboro' | 'ghostwhite' | 'gold' | 'goldenrod' | 'gray' | 'green' | 'greenyellow' | 'grey' | 'honeydew' | 'hotpink' | 'indianred' | 'indigo' | 'ivory' | 'khaki' | 'lavender' | 'lavenderblush' | 'lawngreen' | 'lemonchiffon' | 'lightblue' | 'lightcoral' | 'lightcyan' | 'lightgoldenrodyellow' | 'lightgray' | 'lightgreen' | 'lightgrey' | 'lightpink' | 'lightsalmon' | 'lightseagreen' | 'lightskyblue' | 'lightslategray' | 'lightslategrey' | 'lightsteelblue' | 'lightyellow' | 'lime' | 'limegreen' | 'linen' | 'magenta' | 'maroon' | 'mediumaquamarine' | 'mediumblue' | 'mediumorchid' | 'mediumpurple' | 'mediumseagreen' | 'mediumslateblue' | 'mediumspringgreen' | 'mediumturquoise' | 'mediumvioletred' | 'midnightblue' | 'mintcream' | 'mistyrose' | 'moccasin' | 'navajowhite' | 'navy' | 'oldlace' | 'olive' | 'olivedrab' | 'orange' | 'orangered' | 'orchid' | 'palegoldenrod' | 'palegreen' | 'paleturquoise' | 'palevioletred' | 'papayawhip' | 'peachpuff' | 'peru' | 'pink' | 'plum' | 'powderblue' | 'purple' | 'rebeccapurple' | 'red' | 'rosybrown' | 'royalblue' | 'saddlebrown' | 'salmon' | 'sandybrown' | 'seagreen' | 'seashell' | 'sienna' | 'silver' | 'skyblue' | 'slateblue' | 'slategray' | 'slategrey' | 'snow' | 'springgreen' | 'steelblue' | 'tan' | 'teal' | 'thistle' | 'tomato' | 'turquoise' | 'violet' | 'wheat' | 'white' | 'whitesmoke' | 'yellow' | 'yellowgreen'; declare namespace ansiStyles { interface ColorConvert { /** The RGB color space. @param red - (`0`-`255`) @param green - (`0`-`255`) @param blue - (`0`-`255`) */ rgb(red: number, green: number, blue: number): string; /** The RGB HEX color space. @param hex - A hexadecimal string containing RGB data. */ hex(hex: string): string; /** @param keyword - A CSS color name. */ keyword(keyword: CSSColor): string; /** The HSL color space. @param hue - (`0`-`360`) @param saturation - (`0`-`100`) @param lightness - (`0`-`100`) */ hsl(hue: number, saturation: number, lightness: number): string; /** The HSV color space. @param hue - (`0`-`360`) @param saturation - (`0`-`100`) @param value - (`0`-`100`) */ hsv(hue: number, saturation: number, value: number): string; /** The HSV color space. @param hue - (`0`-`360`) @param whiteness - (`0`-`100`) @param blackness - (`0`-`100`) */ hwb(hue: number, whiteness: number, blackness: number): string; /** Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color. */ ansi(ansi: number): string; /** Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. */ ansi256(ansi: number): string; } interface CSPair { /** The ANSI terminal control sequence for starting this style. */ readonly open: string; /** The ANSI terminal control sequence for ending this style. */ readonly close: string; } interface ColorBase { readonly ansi: ColorConvert; readonly ansi256: ColorConvert; readonly ansi16m: ColorConvert; /** The ANSI terminal control sequence for ending this color. */ readonly close: string; } interface Modifier { /** Resets the current color chain. */ readonly reset: CSPair; /** Make text bold. */ readonly bold: CSPair; /** Emitting only a small amount of light. */ readonly dim: CSPair; /** Make text italic. (Not widely supported) */ readonly italic: CSPair; /** Make text underline. (Not widely supported) */ readonly underline: CSPair; /** Inverse background and foreground colors. */ readonly inverse: CSPair; /** Prints the text, but makes it invisible. */ readonly hidden: CSPair; /** Puts a horizontal line through the center of the text. (Not widely supported) */ readonly strikethrough: CSPair; } interface ForegroundColor { readonly black: CSPair; readonly red: CSPair; readonly green: CSPair; readonly yellow: CSPair; readonly blue: CSPair; readonly cyan: CSPair; readonly magenta: CSPair; readonly white: CSPair; /** Alias for `blackBright`. */ readonly gray: CSPair; /** Alias for `blackBright`. */ readonly grey: CSPair; readonly blackBright: CSPair; readonly redBright: CSPair; readonly greenBright: CSPair; readonly yellowBright: CSPair; readonly blueBright: CSPair; readonly cyanBright: CSPair; readonly magentaBright: CSPair; readonly whiteBright: CSPair; } interface BackgroundColor { readonly bgBlack: CSPair; readonly bgRed: CSPair; readonly bgGreen: CSPair; readonly bgYellow: CSPair; readonly bgBlue: CSPair; readonly bgCyan: CSPair; readonly bgMagenta: CSPair; readonly bgWhite: CSPair; /** Alias for `bgBlackBright`. */ readonly bgGray: CSPair; /** Alias for `bgBlackBright`. */ readonly bgGrey: CSPair; readonly bgBlackBright: CSPair; readonly bgRedBright: CSPair; readonly bgGreenBright: CSPair; readonly bgYellowBright: CSPair; readonly bgBlueBright: CSPair; readonly bgCyanBright: CSPair; readonly bgMagentaBright: CSPair; readonly bgWhiteBright: CSPair; } } declare const ansiStyles: { readonly modifier: ansiStyles.Modifier; readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase; readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase; readonly codes: ReadonlyMap<number, number>; } & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier; export = ansiStyles; node_modules/ansi-styles/index.js 0000664 00000010053 15114743311 0013142 0 ustar 00 'use strict'; const wrapAnsi16 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => (...args) => { const rgb = fn(...args); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; const setLazyProperty = (object, property, get) => { Object.defineProperty(object, property, { get: () => { const value = get(); Object.defineProperty(object, property, { value, enumerable: true, configurable: true }); return value; }, enumerable: true, configurable: true }); }; /** @type {typeof import('color-convert')} */ let colorConvert; const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { if (colorConvert === undefined) { colorConvert = require('color-convert'); } const offset = isBackground ? 10 : 0; const styles = {}; for (const [sourceSpace, suite] of Object.entries(colorConvert)) { const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; if (sourceSpace === targetSpace) { styles[name] = wrap(identity, offset); } else if (typeof suite === 'object') { styles[name] = wrap(suite[targetSpace], offset); } } return styles; }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); node_modules/merge2/package.json 0000664 00000001476 15114743311 0012702 0 ustar 00 { "name": "merge2", "description": "Merge multiple streams into one stream in sequence or parallel.", "authors": [ "Yan Qing <admin@zensh.com>" ], "license": "MIT", "version": "1.4.1", "main": "./index.js", "repository": { "type": "git", "url": "git@github.com:teambition/merge2.git" }, "homepage": "https://github.com/teambition/merge2", "keywords": [ "merge2", "multiple", "sequence", "parallel", "merge", "stream", "merge stream", "sync" ], "engines": { "node": ">= 8" }, "dependencies": {}, "devDependencies": { "standard": "^14.3.4", "through2": "^3.0.1", "thunks": "^4.9.6", "tman": "^1.10.0", "to-through": "^2.0.0" }, "scripts": { "test": "standard && tman" }, "files": [ "README.md", "index.js" ] } node_modules/merge2/LICENSE 0000664 00000002072 15114743311 0011412 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2020 Teambition Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/merge2/index.js 0000664 00000006251 15114743311 0012055 0 ustar 00 'use strict' /* * merge2 * https://github.com/teambition/merge2 * * Copyright (c) 2014-2020 Teambition * Licensed under the MIT license. */ const Stream = require('stream') const PassThrough = Stream.PassThrough const slice = Array.prototype.slice module.exports = merge2 function merge2 () { const streamsQueue = [] const args = slice.call(arguments) let merging = false let options = args[args.length - 1] if (options && !Array.isArray(options) && options.pipe == null) { args.pop() } else { options = {} } const doEnd = options.end !== false const doPipeError = options.pipeError === true if (options.objectMode == null) { options.objectMode = true } if (options.highWaterMark == null) { options.highWaterMark = 64 * 1024 } const mergedStream = PassThrough(options) function addStream () { for (let i = 0, len = arguments.length; i < len; i++) { streamsQueue.push(pauseStreams(arguments[i], options)) } mergeStream() return this } function mergeStream () { if (merging) { return } merging = true let streams = streamsQueue.shift() if (!streams) { process.nextTick(endStream) return } if (!Array.isArray(streams)) { streams = [streams] } let pipesCount = streams.length + 1 function next () { if (--pipesCount > 0) { return } merging = false mergeStream() } function pipe (stream) { function onend () { stream.removeListener('merge2UnpipeEnd', onend) stream.removeListener('end', onend) if (doPipeError) { stream.removeListener('error', onerror) } next() } function onerror (err) { mergedStream.emit('error', err) } // skip ended stream if (stream._readableState.endEmitted) { return next() } stream.on('merge2UnpipeEnd', onend) stream.on('end', onend) if (doPipeError) { stream.on('error', onerror) } stream.pipe(mergedStream, { end: false }) // compatible for old stream stream.resume() } for (let i = 0; i < streams.length; i++) { pipe(streams[i]) } next() } function endStream () { merging = false // emit 'queueDrain' when all streams merged. mergedStream.emit('queueDrain') if (doEnd) { mergedStream.end() } } mergedStream.setMaxListeners(0) mergedStream.add = addStream mergedStream.on('unpipe', function (stream) { stream.emit('merge2UnpipeEnd') }) if (args.length) { addStream.apply(null, args) } return mergedStream } // check and pause streams for pipe. function pauseStreams (streams, options) { if (!Array.isArray(streams)) { // Backwards-compat with old-style streams if (!streams._readableState && streams.pipe) { streams = streams.pipe(PassThrough(options)) } if (!streams._readableState || !streams.pause || !streams.pipe) { throw new Error('Only readable stream can be merged.') } streams.pause() } else { for (let i = 0, len = streams.length; i < len; i++) { streams[i] = pauseStreams(streams[i], options) } } return streams } node_modules/merge2/README.md 0000664 00000007240 15114743311 0011666 0 ustar 00 # merge2 Merge multiple streams into one stream in sequence or parallel. [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Downloads][downloads-image]][downloads-url] ## Install Install with [npm](https://npmjs.org/package/merge2) ```sh npm install merge2 ``` ## Usage ```js const gulp = require('gulp') const merge2 = require('merge2') const concat = require('gulp-concat') const minifyHtml = require('gulp-minify-html') const ngtemplate = require('gulp-ngtemplate') gulp.task('app-js', function () { return merge2( gulp.src('static/src/tpl/*.html') .pipe(minifyHtml({empty: true})) .pipe(ngtemplate({ module: 'genTemplates', standalone: true }) ), gulp.src([ 'static/src/js/app.js', 'static/src/js/locale_zh-cn.js', 'static/src/js/router.js', 'static/src/js/tools.js', 'static/src/js/services.js', 'static/src/js/filters.js', 'static/src/js/directives.js', 'static/src/js/controllers.js' ]) ) .pipe(concat('app.js')) .pipe(gulp.dest('static/dist/js/')) }) ``` ```js const stream = merge2([stream1, stream2], stream3, {end: false}) //... stream.add(stream4, stream5) //.. stream.end() ``` ```js // equal to merge2([stream1, stream2], stream3) const stream = merge2() stream.add([stream1, stream2]) stream.add(stream3) ``` ```js // merge order: // 1. merge `stream1`; // 2. merge `stream2` and `stream3` in parallel after `stream1` merged; // 3. merge 'stream4' after `stream2` and `stream3` merged; const stream = merge2(stream1, [stream2, stream3], stream4) // merge order: // 1. merge `stream5` and `stream6` in parallel after `stream4` merged; // 2. merge 'stream7' after `stream5` and `stream6` merged; stream.add([stream5, stream6], stream7) ``` ```js // nest merge // equal to merge2(stream1, stream2, stream6, stream3, [stream4, stream5]); const streamA = merge2(stream1, stream2) const streamB = merge2(stream3, [stream4, stream5]) const stream = merge2(streamA, streamB) streamA.add(stream6) ``` ## API ```js const merge2 = require('merge2') ``` ### merge2() ### merge2(options) ### merge2(stream1, stream2, ..., streamN) ### merge2(stream1, stream2, ..., streamN, options) ### merge2(stream1, [stream2, stream3, ...], streamN, options) return a duplex stream (mergedStream). streams in array will be merged in parallel. ### mergedStream.add(stream) ### mergedStream.add(stream1, [stream2, stream3, ...], ...) return the mergedStream. ### mergedStream.on('queueDrain', function() {}) It will emit 'queueDrain' when all streams merged. If you set `end === false` in options, this event give you a notice that should add more streams to merge or end the mergedStream. #### stream *option* Type: `Readable` or `Duplex` or `Transform` stream. #### options *option* Type: `Object`. * **end** - `Boolean` - if `end === false` then mergedStream will not be auto ended, you should end by yourself. **Default:** `undefined` * **pipeError** - `Boolean` - if `pipeError === true` then mergedStream will emit `error` event from source streams. **Default:** `undefined` * **objectMode** - `Boolean` . **Default:** `true` `objectMode` and other options(`highWaterMark`, `defaultEncoding` ...) is same as Node.js `Stream`. ## License MIT © [Teambition](https://www.teambition.com) [npm-url]: https://npmjs.org/package/merge2 [npm-image]: http://img.shields.io/npm/v/merge2.svg [travis-url]: https://travis-ci.org/teambition/merge2 [travis-image]: http://img.shields.io/travis/teambition/merge2.svg [downloads-url]: https://npmjs.org/package/merge2 [downloads-image]: http://img.shields.io/npm/dm/merge2.svg?style=flat-square node_modules/unicorn-magic/license 0000664 00000002135 15114743311 0013324 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/unicorn-magic/package.json 0000664 00000001574 15114743311 0014253 0 ustar 00 { "name": "unicorn-magic", "version": "0.1.0", "description": "Some useful utilities I often need", "license": "MIT", "repository": "sindresorhus/unicorn-magic", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": { "types": "./index.d.ts", "node": "./node.js", "default": "./default.js" }, "sideEffects": false, "engines": { "node": ">=18" }, "scripts": { "test": "xo && ava && tsc index.d.ts" }, "files": [ "node.js", "default.js", "index.d.ts" ], "keywords": [ "utilities", "util", "extras", "url", "path", "delay", "wait", "settimeout", "sleep" ], "devDependencies": { "ava": "^5.3.1", "in-range": "^3.0.0", "time-span": "^5.1.0", "typescript": "^5.2.2", "xo": "^0.56.0" } } node_modules/unicorn-magic/readme.md 0000664 00000000442 15114743311 0013535 0 ustar 00 # unicorn-magic > Some useful utilities I often need *I'm not accepting requests.* ## Install ```sh npm install unicorn-magic ``` ## Usage ```js import {delay} from 'unicorn-magic'; await delay({seconds: 1}); console.log('1 second later'); ``` ## API See [the types](index.d.ts). node_modules/unicorn-magic/index.d.ts 0000664 00000001104 15114743311 0013653 0 ustar 00 /** Delay the promise for the given duration. @example ``` import {delay} from 'unicorn-magic'; await delay({seconds: 1}); console.log('1 second later'); ``` */ export function delay(duration: {seconds: number} | {milliseconds: number}): Promise<void>; /** Convert a `URL` or path to a path. **Not available in browsers.** @example ``` import path from 'node:path'; import {toPath} from 'unicorn-magic'; // `cwd` can be `URL` or a path string. const getUnicornPath = cwd => path.join(toPath(cwd), 'unicorn'); ``` */ export function toPath(urlOrPath: URL | string): string; node_modules/unicorn-magic/default.js 0000664 00000000604 15114743311 0013740 0 ustar 00 export async function delay({seconds, milliseconds} = {}) { let duration; if (typeof seconds === 'number') { duration = seconds * 1000; } else if (typeof milliseconds === 'number') { duration = milliseconds; } else { throw new TypeError('Expected an object with either `seconds` or `milliseconds`.'); } return new Promise(resolve => { setTimeout(resolve, duration); }); } node_modules/unicorn-magic/node.js 0000664 00000000267 15114743311 0013246 0 ustar 00 import {fileURLToPath} from 'node:url'; export function toPath(urlOrPath) { return urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath; } export * from './default.js'; node_modules/mkdirp/package.json 0000664 00000001444 15114743311 0013002 0 ustar 00 { "name": "mkdirp", "description": "Recursively mkdir, like `mkdir -p`", "version": "1.0.4", "main": "index.js", "keywords": [ "mkdir", "directory", "make dir", "make", "dir", "recursive", "native" ], "repository": { "type": "git", "url": "https://github.com/isaacs/node-mkdirp.git" }, "scripts": { "test": "tap", "snap": "tap", "preversion": "npm test", "postversion": "npm publish", "postpublish": "git push origin --follow-tags" }, "tap": { "check-coverage": true, "coverage-map": "map.js" }, "devDependencies": { "require-inject": "^1.4.4", "tap": "^14.10.7" }, "bin": "bin/cmd.js", "license": "MIT", "engines": { "node": ">=10" }, "files": [ "bin", "lib", "index.js" ] } node_modules/mkdirp/LICENSE 0000664 00000002216 15114743311 0011517 0 ustar 00 Copyright James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me) This project is free software released under the MIT license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/mkdirp/readme.markdown 0000664 00000020473 15114743311 0013520 0 ustar 00 # mkdirp Like `mkdir -p`, but in Node.js! Now with a modern API and no\* bugs! <small>\* may contain some bugs</small> # example ## pow.js ```js const mkdirp = require('mkdirp') // return value is a Promise resolving to the first directory created mkdirp('/tmp/foo/bar/baz').then(made => console.log(`made directories, starting with ${made}`)) ``` Output (where `/tmp/foo` already exists) ``` made directories, starting with /tmp/foo/bar ``` Or, if you don't have time to wait around for promises: ```js const mkdirp = require('mkdirp') // return value is the first directory created const made = mkdirp.sync('/tmp/foo/bar/baz') console.log(`made directories, starting with ${made}`) ``` And now /tmp/foo/bar/baz exists, huzzah! # methods ```js const mkdirp = require('mkdirp') ``` ## mkdirp(dir, [opts]) -> Promise<String | undefined> Create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a string or number, it will be treated as the `opts.mode`. If `opts.mode` isn't specified, it defaults to `0o777 & (~process.umask())`. Promise resolves to first directory `made` that had to be created, or `undefined` if everything already exists. Promise rejects if any errors are encountered. Note that, in the case of promise rejection, some directories _may_ have been created, as recursive directory creation is not an atomic operation. You can optionally pass in an alternate `fs` implementation by passing in `opts.fs`. Your implementation should have `opts.fs.mkdir(path, opts, cb)` and `opts.fs.stat(path, cb)`. You can also override just one or the other of `mkdir` and `stat` by passing in `opts.stat` or `opts.mkdir`, or providing an `fs` option that only overrides one of these. ## mkdirp.sync(dir, opts) -> String|null Synchronously create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a string or number, it will be treated as the `opts.mode`. If `opts.mode` isn't specified, it defaults to `0o777 & (~process.umask())`. Returns the first directory that had to be created, or undefined if everything already exists. You can optionally pass in an alternate `fs` implementation by passing in `opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and `opts.fs.statSync(path)`. You can also override just one or the other of `mkdirSync` and `statSync` by passing in `opts.statSync` or `opts.mkdirSync`, or providing an `fs` option that only overrides one of these. ## mkdirp.manual, mkdirp.manualSync Use the manual implementation (not the native one). This is the default when the native implementation is not available or the stat/mkdir implementation is overridden. ## mkdirp.native, mkdirp.nativeSync Use the native implementation (not the manual one). This is the default when the native implementation is available and stat/mkdir are not overridden. # implementation On Node.js v10.12.0 and above, use the native `fs.mkdir(p, {recursive:true})` option, unless `fs.mkdir`/`fs.mkdirSync` has been overridden by an option. ## native implementation - If the path is a root directory, then pass it to the underlying implementation and return the result/error. (In this case, it'll either succeed or fail, but we aren't actually creating any dirs.) - Walk up the path statting each directory, to find the first path that will be created, `made`. - Call `fs.mkdir(path, { recursive: true })` (or `fs.mkdirSync`) - If error, raise it to the caller. - Return `made`. ## manual implementation - Call underlying `fs.mkdir` implementation, with `recursive: false` - If error: - If path is a root directory, raise to the caller and do not handle it - If ENOENT, mkdirp parent dir, store result as `made` - stat(path) - If error, raise original `mkdir` error - If directory, return `made` - Else, raise original `mkdir` error - else - return `undefined` if a root dir, or `made` if set, or `path` ## windows vs unix caveat On Windows file systems, attempts to create a root directory (ie, a drive letter or root UNC path) will fail. If the root directory exists, then it will fail with `EPERM`. If the root directory does not exist, then it will fail with `ENOENT`. On posix file systems, attempts to create a root directory (in recursive mode) will succeed silently, as it is treated like just another directory that already exists. (In non-recursive mode, of course, it fails with `EEXIST`.) In order to preserve this system-specific behavior (and because it's not as if we can create the parent of a root directory anyway), attempts to create a root directory are passed directly to the `fs` implementation, and any errors encountered are not handled. ## native error caveat The native implementation (as of at least Node.js v13.4.0) does not provide appropriate errors in some cases (see [nodejs/node#31481](https://github.com/nodejs/node/issues/31481) and [nodejs/node#28015](https://github.com/nodejs/node/issues/28015)). In order to work around this issue, the native implementation will fall back to the manual implementation if an `ENOENT` error is encountered. # choosing a recursive mkdir implementation There are a few to choose from! Use the one that suits your needs best :D ## use `fs.mkdir(path, {recursive: true}, cb)` if: - You wish to optimize performance even at the expense of other factors. - You don't need to know the first dir created. - You are ok with getting `ENOENT` as the error when some other problem is the actual cause. - You can limit your platforms to Node.js v10.12 and above. - You're ok with using callbacks instead of promises. - You don't need/want a CLI. - You don't need to override the `fs` methods in use. ## use this module (mkdirp 1.x) if: - You need to know the first directory that was created. - You wish to use the native implementation if available, but fall back when it's not. - You prefer promise-returning APIs to callback-taking APIs. - You want more useful error messages than the native recursive mkdir provides (at least as of Node.js v13.4), and are ok with re-trying on `ENOENT` to achieve this. - You need (or at least, are ok with) a CLI. - You need to override the `fs` methods in use. ## use [`make-dir`](http://npm.im/make-dir) if: - You do not need to know the first dir created (and wish to save a few `stat` calls when using the native implementation for this reason). - You wish to use the native implementation if available, but fall back when it's not. - You prefer promise-returning APIs to callback-taking APIs. - You are ok with occasionally getting `ENOENT` errors for failures that are actually related to something other than a missing file system entry. - You don't need/want a CLI. - You need to override the `fs` methods in use. ## use mkdirp 0.x if: - You need to know the first directory that was created. - You need (or at least, are ok with) a CLI. - You need to override the `fs` methods in use. - You're ok with using callbacks instead of promises. - You are not running on Windows, where the root-level ENOENT errors can lead to infinite regress. - You think vinyl just sounds warmer and richer for some weird reason. - You are supporting truly ancient Node.js versions, before even the advent of a `Promise` language primitive. (Please don't. You deserve better.) # cli This package also ships with a `mkdirp` command. ``` $ mkdirp -h usage: mkdirp [DIR1,DIR2..] {OPTIONS} Create each supplied directory including any necessary parent directories that don't yet exist. If the directory already exists, do nothing. OPTIONS are: -m<mode> If a directory needs to be created, set the mode as an octal --mode=<mode> permission string. -v --version Print the mkdirp version number -h --help Print this helpful banner -p --print Print the first directories created for each path provided --manual Use manual implementation, even if native is available ``` # install With [npm](http://npmjs.org) do: ``` npm install mkdirp ``` to get the library locally, or ``` npm install -g mkdirp ``` to get the command everywhere, or ``` npx mkdirp ... ``` to run the command without installing it globally. # platform support This module works on node v8, but only v10 and above are officially supported, as Node v8 reached its LTS end of life 2020-01-01, which is in the past, as of this writing. # license MIT node_modules/mkdirp/lib/find-made.js 0000664 00000001373 15114743311 0013445 0 ustar 00 const {dirname} = require('path') const findMade = (opts, parent, path = undefined) => { // we never want the 'made' return value to be a root directory if (path === parent) return Promise.resolve() return opts.statAsync(parent).then( st => st.isDirectory() ? path : undefined, // will fail later er => er.code === 'ENOENT' ? findMade(opts, dirname(parent), parent) : undefined ) } const findMadeSync = (opts, parent, path = undefined) => { if (path === parent) return undefined try { return opts.statSync(parent).isDirectory() ? path : undefined } catch (er) { return er.code === 'ENOENT' ? findMadeSync(opts, dirname(parent), parent) : undefined } } module.exports = {findMade, findMadeSync} node_modules/mkdirp/lib/use-native.js 0000664 00000000700 15114743311 0013672 0 ustar 00 const fs = require('fs') const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version const versArr = version.replace(/^v/, '').split('.') const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync module.exports = {useNative, useNativeSync} node_modules/mkdirp/lib/opts-arg.js 0000664 00000001420 15114743311 0013346 0 ustar 00 const { promisify } = require('util') const fs = require('fs') const optsArg = opts => { if (!opts) opts = { mode: 0o777, fs } else if (typeof opts === 'object') opts = { mode: 0o777, fs, ...opts } else if (typeof opts === 'number') opts = { mode: opts, fs } else if (typeof opts === 'string') opts = { mode: parseInt(opts, 8), fs } else throw new TypeError('invalid options argument') opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir opts.mkdirAsync = promisify(opts.mkdir) opts.stat = opts.stat || opts.fs.stat || fs.stat opts.statAsync = promisify(opts.stat) opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync return opts } module.exports = optsArg node_modules/mkdirp/lib/path-arg.js 0000664 00000001332 15114743311 0013317 0 ustar 00 const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform const { resolve, parse } = require('path') const pathArg = path => { if (/\0/.test(path)) { // simulate same failure that node raises throw Object.assign( new TypeError('path must be a string without null bytes'), { path, code: 'ERR_INVALID_ARG_VALUE', } ) } path = resolve(path) if (platform === 'win32') { const badWinChars = /[*|"<>?:]/ const {root} = parse(path) if (badWinChars.test(path.substr(root.length))) { throw Object.assign(new Error('Illegal characters in path.'), { path, code: 'EINVAL', }) } } return path } module.exports = pathArg node_modules/mkdirp/lib/mkdirp-native.js 0000664 00000001711 15114743311 0014367 0 ustar 00 const {dirname} = require('path') const {findMade, findMadeSync} = require('./find-made.js') const {mkdirpManual, mkdirpManualSync} = require('./mkdirp-manual.js') const mkdirpNative = (path, opts) => { opts.recursive = true const parent = dirname(path) if (parent === path) return opts.mkdirAsync(path, opts) return findMade(opts, path).then(made => opts.mkdirAsync(path, opts).then(() => made) .catch(er => { if (er.code === 'ENOENT') return mkdirpManual(path, opts) else throw er })) } const mkdirpNativeSync = (path, opts) => { opts.recursive = true const parent = dirname(path) if (parent === path) return opts.mkdirSync(path, opts) const made = findMadeSync(opts, path) try { opts.mkdirSync(path, opts) return made } catch (er) { if (er.code === 'ENOENT') return mkdirpManualSync(path, opts) else throw er } } module.exports = {mkdirpNative, mkdirpNativeSync} node_modules/mkdirp/lib/mkdirp-manual.js 0000664 00000003112 15114743311 0014353 0 ustar 00 const {dirname} = require('path') const mkdirpManual = (path, opts, made) => { opts.recursive = false const parent = dirname(path) if (parent === path) { return opts.mkdirAsync(path, opts).catch(er => { // swallowed by recursive implementation on posix systems // any other error is a failure if (er.code !== 'EISDIR') throw er }) } return opts.mkdirAsync(path, opts).then(() => made || path, er => { if (er.code === 'ENOENT') return mkdirpManual(parent, opts) .then(made => mkdirpManual(path, opts, made)) if (er.code !== 'EEXIST' && er.code !== 'EROFS') throw er return opts.statAsync(path).then(st => { if (st.isDirectory()) return made else throw er }, () => { throw er }) }) } const mkdirpManualSync = (path, opts, made) => { const parent = dirname(path) opts.recursive = false if (parent === path) { try { return opts.mkdirSync(path, opts) } catch (er) { // swallowed by recursive implementation on posix systems // any other error is a failure if (er.code !== 'EISDIR') throw er else return } } try { opts.mkdirSync(path, opts) return made || path } catch (er) { if (er.code === 'ENOENT') return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) if (er.code !== 'EEXIST' && er.code !== 'EROFS') throw er try { if (!opts.statSync(path).isDirectory()) throw er } catch (_) { throw er } } } module.exports = {mkdirpManual, mkdirpManualSync} node_modules/mkdirp/index.js 0000664 00000002005 15114743311 0012153 0 ustar 00 const optsArg = require('./lib/opts-arg.js') const pathArg = require('./lib/path-arg.js') const {mkdirpNative, mkdirpNativeSync} = require('./lib/mkdirp-native.js') const {mkdirpManual, mkdirpManualSync} = require('./lib/mkdirp-manual.js') const {useNative, useNativeSync} = require('./lib/use-native.js') const mkdirp = (path, opts) => { path = pathArg(path) opts = optsArg(opts) return useNative(opts) ? mkdirpNative(path, opts) : mkdirpManual(path, opts) } const mkdirpSync = (path, opts) => { path = pathArg(path) opts = optsArg(opts) return useNativeSync(opts) ? mkdirpNativeSync(path, opts) : mkdirpManualSync(path, opts) } mkdirp.sync = mkdirpSync mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) module.exports = mkdirp node_modules/mkdirp/CHANGELOG.md 0000664 00000000700 15114743311 0012317 0 ustar 00 # Changers Lorgs! ## 1.0 Full rewrite. Essentially a brand new module. - Return a promise instead of taking a callback. - Use native `fs.mkdir(path, { recursive: true })` when available. - Drop support for outdated Node.js versions. (Technically still works on Node.js v8, but only 10 and above are officially supported.) ## 0.x Original and most widely used recursive directory creation implementation in JavaScript, dating back to 2010. node_modules/picomatch/package.json 0000664 00000003570 15114743311 0013465 0 ustar 00 { "name": "picomatch", "description": "Blazing fast and accurate glob matcher written in JavaScript, with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.", "version": "2.3.1", "homepage": "https://github.com/micromatch/picomatch", "author": "Jon Schlinkert (https://github.com/jonschlinkert)", "funding": "https://github.com/sponsors/jonschlinkert", "repository": "micromatch/picomatch", "bugs": { "url": "https://github.com/micromatch/picomatch/issues" }, "license": "MIT", "files": [ "index.js", "lib" ], "main": "index.js", "engines": { "node": ">=8.6" }, "scripts": { "lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .", "mocha": "mocha --reporter dot", "test": "npm run lint && npm run mocha", "test:ci": "npm run test:cover", "test:cover": "nyc npm run mocha" }, "devDependencies": { "eslint": "^6.8.0", "fill-range": "^7.0.1", "gulp-format-md": "^2.0.0", "mocha": "^6.2.2", "nyc": "^15.0.0", "time-require": "github:jonschlinkert/time-require" }, "keywords": [ "glob", "match", "picomatch" ], "nyc": { "reporter": [ "html", "lcov", "text-summary" ] }, "verb": { "toc": { "render": true, "method": "preWrite", "maxdepth": 3 }, "layout": "empty", "tasks": [ "readme" ], "plugins": [ "gulp-format-md" ], "lint": { "reflinks": true }, "related": { "list": [ "braces", "micromatch" ] }, "reflinks": [ "braces", "expand-brackets", "extglob", "fill-range", "micromatch", "minimatch", "nanomatch", "picomatch" ] } } node_modules/picomatch/LICENSE 0000664 00000002103 15114743311 0012173 0 ustar 00 The MIT License (MIT) Copyright (c) 2017-present, Jon Schlinkert. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/picomatch/lib/utils.js 0000664 00000003535 15114743311 0013444 0 ustar 00 'use strict'; const path = require('path'); const win32 = process.platform === 'win32'; const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require('./constants'); exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); exports.removeBackslashes = str => { return str.replace(REGEX_REMOVE_BACKSLASH, match => { return match === '\\' ? '' : match; }); }; exports.supportsLookbehinds = () => { const segs = process.version.slice(1).split('.').map(Number); if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { return true; } return false; }; exports.isWindows = options => { if (options && typeof options.windows === 'boolean') { return options.windows; } return win32 === true || path.sep === '\\'; }; exports.escapeLast = (input, char, lastIdx) => { const idx = input.lastIndexOf(char, lastIdx); if (idx === -1) return input; if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); return `${input.slice(0, idx)}\\${input.slice(idx)}`; }; exports.removePrefix = (input, state = {}) => { let output = input; if (output.startsWith('./')) { output = output.slice(2); state.prefix = './'; } return output; }; exports.wrapOutput = (input, state = {}, options = {}) => { const prepend = options.contains ? '' : '^'; const append = options.contains ? '' : '$'; let output = `${prepend}(?:${input})${append}`; if (state.negated === true) { output = `(?:^(?!${output}).*$)`; } return output; }; node_modules/picomatch/lib/picomatch.js 0000664 00000023344 15114743311 0014253 0 ustar 00 'use strict'; const path = require('path'); const scan = require('./scan'); const parse = require('./parse'); const utils = require('./utils'); const constants = require('./constants'); const isObject = val => val && typeof val === 'object' && !Array.isArray(val); /** * Creates a matcher function from one or more glob patterns. The * returned function takes a string to match as its first argument, * and returns true if the string is a match. The returned matcher * function also takes a boolean as the second argument that, when true, * returns an object with additional information. * * ```js * const picomatch = require('picomatch'); * // picomatch(glob[, options]); * * const isMatch = picomatch('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @name picomatch * @param {String|Array} `globs` One or more glob patterns. * @param {Object=} `options` * @return {Function=} Returns a matcher function. * @api public */ const picomatch = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map(input => picomatch(input, options, returnState)); const arrayMatcher = str => { for (const isMatch of fns) { const state = isMatch(str); if (state) return state; } return false; }; return arrayMatcher; } const isState = isObject(glob) && glob.tokens && glob.input; if (glob === '' || (typeof glob !== 'string' && !isState)) { throw new TypeError('Expected pattern to be a non-empty string'); } const opts = options || {}; const posix = utils.isWindows(options); const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true); const state = regex.state; delete regex.state; let isIgnored = () => false; if (opts.ignore) { const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); const result = { glob, state, regex, posix, input, output, match, isMatch }; if (typeof opts.onResult === 'function') { opts.onResult(result); } if (isMatch === false) { result.isMatch = false; return returnObject ? result : false; } if (isIgnored(input)) { if (typeof opts.onIgnore === 'function') { opts.onIgnore(result); } result.isMatch = false; return returnObject ? result : false; } if (typeof opts.onMatch === 'function') { opts.onMatch(result); } return returnObject ? result : true; }; if (returnState) { matcher.state = state; } return matcher; }; /** * Test `input` with the given `regex`. This is used by the main * `picomatch()` function to test the input string. * * ```js * const picomatch = require('picomatch'); * // picomatch.test(input, regex[, options]); * * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } * ``` * @param {String} `input` String to test. * @param {RegExp} `regex` * @return {Object} Returns an object with matching info. * @api public */ picomatch.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected input to be a string'); } if (input === '') { return { isMatch: false, output: '' }; } const opts = options || {}; const format = opts.format || (posix ? utils.toPosixSlashes : null); let match = input === glob; let output = (match && format) ? format(input) : input; if (match === false) { output = format ? format(input) : input; match = output === glob; } if (match === false || opts.capture === true) { if (opts.matchBase === true || opts.basename === true) { match = picomatch.matchBase(input, regex, options, posix); } else { match = regex.exec(output); } } return { isMatch: Boolean(match), match, output }; }; /** * Match the basename of a filepath. * * ```js * const picomatch = require('picomatch'); * // picomatch.matchBase(input, glob[, options]); * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true * ``` * @param {String} `input` String to test. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). * @return {Boolean} * @api public */ picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); return regex.test(path.basename(input)); }; /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const picomatch = require('picomatch'); * // picomatch.isMatch(string, patterns[, options]); * * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String|Array} str The string to test. * @param {String|Array} patterns One or more glob patterns to use for matching. * @param {Object} [options] See available [options](#options). * @return {Boolean} Returns true if any patterns match `str` * @api public */ picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const picomatch = require('picomatch'); * const result = picomatch.parse(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as a regex source string. * @api public */ picomatch.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); return parse(pattern, { ...options, fastpaths: false }); }; /** * Scan a glob pattern to separate the pattern into segments. * * ```js * const picomatch = require('picomatch'); * // picomatch.scan(input[, options]); * * const result = picomatch.scan('!./foo/*.js'); * console.log(result); * { prefix: '!./', * input: '!./foo/*.js', * start: 3, * base: 'foo', * glob: '*.js', * isBrace: false, * isBracket: false, * isGlob: true, * isExtglob: false, * isGlobstar: false, * negated: true } * ``` * @param {String} `input` Glob pattern to scan. * @param {Object} `options` * @return {Object} Returns an object with * @api public */ picomatch.scan = (input, options) => scan(input, options); /** * Compile a regular expression from the `state` object returned by the * [parse()](#parse) method. * * @param {Object} `state` * @param {Object} `options` * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. * @return {RegExp} * @api public */ picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { if (returnOutput === true) { return state.output; } const opts = options || {}; const prepend = opts.contains ? '' : '^'; const append = opts.contains ? '' : '$'; let source = `${prepend}(?:${state.output})${append}`; if (state && state.negated === true) { source = `^(?!${source}).*$`; } const regex = picomatch.toRegex(source, options); if (returnState === true) { regex.state = state; } return regex; }; /** * Create a regular expression from a parsed glob pattern. * * ```js * const picomatch = require('picomatch'); * const state = picomatch.parse('*.js'); * // picomatch.compileRe(state[, options]); * * console.log(picomatch.compileRe(state)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `state` The object returned from the `.parse` method. * @param {Object} `options` * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. * @return {RegExp} Returns a regex created from the given pattern. * @api public */ picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { if (!input || typeof input !== 'string') { throw new TypeError('Expected a non-empty string'); } let parsed = { negated: false, fastpaths: true }; if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { parsed.output = parse.fastpaths(input, options); } if (!parsed.output) { parsed = parse(input, options); } return picomatch.compileRe(parsed, options, returnOutput, returnState); }; /** * Create a regular expression from the given regex source string. * * ```js * const picomatch = require('picomatch'); * // picomatch.toRegex(source[, options]); * * const { output } = picomatch.parse('*.js'); * console.log(picomatch.toRegex(output)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `source` Regular expression source string. * @param {Object} `options` * @return {RegExp} * @api public */ picomatch.toRegex = (source, options) => { try { const opts = options || {}; return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); } catch (err) { if (options && options.debug === true) throw err; return /$^/; } }; /** * Picomatch constants. * @return {Object} */ picomatch.constants = constants; /** * Expose "picomatch" */ module.exports = picomatch; node_modules/picomatch/lib/scan.js 0000664 00000021745 15114743311 0013233 0 ustar 00 'use strict'; const utils = require('./utils'); const { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_RIGHT_SQUARE_BRACKET /* ] */ } = require('./constants'); const isPathSeparator = code => { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; }; const depth = token => { if (token.isPrefix !== true) { token.depth = token.isGlobstar ? Infinity : 1; } }; /** * Quickly scans a glob pattern and returns an object with a handful of * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). * * ```js * const pm = require('picomatch'); * console.log(pm.scan('foo/bar/*.js')); * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } * ``` * @param {String} `str` * @param {Object} `options` * @return {Object} Returns an object with tokens and regex source string. * @api public */ const scan = (input, options) => { const opts = options || {}; const length = input.length - 1; const scanToEnd = opts.parts === true || opts.scanToEnd === true; const slashes = []; const tokens = []; const parts = []; let str = input; let index = -1; let start = 0; let lastIndex = 0; let isBrace = false; let isBracket = false; let isGlob = false; let isExtglob = false; let isGlobstar = false; let braceEscaped = false; let backslashes = false; let negated = false; let negatedExtglob = false; let finished = false; let braces = 0; let prev; let code; let token = { value: '', depth: 0, isGlob: false }; const eos = () => index >= length; const peek = () => str.charCodeAt(index + 1); const advance = () => { prev = code; return str.charCodeAt(++index); }; while (index < length) { code = advance(); let next; if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE) { braces--; if (braces === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH) { slashes.push(index); tokens.push(token); token = { value: '', depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT && index === (start + 1)) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; isExtglob = token.isExtglob = true; finished = true; if (code === CHAR_EXCLAMATION_MARK && index === start) { negatedExtglob = true; } if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { isGlob = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK) { if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK) { isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET) { isBracket = token.isBracket = true; isGlob = token.isGlob = true; finished = true; break; } } if (scanToEnd === true) { continue; } break; } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { finished = true; break; } } continue; } break; } if (isGlob === true) { finished = true; if (scanToEnd === true) { continue; } break; } } if (opts.noext === true) { isExtglob = false; isGlob = false; } let base = str; let prefix = ''; let glob = ''; if (start > 0) { prefix = str.slice(0, start); str = str.slice(start); lastIndex -= start; } if (base && isGlob === true && lastIndex > 0) { base = str.slice(0, lastIndex); glob = str.slice(lastIndex); } else if (isGlob === true) { base = ''; glob = str; } else { base = str; } if (base && base !== '' && base !== '/' && base !== str) { if (isPathSeparator(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob) glob = utils.removeBackslashes(glob); if (base && backslashes === true) { base = utils.removeBackslashes(base); } } const state = { prefix, input, start, base, glob, isBrace, isBracket, isGlob, isExtglob, isGlobstar, negated, negatedExtglob }; if (opts.tokens === true) { state.maxDepth = 0; if (!isPathSeparator(code)) { tokens.push(token); } state.tokens = tokens; } if (opts.parts === true || opts.tokens === true) { let prevIndex; for (let idx = 0; idx < slashes.length; idx++) { const n = prevIndex ? prevIndex + 1 : start; const i = slashes[idx]; const value = input.slice(n, i); if (opts.tokens) { if (idx === 0 && start !== 0) { tokens[idx].isPrefix = true; tokens[idx].value = prefix; } else { tokens[idx].value = value; } depth(tokens[idx]); state.maxDepth += tokens[idx].depth; } if (idx !== 0 || value !== '') { parts.push(value); } prevIndex = i; } if (prevIndex && prevIndex + 1 < input.length) { const value = input.slice(prevIndex + 1); parts.push(value); if (opts.tokens) { tokens[tokens.length - 1].value = value; depth(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; module.exports = scan; node_modules/picomatch/lib/parse.js 0000664 00000066163 15114743311 0013424 0 ustar 00 'use strict'; const constants = require('./constants'); const utils = require('./utils'); /** * Constants */ const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants; /** * Helpers */ const expandRange = (args, options) => { if (typeof options.expandRange === 'function') { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join('-')}]`; try { /* eslint-disable-next-line no-new */ new RegExp(value); } catch (ex) { return args.map(v => utils.escapeRegex(v)).join('..'); } return value; }; /** * Create the message for a syntax error */ const syntaxError = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; /** * Parse the given input string. * @param {String} input * @param {Object} options * @return {Object} */ const parse = (input, options) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } input = REPLACEMENTS[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: 'bos', value: '', output: opts.prepend || '' }; const tokens = [bos]; const capture = opts.capture ? '' : '?:'; const win32 = utils.isWindows(options); // create constants based on platform, for windows or posix const PLATFORM_CHARS = constants.globChars(win32); const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; const globstar = opts => { return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const nodot = opts.dot ? '' : NO_DOT; const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; let star = opts.bash === true ? globstar(opts) : STAR; if (opts.capture) { star = `(${star})`; } // minimatch options support if (typeof opts.noext === 'boolean') { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: '', output: '', prefix: '', backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils.removePrefix(input, state); len = input.length; const extglobs = []; const braces = []; const stack = []; let prev = bos; let value; /** * Tokenizing helpers */ const eos = () => state.index === len - 1; const peek = state.peek = (n = 1) => input[state.index + n]; const advance = state.advance = () => input[++state.index] || ''; const remaining = () => input.slice(state.index + 1); const consume = (value = '', num = 0) => { state.consumed += value; state.index += num; }; const append = token => { state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = () => { let count = 1; while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = type => { state[type]++; stack.push(type); }; const decrement = type => { state[type]--; stack.pop(); }; /** * Push tokens onto the tokens array. This helper speeds up * tokenizing by 1) helping us avoid backtracking as much as possible, * and 2) helping us avoid creating extra tokens when consecutive * characters are plain text. This improves performance and simplifies * lookbehinds. */ const push = tok => { if (prev.type === 'globstar') { const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { state.output = state.output.slice(0, -prev.output.length); prev.type = 'star'; prev.value = '*'; prev.output = star; state.output += prev.output; } } if (extglobs.length && tok.type !== 'paren') { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append(tok); if (prev && prev.type === 'text' && tok.type === 'text') { prev.value += tok.value; prev.output = (prev.output || '') + tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value) => { const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; token.prev = prev; token.parens = state.parens; token.output = state.output; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); push({ type, value, output: state.output ? '' : ONE_CHAR }); push({ type: 'paren', extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = token => { let output = token.close + (opts.capture ? ')' : ''); let rest; if (token.type === 'negate') { let extglobStar = star; if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { extglobStar = globstar(opts); } if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. // In this case, we need to parse the string and use it in the output of the original pattern. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. // // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. const expression = parse(rest, { ...options, fastpaths: false }).output; output = token.close = `)${expression})${extglobStar})`; } if (token.prev.type === 'bos') { state.negatedExtglob = true; } } push({ type: 'paren', extglob: true, value, output }); decrement('parens'); }; /** * Fast paths */ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { if (first === '\\') { backslashes = true; return m; } if (first === '?') { if (esc) { return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } if (index === 0) { return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } return QMARK.repeat(chars.length); } if (first === '.') { return DOT_LITERAL.repeat(chars.length); } if (first === '*') { if (esc) { return esc + first + (rest ? star : ''); } return star; } return esc ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ''); } else { output = output.replace(/\\+/g, m => { return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils.wrapOutput(output, state, options); return state; } /** * Tokenize input until we reach end-of-string */ while (!eos()) { value = advance(); if (value === '\u0000') { continue; } /** * Escaped characters */ if (value === '\\') { const next = peek(); if (next === '/' && opts.bash !== true) { continue; } if (next === '.' || next === ';') { continue; } if (!next) { value += '\\'; push({ type: 'text', value }); continue; } // collapse slashes to reduce potential for exploits const match = /^\\+/.exec(remaining()); let slashes = 0; if (match && match[0].length > 2) { slashes = match[0].length; state.index += slashes; if (slashes % 2 !== 0) { value += '\\'; } } if (opts.unescape === true) { value = advance(); } else { value += advance(); } if (state.brackets === 0) { push({ type: 'text', value }); continue; } } /** * If we're inside a regex character class, continue * until we reach the closing bracket. */ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { if (opts.posix !== false && value === ':') { const inner = prev.value.slice(1); if (inner.includes('[')) { prev.posix = true; if (inner.includes(':')) { const idx = prev.value.lastIndexOf('['); const pre = prev.value.slice(0, idx); const rest = prev.value.slice(idx + 2); const posix = POSIX_REGEX_SOURCE[rest]; if (posix) { prev.value = pre + posix; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR; } continue; } } } } if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { value = `\\${value}`; } if (value === ']' && (prev.value === '[' || prev.value === '[^')) { value = `\\${value}`; } if (opts.posix === true && value === '!' && prev.value === '[') { value = '^'; } prev.value += value; append({ value }); continue; } /** * If we're inside a quoted string, continue * until we reach the closing double quote. */ if (state.quotes === 1 && value !== '"') { value = utils.escapeRegex(value); prev.value += value; append({ value }); continue; } /** * Double quotes */ if (value === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push({ type: 'text', value }); } continue; } /** * Parentheses */ if (value === '(') { increment('parens'); push({ type: 'paren', value }); continue; } if (value === ')') { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '(')); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); decrement('parens'); continue; } /** * Square brackets */ if (value === '[') { if (opts.nobracket === true || !remaining().includes(']')) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('closing', ']')); } value = `\\${value}`; } else { increment('brackets'); } push({ type: 'bracket', value }); continue; } if (value === ']') { if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { push({ type: 'text', value, output: `\\${value}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '[')); } push({ type: 'text', value, output: `\\${value}` }); continue; } decrement('brackets'); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { value = `/${value}`; } prev.value += value; append({ value }); // when literal brackets are explicitly disabled // assume we should match with a regex character class if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { continue; } const escaped = utils.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled // assume we should escape the brackets to match literal characters if (opts.literalBrackets === true) { state.output += escaped; prev.value = escaped; continue; } // when the user specifies nothing, try to match both prev.value = `(${capture}${escaped}|${prev.value})`; state.output += prev.value; continue; } /** * Braces */ if (value === '{' && opts.nobrace !== true) { increment('braces'); const open = { type: 'brace', value, output: '(', outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces.push(open); push(open); continue; } if (value === '}') { const brace = braces[braces.length - 1]; if (opts.nobrace === true || !brace) { push({ type: 'text', value, output: value }); continue; } let output = ')'; if (brace.dots === true) { const arr = tokens.slice(); const range = []; for (let i = arr.length - 1; i >= 0; i--) { tokens.pop(); if (arr[i].type === 'brace') { break; } if (arr[i].type !== 'dots') { range.unshift(arr[i].value); } } output = expandRange(range, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = '\\{'; value = output = '\\}'; state.output = out; for (const t of toks) { state.output += (t.output || t.value); } } push({ type: 'brace', value, output }); decrement('braces'); braces.pop(); continue; } /** * Pipes */ if (value === '|') { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push({ type: 'text', value }); continue; } /** * Commas */ if (value === ',') { let output = value; const brace = braces[braces.length - 1]; if (brace && stack[stack.length - 1] === 'braces') { brace.comma = true; output = '|'; } push({ type: 'comma', value, output }); continue; } /** * Slashes */ if (value === '/') { // if the beginning of the glob is "./", advance the start // to the current index, and don't add the "./" characters // to the state. This greatly simplifies lookbehinds when // checking for BOS characters like "!" and "." (not "./") if (prev.type === 'dot' && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ''; state.output = ''; tokens.pop(); prev = bos; // reset "prev" to the first token continue; } push({ type: 'slash', value, output: SLASH_LITERAL }); continue; } /** * Dots */ if (value === '.') { if (state.braces > 0 && prev.type === 'dot') { if (prev.value === '.') prev.output = DOT_LITERAL; const brace = braces[braces.length - 1]; prev.type = 'dots'; prev.output += value; prev.value += value; brace.dots = true; continue; } if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { push({ type: 'text', value, output: DOT_LITERAL }); continue; } push({ type: 'dot', value, output: DOT_LITERAL }); continue; } /** * Question marks */ if (value === '?') { const isGroup = prev && prev.value === '('; if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('qmark', value); continue; } if (prev && prev.type === 'paren') { const next = peek(); let output = value; if (next === '<' && !utils.supportsLookbehinds()) { throw new Error('Node.js v10 or higher is required for regex lookbehinds'); } if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { output = `\\${value}`; } push({ type: 'text', value, output }); continue; } if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { push({ type: 'qmark', value, output: QMARK_NO_DOT }); continue; } push({ type: 'qmark', value, output: QMARK }); continue; } /** * Exclamation */ if (value === '!') { if (opts.noextglob !== true && peek() === '(') { if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { extglobOpen('negate', value); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } /** * Plus */ if (value === '+') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('plus', value); continue; } if ((prev && prev.value === '(') || opts.regex === false) { push({ type: 'plus', value, output: PLUS_LITERAL }); continue; } if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { push({ type: 'plus', value }); continue; } push({ type: 'plus', value: PLUS_LITERAL }); continue; } /** * Plain text */ if (value === '@') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { push({ type: 'at', extglob: true, value, output: '' }); continue; } push({ type: 'text', value }); continue; } /** * Plain text */ if (value !== '*') { if (value === '$' || value === '^') { value = `\\${value}`; } const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); if (match) { value += match[0]; state.index += match[0].length; } push({ type: 'text', value }); continue; } /** * Stars */ if (prev && (prev.type === 'globstar' || prev.star === true)) { prev.type = 'star'; prev.star = true; prev.value += value; prev.output = star; state.backtrack = true; state.globstar = true; consume(value); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen('star', value); continue; } if (prev.type === 'star') { if (opts.noglobstar === true) { consume(value); continue; } const prior = prev.prev; const before = prior.prev; const isStart = prior.type === 'slash' || prior.type === 'bos'; const afterStar = before && (before.type === 'star' || before.type === 'globstar'); if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { push({ type: 'star', value, output: '' }); continue; } const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { push({ type: 'star', value, output: '' }); continue; } // strip consecutive `/**/` while (rest.slice(0, 3) === '/**') { const after = input[state.index + 4]; if (after && after !== '/') { break; } rest = rest.slice(3); consume('/**', 3); } if (prior.type === 'bos' && eos()) { prev.type = 'globstar'; prev.value += value; prev.output = globstar(opts); state.output = prev.output; state.globstar = true; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); prev.value += value; state.globstar = true; state.output += prior.output + prev.output; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { const end = rest[1] !== void 0 ? '|$' : ''; state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; prev.value += value; state.output += prior.output + prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } if (prior.type === 'bos' && rest[0] === '/') { prev.type = 'globstar'; prev.value += value; prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; state.output = prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } // remove single star from output state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar prev.type = 'globstar'; prev.output = globstar(opts); prev.value += value; // reset output with globstar state.output += prev.output; state.globstar = true; consume(value); continue; } const token = { type: 'star', value, output: star }; if (opts.bash === true) { token.output = '.*?'; if (prev.type === 'bos' || prev.type === 'slash') { token.output = nodot + token.output; } push(token); continue; } if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { token.output = value; push(token); continue; } if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { if (prev.type === 'dot') { state.output += NO_DOT_SLASH; prev.output += NO_DOT_SLASH; } else if (opts.dot === true) { state.output += NO_DOTS_SLASH; prev.output += NO_DOTS_SLASH; } else { state.output += nodot; prev.output += nodot; } if (peek() !== '*') { state.output += ONE_CHAR; prev.output += ONE_CHAR; } } push(token); } while (state.brackets > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); state.output = utils.escapeLast(state.output, '['); decrement('brackets'); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); state.output = utils.escapeLast(state.output, '('); decrement('parens'); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); state.output = utils.escapeLast(state.output, '{'); decrement('braces'); } if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); } // rebuild the output if we had to backtrack at any point if (state.backtrack === true) { state.output = ''; for (const token of state.tokens) { state.output += token.output != null ? token.output : token.value; if (token.suffix) { state.output += token.suffix; } } } return state; }; /** * Fast paths for creating regular expressions for common glob patterns. * This can significantly speed up processing and has very little downside * impact when none of the fast paths match. */ parse.fastpaths = (input, options) => { const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS[input] || input; const win32 = utils.isWindows(options); // create constants based on platform, for windows or posix const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants.globChars(win32); const nodot = opts.dot ? NO_DOTS : NO_DOT; const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; const capture = opts.capture ? '' : '?:'; const state = { negated: false, prefix: '' }; let star = opts.bash === true ? '.*?' : STAR; if (opts.capture) { star = `(${star})`; } const globstar = opts => { if (opts.noglobstar === true) return star; return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const create = str => { switch (str) { case '*': return `${nodot}${ONE_CHAR}${star}`; case '.*': return `${DOT_LITERAL}${ONE_CHAR}${star}`; case '*.*': return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '*/*': return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; case '**': return nodot + globstar(opts); case '**/*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; case '**/*.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '**/.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; default: { const match = /^(.*?)\.(\w+)$/.exec(str); if (!match) return; const source = create(match[1]); if (!source) return; return source + DOT_LITERAL + match[2]; } } }; const output = utils.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; module.exports = parse; node_modules/picomatch/lib/constants.js 0000664 00000010540 15114743311 0014312 0 ustar 00 'use strict'; const path = require('path'); const WIN_SLASH = '\\\\/'; const WIN_NO_SLASH = `[^${WIN_SLASH}]`; /** * Posix glob regex */ const DOT_LITERAL = '\\.'; const PLUS_LITERAL = '\\+'; const QMARK_LITERAL = '\\?'; const SLASH_LITERAL = '\\/'; const ONE_CHAR = '(?=.)'; const QMARK = '[^/]'; const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; const NO_DOT = `(?!${DOT_LITERAL})`; const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; const STAR = `${QMARK}*?`; const POSIX_CHARS = { DOT_LITERAL, PLUS_LITERAL, QMARK_LITERAL, SLASH_LITERAL, ONE_CHAR, QMARK, END_ANCHOR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK_NO_DOT, STAR, START_ANCHOR }; /** * Windows glob regex */ const WINDOWS_CHARS = { ...POSIX_CHARS, SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` }; /** * POSIX Bracket Regex */ const POSIX_REGEX_SOURCE = { alnum: 'a-zA-Z0-9', alpha: 'a-zA-Z', ascii: '\\x00-\\x7F', blank: ' \\t', cntrl: '\\x00-\\x1F\\x7F', digit: '0-9', graph: '\\x21-\\x7E', lower: 'a-z', print: '\\x20-\\x7E ', punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', space: ' \\t\\r\\n\\v\\f', upper: 'A-Z', word: 'A-Za-z0-9_', xdigit: 'A-Fa-f0-9' }; module.exports = { MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE, // regular expressions REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { '***': '*', '**/**': '**', '**/**/**': '**' }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ CHAR_ASTERISK: 42, /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ CHAR_COLON: 58, /* : */ CHAR_COMMA: 44, /* , */ CHAR_DOT: 46, /* . */ CHAR_DOUBLE_QUOTE: 34, /* " */ CHAR_EQUAL: 61, /* = */ CHAR_EXCLAMATION_MARK: 33, /* ! */ CHAR_FORM_FEED: 12, /* \f */ CHAR_FORWARD_SLASH: 47, /* / */ CHAR_GRAVE_ACCENT: 96, /* ` */ CHAR_HASH: 35, /* # */ CHAR_HYPHEN_MINUS: 45, /* - */ CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ CHAR_LEFT_CURLY_BRACE: 123, /* { */ CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ CHAR_LINE_FEED: 10, /* \n */ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ CHAR_PERCENT: 37, /* % */ CHAR_PLUS: 43, /* + */ CHAR_QUESTION_MARK: 63, /* ? */ CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ CHAR_RIGHT_CURLY_BRACE: 125, /* } */ CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ CHAR_SEMICOLON: 59, /* ; */ CHAR_SINGLE_QUOTE: 39, /* ' */ CHAR_SPACE: 32, /* */ CHAR_TAB: 9, /* \t */ CHAR_UNDERSCORE: 95, /* _ */ CHAR_VERTICAL_LINE: 124, /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ SEP: path.sep, /** * Create EXTGLOB_CHARS */ extglobChars(chars) { return { '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, '?': { type: 'qmark', open: '(?:', close: ')?' }, '+': { type: 'plus', open: '(?:', close: ')+' }, '*': { type: 'star', open: '(?:', close: ')*' }, '@': { type: 'at', open: '(?:', close: ')' } }; }, /** * Create GLOB_CHARS */ globChars(win32) { return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; } }; node_modules/picomatch/index.js 0000664 00000000074 15114743311 0012640 0 ustar 00 'use strict'; module.exports = require('./lib/picomatch'); node_modules/picomatch/CHANGELOG.md 0000664 00000014073 15114743311 0013010 0 ustar 00 # Release history **All notable changes to this project will be documented in this file.** The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). <details> <summary><strong>Guiding Principles</strong></summary> - Changelogs are for humans, not machines. - There should be an entry for every single version. - The same types of changes should be grouped. - Versions and sections should be linkable. - The latest version comes first. - The release date of each versions is displayed. - Mention whether you follow Semantic Versioning. </details> <details> <summary><strong>Types of changes</strong></summary> Changelog entries are classified using the following labels _(from [keep-a-changelog](http://keepachangelog.com/)_): - `Added` for new features. - `Changed` for changes in existing functionality. - `Deprecated` for soon-to-be removed features. - `Removed` for now removed features. - `Fixed` for any bug fixes. - `Security` in case of vulnerabilities. </details> ## 2.3.1 (2022-01-02) ### Fixed * Fixes bug when a pattern containing an expression after the closing parenthesis (`/!(*.d).{ts,tsx}`) was incorrectly converted to regexp ([9f241ef](https://github.com/micromatch/picomatch/commit/9f241ef)). ### Changed * Some documentation improvements ([f81d236](https://github.com/micromatch/picomatch/commit/f81d236), [421e0e7](https://github.com/micromatch/picomatch/commit/421e0e7)). ## 2.3.0 (2021-05-21) ### Fixed * Fixes bug where file names with two dots were not being matched consistently with negation extglobs containing a star ([56083ef](https://github.com/micromatch/picomatch/commit/56083ef)) ## 2.2.3 (2021-04-10) ### Fixed * Do not skip pattern seperator for square brackets ([fb08a30](https://github.com/micromatch/picomatch/commit/fb08a30)). * Set negatedExtGlob also if it does not span the whole pattern ([032e3f5](https://github.com/micromatch/picomatch/commit/032e3f5)). ## 2.2.2 (2020-03-21) ### Fixed * Correctly handle parts of the pattern after parentheses in the `scan` method ([e15b920](https://github.com/micromatch/picomatch/commit/e15b920)). ## 2.2.1 (2020-01-04) * Fixes [#49](https://github.com/micromatch/picomatch/issues/49), so that braces with no sets or ranges are now propertly treated as literals. ## 2.2.0 (2020-01-04) * Disable fastpaths mode for the parse method ([5b8d33f](https://github.com/micromatch/picomatch/commit/5b8d33f)) * Add `tokens`, `slashes`, and `parts` to the object returned by `picomatch.scan()`. ## 2.1.0 (2019-10-31) * add benchmarks for scan ([4793b92](https://github.com/micromatch/picomatch/commit/4793b92)) * Add eslint object-curly-spacing rule ([707c650](https://github.com/micromatch/picomatch/commit/707c650)) * Add prefer-const eslint rule ([5c7501c](https://github.com/micromatch/picomatch/commit/5c7501c)) * Add support for nonegate in scan API ([275c9b9](https://github.com/micromatch/picomatch/commit/275c9b9)) * Change lets to consts. Move root import up. ([4840625](https://github.com/micromatch/picomatch/commit/4840625)) * closes https://github.com/micromatch/picomatch/issues/21 ([766bcb0](https://github.com/micromatch/picomatch/commit/766bcb0)) * Fix "Extglobs" table in readme ([eb19da8](https://github.com/micromatch/picomatch/commit/eb19da8)) * fixes https://github.com/micromatch/picomatch/issues/20 ([9caca07](https://github.com/micromatch/picomatch/commit/9caca07)) * fixes https://github.com/micromatch/picomatch/issues/26 ([fa58f45](https://github.com/micromatch/picomatch/commit/fa58f45)) * Lint test ([d433a34](https://github.com/micromatch/picomatch/commit/d433a34)) * lint unit tests ([0159b55](https://github.com/micromatch/picomatch/commit/0159b55)) * Make scan work with noext ([6c02e03](https://github.com/micromatch/picomatch/commit/6c02e03)) * minor linting ([c2a2b87](https://github.com/micromatch/picomatch/commit/c2a2b87)) * minor parser improvements ([197671d](https://github.com/micromatch/picomatch/commit/197671d)) * remove eslint since it... ([07876fa](https://github.com/micromatch/picomatch/commit/07876fa)) * remove funding file ([8ebe96d](https://github.com/micromatch/picomatch/commit/8ebe96d)) * Remove unused funks ([cbc6d54](https://github.com/micromatch/picomatch/commit/cbc6d54)) * Run eslint during pretest, fix existing eslint findings ([0682367](https://github.com/micromatch/picomatch/commit/0682367)) * support `noparen` in scan ([3d37569](https://github.com/micromatch/picomatch/commit/3d37569)) * update changelog ([7b34e77](https://github.com/micromatch/picomatch/commit/7b34e77)) * update travis ([777f038](https://github.com/micromatch/picomatch/commit/777f038)) * Use eslint-disable-next-line instead of eslint-disable ([4e7c1fd](https://github.com/micromatch/picomatch/commit/4e7c1fd)) ## 2.0.7 (2019-05-14) * 2.0.7 ([9eb9a71](https://github.com/micromatch/picomatch/commit/9eb9a71)) * supports lookbehinds ([1f63f7e](https://github.com/micromatch/picomatch/commit/1f63f7e)) * update .verb.md file with typo change ([2741279](https://github.com/micromatch/picomatch/commit/2741279)) * fix: typo in README ([0753e44](https://github.com/micromatch/picomatch/commit/0753e44)) ## 2.0.4 (2019-04-10) ### Fixed - Readme link [fixed](https://github.com/micromatch/picomatch/pull/13/commits/a96ab3aa2b11b6861c23289964613d85563b05df) by @danez. - `options.capture` now works as expected when fastpaths are enabled. See https://github.com/micromatch/picomatch/pull/12/commits/26aefd71f1cfaf95c37f1c1fcab68a693b037304. Thanks to @DrPizza. ## 2.0.0 (2019-04-10) ### Added - Adds support for `options.onIgnore`. See the readme for details - Adds support for `options.onResult`. See the readme for details ### Breaking changes - The unixify option was renamed to `windows` - caching and all related options and methods have been removed ## 1.0.0 (2018-11-05) - adds `.onMatch` option - improvements to `.scan` method - numerous improvements and optimizations for matching and parsing - better windows path handling ## 0.1.0 - 2017-04-13 First release. [keep-a-changelog]: https://github.com/olivierlacan/keep-a-changelog node_modules/picomatch/README.md 0000664 00000065465 15114743311 0012471 0 ustar 00 <h1 align="center">Picomatch</h1> <p align="center"> <a href="https://npmjs.org/package/picomatch"> <img src="https://img.shields.io/npm/v/picomatch.svg" alt="version"> </a> <a href="https://github.com/micromatch/picomatch/actions?workflow=Tests"> <img src="https://github.com/micromatch/picomatch/workflows/Tests/badge.svg" alt="test status"> </a> <a href="https://coveralls.io/github/micromatch/picomatch"> <img src="https://img.shields.io/coveralls/github/micromatch/picomatch/master.svg" alt="coverage status"> </a> <a href="https://npmjs.org/package/picomatch"> <img src="https://img.shields.io/npm/dm/picomatch.svg" alt="downloads"> </a> </p> <br> <br> <p align="center"> <strong>Blazing fast and accurate glob matcher written in JavaScript.</strong></br> <em>No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.</em> </p> <br> <br> ## Why picomatch? * **Lightweight** - No dependencies * **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function. * **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps) * **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files) * **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes. * **Well tested** - Thousands of unit tests See the [library comparison](#library-comparisons) to other libraries. <br> <br> ## Table of Contents <details><summary> Click to expand </summary> - [Install](#install) - [Usage](#usage) - [API](#api) * [picomatch](#picomatch) * [.test](#test) * [.matchBase](#matchbase) * [.isMatch](#ismatch) * [.parse](#parse) * [.scan](#scan) * [.compileRe](#compilere) * [.makeRe](#makere) * [.toRegex](#toregex) - [Options](#options) * [Picomatch options](#picomatch-options) * [Scan Options](#scan-options) * [Options Examples](#options-examples) - [Globbing features](#globbing-features) * [Basic globbing](#basic-globbing) * [Advanced globbing](#advanced-globbing) * [Braces](#braces) * [Matching special characters as literals](#matching-special-characters-as-literals) - [Library Comparisons](#library-comparisons) - [Benchmarks](#benchmarks) - [Philosophies](#philosophies) - [About](#about) * [Author](#author) * [License](#license) _(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_ </details> <br> <br> ## Install Install with [npm](https://www.npmjs.com/): ```sh npm install --save picomatch ``` <br> ## Usage The main export is a function that takes a glob pattern and an options object and returns a function for matching strings. ```js const pm = require('picomatch'); const isMatch = pm('*.js'); console.log(isMatch('abcd')); //=> false console.log(isMatch('a.js')); //=> true console.log(isMatch('a.md')); //=> false console.log(isMatch('a/b.js')); //=> false ``` <br> ## API ### [picomatch](lib/picomatch.js#L32) Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information. **Params** * `globs` **{String|Array}**: One or more glob patterns. * `options` **{Object=}** * `returns` **{Function=}**: Returns a matcher function. **Example** ```js const picomatch = require('picomatch'); // picomatch(glob[, options]); const isMatch = picomatch('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` ### [.test](lib/picomatch.js#L117) Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string. **Params** * `input` **{String}**: String to test. * `regex` **{RegExp}** * `returns` **{Object}**: Returns an object with matching info. **Example** ```js const picomatch = require('picomatch'); // picomatch.test(input, regex[, options]); console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } ``` ### [.matchBase](lib/picomatch.js#L161) Match the basename of a filepath. **Params** * `input` **{String}**: String to test. * `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe). * `returns` **{Boolean}** **Example** ```js const picomatch = require('picomatch'); // picomatch.matchBase(input, glob[, options]); console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true ``` ### [.isMatch](lib/picomatch.js#L183) Returns true if **any** of the given glob `patterns` match the specified `string`. **Params** * **{String|Array}**: str The string to test. * **{String|Array}**: patterns One or more glob patterns to use for matching. * **{Object}**: See available [options](#options). * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const picomatch = require('picomatch'); // picomatch.isMatch(string, patterns[, options]); console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true console.log(picomatch.isMatch('a.a', 'b.*')); //=> false ``` ### [.parse](lib/picomatch.js#L199) Parse a glob pattern to create the source string for a regular expression. **Params** * `pattern` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string. **Example** ```js const picomatch = require('picomatch'); const result = picomatch.parse(pattern[, options]); ``` ### [.scan](lib/picomatch.js#L231) Scan a glob pattern to separate the pattern into segments. **Params** * `input` **{String}**: Glob pattern to scan. * `options` **{Object}** * `returns` **{Object}**: Returns an object with **Example** ```js const picomatch = require('picomatch'); // picomatch.scan(input[, options]); const result = picomatch.scan('!./foo/*.js'); console.log(result); { prefix: '!./', input: '!./foo/*.js', start: 3, base: 'foo', glob: '*.js', isBrace: false, isBracket: false, isGlob: true, isExtglob: false, isGlobstar: false, negated: true } ``` ### [.compileRe](lib/picomatch.js#L245) Compile a regular expression from the `state` object returned by the [parse()](#parse) method. **Params** * `state` **{Object}** * `options` **{Object}** * `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser. * `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. * `returns` **{RegExp}** ### [.makeRe](lib/picomatch.js#L286) Create a regular expression from a parsed glob pattern. **Params** * `state` **{String}**: The object returned from the `.parse` method. * `options` **{Object}** * `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. * `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression. * `returns` **{RegExp}**: Returns a regex created from the given pattern. **Example** ```js const picomatch = require('picomatch'); const state = picomatch.parse('*.js'); // picomatch.compileRe(state[, options]); console.log(picomatch.compileRe(state)); //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ ``` ### [.toRegex](lib/picomatch.js#L321) Create a regular expression from the given regex source string. **Params** * `source` **{String}**: Regular expression source string. * `options` **{Object}** * `returns` **{RegExp}** **Example** ```js const picomatch = require('picomatch'); // picomatch.toRegex(source[, options]); const { output } = picomatch.parse('*.js'); console.log(picomatch.toRegex(output)); //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ ``` <br> ## Options ### Picomatch options The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API. | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | | `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | | `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | | `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | | `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | | `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | | `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true | | `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. | | `failglob` | `boolean` | `false` | Throws an error if no matches are found. Based on the bash option of the same name. | | `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | | `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | | [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | | `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | | `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | | `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | | `matchBase` | `boolean` | `false` | Alias for `basename` | | `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | | `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | | `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | | `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. | | `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | | `noext` | `boolean` | `false` | Alias for `noextglob` | | `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) | | `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | | `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | | `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | | [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | | [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | | [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | | `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). | | `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | | `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. | | `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | | `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | | `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | | `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. | | `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatibility. | picomatch has automatic detection for regex positive and negative lookbehinds. If the pattern contains a negative lookbehind, you must be using Node.js >= 8.10 or else picomatch will throw an error. ### Scan Options In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method. | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern | | `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true | **Example** ```js const picomatch = require('picomatch'); const result = picomatch.scan('!./foo/*.js', { tokens: true }); console.log(result); // { // prefix: '!./', // input: '!./foo/*.js', // start: 3, // base: 'foo', // glob: '*.js', // isBrace: false, // isBracket: false, // isGlob: true, // isExtglob: false, // isGlobstar: false, // negated: true, // maxDepth: 2, // tokens: [ // { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true }, // { value: 'foo', depth: 1, isGlob: false }, // { value: '*.js', depth: 1, isGlob: true } // ], // slashes: [ 2, 6 ], // parts: [ 'foo', '*.js' ] // } ``` <br> ### Options Examples #### options.expandRange **Type**: `function` **Default**: `undefined` Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. **Example** The following example shows how to create a glob that matches a folder ```js const fill = require('fill-range'); const regex = pm.makeRe('foo/{01..25}/bar', { expandRange(a, b) { return `(${fill(a, b, { toRegex: true })})`; } }); console.log(regex); //=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ console.log(regex.test('foo/00/bar')) // false console.log(regex.test('foo/01/bar')) // true console.log(regex.test('foo/10/bar')) // true console.log(regex.test('foo/22/bar')) // true console.log(regex.test('foo/25/bar')) // true console.log(regex.test('foo/26/bar')) // false ``` #### options.format **Type**: `function` **Default**: `undefined` Custom function for formatting strings before they're matched. **Example** ```js // strip leading './' from strings const format = str => str.replace(/^\.\//, ''); const isMatch = picomatch('foo/*.js', { format }); console.log(isMatch('./foo/bar.js')); //=> true ``` #### options.onMatch ```js const onMatch = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onMatch }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` #### options.onIgnore ```js const onIgnore = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onIgnore, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` #### options.onResult ```js const onResult = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onResult, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` <br> <br> ## Globbing features * [Basic globbing](#basic-globbing) (Wildcard matching) * [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching) ### Basic globbing | **Character** | **Description** | | --- | --- | | `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. | | `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` on Windows) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. | | `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. | | `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. | #### Matching behavior vs. Bash Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions: * Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`. * Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`. <br> ### Advanced globbing * [extglobs](#extglobs) * [POSIX brackets](#posix-brackets) * [Braces](#brace-expansion) #### Extglobs | **Pattern** | **Description** | | --- | --- | | `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` | | `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` | | `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` | | `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` | | `!(pattern)` | Match _anything but_ `pattern` | **Examples** ```js const pm = require('picomatch'); // *(pattern) matches ZERO or more of "pattern" console.log(pm.isMatch('a', 'a*(z)')); // true console.log(pm.isMatch('az', 'a*(z)')); // true console.log(pm.isMatch('azzz', 'a*(z)')); // true // +(pattern) matches ONE or more of "pattern" console.log(pm.isMatch('a', 'a*(z)')); // true console.log(pm.isMatch('az', 'a*(z)')); // true console.log(pm.isMatch('azzz', 'a*(z)')); // true // supports multiple extglobs console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false // supports nested extglobs console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true ``` #### POSIX brackets POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true. **Enable POSIX bracket support** ```js console.log(pm.makeRe('[[:word:]]+', { posix: true })); //=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/ ``` **Supported POSIX classes** The following named POSIX bracket expressions are supported: * `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]` * `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`. * `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`. * `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`. * `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`. * `[:digit:]` - Numerical digits, equivalent to `[0-9]`. * `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`. * `[:lower:]` - Lowercase letters, equivalent to `[a-z]`. * `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`. * `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`. * `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`. * `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`. * `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`. * `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`. See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information. ### Braces Picomatch does not do brace expansion. For [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) and advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch) instead. Picomatch has very basic support for braces. ### Matching special characters as literals If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes: **Special Characters** Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms. To match any of the following characters as literals: `$^*+?()[] Examples: ```js console.log(pm.makeRe('foo/bar \\(1\\)')); console.log(pm.makeRe('foo/bar \\(1\\)')); ``` <br> <br> ## Library Comparisons The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets). | **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` | | --- | --- | --- | --- | --- | --- | --- | --- | | Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - | | Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - | | Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - | | Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - | | Extglobs | partial | ✔ | ✔ | - | ✔ | - | - | | Posix brackets | - | ✔ | ✔ | - | - | - | ✔ | | Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ | | File system operations | - | - | - | - | - | - | - | <br> <br> ## Benchmarks Performance comparison of picomatch and minimatch. ``` # .makeRe star picomatch x 1,993,050 ops/sec ±0.51% (91 runs sampled) minimatch x 627,206 ops/sec ±1.96% (87 runs sampled)) # .makeRe star; dot=true picomatch x 1,436,640 ops/sec ±0.62% (91 runs sampled) minimatch x 525,876 ops/sec ±0.60% (88 runs sampled) # .makeRe globstar picomatch x 1,592,742 ops/sec ±0.42% (90 runs sampled) minimatch x 962,043 ops/sec ±1.76% (91 runs sampled)d) # .makeRe globstars picomatch x 1,615,199 ops/sec ±0.35% (94 runs sampled) minimatch x 477,179 ops/sec ±1.33% (91 runs sampled) # .makeRe with leading star picomatch x 1,220,856 ops/sec ±0.40% (92 runs sampled) minimatch x 453,564 ops/sec ±1.43% (94 runs sampled) # .makeRe - basic braces picomatch x 392,067 ops/sec ±0.70% (90 runs sampled) minimatch x 99,532 ops/sec ±2.03% (87 runs sampled)) ``` <br> <br> ## Philosophies The goal of this library is to be blazing fast, without compromising on accuracy. **Accuracy** The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`. Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements. **Performance** Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer. <br> <br> ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). node_modules/@clack/prompts/package.json 0000664 00000002470 15114743311 0014375 0 ustar 00 { "name": "@clack/prompts", "version": "0.7.0", "type": "module", "main": "./dist/index.cjs", "module": "./dist/index.mjs", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.cjs" }, "./package.json": "./package.json" }, "types": "./dist/index.d.ts", "repository": { "type": "git", "url": "https://github.com/natemoo-re/clack", "directory": "packages/prompts" }, "bugs": { "url": "https://github.com/natemoo-re/clack/issues" }, "homepage": "https://github.com/natemoo-re/clack/tree/main/packages/prompts#readme", "files": [ "dist", "CHANGELOG.md" ], "author": { "name": "Nate Moore", "email": "nate@natemoo.re", "url": "https://twitter.com/n_moore" }, "license": "MIT", "keywords": [ "ask", "clack", "cli", "command-line", "command", "input", "interact", "interface", "menu", "prompt", "prompts", "stdin", "ui" ], "packageManager": "pnpm@7.6.0", "dependencies": { "@clack/core": "^0.3.3", "picocolors": "^1.0.0", "sisteransi": "^1.0.5" }, "devDependencies": { "is-unicode-supported": "^1.3.0" }, "bundledDependencies": [ "is-unicode-supported" ], "scripts": { "build": "unbuild" } } node_modules/@clack/prompts/LICENSE 0000664 00000004313 15114743311 0013112 0 ustar 00 MIT License Copyright (c) Nate Moore Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --- `ansi-regex` is adapted from https://github.com/chalk/ansi-regex MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/@clack/prompts/dist/index.d.ts 0000664 00000007651 15114743311 0014761 0 ustar 00 export { isCancel } from '@clack/core'; interface TextOptions { message: string; placeholder?: string; defaultValue?: string; initialValue?: string; validate?: (value: string) => string | void; } declare const text: (opts: TextOptions) => Promise<string | symbol>; interface PasswordOptions { message: string; mask?: string; validate?: (value: string) => string | void; } declare const password: (opts: PasswordOptions) => Promise<string | symbol>; interface ConfirmOptions { message: string; active?: string; inactive?: string; initialValue?: boolean; } declare const confirm: (opts: ConfirmOptions) => Promise<boolean | symbol>; type Primitive = Readonly<string | boolean | number>; type Option<Value> = Value extends Primitive ? { value: Value; label?: string; hint?: string; } : { value: Value; label: string; hint?: string; }; interface SelectOptions<Options extends Option<Value>[], Value> { message: string; options: Options; initialValue?: Value; maxItems?: number; } declare const select: <Options extends Option<Value>[], Value>(opts: SelectOptions<Options, Value>) => Promise<symbol | Value>; declare const selectKey: <Options extends Option<Value>[], Value extends string>(opts: SelectOptions<Options, Value>) => Promise<symbol | Value>; interface MultiSelectOptions<Options extends Option<Value>[], Value> { message: string; options: Options; initialValues?: Value[]; required?: boolean; cursorAt?: Value; } declare const multiselect: <Options extends Option<Value>[], Value>(opts: MultiSelectOptions<Options, Value>) => Promise<symbol | Value[]>; interface GroupMultiSelectOptions<Options extends Option<Value>[], Value> { message: string; options: Record<string, Options>; initialValues?: Value[]; required?: boolean; cursorAt?: Value; } declare const groupMultiselect: <Options extends Option<Value>[], Value>(opts: GroupMultiSelectOptions<Options, Value>) => Promise<symbol | Value[]>; declare const note: (message?: string, title?: string) => void; declare const cancel: (message?: string) => void; declare const intro: (title?: string) => void; declare const outro: (message?: string) => void; type LogMessageOptions = { symbol?: string; }; declare const log: { message: (message?: string, { symbol }?: LogMessageOptions) => void; info: (message: string) => void; success: (message: string) => void; step: (message: string) => void; warn: (message: string) => void; /** alias for `log.warn()`. */ warning: (message: string) => void; error: (message: string) => void; }; declare const spinner: () => { start: (msg?: string) => void; stop: (msg?: string, code?: number) => void; message: (msg?: string) => void; }; type PromptGroupAwaitedReturn<T> = { [P in keyof T]: Exclude<Awaited<T[P]>, symbol>; }; interface PromptGroupOptions<T> { /** * Control how the group can be canceled * if one of the prompts is canceled. */ onCancel?: (opts: { results: Prettify<Partial<PromptGroupAwaitedReturn<T>>>; }) => void; } type Prettify<T> = { [P in keyof T]: T[P]; } & {}; type PromptGroup<T> = { [P in keyof T]: (opts: { results: Prettify<Partial<PromptGroupAwaitedReturn<Omit<T, P>>>>; }) => void | Promise<T[P] | void>; }; /** * Define a group of prompts to be displayed * and return a results of objects within the group */ declare const group: <T>(prompts: PromptGroup<T>, opts?: PromptGroupOptions<T> | undefined) => Promise<PromptGroupAwaitedReturn<T> extends infer T_1 ? { [P in keyof T_1]: PromptGroupAwaitedReturn<T>[P]; } : never>; export { ConfirmOptions, GroupMultiSelectOptions, LogMessageOptions, MultiSelectOptions, PasswordOptions, PromptGroup, PromptGroupAwaitedReturn, PromptGroupOptions, SelectOptions, TextOptions, cancel, confirm, group, groupMultiselect, intro, log, multiselect, note, outro, password, select, selectKey, spinner, text }; node_modules/@clack/prompts/dist/index.mjs 0000664 00000026301 15114743311 0014673 0 ustar 00 import{TextPrompt as V,PasswordPrompt as j,ConfirmPrompt as N,SelectPrompt as k,SelectKeyPrompt as W,MultiSelectPrompt as D,GroupMultiSelectPrompt as L,isCancel as G,block as F}from"@clack/core";export{isCancel}from"@clack/core";import h from"node:process";import e from"picocolors";import{cursor as T,erase as A}from"sisteransi";function q(){return h.platform!=="win32"?h.env.TERM!=="linux":Boolean(h.env.CI)||Boolean(h.env.WT_SESSION)||Boolean(h.env.TERMINUS_SUBLIME)||h.env.ConEmuTask==="{cmd::Cmder}"||h.env.TERM_PROGRAM==="Terminus-Sublime"||h.env.TERM_PROGRAM==="vscode"||h.env.TERM==="xterm-256color"||h.env.TERM==="alacritty"||h.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}const _=q(),o=(r,n)=>_?r:n,H=o("\u25C6","*"),I=o("\u25A0","x"),x=o("\u25B2","x"),S=o("\u25C7","o"),K=o("\u250C","T"),a=o("\u2502","|"),d=o("\u2514","\u2014"),b=o("\u25CF",">"),E=o("\u25CB"," "),C=o("\u25FB","[\u2022]"),w=o("\u25FC","[+]"),M=o("\u25FB","[ ]"),U=o("\u25AA","\u2022"),B=o("\u2500","-"),Z=o("\u256E","+"),z=o("\u251C","+"),X=o("\u256F","+"),J=o("\u25CF","\u2022"),Y=o("\u25C6","*"),Q=o("\u25B2","!"),ee=o("\u25A0","x"),y=r=>{switch(r){case"initial":case"active":return e.cyan(H);case"cancel":return e.red(I);case"error":return e.yellow(x);case"submit":return e.green(S)}},te=r=>new V({validate:r.validate,placeholder:r.placeholder,defaultValue:r.defaultValue,initialValue:r.initialValue,render(){const n=`${e.gray(a)} ${y(this.state)} ${r.message} `,i=r.placeholder?e.inverse(r.placeholder[0])+e.dim(r.placeholder.slice(1)):e.inverse(e.hidden("_")),t=this.value?this.valueWithCursor:i;switch(this.state){case"error":return`${n.trim()} ${e.yellow(a)} ${t} ${e.yellow(d)} ${e.yellow(this.error)} `;case"submit":return`${n}${e.gray(a)} ${e.dim(this.value||r.placeholder)}`;case"cancel":return`${n}${e.gray(a)} ${e.strikethrough(e.dim(this.value??""))}${this.value?.trim()?` `+e.gray(a):""}`;default:return`${n}${e.cyan(a)} ${t} ${e.cyan(d)} `}}}).prompt(),re=r=>new j({validate:r.validate,mask:r.mask??U,render(){const n=`${e.gray(a)} ${y(this.state)} ${r.message} `,i=this.valueWithCursor,t=this.masked;switch(this.state){case"error":return`${n.trim()} ${e.yellow(a)} ${t} ${e.yellow(d)} ${e.yellow(this.error)} `;case"submit":return`${n}${e.gray(a)} ${e.dim(t)}`;case"cancel":return`${n}${e.gray(a)} ${e.strikethrough(e.dim(t??""))}${t?` `+e.gray(a):""}`;default:return`${n}${e.cyan(a)} ${i} ${e.cyan(d)} `}}}).prompt(),se=r=>{const n=r.active??"Yes",i=r.inactive??"No";return new N({active:n,inactive:i,initialValue:r.initialValue??!0,render(){const t=`${e.gray(a)} ${y(this.state)} ${r.message} `,s=this.value?n:i;switch(this.state){case"submit":return`${t}${e.gray(a)} ${e.dim(s)}`;case"cancel":return`${t}${e.gray(a)} ${e.strikethrough(e.dim(s))} ${e.gray(a)}`;default:return`${t}${e.cyan(a)} ${this.value?`${e.green(b)} ${n}`:`${e.dim(E)} ${e.dim(n)}`} ${e.dim("/")} ${this.value?`${e.dim(E)} ${e.dim(i)}`:`${e.green(b)} ${i}`} ${e.cyan(d)} `}}}).prompt()},ie=r=>{const n=(t,s)=>{const c=t.label??String(t.value);return s==="active"?`${e.green(b)} ${c} ${t.hint?e.dim(`(${t.hint})`):""}`:s==="selected"?`${e.dim(c)}`:s==="cancelled"?`${e.strikethrough(e.dim(c))}`:`${e.dim(E)} ${e.dim(c)}`};let i=0;return new k({options:r.options,initialValue:r.initialValue,render(){const t=`${e.gray(a)} ${y(this.state)} ${r.message} `;switch(this.state){case"submit":return`${t}${e.gray(a)} ${n(this.options[this.cursor],"selected")}`;case"cancel":return`${t}${e.gray(a)} ${n(this.options[this.cursor],"cancelled")} ${e.gray(a)}`;default:{const s=r.maxItems===void 0?1/0:Math.max(r.maxItems,5);this.cursor>=i+s-3?i=Math.max(Math.min(this.cursor-s+3,this.options.length-s),0):this.cursor<i+2&&(i=Math.max(this.cursor-2,0));const c=s<this.options.length&&i>0,l=s<this.options.length&&i+s<this.options.length;return`${t}${e.cyan(a)} ${this.options.slice(i,i+s).map((u,m,$)=>m===0&&c?e.dim("..."):m===$.length-1&&l?e.dim("..."):n(u,m+i===this.cursor?"active":"inactive")).join(` ${e.cyan(a)} `)} ${e.cyan(d)} `}}}}).prompt()},ne=r=>{const n=(i,t="inactive")=>{const s=i.label??String(i.value);return t==="selected"?`${e.dim(s)}`:t==="cancelled"?`${e.strikethrough(e.dim(s))}`:t==="active"?`${e.bgCyan(e.gray(` ${i.value} `))} ${s} ${i.hint?e.dim(`(${i.hint})`):""}`:`${e.gray(e.bgWhite(e.inverse(` ${i.value} `)))} ${s} ${i.hint?e.dim(`(${i.hint})`):""}`};return new W({options:r.options,initialValue:r.initialValue,render(){const i=`${e.gray(a)} ${y(this.state)} ${r.message} `;switch(this.state){case"submit":return`${i}${e.gray(a)} ${n(this.options.find(t=>t.value===this.value),"selected")}`;case"cancel":return`${i}${e.gray(a)} ${n(this.options[0],"cancelled")} ${e.gray(a)}`;default:return`${i}${e.cyan(a)} ${this.options.map((t,s)=>n(t,s===this.cursor?"active":"inactive")).join(` ${e.cyan(a)} `)} ${e.cyan(d)} `}}}).prompt()},ae=r=>{const n=(i,t)=>{const s=i.label??String(i.value);return t==="active"?`${e.cyan(C)} ${s} ${i.hint?e.dim(`(${i.hint})`):""}`:t==="selected"?`${e.green(w)} ${e.dim(s)}`:t==="cancelled"?`${e.strikethrough(e.dim(s))}`:t==="active-selected"?`${e.green(w)} ${s} ${i.hint?e.dim(`(${i.hint})`):""}`:t==="submitted"?`${e.dim(s)}`:`${e.dim(M)} ${e.dim(s)}`};return new D({options:r.options,initialValues:r.initialValues,required:r.required??!0,cursorAt:r.cursorAt,validate(i){if(this.required&&i.length===0)return`Please select at least one option. ${e.reset(e.dim(`Press ${e.gray(e.bgWhite(e.inverse(" space ")))} to select, ${e.gray(e.bgWhite(e.inverse(" enter ")))} to submit`))}`},render(){let i=`${e.gray(a)} ${y(this.state)} ${r.message} `;switch(this.state){case"submit":return`${i}${e.gray(a)} ${this.options.filter(({value:t})=>this.value.includes(t)).map(t=>n(t,"submitted")).join(e.dim(", "))||e.dim("none")}`;case"cancel":{const t=this.options.filter(({value:s})=>this.value.includes(s)).map(s=>n(s,"cancelled")).join(e.dim(", "));return`${i}${e.gray(a)} ${t.trim()?`${t} ${e.gray(a)}`:""}`}case"error":{const t=this.error.split(` `).map((s,c)=>c===0?`${e.yellow(d)} ${e.yellow(s)}`:` ${s}`).join(` `);return i+e.yellow(a)+" "+this.options.map((s,c)=>{const l=this.value.includes(s.value),u=c===this.cursor;return u&&l?n(s,"active-selected"):l?n(s,"selected"):n(s,u?"active":"inactive")}).join(` ${e.yellow(a)} `)+` `+t+` `}default:return`${i}${e.cyan(a)} ${this.options.map((t,s)=>{const c=this.value.includes(t.value),l=s===this.cursor;return l&&c?n(t,"active-selected"):c?n(t,"selected"):n(t,l?"active":"inactive")}).join(` ${e.cyan(a)} `)} ${e.cyan(d)} `}}}).prompt()},ce=r=>{const n=(i,t,s=[])=>{const c=i.label??String(i.value),l=typeof i.group=="string",u=l&&(s[s.indexOf(i)+1]??{group:!0}),m=l&&u.group===!0,$=l?`${m?d:a} `:"";return t==="active"?`${e.dim($)}${e.cyan(C)} ${c} ${i.hint?e.dim(`(${i.hint})`):""}`:t==="group-active"?`${$}${e.cyan(C)} ${e.dim(c)}`:t==="group-active-selected"?`${$}${e.green(w)} ${e.dim(c)}`:t==="selected"?`${e.dim($)}${e.green(w)} ${e.dim(c)}`:t==="cancelled"?`${e.strikethrough(e.dim(c))}`:t==="active-selected"?`${e.dim($)}${e.green(w)} ${c} ${i.hint?e.dim(`(${i.hint})`):""}`:t==="submitted"?`${e.dim(c)}`:`${e.dim($)}${e.dim(M)} ${e.dim(c)}`};return new L({options:r.options,initialValues:r.initialValues,required:r.required??!0,cursorAt:r.cursorAt,validate(i){if(this.required&&i.length===0)return`Please select at least one option. ${e.reset(e.dim(`Press ${e.gray(e.bgWhite(e.inverse(" space ")))} to select, ${e.gray(e.bgWhite(e.inverse(" enter ")))} to submit`))}`},render(){let i=`${e.gray(a)} ${y(this.state)} ${r.message} `;switch(this.state){case"submit":return`${i}${e.gray(a)} ${this.options.filter(({value:t})=>this.value.includes(t)).map(t=>n(t,"submitted")).join(e.dim(", "))}`;case"cancel":{const t=this.options.filter(({value:s})=>this.value.includes(s)).map(s=>n(s,"cancelled")).join(e.dim(", "));return`${i}${e.gray(a)} ${t.trim()?`${t} ${e.gray(a)}`:""}`}case"error":{const t=this.error.split(` `).map((s,c)=>c===0?`${e.yellow(d)} ${e.yellow(s)}`:` ${s}`).join(` `);return`${i}${e.yellow(a)} ${this.options.map((s,c,l)=>{const u=this.value.includes(s.value)||s.group===!0&&this.isGroupSelected(`${s.value}`),m=c===this.cursor;return!m&&typeof s.group=="string"&&this.options[this.cursor].value===s.group?n(s,u?"group-active-selected":"group-active",l):m&&u?n(s,"active-selected",l):u?n(s,"selected",l):n(s,m?"active":"inactive",l)}).join(` ${e.yellow(a)} `)} ${t} `}default:return`${i}${e.cyan(a)} ${this.options.map((t,s,c)=>{const l=this.value.includes(t.value)||t.group===!0&&this.isGroupSelected(`${t.value}`),u=s===this.cursor;return!u&&typeof t.group=="string"&&this.options[this.cursor].value===t.group?n(t,l?"group-active-selected":"group-active",c):u&&l?n(t,"active-selected",c):l?n(t,"selected",c):n(t,u?"active":"inactive",c)}).join(` ${e.cyan(a)} `)} ${e.cyan(d)} `}}}).prompt()},R=r=>r.replace(me(),""),le=(r="",n="")=>{const i=` ${r} `.split(` `),t=R(n).length,s=Math.max(i.reduce((l,u)=>(u=R(u),u.length>l?u.length:l),0),t)+2,c=i.map(l=>`${e.gray(a)} ${e.dim(l)}${" ".repeat(s-R(l).length)}${e.gray(a)}`).join(` `);process.stdout.write(`${e.gray(a)} ${e.green(S)} ${e.reset(n)} ${e.gray(B.repeat(Math.max(s-t-1,1))+Z)} ${c} ${e.gray(z+B.repeat(s+2)+X)} `)},ue=(r="")=>{process.stdout.write(`${e.gray(d)} ${e.red(r)} `)},oe=(r="")=>{process.stdout.write(`${e.gray(K)} ${r} `)},$e=(r="")=>{process.stdout.write(`${e.gray(a)} ${e.gray(d)} ${r} `)},f={message:(r="",{symbol:n=e.gray(a)}={})=>{const i=[`${e.gray(a)}`];if(r){const[t,...s]=r.split(` `);i.push(`${n} ${t}`,...s.map(c=>`${e.gray(a)} ${c}`))}process.stdout.write(`${i.join(` `)} `)},info:r=>{f.message(r,{symbol:e.blue(J)})},success:r=>{f.message(r,{symbol:e.green(Y)})},step:r=>{f.message(r,{symbol:e.green(S)})},warn:r=>{f.message(r,{symbol:e.yellow(Q)})},warning:r=>{f.warn(r)},error:r=>{f.message(r,{symbol:e.red(ee)})}},de=()=>{const r=_?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],n=_?80:120;let i,t,s=!1,c="";const l=(v="")=>{s=!0,i=F(),c=v.replace(/\.+$/,""),process.stdout.write(`${e.gray(a)} `);let g=0,p=0;t=setInterval(()=>{const O=e.magenta(r[g]),P=".".repeat(Math.floor(p)).slice(0,3);process.stdout.write(T.move(-999,0)),process.stdout.write(A.down(1)),process.stdout.write(`${O} ${c}${P}`),g=g+1<r.length?g+1:0,p=p<r.length?p+.125:0},n)},u=(v="",g=0)=>{c=v??c,s=!1,clearInterval(t);const p=g===0?e.green(S):g===1?e.red(I):e.red(x);process.stdout.write(T.move(-999,0)),process.stdout.write(A.down(1)),process.stdout.write(`${p} ${c} `),i()},m=(v="")=>{c=v??c},$=v=>{const g=v>1?"Something went wrong":"Canceled";s&&u(g,v)};return process.on("uncaughtExceptionMonitor",()=>$(2)),process.on("unhandledRejection",()=>$(2)),process.on("SIGINT",()=>$(1)),process.on("SIGTERM",()=>$(1)),process.on("exit",$),{start:l,stop:u,message:m}};function me(){const r=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(r,"g")}const he=async(r,n)=>{const i={},t=Object.keys(r);for(const s of t){const c=r[s],l=await c({results:i})?.catch(u=>{throw u});if(typeof n?.onCancel=="function"&&G(l)){i[s]="canceled",n.onCancel({results:i});continue}i[s]=l}return i};export{ue as cancel,se as confirm,he as group,ce as groupMultiselect,oe as intro,f as log,ae as multiselect,le as note,$e as outro,re as password,ie as select,ne as selectKey,de as spinner,te as text}; node_modules/@clack/prompts/dist/index.cjs 0000664 00000032571 15114743311 0014667 0 ustar 00 "use strict";const core=require("@clack/core"),process$1=require("node:process"),color=require("picocolors"),sisteransi=require("sisteransi");function isUnicodeSupported(){return process$1.platform!=="win32"?process$1.env.TERM!=="linux":Boolean(process$1.env.CI)||Boolean(process$1.env.WT_SESSION)||Boolean(process$1.env.TERMINUS_SUBLIME)||process$1.env.ConEmuTask==="{cmd::Cmder}"||process$1.env.TERM_PROGRAM==="Terminus-Sublime"||process$1.env.TERM_PROGRAM==="vscode"||process$1.env.TERM==="xterm-256color"||process$1.env.TERM==="alacritty"||process$1.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}const unicode=isUnicodeSupported(),s=(t,n)=>unicode?t:n,S_STEP_ACTIVE=s("\u25C6","*"),S_STEP_CANCEL=s("\u25A0","x"),S_STEP_ERROR=s("\u25B2","x"),S_STEP_SUBMIT=s("\u25C7","o"),S_BAR_START=s("\u250C","T"),S_BAR=s("\u2502","|"),S_BAR_END=s("\u2514","\u2014"),S_RADIO_ACTIVE=s("\u25CF",">"),S_RADIO_INACTIVE=s("\u25CB"," "),S_CHECKBOX_ACTIVE=s("\u25FB","[\u2022]"),S_CHECKBOX_SELECTED=s("\u25FC","[+]"),S_CHECKBOX_INACTIVE=s("\u25FB","[ ]"),S_PASSWORD_MASK=s("\u25AA","\u2022"),S_BAR_H=s("\u2500","-"),S_CORNER_TOP_RIGHT=s("\u256E","+"),S_CONNECT_LEFT=s("\u251C","+"),S_CORNER_BOTTOM_RIGHT=s("\u256F","+"),S_INFO=s("\u25CF","\u2022"),S_SUCCESS=s("\u25C6","*"),S_WARN=s("\u25B2","!"),S_ERROR=s("\u25A0","x"),symbol=t=>{switch(t){case"initial":case"active":return color.cyan(S_STEP_ACTIVE);case"cancel":return color.red(S_STEP_CANCEL);case"error":return color.yellow(S_STEP_ERROR);case"submit":return color.green(S_STEP_SUBMIT)}},text=t=>new core.TextPrompt({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,render(){const n=`${color.gray(S_BAR)} ${symbol(this.state)} ${t.message} `,i=t.placeholder?color.inverse(t.placeholder[0])+color.dim(t.placeholder.slice(1)):color.inverse(color.hidden("_")),e=this.value?this.valueWithCursor:i;switch(this.state){case"error":return`${n.trim()} ${color.yellow(S_BAR)} ${e} ${color.yellow(S_BAR_END)} ${color.yellow(this.error)} `;case"submit":return`${n}${color.gray(S_BAR)} ${color.dim(this.value||t.placeholder)}`;case"cancel":return`${n}${color.gray(S_BAR)} ${color.strikethrough(color.dim(this.value??""))}${this.value?.trim()?` `+color.gray(S_BAR):""}`;default:return`${n}${color.cyan(S_BAR)} ${e} ${color.cyan(S_BAR_END)} `}}}).prompt(),password=t=>new core.PasswordPrompt({validate:t.validate,mask:t.mask??S_PASSWORD_MASK,render(){const n=`${color.gray(S_BAR)} ${symbol(this.state)} ${t.message} `,i=this.valueWithCursor,e=this.masked;switch(this.state){case"error":return`${n.trim()} ${color.yellow(S_BAR)} ${e} ${color.yellow(S_BAR_END)} ${color.yellow(this.error)} `;case"submit":return`${n}${color.gray(S_BAR)} ${color.dim(e)}`;case"cancel":return`${n}${color.gray(S_BAR)} ${color.strikethrough(color.dim(e??""))}${e?` `+color.gray(S_BAR):""}`;default:return`${n}${color.cyan(S_BAR)} ${i} ${color.cyan(S_BAR_END)} `}}}).prompt(),confirm=t=>{const n=t.active??"Yes",i=t.inactive??"No";return new core.ConfirmPrompt({active:n,inactive:i,initialValue:t.initialValue??!0,render(){const e=`${color.gray(S_BAR)} ${symbol(this.state)} ${t.message} `,r=this.value?n:i;switch(this.state){case"submit":return`${e}${color.gray(S_BAR)} ${color.dim(r)}`;case"cancel":return`${e}${color.gray(S_BAR)} ${color.strikethrough(color.dim(r))} ${color.gray(S_BAR)}`;default:return`${e}${color.cyan(S_BAR)} ${this.value?`${color.green(S_RADIO_ACTIVE)} ${n}`:`${color.dim(S_RADIO_INACTIVE)} ${color.dim(n)}`} ${color.dim("/")} ${this.value?`${color.dim(S_RADIO_INACTIVE)} ${color.dim(i)}`:`${color.green(S_RADIO_ACTIVE)} ${i}`} ${color.cyan(S_BAR_END)} `}}}).prompt()},select=t=>{const n=(e,r)=>{const c=e.label??String(e.value);return r==="active"?`${color.green(S_RADIO_ACTIVE)} ${c} ${e.hint?color.dim(`(${e.hint})`):""}`:r==="selected"?`${color.dim(c)}`:r==="cancelled"?`${color.strikethrough(color.dim(c))}`:`${color.dim(S_RADIO_INACTIVE)} ${color.dim(c)}`};let i=0;return new core.SelectPrompt({options:t.options,initialValue:t.initialValue,render(){const e=`${color.gray(S_BAR)} ${symbol(this.state)} ${t.message} `;switch(this.state){case"submit":return`${e}${color.gray(S_BAR)} ${n(this.options[this.cursor],"selected")}`;case"cancel":return`${e}${color.gray(S_BAR)} ${n(this.options[this.cursor],"cancelled")} ${color.gray(S_BAR)}`;default:{const r=t.maxItems===void 0?1/0:Math.max(t.maxItems,5);this.cursor>=i+r-3?i=Math.max(Math.min(this.cursor-r+3,this.options.length-r),0):this.cursor<i+2&&(i=Math.max(this.cursor-2,0));const c=r<this.options.length&&i>0,a=r<this.options.length&&i+r<this.options.length;return`${e}${color.cyan(S_BAR)} ${this.options.slice(i,i+r).map((l,o,u)=>o===0&&c||o===u.length-1&&a?color.dim("..."):n(l,o+i===this.cursor?"active":"inactive")).join(` ${color.cyan(S_BAR)} `)} ${color.cyan(S_BAR_END)} `}}}}).prompt()},selectKey=t=>{const n=(i,e="inactive")=>{const r=i.label??String(i.value);return e==="selected"?`${color.dim(r)}`:e==="cancelled"?`${color.strikethrough(color.dim(r))}`:e==="active"?`${color.bgCyan(color.gray(` ${i.value} `))} ${r} ${i.hint?color.dim(`(${i.hint})`):""}`:`${color.gray(color.bgWhite(color.inverse(` ${i.value} `)))} ${r} ${i.hint?color.dim(`(${i.hint})`):""}`};return new core.SelectKeyPrompt({options:t.options,initialValue:t.initialValue,render(){const i=`${color.gray(S_BAR)} ${symbol(this.state)} ${t.message} `;switch(this.state){case"submit":return`${i}${color.gray(S_BAR)} ${n(this.options.find(e=>e.value===this.value),"selected")}`;case"cancel":return`${i}${color.gray(S_BAR)} ${n(this.options[0],"cancelled")} ${color.gray(S_BAR)}`;default:return`${i}${color.cyan(S_BAR)} ${this.options.map((e,r)=>n(e,r===this.cursor?"active":"inactive")).join(` ${color.cyan(S_BAR)} `)} ${color.cyan(S_BAR_END)} `}}}).prompt()},multiselect=t=>{const n=(i,e)=>{const r=i.label??String(i.value);return e==="active"?`${color.cyan(S_CHECKBOX_ACTIVE)} ${r} ${i.hint?color.dim(`(${i.hint})`):""}`:e==="selected"?`${color.green(S_CHECKBOX_SELECTED)} ${color.dim(r)}`:e==="cancelled"?`${color.strikethrough(color.dim(r))}`:e==="active-selected"?`${color.green(S_CHECKBOX_SELECTED)} ${r} ${i.hint?color.dim(`(${i.hint})`):""}`:e==="submitted"?`${color.dim(r)}`:`${color.dim(S_CHECKBOX_INACTIVE)} ${color.dim(r)}`};return new core.MultiSelectPrompt({options:t.options,initialValues:t.initialValues,required:t.required??!0,cursorAt:t.cursorAt,validate(i){if(this.required&&i.length===0)return`Please select at least one option. ${color.reset(color.dim(`Press ${color.gray(color.bgWhite(color.inverse(" space ")))} to select, ${color.gray(color.bgWhite(color.inverse(" enter ")))} to submit`))}`},render(){let i=`${color.gray(S_BAR)} ${symbol(this.state)} ${t.message} `;switch(this.state){case"submit":return`${i}${color.gray(S_BAR)} ${this.options.filter(({value:e})=>this.value.includes(e)).map(e=>n(e,"submitted")).join(color.dim(", "))||color.dim("none")}`;case"cancel":{const e=this.options.filter(({value:r})=>this.value.includes(r)).map(r=>n(r,"cancelled")).join(color.dim(", "));return`${i}${color.gray(S_BAR)} ${e.trim()?`${e} ${color.gray(S_BAR)}`:""}`}case"error":{const e=this.error.split(` `).map((r,c)=>c===0?`${color.yellow(S_BAR_END)} ${color.yellow(r)}`:` ${r}`).join(` `);return i+color.yellow(S_BAR)+" "+this.options.map((r,c)=>{const a=this.value.includes(r.value),l=c===this.cursor;return l&&a?n(r,"active-selected"):a?n(r,"selected"):n(r,l?"active":"inactive")}).join(` ${color.yellow(S_BAR)} `)+` `+e+` `}default:return`${i}${color.cyan(S_BAR)} ${this.options.map((e,r)=>{const c=this.value.includes(e.value),a=r===this.cursor;return a&&c?n(e,"active-selected"):c?n(e,"selected"):n(e,a?"active":"inactive")}).join(` ${color.cyan(S_BAR)} `)} ${color.cyan(S_BAR_END)} `}}}).prompt()},groupMultiselect=t=>{const n=(i,e,r=[])=>{const c=i.label??String(i.value),a=typeof i.group=="string",l=a&&(r[r.indexOf(i)+1]??{group:!0}),o=a&&l.group===!0,u=a?`${o?S_BAR_END:S_BAR} `:"";return e==="active"?`${color.dim(u)}${color.cyan(S_CHECKBOX_ACTIVE)} ${c} ${i.hint?color.dim(`(${i.hint})`):""}`:e==="group-active"?`${u}${color.cyan(S_CHECKBOX_ACTIVE)} ${color.dim(c)}`:e==="group-active-selected"?`${u}${color.green(S_CHECKBOX_SELECTED)} ${color.dim(c)}`:e==="selected"?`${color.dim(u)}${color.green(S_CHECKBOX_SELECTED)} ${color.dim(c)}`:e==="cancelled"?`${color.strikethrough(color.dim(c))}`:e==="active-selected"?`${color.dim(u)}${color.green(S_CHECKBOX_SELECTED)} ${c} ${i.hint?color.dim(`(${i.hint})`):""}`:e==="submitted"?`${color.dim(c)}`:`${color.dim(u)}${color.dim(S_CHECKBOX_INACTIVE)} ${color.dim(c)}`};return new core.GroupMultiSelectPrompt({options:t.options,initialValues:t.initialValues,required:t.required??!0,cursorAt:t.cursorAt,validate(i){if(this.required&&i.length===0)return`Please select at least one option. ${color.reset(color.dim(`Press ${color.gray(color.bgWhite(color.inverse(" space ")))} to select, ${color.gray(color.bgWhite(color.inverse(" enter ")))} to submit`))}`},render(){let i=`${color.gray(S_BAR)} ${symbol(this.state)} ${t.message} `;switch(this.state){case"submit":return`${i}${color.gray(S_BAR)} ${this.options.filter(({value:e})=>this.value.includes(e)).map(e=>n(e,"submitted")).join(color.dim(", "))}`;case"cancel":{const e=this.options.filter(({value:r})=>this.value.includes(r)).map(r=>n(r,"cancelled")).join(color.dim(", "));return`${i}${color.gray(S_BAR)} ${e.trim()?`${e} ${color.gray(S_BAR)}`:""}`}case"error":{const e=this.error.split(` `).map((r,c)=>c===0?`${color.yellow(S_BAR_END)} ${color.yellow(r)}`:` ${r}`).join(` `);return`${i}${color.yellow(S_BAR)} ${this.options.map((r,c,a)=>{const l=this.value.includes(r.value)||r.group===!0&&this.isGroupSelected(`${r.value}`),o=c===this.cursor;return!o&&typeof r.group=="string"&&this.options[this.cursor].value===r.group?n(r,l?"group-active-selected":"group-active",a):o&&l?n(r,"active-selected",a):l?n(r,"selected",a):n(r,o?"active":"inactive",a)}).join(` ${color.yellow(S_BAR)} `)} ${e} `}default:return`${i}${color.cyan(S_BAR)} ${this.options.map((e,r,c)=>{const a=this.value.includes(e.value)||e.group===!0&&this.isGroupSelected(`${e.value}`),l=r===this.cursor;return!l&&typeof e.group=="string"&&this.options[this.cursor].value===e.group?n(e,a?"group-active-selected":"group-active",c):l&&a?n(e,"active-selected",c):a?n(e,"selected",c):n(e,l?"active":"inactive",c)}).join(` ${color.cyan(S_BAR)} `)} ${color.cyan(S_BAR_END)} `}}}).prompt()},strip=t=>t.replace(ansiRegex(),""),note=(t="",n="")=>{const i=` ${t} `.split(` `),e=strip(n).length,r=Math.max(i.reduce((a,l)=>(l=strip(l),l.length>a?l.length:a),0),e)+2,c=i.map(a=>`${color.gray(S_BAR)} ${color.dim(a)}${" ".repeat(r-strip(a).length)}${color.gray(S_BAR)}`).join(` `);process.stdout.write(`${color.gray(S_BAR)} ${color.green(S_STEP_SUBMIT)} ${color.reset(n)} ${color.gray(S_BAR_H.repeat(Math.max(r-e-1,1))+S_CORNER_TOP_RIGHT)} ${c} ${color.gray(S_CONNECT_LEFT+S_BAR_H.repeat(r+2)+S_CORNER_BOTTOM_RIGHT)} `)},cancel=(t="")=>{process.stdout.write(`${color.gray(S_BAR_END)} ${color.red(t)} `)},intro=(t="")=>{process.stdout.write(`${color.gray(S_BAR_START)} ${t} `)},outro=(t="")=>{process.stdout.write(`${color.gray(S_BAR)} ${color.gray(S_BAR_END)} ${t} `)},log={message:(t="",{symbol:n=color.gray(S_BAR)}={})=>{const i=[`${color.gray(S_BAR)}`];if(t){const[e,...r]=t.split(` `);i.push(`${n} ${e}`,...r.map(c=>`${color.gray(S_BAR)} ${c}`))}process.stdout.write(`${i.join(` `)} `)},info:t=>{log.message(t,{symbol:color.blue(S_INFO)})},success:t=>{log.message(t,{symbol:color.green(S_SUCCESS)})},step:t=>{log.message(t,{symbol:color.green(S_STEP_SUBMIT)})},warn:t=>{log.message(t,{symbol:color.yellow(S_WARN)})},warning:t=>{log.warn(t)},error:t=>{log.message(t,{symbol:color.red(S_ERROR)})}},spinner=()=>{const t=unicode?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],n=unicode?80:120;let i,e,r=!1,c="";const a=(d="")=>{r=!0,i=core.block(),c=d.replace(/\.+$/,""),process.stdout.write(`${color.gray(S_BAR)} `);let $=0,m=0;e=setInterval(()=>{const h=color.magenta(t[$]),g=".".repeat(Math.floor(m)).slice(0,3);process.stdout.write(sisteransi.cursor.move(-999,0)),process.stdout.write(sisteransi.erase.down(1)),process.stdout.write(`${h} ${c}${g}`),$=$+1<t.length?$+1:0,m=m<t.length?m+.125:0},n)},l=(d="",$=0)=>{c=d??c,r=!1,clearInterval(e);const m=$===0?color.green(S_STEP_SUBMIT):$===1?color.red(S_STEP_CANCEL):color.red(S_STEP_ERROR);process.stdout.write(sisteransi.cursor.move(-999,0)),process.stdout.write(sisteransi.erase.down(1)),process.stdout.write(`${m} ${c} `),i()},o=(d="")=>{c=d??c},u=d=>{const $=d>1?"Something went wrong":"Canceled";r&&l($,d)};return process.on("uncaughtExceptionMonitor",()=>u(2)),process.on("unhandledRejection",()=>u(2)),process.on("SIGINT",()=>u(1)),process.on("SIGTERM",()=>u(1)),process.on("exit",u),{start:a,stop:l,message:o}};function ansiRegex(){const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(t,"g")}const group=async(t,n)=>{const i={},e=Object.keys(t);for(const r of e){const c=t[r],a=await c({results:i})?.catch(l=>{throw l});if(typeof n?.onCancel=="function"&&core.isCancel(a)){i[r]="canceled",n.onCancel({results:i});continue}i[r]=a}return i};exports.isCancel=core.isCancel,exports.cancel=cancel,exports.confirm=confirm,exports.group=group,exports.groupMultiselect=groupMultiselect,exports.intro=intro,exports.log=log,exports.multiselect=multiselect,exports.note=note,exports.outro=outro,exports.password=password,exports.select=select,exports.selectKey=selectKey,exports.spinner=spinner,exports.text=text; node_modules/@clack/prompts/node_modules/is-unicode-supported/license 0000664 00000002135 15114743311 0022211 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/@clack/prompts/node_modules/is-unicode-supported/package.json 0000664 00000001413 15114743311 0023130 0 ustar 00 { "name": "is-unicode-supported", "version": "1.3.0", "description": "Detect whether the terminal supports Unicode", "license": "MIT", "repository": "sindresorhus/is-unicode-supported", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": ">=12" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "terminal", "unicode", "detect", "utf8", "console", "shell", "support", "supports", "supported", "check", "detection" ], "devDependencies": { "ava": "^4.0.1", "tsd": "^0.19.1", "xo": "^0.47.0" } } node_modules/@clack/prompts/node_modules/is-unicode-supported/readme.md 0000664 00000002143 15114743311 0022422 0 ustar 00 # is-unicode-supported > Detect whether the terminal supports Unicode This can be useful to decide whether to use Unicode characters or fallback ASCII characters in command-line output. Note that the check is quite naive. It just assumes all non-Windows terminals support Unicode and hard-codes which Windows terminals that do support Unicode. However, I have been using this logic in some popular packages for years without problems. ## Install ```sh npm install is-unicode-supported ``` ## Usage ```js import isUnicodeSupported from 'is-unicode-supported'; isUnicodeSupported(); //=> true ``` ## API ### isUnicodeSupported() Returns a `boolean` for whether the terminal supports Unicode. ## Related - [is-interactive](https://github.com/sindresorhus/is-interactive) - Check if stdout or stderr is interactive - [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color - [figures](https://github.com/sindresorhus/figures) - Unicode symbols with Windows fallbacks - [log-symbols](https://github.com/sindresorhus/log-symbols) - Colored symbols for various log levels node_modules/@clack/prompts/node_modules/is-unicode-supported/index.d.ts 0000664 00000000326 15114743311 0022545 0 ustar 00 /** Detect whether the terminal supports Unicode. @example ``` import isUnicodeSupported from 'is-unicode-supported'; isUnicodeSupported(); //=> true ``` */ export default function isUnicodeSupported(): boolean; node_modules/@clack/prompts/node_modules/is-unicode-supported/index.js 0000664 00000001213 15114743311 0022305 0 ustar 00 import process from 'node:process'; export default function isUnicodeSupported() { if (process.platform !== 'win32') { return process.env.TERM !== 'linux'; // Linux console (kernel) } return Boolean(process.env.CI) || Boolean(process.env.WT_SESSION) // Windows Terminal || Boolean(process.env.TERMINUS_SUBLIME) // Terminus (<0.2.27) || process.env.ConEmuTask === '{cmd::Cmder}' // ConEmu and cmder || process.env.TERM_PROGRAM === 'Terminus-Sublime' || process.env.TERM_PROGRAM === 'vscode' || process.env.TERM === 'xterm-256color' || process.env.TERM === 'alacritty' || process.env.TERMINAL_EMULATOR === 'JetBrains-JediTerm'; } node_modules/@clack/prompts/CHANGELOG.md 0000664 00000010771 15114743311 0013723 0 ustar 00 # @clack/prompts ## 0.7.0 ### Minor Changes - b27a701: add maxItems option to select prompt - 89371be: added a new method called `spinner.message(msg: string)` ### Patch Changes - 52183c4: Fix `spinner` conflict with terminal on error between `spinner.start()` and `spinner.stop()` - ab51d29: Fixes cases where the note title length was miscalculated due to ansi characters - Updated dependencies [cd79076] - @clack/core@0.3.3 ## 0.6.3 ### Patch Changes - c96eda5: Enable hard line-wrapping behavior for long words without spaces - Updated dependencies [c96eda5] - @clack/core@0.3.2 ## 0.6.2 ### Patch Changes - 58a1df1: Fix line duplication bug by automatically wrapping prompts to `process.stdout.columns` - Updated dependencies [58a1df1] - @clack/core@0.3.1 ## 0.6.1 ### Patch Changes - ca08fb6: Support complex value types for `select`, `multiselect` and `groupMultiselect`. ## 0.6.0 ### Minor Changes - 8a4a12f: add `groupMultiselect` prompt - 165a1b3: Add `log` APIs. Supports `log.info`, `log.success`, `log.warn`, and `log.error`. For low-level control, `log.message` is also exposed. ### Patch Changes - Updated dependencies [8a4a12f] - Updated dependencies [8a4a12f] - @clack/core@0.3.0 ## 0.5.1 ### Patch Changes - cc11917: Update default `password` mask - Updated dependencies [ec812b6] - @clack/core@0.2.1 ## 0.5.0 ### Minor Changes - d74dd05: Adds a `selectKey` prompt type - 54c1bc3: **Breaking Change** `multiselect` has renamed `initialValue` to `initialValues` ### Patch Changes - Updated dependencies [d74dd05] - Updated dependencies [54c1bc3] - @clack/core@0.2.0 ## 0.4.5 ### Patch Changes - 1251132: Multiselect: return `Value[]` instead of `Option[]`. - 8994382: Add a password prompt to `@clack/prompts` - Updated dependencies [1251132] - Updated dependencies [8994382] - @clack/core@0.1.9 ## 0.4.4 ### Patch Changes - d96071c: Don't mutate `initialValue` in `multiselect`, fix parameter type for `validate()`. Credits to @banjo for the bug report and initial PR! - Updated dependencies [d96071c] - @clack/core@0.1.8 ## 0.4.3 ### Patch Changes - 83d890e: Fix text cancel display bug ## 0.4.2 ### Patch Changes - Update README ## 0.4.1 ### Patch Changes - 7fb5375: Adds a new `defaultValue` option to the text prompt, removes automatic usage of the placeholder value. - Updated dependencies [7fb5375] - @clack/core@0.1.6 ## 0.4.0 ### Minor Changes - 61b88b6: Add `group` construct to group many prompts together ### Patch Changes - de1314e: Support `required` option for multi-select - Updated dependencies [de1314e] - @clack/core@0.1.5 ## 0.3.0 ### Minor Changes - 493c592: Improve types for select/multiselect prompts. Numbers and booleans are now supported as the `value` option. - 15558e3: Improved Windows/non-unicode support ### Patch Changes - ca77da1: Fix multiselect initial value logic - Updated dependencies [ca77da1] - Updated dependencies [8aed606] - @clack/core@0.1.4 ## 0.2.2 ### Patch Changes - 94b24d9: Fix CJS `ansi-regex` interop ## 0.2.1 ### Patch Changes - a99c458: Support `initialValue` option for text prompt - Updated dependencies [a99c458] - @clack/core@0.1.3 ## 0.2.0 ### Minor Changes - Improved type safety - b1341d6: Updated styles, new note component ### Patch Changes - Updated dependencies [7dcad8f] - Updated dependencies [2242f13] - Updated dependencies [b1341d6] - @clack/core@0.1.2 ## 0.1.1 ### Patch Changes - fa09bf5: Use circle for radio, square for checkbox - Updated dependencies [4be7dbf] - Updated dependencies [b480679] - @clack/core@0.1.1 ## 0.1.0 ### Minor Changes - 7015ec9: Create new prompt: multi-select ### Patch Changes - Updated dependencies [7015ec9] - @clack/core@0.1.0 ## 0.0.10 ### Patch Changes - e0b49e5: Update spinner so it actually spins ## 0.0.9 ### Patch Changes - Update README ## 0.0.8 ### Patch Changes - Updated dependencies [9d371c3] - @clack/core@0.0.12 ## 0.0.7 ### Patch Changes - Update README ## 0.0.6 ### Patch Changes - d20ef2a: Update keywords, URLs - Updated dependencies [441d5b7] - Updated dependencies [d20ef2a] - Updated dependencies [fe13c2f] - @clack/core@0.0.11 ## 0.0.5 ### Patch Changes - Update README ## 0.0.4 ### Patch Changes - 80404ab: Update README ## 0.0.3 ### Patch Changes - a0cb382: Add `main` entrypoint - Updated dependencies [a0cb382] - @clack/core@0.0.10 ## 0.0.2 ### Patch Changes - Updated dependencies - @clack/core@0.0.9 ## 0.0.1 ### Patch Changes - a4b5e13: Initial release - Updated dependencies [a4b5e13] - @clack/core@0.0.8 node_modules/@clack/prompts/README.md 0000664 00000010042 15114743311 0013360 0 ustar 00 # `@clack/prompts` Effortlessly build beautiful command-line apps 🪄 [Try the demo](https://stackblitz.com/edit/clack-prompts?file=index.js)  --- `@clack/prompts` is an opinionated, pre-styled wrapper around [`@clack/core`](https://www.npmjs.com/package/@clack/core). - 🤏 80% smaller than other options - 💎 Beautiful, minimal UI - ✅ Simple API - 🧱 Comes with `text`, `confirm`, `select`, `multiselect`, and `spinner` components ## Basics ### Setup The `intro` and `outro` functions will print a message to begin or end a prompt session, respectively. ```js import { intro, outro } from '@clack/prompts'; intro(`create-my-app`); // Do stuff outro(`You're all set!`); ``` ### Cancellation The `isCancel` function is a guard that detects when a user cancels a question with `CTRL + C`. You should handle this situation for each prompt, optionally providing a nice cancellation message with the `cancel` utility. ```js import { isCancel, cancel, text } from '@clack/prompts'; const value = await text(/* TODO */); if (isCancel(value)) { cancel('Operation cancelled.'); process.exit(0); } ``` ## Components ### Text The text component accepts a single line of text. ```js import { text } from '@clack/prompts'; const meaning = await text({ message: 'What is the meaning of life?', placeholder: 'Not sure', initialValue: '42', validate(value) { if (value.length === 0) return `Value is required!`; }, }); ``` ### Confirm The confirm component accepts a yes or no answer. The result is a boolean value of `true` or `false`. ```js import { confirm } from '@clack/prompts'; const shouldContinue = await confirm({ message: 'Do you want to continue?', }); ``` ### Select The select component allows a user to choose one value from a list of options. The result is the `value` prop of a given option. ```js import { select } from '@clack/prompts'; const projectType = await select({ message: 'Pick a project type.', options: [ { value: 'ts', label: 'TypeScript' }, { value: 'js', label: 'JavaScript' }, { value: 'coffee', label: 'CoffeeScript', hint: 'oh no' }, ], }); ``` ### Multi-Select The `multiselect` component allows a user to choose many values from a list of options. The result is an array with all selected `value` props. ```js import { multiselect } from '@clack/prompts'; const additionalTools = await multiselect({ message: 'Select additional tools.', options: [ { value: 'eslint', label: 'ESLint', hint: 'recommended' }, { value: 'prettier', label: 'Prettier' }, { value: 'gh-action', label: 'GitHub Action' }, ], required: false, }); ``` ### Spinner The spinner component surfaces a pending action, such as a long-running download or dependency installation. ```js import { spinner } from '@clack/prompts'; const s = spinner(); s.start('Installing via npm'); // Do installation s.stop('Installed via npm'); ``` ## Utilities ### Grouping Grouping prompts together is a great way to keep your code organized. This accepts a JSON object with a name that can be used to reference the group later. The second argument is an optional but has a `onCancel` callback that will be called if the user cancels one of the prompts in the group. ```js import * as p from '@clack/prompts'; const group = await p.group( { name: () => p.text({ message: 'What is your name?' }), age: () => p.text({ message: 'What is your age?' }), color: ({ results }) => p.multiselect({ message: `What is your favorite color ${results.name}?`, options: [ { value: 'red', label: 'Red' }, { value: 'green', label: 'Green' }, { value: 'blue', label: 'Blue' }, ], }), }, { // On Cancel callback that wraps the group // So if the user cancels one of the prompts in the group this function will be called onCancel: ({ results }) => { p.cancel('Operation cancelled.'); process.exit(0); }, } ); console.log(group.name, group.age, group.color); ``` node_modules/@clack/core/package.json 0000664 00000002334 15114743311 0013620 0 ustar 00 { "name": "@clack/core", "version": "0.3.5", "type": "module", "main": "./dist/index.cjs", "module": "./dist/index.mjs", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.cjs" }, "./package.json": "./package.json" }, "types": "./dist/index.d.ts", "repository": { "type": "git", "url": "https://github.com/natemoo-re/clack", "directory": "packages/core" }, "bugs": { "url": "https://github.com/natemoo-re/clack/issues" }, "homepage": "https://github.com/natemoo-re/clack/tree/main/packages/core#readme", "files": [ "dist", "CHANGELOG.md" ], "keywords": [ "ask", "clack", "cli", "command-line", "command", "input", "interact", "interface", "menu", "prompt", "prompts", "stdin", "ui" ], "author": { "name": "Nate Moore", "email": "nate@natemoo.re", "url": "https://twitter.com/n_moore" }, "license": "MIT", "dependencies": { "picocolors": "^1.0.0", "sisteransi": "^1.0.5" }, "devDependencies": { "vitest": "^1.6.0", "wrap-ansi": "^8.1.0" }, "scripts": { "build": "unbuild", "test": "vitest run" } } node_modules/@clack/core/LICENSE 0000664 00000002046 15114743311 0012337 0 ustar 00 MIT License Copyright (c) Nate Moore Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/@clack/core/dist/index.d.mts 0000664 00000010024 15114743311 0014346 0 ustar 00 import { Readable, Writable } from 'node:stream'; declare function isCancel(value: unknown): value is symbol; interface PromptOptions<Self extends Prompt> { render(this: Omit<Self, 'prompt'>): string | void; placeholder?: string; initialValue?: any; validate?: ((value: any) => string | void) | undefined; input?: Readable; output?: Writable; debug?: boolean; } type State = 'initial' | 'active' | 'cancel' | 'submit' | 'error'; declare class Prompt { protected input: Readable; protected output: Writable; private rl; private opts; private _track; private _render; protected _cursor: number; state: State; value: any; error: string; constructor({ render, input, output, ...opts }: PromptOptions<Prompt>, trackValue?: boolean); prompt(): Promise<string | symbol>; private subscribers; on(event: string, cb: (...args: any) => any): void; once(event: string, cb: (...args: any) => any): void; emit(event: string, ...data: any[]): void; private unsubscribe; private onKeypress; protected close(): void; private restoreCursor; private _prevFrame; private render; } interface ConfirmOptions extends PromptOptions<ConfirmPrompt> { active: string; inactive: string; initialValue?: boolean; } declare class ConfirmPrompt extends Prompt { get cursor(): 0 | 1; private get _value(); constructor(opts: ConfirmOptions); } interface GroupMultiSelectOptions<T extends { value: any; }> extends PromptOptions<GroupMultiSelectPrompt<T>> { options: Record<string, T[]>; initialValues?: T['value'][]; required?: boolean; cursorAt?: T['value']; } declare class GroupMultiSelectPrompt<T extends { value: any; }> extends Prompt { options: (T & { group: string | boolean; })[]; cursor: number; getGroupItems(group: string): T[]; isGroupSelected(group: string): boolean; private toggleValue; constructor(opts: GroupMultiSelectOptions<T>); } interface MultiSelectOptions<T extends { value: any; }> extends PromptOptions<MultiSelectPrompt<T>> { options: T[]; initialValues?: T['value'][]; required?: boolean; cursorAt?: T['value']; } declare class MultiSelectPrompt<T extends { value: any; }> extends Prompt { options: T[]; cursor: number; private get _value(); private toggleAll; private toggleValue; constructor(opts: MultiSelectOptions<T>); } interface PasswordOptions extends PromptOptions<PasswordPrompt> { mask?: string; } declare class PasswordPrompt extends Prompt { valueWithCursor: string; private _mask; get cursor(): number; get masked(): any; constructor({ mask, ...opts }: PasswordOptions); } interface SelectOptions<T extends { value: any; }> extends PromptOptions<SelectPrompt<T>> { options: T[]; initialValue?: T['value']; } declare class SelectPrompt<T extends { value: any; }> extends Prompt { options: T[]; cursor: number; private get _value(); private changeValue; constructor(opts: SelectOptions<T>); } interface SelectKeyOptions<T extends { value: any; }> extends PromptOptions<SelectKeyPrompt<T>> { options: T[]; } declare class SelectKeyPrompt<T extends { value: any; }> extends Prompt { options: T[]; cursor: number; constructor(opts: SelectKeyOptions<T>); } interface TextOptions extends PromptOptions<TextPrompt> { placeholder?: string; defaultValue?: string; } declare class TextPrompt extends Prompt { valueWithCursor: string; get cursor(): number; constructor(opts: TextOptions); } declare function block({ input, output, overwrite, hideCursor, }?: { input?: (NodeJS.ReadStream & { fd: 0; }) | undefined; output?: (NodeJS.WriteStream & { fd: 1; }) | undefined; overwrite?: boolean | undefined; hideCursor?: boolean | undefined; }): () => void; export { ConfirmPrompt, GroupMultiSelectPrompt, MultiSelectPrompt, PasswordPrompt, Prompt, SelectKeyPrompt, SelectPrompt, type State, TextPrompt, block, isCancel }; node_modules/@clack/core/dist/index.mjs.map 0000664 00000262065 15114743311 0014704 0 ustar 00 {"version":3,"file":"index.mjs","sources":["../../../node_modules/.pnpm/ansi-regex@6.1.0/node_modules/ansi-regex/index.js","../../../node_modules/.pnpm/strip-ansi@7.1.0/node_modules/strip-ansi/index.js","../../../node_modules/.pnpm/eastasianwidth@0.2.0/node_modules/eastasianwidth/eastasianwidth.js","../../../node_modules/.pnpm/emoji-regex@9.2.2/node_modules/emoji-regex/index.js","../../../node_modules/.pnpm/string-width@5.1.2/node_modules/string-width/index.js","../../../node_modules/.pnpm/ansi-styles@6.2.1/node_modules/ansi-styles/index.js","../../../node_modules/.pnpm/wrap-ansi@8.1.0/node_modules/wrap-ansi/index.js","../src/prompts/prompt.ts","../src/prompts/confirm.ts","../src/prompts/group-multiselect.ts","../src/prompts/multi-select.ts","../src/prompts/password.ts","../src/prompts/select.ts","../src/prompts/select-key.ts","../src/prompts/text.ts","../src/utils.ts"],"sourcesContent":["export default function ansiRegex({onlyFirst = false} = {}) {\n\t// Valid string terminator sequences are BEL, ESC\\, and 0x9c\n\tconst ST = '(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)';\n\tconst pattern = [\n\t\t`[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?${ST})`,\n\t\t'(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]))',\n\t].join('|');\n\n\treturn new RegExp(pattern, onlyFirst ? undefined : 'g');\n}\n","import ansiRegex from 'ansi-regex';\n\nconst regex = ansiRegex();\n\nexport default function stripAnsi(string) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof string}\\``);\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn string.replace(regex, '');\n}\n","var eaw = {};\n\nif ('undefined' == typeof module) {\n window.eastasianwidth = eaw;\n} else {\n module.exports = eaw;\n}\n\neaw.eastAsianWidth = function(character) {\n var x = character.charCodeAt(0);\n var y = (character.length == 2) ? character.charCodeAt(1) : 0;\n var codePoint = x;\n if ((0xD800 <= x && x <= 0xDBFF) && (0xDC00 <= y && y <= 0xDFFF)) {\n x &= 0x3FF;\n y &= 0x3FF;\n codePoint = (x << 10) | y;\n codePoint += 0x10000;\n }\n\n if ((0x3000 == codePoint) ||\n (0xFF01 <= codePoint && codePoint <= 0xFF60) ||\n (0xFFE0 <= codePoint && codePoint <= 0xFFE6)) {\n return 'F';\n }\n if ((0x20A9 == codePoint) ||\n (0xFF61 <= codePoint && codePoint <= 0xFFBE) ||\n (0xFFC2 <= codePoint && codePoint <= 0xFFC7) ||\n (0xFFCA <= codePoint && codePoint <= 0xFFCF) ||\n (0xFFD2 <= codePoint && codePoint <= 0xFFD7) ||\n (0xFFDA <= codePoint && codePoint <= 0xFFDC) ||\n (0xFFE8 <= codePoint && codePoint <= 0xFFEE)) {\n return 'H';\n }\n if ((0x1100 <= codePoint && codePoint <= 0x115F) ||\n (0x11A3 <= codePoint && codePoint <= 0x11A7) ||\n (0x11FA <= codePoint && codePoint <= 0x11FF) ||\n (0x2329 <= codePoint && codePoint <= 0x232A) ||\n (0x2E80 <= codePoint && codePoint <= 0x2E99) ||\n (0x2E9B <= codePoint && codePoint <= 0x2EF3) ||\n (0x2F00 <= codePoint && codePoint <= 0x2FD5) ||\n (0x2FF0 <= codePoint && codePoint <= 0x2FFB) ||\n (0x3001 <= codePoint && codePoint <= 0x303E) ||\n (0x3041 <= codePoint && codePoint <= 0x3096) ||\n (0x3099 <= codePoint && codePoint <= 0x30FF) ||\n (0x3105 <= codePoint && codePoint <= 0x312D) ||\n (0x3131 <= codePoint && codePoint <= 0x318E) ||\n (0x3190 <= codePoint && codePoint <= 0x31BA) ||\n (0x31C0 <= codePoint && codePoint <= 0x31E3) ||\n (0x31F0 <= codePoint && codePoint <= 0x321E) ||\n (0x3220 <= codePoint && codePoint <= 0x3247) ||\n (0x3250 <= codePoint && codePoint <= 0x32FE) ||\n (0x3300 <= codePoint && codePoint <= 0x4DBF) ||\n (0x4E00 <= codePoint && codePoint <= 0xA48C) ||\n (0xA490 <= codePoint && codePoint <= 0xA4C6) ||\n (0xA960 <= codePoint && codePoint <= 0xA97C) ||\n (0xAC00 <= codePoint && codePoint <= 0xD7A3) ||\n (0xD7B0 <= codePoint && codePoint <= 0xD7C6) ||\n (0xD7CB <= codePoint && codePoint <= 0xD7FB) ||\n (0xF900 <= codePoint && codePoint <= 0xFAFF) ||\n (0xFE10 <= codePoint && codePoint <= 0xFE19) ||\n (0xFE30 <= codePoint && codePoint <= 0xFE52) ||\n (0xFE54 <= codePoint && codePoint <= 0xFE66) ||\n (0xFE68 <= codePoint && codePoint <= 0xFE6B) ||\n (0x1B000 <= codePoint && codePoint <= 0x1B001) ||\n (0x1F200 <= codePoint && codePoint <= 0x1F202) ||\n (0x1F210 <= codePoint && codePoint <= 0x1F23A) ||\n (0x1F240 <= codePoint && codePoint <= 0x1F248) ||\n (0x1F250 <= codePoint && codePoint <= 0x1F251) ||\n (0x20000 <= codePoint && codePoint <= 0x2F73F) ||\n (0x2B740 <= codePoint && codePoint <= 0x2FFFD) ||\n (0x30000 <= codePoint && codePoint <= 0x3FFFD)) {\n return 'W';\n }\n if ((0x0020 <= codePoint && codePoint <= 0x007E) ||\n (0x00A2 <= codePoint && codePoint <= 0x00A3) ||\n (0x00A5 <= codePoint && codePoint <= 0x00A6) ||\n (0x00AC == codePoint) ||\n (0x00AF == codePoint) ||\n (0x27E6 <= codePoint && codePoint <= 0x27ED) ||\n (0x2985 <= codePoint && codePoint <= 0x2986)) {\n return 'Na';\n }\n if ((0x00A1 == codePoint) ||\n (0x00A4 == codePoint) ||\n (0x00A7 <= codePoint && codePoint <= 0x00A8) ||\n (0x00AA == codePoint) ||\n (0x00AD <= codePoint && codePoint <= 0x00AE) ||\n (0x00B0 <= codePoint && codePoint <= 0x00B4) ||\n (0x00B6 <= codePoint && codePoint <= 0x00BA) ||\n (0x00BC <= codePoint && codePoint <= 0x00BF) ||\n (0x00C6 == codePoint) ||\n (0x00D0 == codePoint) ||\n (0x00D7 <= codePoint && codePoint <= 0x00D8) ||\n (0x00DE <= codePoint && codePoint <= 0x00E1) ||\n (0x00E6 == codePoint) ||\n (0x00E8 <= codePoint && codePoint <= 0x00EA) ||\n (0x00EC <= codePoint && codePoint <= 0x00ED) ||\n (0x00F0 == codePoint) ||\n (0x00F2 <= codePoint && codePoint <= 0x00F3) ||\n (0x00F7 <= codePoint && codePoint <= 0x00FA) ||\n (0x00FC == codePoint) ||\n (0x00FE == codePoint) ||\n (0x0101 == codePoint) ||\n (0x0111 == codePoint) ||\n (0x0113 == codePoint) ||\n (0x011B == codePoint) ||\n (0x0126 <= codePoint && codePoint <= 0x0127) ||\n (0x012B == codePoint) ||\n (0x0131 <= codePoint && codePoint <= 0x0133) ||\n (0x0138 == codePoint) ||\n (0x013F <= codePoint && codePoint <= 0x0142) ||\n (0x0144 == codePoint) ||\n (0x0148 <= codePoint && codePoint <= 0x014B) ||\n (0x014D == codePoint) ||\n (0x0152 <= codePoint && codePoint <= 0x0153) ||\n (0x0166 <= codePoint && codePoint <= 0x0167) ||\n (0x016B == codePoint) ||\n (0x01CE == codePoint) ||\n (0x01D0 == codePoint) ||\n (0x01D2 == codePoint) ||\n (0x01D4 == codePoint) ||\n (0x01D6 == codePoint) ||\n (0x01D8 == codePoint) ||\n (0x01DA == codePoint) ||\n (0x01DC == codePoint) ||\n (0x0251 == codePoint) ||\n (0x0261 == codePoint) ||\n (0x02C4 == codePoint) ||\n (0x02C7 == codePoint) ||\n (0x02C9 <= codePoint && codePoint <= 0x02CB) ||\n (0x02CD == codePoint) ||\n (0x02D0 == codePoint) ||\n (0x02D8 <= codePoint && codePoint <= 0x02DB) ||\n (0x02DD == codePoint) ||\n (0x02DF == codePoint) ||\n (0x0300 <= codePoint && codePoint <= 0x036F) ||\n (0x0391 <= codePoint && codePoint <= 0x03A1) ||\n (0x03A3 <= codePoint && codePoint <= 0x03A9) ||\n (0x03B1 <= codePoint && codePoint <= 0x03C1) ||\n (0x03C3 <= codePoint && codePoint <= 0x03C9) ||\n (0x0401 == codePoint) ||\n (0x0410 <= codePoint && codePoint <= 0x044F) ||\n (0x0451 == codePoint) ||\n (0x2010 == codePoint) ||\n (0x2013 <= codePoint && codePoint <= 0x2016) ||\n (0x2018 <= codePoint && codePoint <= 0x2019) ||\n (0x201C <= codePoint && codePoint <= 0x201D) ||\n (0x2020 <= codePoint && codePoint <= 0x2022) ||\n (0x2024 <= codePoint && codePoint <= 0x2027) ||\n (0x2030 == codePoint) ||\n (0x2032 <= codePoint && codePoint <= 0x2033) ||\n (0x2035 == codePoint) ||\n (0x203B == codePoint) ||\n (0x203E == codePoint) ||\n (0x2074 == codePoint) ||\n (0x207F == codePoint) ||\n (0x2081 <= codePoint && codePoint <= 0x2084) ||\n (0x20AC == codePoint) ||\n (0x2103 == codePoint) ||\n (0x2105 == codePoint) ||\n (0x2109 == codePoint) ||\n (0x2113 == codePoint) ||\n (0x2116 == codePoint) ||\n (0x2121 <= codePoint && codePoint <= 0x2122) ||\n (0x2126 == codePoint) ||\n (0x212B == codePoint) ||\n (0x2153 <= codePoint && codePoint <= 0x2154) ||\n (0x215B <= codePoint && codePoint <= 0x215E) ||\n (0x2160 <= codePoint && codePoint <= 0x216B) ||\n (0x2170 <= codePoint && codePoint <= 0x2179) ||\n (0x2189 == codePoint) ||\n (0x2190 <= codePoint && codePoint <= 0x2199) ||\n (0x21B8 <= codePoint && codePoint <= 0x21B9) ||\n (0x21D2 == codePoint) ||\n (0x21D4 == codePoint) ||\n (0x21E7 == codePoint) ||\n (0x2200 == codePoint) ||\n (0x2202 <= codePoint && codePoint <= 0x2203) ||\n (0x2207 <= codePoint && codePoint <= 0x2208) ||\n (0x220B == codePoint) ||\n (0x220F == codePoint) ||\n (0x2211 == codePoint) ||\n (0x2215 == codePoint) ||\n (0x221A == codePoint) ||\n (0x221D <= codePoint && codePoint <= 0x2220) ||\n (0x2223 == codePoint) ||\n (0x2225 == codePoint) ||\n (0x2227 <= codePoint && codePoint <= 0x222C) ||\n (0x222E == codePoint) ||\n (0x2234 <= codePoint && codePoint <= 0x2237) ||\n (0x223C <= codePoint && codePoint <= 0x223D) ||\n (0x2248 == codePoint) ||\n (0x224C == codePoint) ||\n (0x2252 == codePoint) ||\n (0x2260 <= codePoint && codePoint <= 0x2261) ||\n (0x2264 <= codePoint && codePoint <= 0x2267) ||\n (0x226A <= codePoint && codePoint <= 0x226B) ||\n (0x226E <= codePoint && codePoint <= 0x226F) ||\n (0x2282 <= codePoint && codePoint <= 0x2283) ||\n (0x2286 <= codePoint && codePoint <= 0x2287) ||\n (0x2295 == codePoint) ||\n (0x2299 == codePoint) ||\n (0x22A5 == codePoint) ||\n (0x22BF == codePoint) ||\n (0x2312 == codePoint) ||\n (0x2460 <= codePoint && codePoint <= 0x24E9) ||\n (0x24EB <= codePoint && codePoint <= 0x254B) ||\n (0x2550 <= codePoint && codePoint <= 0x2573) ||\n (0x2580 <= codePoint && codePoint <= 0x258F) ||\n (0x2592 <= codePoint && codePoint <= 0x2595) ||\n (0x25A0 <= codePoint && codePoint <= 0x25A1) ||\n (0x25A3 <= codePoint && codePoint <= 0x25A9) ||\n (0x25B2 <= codePoint && codePoint <= 0x25B3) ||\n (0x25B6 <= codePoint && codePoint <= 0x25B7) ||\n (0x25BC <= codePoint && codePoint <= 0x25BD) ||\n (0x25C0 <= codePoint && codePoint <= 0x25C1) ||\n (0x25C6 <= codePoint && codePoint <= 0x25C8) ||\n (0x25CB == codePoint) ||\n (0x25CE <= codePoint && codePoint <= 0x25D1) ||\n (0x25E2 <= codePoint && codePoint <= 0x25E5) ||\n (0x25EF == codePoint) ||\n (0x2605 <= codePoint && codePoint <= 0x2606) ||\n (0x2609 == codePoint) ||\n (0x260E <= codePoint && codePoint <= 0x260F) ||\n (0x2614 <= codePoint && codePoint <= 0x2615) ||\n (0x261C == codePoint) ||\n (0x261E == codePoint) ||\n (0x2640 == codePoint) ||\n (0x2642 == codePoint) ||\n (0x2660 <= codePoint && codePoint <= 0x2661) ||\n (0x2663 <= codePoint && codePoint <= 0x2665) ||\n (0x2667 <= codePoint && codePoint <= 0x266A) ||\n (0x266C <= codePoint && codePoint <= 0x266D) ||\n (0x266F == codePoint) ||\n (0x269E <= codePoint && codePoint <= 0x269F) ||\n (0x26BE <= codePoint && codePoint <= 0x26BF) ||\n (0x26C4 <= codePoint && codePoint <= 0x26CD) ||\n (0x26CF <= codePoint && codePoint <= 0x26E1) ||\n (0x26E3 == codePoint) ||\n (0x26E8 <= codePoint && codePoint <= 0x26FF) ||\n (0x273D == codePoint) ||\n (0x2757 == codePoint) ||\n (0x2776 <= codePoint && codePoint <= 0x277F) ||\n (0x2B55 <= codePoint && codePoint <= 0x2B59) ||\n (0x3248 <= codePoint && codePoint <= 0x324F) ||\n (0xE000 <= codePoint && codePoint <= 0xF8FF) ||\n (0xFE00 <= codePoint && codePoint <= 0xFE0F) ||\n (0xFFFD == codePoint) ||\n (0x1F100 <= codePoint && codePoint <= 0x1F10A) ||\n (0x1F110 <= codePoint && codePoint <= 0x1F12D) ||\n (0x1F130 <= codePoint && codePoint <= 0x1F169) ||\n (0x1F170 <= codePoint && codePoint <= 0x1F19A) ||\n (0xE0100 <= codePoint && codePoint <= 0xE01EF) ||\n (0xF0000 <= codePoint && codePoint <= 0xFFFFD) ||\n (0x100000 <= codePoint && codePoint <= 0x10FFFD)) {\n return 'A';\n }\n\n return 'N';\n};\n\neaw.characterLength = function(character) {\n var code = this.eastAsianWidth(character);\n if (code == 'F' || code == 'W' || code == 'A') {\n return 2;\n } else {\n return 1;\n }\n};\n\n// Split a string considering surrogate-pairs.\nfunction stringToArray(string) {\n return string.match(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[^\\uD800-\\uDFFF]/g) || [];\n}\n\neaw.length = function(string) {\n var characters = stringToArray(string);\n var len = 0;\n for (var i = 0; i < characters.length; i++) {\n len = len + this.characterLength(characters[i]);\n }\n return len;\n};\n\neaw.slice = function(text, start, end) {\n textLen = eaw.length(text)\n start = start ? start : 0;\n end = end ? end : 1;\n if (start < 0) {\n start = textLen + start;\n }\n if (end < 0) {\n end = textLen + end;\n }\n var result = '';\n var eawLen = 0;\n var chars = stringToArray(text);\n for (var i = 0; i < chars.length; i++) {\n var char = chars[i];\n var charLen = eaw.length(char);\n if (eawLen >= start - (charLen == 2 ? 1 : 0)) {\n if (eawLen + charLen <= end) {\n result += char;\n } else {\n break;\n }\n }\n eawLen += charLen;\n }\n return result;\n};\n","\"use strict\";\n\nmodule.exports = function () {\n // https://mths.be/emoji\n return /\\uD83C\\uDFF4\\uDB40\\uDC67\\uDB40\\uDC62(?:\\uDB40\\uDC77\\uDB40\\uDC6C\\uDB40\\uDC73|\\uDB40\\uDC73\\uDB40\\uDC63\\uDB40\\uDC74|\\uDB40\\uDC65\\uDB40\\uDC6E\\uDB40\\uDC67)\\uDB40\\uDC7F|(?:\\uD83E\\uDDD1\\uD83C\\uDFFF\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFF\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB-\\uDFFE])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFE\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFE\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFD\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFD\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFC\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFC\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFB\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFB\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFC-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C\\uDFFB(?:\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF]))|\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFC-\\uDFFF])|[\\u2695\\u2696\\u2708]\\uFE0F|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD]))?|(?:\\uD83C[\\uDFFC-\\uDFFF])\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF]))|\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83D\\uDC68|(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]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u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])\\uFE0F|\\u200D(?:(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83D[\\uDC66\\uDC67])|\\uD83C\\uDFFF|\\uD83C\\uDFFE|\\uD83C\\uDFFD|\\uD83C\\uDFFC)?|(?:\\uD83D\\uDC69(?:\\uD83C\\uDFFB\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69])|(?:\\uD83C[\\uDFFC-\\uDFFF])\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69]))|\\uD83E\\uDDD1(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1)(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC69(?:\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFF\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\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\\uFE0F\\u200D\\uD83D\\uDDE8|\\uD83E\\uDDD1(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])|\\uD83D\\uDC69(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])|\\uD83D\\uDE36\\u200D\\uD83C\\uDF2B|\\uD83C\\uDFF3\\uFE0F\\u200D\\u26A7|\\uD83D\\uDC3B\\u200D\\u2744|(?:(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC70\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD35\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD-\\uDDCF\\uDDD4\\uDDD6-\\uDDDD])(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC6F|\\uD83E[\\uDD3C\\uDDDE\\uDDDF])\\u200D[\\u2640\\u2642]|(?:\\u26F9|\\uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)(?:\\uFE0F|\\uD83C[\\uDFFB-\\uDFFF])\\u200D[\\u2640\\u2642]|\\uD83C\\uDFF4\\u200D\\u2620|(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC70\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD35\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD-\\uDDCF\\uDDD4\\uDDD6-\\uDDDD])\\u200D[\\u2640\\u2642]|[\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u2328\\u23CF\\u23ED-\\u23EF\\u23F1\\u23F2\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB\\u25FC\\u2600-\\u2604\\u260E\\u2611\\u2618\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u2692\\u2694-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A7\\u26B0\\u26B1\\u26C8\\u26CF\\u26D1\\u26D3\\u26E9\\u26F0\\u26F1\\u26F4\\u26F7\\u26F8\\u2702\\u2708\\u2709\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2733\\u2734\\u2744\\u2747\\u2763\\u27A1\\u2934\\u2935\\u2B05-\\u2B07\\u3030\\u303D\\u3297\\u3299]|\\uD83C[\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDE02\\uDE37\\uDF21\\uDF24-\\uDF2C\\uDF36\\uDF7D\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E\\uDF9F\\uDFCD\\uDFCE\\uDFD4-\\uDFDF\\uDFF5\\uDFF7]|\\uD83D[\\uDC3F\\uDCFD\\uDD49\\uDD4A\\uDD6F\\uDD70\\uDD73\\uDD76-\\uDD79\\uDD87\\uDD8A-\\uDD8D\\uDDA5\\uDD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\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6]|(?:[\\u231A\\u231B\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u25FE\\u2614\\u2615\\u2648-\\u2653\\u267F\\u2693\\u26A1\\u26AA\\u26AB\\u26BD\\u26BE\\u26C4\\u26C5\\u26CE\\u26D4\\u26EA\\u26F2\\u26F3\\u26F5\\u26FA\\u26FD\\u2705\\u270A\\u270B\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2795-\\u2797\\u27B0\\u27BF\\u2B1B\\u2B1C\\u2B50\\u2B55]|\\uD83C[\\uDC04\\uDCCF\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE1A\\uDE2F\\uDE32-\\uDE36\\uDE38-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF20\\uDF2D-\\uDF35\\uDF37-\\uDF7C\\uDF7E-\\uDF93\\uDFA0-\\uDFCA\\uDFCF-\\uDFD3\\uDFE0-\\uDFF0\\uDFF4\\uDFF8-\\uDFFF]|\\uD83D[\\uDC00-\\uDC3E\\uDC40\\uDC42-\\uDCFC\\uDCFF-\\uDD3D\\uDD4B-\\uDD4E\\uDD50-\\uDD67\\uDD7A\\uDD95\\uDD96\\uDDA4\\uDDFB-\\uDE4F\\uDE80-\\uDEC5\\uDECC\\uDED0-\\uDED2\\uDED5-\\uDED7\\uDEEB\\uDEEC\\uDEF4-\\uDEFC\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0C-\\uDD3A\\uDD3C-\\uDD45\\uDD47-\\uDD78\\uDD7A-\\uDDCB\\uDDCD-\\uDDFF\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6])|(?:[#\\*0-9\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23E9-\\u23F3\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB-\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u261D\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A1\\u26A7\\u26AA\\u26AB\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C5\\u26C8\\u26CE\\u26CF\\u26D1\\u26D3\\u26D4\\u26E9\\u26EA\\u26F0-\\u26F5\\u26F7-\\u26FA\\u26FD\\u2702\\u2705\\u2708-\\u270D\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2728\\u2733\\u2734\\u2744\\u2747\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2763\\u2764\\u2795-\\u2797\\u27A1\\u27B0\\u27BF\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B50\\u2B55\\u3030\\u303D\\u3297\\u3299]|\\uD83C[\\uDC04\\uDCCF\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE02\\uDE1A\\uDE2F\\uDE32-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF21\\uDF24-\\uDF93\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E-\\uDFF0\\uDFF3-\\uDFF5\\uDFF7-\\uDFFF]|\\uD83D[\\uDC00-\\uDCFD\\uDCFF-\\uDD3D\\uDD49-\\uDD4E\\uDD50-\\uDD67\\uDD6F\\uDD70\\uDD73-\\uDD7A\\uDD87\\uDD8A-\\uDD8D\\uDD90\\uDD95\\uDD96\\uDDA4\\uDDA5\\uDDA8\\uDDB1\\uDDB2\\uDDBC\\uDDC2-\\uDDC4\\uDDD1-\\uDDD3\\uDDDC-\\uDDDE\\uDDE1\\uDDE3\\uDDE8\\uDDEF\\uDDF3\\uDDFA-\\uDE4F\\uDE80-\\uDEC5\\uDECB-\\uDED2\\uDED5-\\uDED7\\uDEE0-\\uDEE5\\uDEE9\\uDEEB\\uDEEC\\uDEF0\\uDEF3-\\uDEFC\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0C-\\uDD3A\\uDD3C-\\uDD45\\uDD47-\\uDD78\\uDD7A-\\uDDCB\\uDDCD-\\uDDFF\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6])\\uFE0F|(?:[\\u261D\\u26F9\\u270A-\\u270D]|\\uD83C[\\uDF85\\uDFC2-\\uDFC4\\uDFC7\\uDFCA-\\uDFCC]|\\uD83D[\\uDC42\\uDC43\\uDC46-\\uDC50\\uDC66-\\uDC78\\uDC7C\\uDC81-\\uDC83\\uDC85-\\uDC87\\uDC8F\\uDC91\\uDCAA\\uDD74\\uDD75\\uDD7A\\uDD90\\uDD95\\uDD96\\uDE45-\\uDE47\\uDE4B-\\uDE4F\\uDEA3\\uDEB4-\\uDEB6\\uDEC0\\uDECC]|\\uD83E[\\uDD0C\\uDD0F\\uDD18-\\uDD1F\\uDD26\\uDD30-\\uDD39\\uDD3C-\\uDD3E\\uDD77\\uDDB5\\uDDB6\\uDDB8\\uDDB9\\uDDBB\\uDDCD-\\uDDCF\\uDDD1-\\uDDDD])/g;\n};\n","import stripAnsi from 'strip-ansi';\nimport eastAsianWidth from 'eastasianwidth';\nimport emojiRegex from 'emoji-regex';\n\nexport default function stringWidth(string, options = {}) {\n\tif (typeof string !== 'string' || string.length === 0) {\n\t\treturn 0;\n\t}\n\n\toptions = {\n\t\tambiguousIsNarrow: true,\n\t\t...options\n\t};\n\n\tstring = stripAnsi(string);\n\n\tif (string.length === 0) {\n\t\treturn 0;\n\t}\n\n\tstring = string.replace(emojiRegex(), ' ');\n\n\tconst ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2;\n\tlet width = 0;\n\n\tfor (const character of string) {\n\t\tconst codePoint = character.codePointAt(0);\n\n\t\t// Ignore control characters\n\t\tif (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore combining characters\n\t\tif (codePoint >= 0x300 && codePoint <= 0x36F) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst code = eastAsianWidth.eastAsianWidth(character);\n\t\tswitch (code) {\n\t\t\tcase 'F':\n\t\t\tcase 'W':\n\t\t\t\twidth += 2;\n\t\t\t\tbreak;\n\t\t\tcase 'A':\n\t\t\t\twidth += ambiguousCharacterWidth;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\twidth += 1;\n\t\t}\n\t}\n\n\treturn width;\n}\n","const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue: (red, green, blue) => {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue: hex => {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue: code => {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n","import stringWidth from 'string-width';\nimport stripAnsi from 'strip-ansi';\nimport ansiStyles from 'ansi-styles';\n\nconst ESCAPES = new Set([\n\t'\\u001B',\n\t'\\u009B',\n]);\n\nconst END_CODE = 39;\nconst ANSI_ESCAPE_BELL = '\\u0007';\nconst ANSI_CSI = '[';\nconst ANSI_OSC = ']';\nconst ANSI_SGR_TERMINATOR = 'm';\nconst ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;\n\nconst wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;\nconst wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`;\n\n// Calculate the length of words split on ' ', ignoring\n// the extra characters added by ansi escape codes\nconst wordLengths = string => string.split(' ').map(character => stringWidth(character));\n\n// Wrap a long word across multiple rows\n// Ansi escape codes do not count towards length\nconst wrapWord = (rows, word, columns) => {\n\tconst characters = [...word];\n\n\tlet isInsideEscape = false;\n\tlet isInsideLinkEscape = false;\n\tlet visible = stringWidth(stripAnsi(rows[rows.length - 1]));\n\n\tfor (const [index, character] of characters.entries()) {\n\t\tconst characterLength = stringWidth(character);\n\n\t\tif (visible + characterLength <= columns) {\n\t\t\trows[rows.length - 1] += character;\n\t\t} else {\n\t\t\trows.push(character);\n\t\t\tvisible = 0;\n\t\t}\n\n\t\tif (ESCAPES.has(character)) {\n\t\t\tisInsideEscape = true;\n\t\t\tisInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK);\n\t\t}\n\n\t\tif (isInsideEscape) {\n\t\t\tif (isInsideLinkEscape) {\n\t\t\t\tif (character === ANSI_ESCAPE_BELL) {\n\t\t\t\t\tisInsideEscape = false;\n\t\t\t\t\tisInsideLinkEscape = false;\n\t\t\t\t}\n\t\t\t} else if (character === ANSI_SGR_TERMINATOR) {\n\t\t\t\tisInsideEscape = false;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tvisible += characterLength;\n\n\t\tif (visible === columns && index < characters.length - 1) {\n\t\t\trows.push('');\n\t\t\tvisible = 0;\n\t\t}\n\t}\n\n\t// It's possible that the last row we copy over is only\n\t// ansi escape characters, handle this edge-case\n\tif (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {\n\t\trows[rows.length - 2] += rows.pop();\n\t}\n};\n\n// Trims spaces from a string ignoring invisible sequences\nconst stringVisibleTrimSpacesRight = string => {\n\tconst words = string.split(' ');\n\tlet last = words.length;\n\n\twhile (last > 0) {\n\t\tif (stringWidth(words[last - 1]) > 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlast--;\n\t}\n\n\tif (last === words.length) {\n\t\treturn string;\n\t}\n\n\treturn words.slice(0, last).join(' ') + words.slice(last).join('');\n};\n\n// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode\n//\n// 'hard' will never allow a string to take up more than columns characters\n//\n// 'soft' allows long words to expand past the column length\nconst exec = (string, columns, options = {}) => {\n\tif (options.trim !== false && string.trim() === '') {\n\t\treturn '';\n\t}\n\n\tlet returnValue = '';\n\tlet escapeCode;\n\tlet escapeUrl;\n\n\tconst lengths = wordLengths(string);\n\tlet rows = [''];\n\n\tfor (const [index, word] of string.split(' ').entries()) {\n\t\tif (options.trim !== false) {\n\t\t\trows[rows.length - 1] = rows[rows.length - 1].trimStart();\n\t\t}\n\n\t\tlet rowLength = stringWidth(rows[rows.length - 1]);\n\n\t\tif (index !== 0) {\n\t\t\tif (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {\n\t\t\t\t// If we start with a new word but the current row length equals the length of the columns, add a new row\n\t\t\t\trows.push('');\n\t\t\t\trowLength = 0;\n\t\t\t}\n\n\t\t\tif (rowLength > 0 || options.trim === false) {\n\t\t\t\trows[rows.length - 1] += ' ';\n\t\t\t\trowLength++;\n\t\t\t}\n\t\t}\n\n\t\t// In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns'\n\t\tif (options.hard && lengths[index] > columns) {\n\t\t\tconst remainingColumns = (columns - rowLength);\n\t\t\tconst breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);\n\t\t\tconst breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);\n\t\t\tif (breaksStartingNextLine < breaksStartingThisLine) {\n\t\t\t\trows.push('');\n\t\t\t}\n\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {\n\t\t\tif (options.wordWrap === false && rowLength < columns) {\n\t\t\t\twrapWord(rows, word, columns);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\trows.push('');\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && options.wordWrap === false) {\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\trows[rows.length - 1] += word;\n\t}\n\n\tif (options.trim !== false) {\n\t\trows = rows.map(row => stringVisibleTrimSpacesRight(row));\n\t}\n\n\tconst pre = [...rows.join('\\n')];\n\n\tfor (const [index, character] of pre.entries()) {\n\t\treturnValue += character;\n\n\t\tif (ESCAPES.has(character)) {\n\t\t\tconst {groups} = new RegExp(`(?:\\\\${ANSI_CSI}(?<code>\\\\d+)m|\\\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}};\n\t\t\tif (groups.code !== undefined) {\n\t\t\t\tconst code = Number.parseFloat(groups.code);\n\t\t\t\tescapeCode = code === END_CODE ? undefined : code;\n\t\t\t} else if (groups.uri !== undefined) {\n\t\t\t\tescapeUrl = groups.uri.length === 0 ? undefined : groups.uri;\n\t\t\t}\n\t\t}\n\n\t\tconst code = ansiStyles.codes.get(Number(escapeCode));\n\n\t\tif (pre[index + 1] === '\\n') {\n\t\t\tif (escapeUrl) {\n\t\t\t\treturnValue += wrapAnsiHyperlink('');\n\t\t\t}\n\n\t\t\tif (escapeCode && code) {\n\t\t\t\treturnValue += wrapAnsiCode(code);\n\t\t\t}\n\t\t} else if (character === '\\n') {\n\t\t\tif (escapeCode && code) {\n\t\t\t\treturnValue += wrapAnsiCode(escapeCode);\n\t\t\t}\n\n\t\t\tif (escapeUrl) {\n\t\t\t\treturnValue += wrapAnsiHyperlink(escapeUrl);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn returnValue;\n};\n\n// For each newline, invoke the method separately\nexport default function wrapAnsi(string, columns, options) {\n\treturn String(string)\n\t\t.normalize()\n\t\t.replace(/\\r\\n/g, '\\n')\n\t\t.split('\\n')\n\t\t.map(line => exec(line, columns, options))\n\t\t.join('\\n');\n}\n","import type { Key, ReadLine } from 'node:readline';\n\nimport { stdin, stdout } from 'node:process';\nimport readline from 'node:readline';\nimport { Readable, Writable } from 'node:stream';\nimport { WriteStream } from 'node:tty';\nimport { cursor, erase } from 'sisteransi';\nimport wrap from 'wrap-ansi';\n\nfunction diffLines(a: string, b: string) {\n\tif (a === b) return;\n\n\tconst aLines = a.split('\\n');\n\tconst bLines = b.split('\\n');\n\tconst diff: number[] = [];\n\n\tfor (let i = 0; i < Math.max(aLines.length, bLines.length); i++) {\n\t\tif (aLines[i] !== bLines[i]) diff.push(i);\n\t}\n\n\treturn diff;\n}\n\nconst cancel = Symbol('clack:cancel');\nexport function isCancel(value: unknown): value is symbol {\n\treturn value === cancel;\n}\n\nfunction setRawMode(input: Readable, value: boolean) {\n\tif ((input as typeof stdin).isTTY) (input as typeof stdin).setRawMode(value);\n}\n\nconst aliases = new Map([\n\t['k', 'up'],\n\t['j', 'down'],\n\t['h', 'left'],\n\t['l', 'right'],\n]);\nconst keys = new Set(['up', 'down', 'left', 'right', 'space', 'enter']);\n\nexport interface PromptOptions<Self extends Prompt> {\n\trender(this: Omit<Self, 'prompt'>): string | void;\n\tplaceholder?: string;\n\tinitialValue?: any;\n\tvalidate?: ((value: any) => string | void) | undefined;\n\tinput?: Readable;\n\toutput?: Writable;\n\tdebug?: boolean;\n}\n\nexport type State = 'initial' | 'active' | 'cancel' | 'submit' | 'error';\n\nexport default class Prompt {\n\tprotected input: Readable;\n\tprotected output: Writable;\n\tprivate rl!: ReadLine;\n\tprivate opts: Omit<PromptOptions<Prompt>, 'render' | 'input' | 'output'>;\n\tprivate _track: boolean = false;\n\tprivate _render: (context: Omit<Prompt, 'prompt'>) => string | void;\n\tprotected _cursor: number = 0;\n\n\tpublic state: State = 'initial';\n\tpublic value: any;\n\tpublic error: string = '';\n\n\tconstructor(\n\t\t{ render, input = stdin, output = stdout, ...opts }: PromptOptions<Prompt>,\n\t\ttrackValue: boolean = true\n\t) {\n\t\tthis.opts = opts;\n\t\tthis.onKeypress = this.onKeypress.bind(this);\n\t\tthis.close = this.close.bind(this);\n\t\tthis.render = this.render.bind(this);\n\t\tthis._render = render.bind(this);\n\t\tthis._track = trackValue;\n\n\t\tthis.input = input;\n\t\tthis.output = output;\n\t}\n\n\tpublic prompt() {\n\t\tconst sink = new WriteStream(0);\n\t\tsink._write = (chunk, encoding, done) => {\n\t\t\tif (this._track) {\n\t\t\t\tthis.value = this.rl.line.replace(/\\t/g, '');\n\t\t\t\tthis._cursor = this.rl.cursor;\n\t\t\t\tthis.emit('value', this.value);\n\t\t\t}\n\t\t\tdone();\n\t\t};\n\t\tthis.input.pipe(sink);\n\n\t\tthis.rl = readline.createInterface({\n\t\t\tinput: this.input,\n\t\t\toutput: sink,\n\t\t\ttabSize: 2,\n\t\t\tprompt: '',\n\t\t\tescapeCodeTimeout: 50,\n\t\t});\n\t\treadline.emitKeypressEvents(this.input, this.rl);\n\t\tthis.rl.prompt();\n\t\tif (this.opts.initialValue !== undefined && this._track) {\n\t\t\tthis.rl.write(this.opts.initialValue);\n\t\t}\n\n\t\tthis.input.on('keypress', this.onKeypress);\n\t\tsetRawMode(this.input, true);\n\t\tthis.output.on('resize', this.render);\n\n\t\tthis.render();\n\n\t\treturn new Promise<string | symbol>((resolve, reject) => {\n\t\t\tthis.once('submit', () => {\n\t\t\t\tthis.output.write(cursor.show);\n\t\t\t\tthis.output.off('resize', this.render);\n\t\t\t\tsetRawMode(this.input, false);\n\t\t\t\tresolve(this.value);\n\t\t\t});\n\t\t\tthis.once('cancel', () => {\n\t\t\t\tthis.output.write(cursor.show);\n\t\t\t\tthis.output.off('resize', this.render);\n\t\t\t\tsetRawMode(this.input, false);\n\t\t\t\tresolve(cancel);\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate subscribers = new Map<string, { cb: (...args: any) => any; once?: boolean }[]>();\n\tpublic on(event: string, cb: (...args: any) => any) {\n\t\tconst arr = this.subscribers.get(event) ?? [];\n\t\tarr.push({ cb });\n\t\tthis.subscribers.set(event, arr);\n\t}\n\tpublic once(event: string, cb: (...args: any) => any) {\n\t\tconst arr = this.subscribers.get(event) ?? [];\n\t\tarr.push({ cb, once: true });\n\t\tthis.subscribers.set(event, arr);\n\t}\n\tpublic emit(event: string, ...data: any[]) {\n\t\tconst cbs = this.subscribers.get(event) ?? [];\n\t\tconst cleanup: (() => void)[] = [];\n\t\tfor (const subscriber of cbs) {\n\t\t\tsubscriber.cb(...data);\n\t\t\tif (subscriber.once) {\n\t\t\t\tcleanup.push(() => cbs.splice(cbs.indexOf(subscriber), 1));\n\t\t\t}\n\t\t}\n\t\tfor (const cb of cleanup) {\n\t\t\tcb();\n\t\t}\n\t}\n\tprivate unsubscribe() {\n\t\tthis.subscribers.clear();\n\t}\n\n\tprivate onKeypress(char: string, key?: Key) {\n\t\tif (this.state === 'error') {\n\t\t\tthis.state = 'active';\n\t\t}\n\t\tif (key?.name && !this._track && aliases.has(key.name)) {\n\t\t\tthis.emit('cursor', aliases.get(key.name));\n\t\t}\n\t\tif (key?.name && keys.has(key.name)) {\n\t\t\tthis.emit('cursor', key.name);\n\t\t}\n\t\tif (char && (char.toLowerCase() === 'y' || char.toLowerCase() === 'n')) {\n\t\t\tthis.emit('confirm', char.toLowerCase() === 'y');\n\t\t}\n\t\tif (char === '\\t' && this.opts.placeholder) {\n\t\t\tif (!this.value) {\n\t\t\t\tthis.rl.write(this.opts.placeholder);\n\t\t\t\tthis.emit('value', this.opts.placeholder);\n\t\t\t}\n\t\t}\n\t\tif (char) {\n\t\t\tthis.emit('key', char.toLowerCase());\n\t\t}\n\n\t\tif (key?.name === 'return') {\n\t\t\tif (this.opts.validate) {\n\t\t\t\tconst problem = this.opts.validate(this.value);\n\t\t\t\tif (problem) {\n\t\t\t\t\tthis.error = problem;\n\t\t\t\t\tthis.state = 'error';\n\t\t\t\t\tthis.rl.write(this.value);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.state !== 'error') {\n\t\t\t\tthis.state = 'submit';\n\t\t\t}\n\t\t}\n\t\tif (char === '\\x03') {\n\t\t\tthis.state = 'cancel';\n\t\t}\n\t\tif (this.state === 'submit' || this.state === 'cancel') {\n\t\t\tthis.emit('finalize');\n\t\t}\n\t\tthis.render();\n\t\tif (this.state === 'submit' || this.state === 'cancel') {\n\t\t\tthis.close();\n\t\t}\n\t}\n\n\tprotected close() {\n\t\tthis.input.unpipe();\n\t\tthis.input.removeListener('keypress', this.onKeypress);\n\t\tthis.output.write('\\n');\n\t\tsetRawMode(this.input, false);\n\t\tthis.rl.close();\n\t\tthis.emit(`${this.state}`, this.value);\n\t\tthis.unsubscribe();\n\t}\n\n\tprivate restoreCursor() {\n\t\tconst lines =\n\t\t\twrap(this._prevFrame, process.stdout.columns, { hard: true }).split('\\n').length - 1;\n\t\tthis.output.write(cursor.move(-999, lines * -1));\n\t}\n\n\tprivate _prevFrame = '';\n\tprivate render() {\n\t\tconst frame = wrap(this._render(this) ?? '', process.stdout.columns, { hard: true });\n\t\tif (frame === this._prevFrame) return;\n\n\t\tif (this.state === 'initial') {\n\t\t\tthis.output.write(cursor.hide);\n\t\t} else {\n\t\t\tconst diff = diffLines(this._prevFrame, frame);\n\t\t\tthis.restoreCursor();\n\t\t\t// If a single line has changed, only update that line\n\t\t\tif (diff && diff?.length === 1) {\n\t\t\t\tconst diffLine = diff[0];\n\t\t\t\tthis.output.write(cursor.move(0, diffLine));\n\t\t\t\tthis.output.write(erase.lines(1));\n\t\t\t\tconst lines = frame.split('\\n');\n\t\t\t\tthis.output.write(lines[diffLine]);\n\t\t\t\tthis._prevFrame = frame;\n\t\t\t\tthis.output.write(cursor.move(0, lines.length - diffLine - 1));\n\t\t\t\treturn;\n\t\t\t\t// If many lines have changed, rerender everything past the first line\n\t\t\t} else if (diff && diff?.length > 1) {\n\t\t\t\tconst diffLine = diff[0];\n\t\t\t\tthis.output.write(cursor.move(0, diffLine));\n\t\t\t\tthis.output.write(erase.down());\n\t\t\t\tconst lines = frame.split('\\n');\n\t\t\t\tconst newLines = lines.slice(diffLine);\n\t\t\t\tthis.output.write(newLines.join('\\n'));\n\t\t\t\tthis._prevFrame = frame;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.output.write(erase.down());\n\t\t}\n\n\t\tthis.output.write(frame);\n\t\tif (this.state === 'initial') {\n\t\t\tthis.state = 'active';\n\t\t}\n\t\tthis._prevFrame = frame;\n\t}\n}\n","import { cursor } from 'sisteransi';\nimport Prompt, { PromptOptions } from './prompt';\n\ninterface ConfirmOptions extends PromptOptions<ConfirmPrompt> {\n\tactive: string;\n\tinactive: string;\n\tinitialValue?: boolean;\n}\nexport default class ConfirmPrompt extends Prompt {\n\tget cursor() {\n\t\treturn this.value ? 0 : 1;\n\t}\n\n\tprivate get _value() {\n\t\treturn this.cursor === 0;\n\t}\n\n\tconstructor(opts: ConfirmOptions) {\n\t\tsuper(opts, false);\n\t\tthis.value = opts.initialValue ? true : false;\n\n\t\tthis.on('value', () => {\n\t\t\tthis.value = this._value;\n\t\t});\n\n\t\tthis.on('confirm', (confirm) => {\n\t\t\tthis.output.write(cursor.move(0, -1));\n\t\t\tthis.value = confirm;\n\t\t\tthis.state = 'submit';\n\t\t\tthis.close();\n\t\t});\n\n\t\tthis.on('cursor', () => {\n\t\t\tthis.value = !this.value;\n\t\t});\n\t}\n}\n","import Prompt, { PromptOptions } from './prompt';\n\ninterface GroupMultiSelectOptions<T extends { value: any }>\n\textends PromptOptions<GroupMultiSelectPrompt<T>> {\n\toptions: Record<string, T[]>;\n\tinitialValues?: T['value'][];\n\trequired?: boolean;\n\tcursorAt?: T['value'];\n}\nexport default class GroupMultiSelectPrompt<T extends { value: any }> extends Prompt {\n\toptions: (T & { group: string | boolean })[];\n\tcursor: number = 0;\n\n\tgetGroupItems(group: string): T[] {\n\t\treturn this.options.filter((o) => o.group === group);\n\t}\n\n\tisGroupSelected(group: string) {\n\t\tconst items = this.getGroupItems(group);\n\t\treturn items.every((i) => this.value.includes(i.value));\n\t}\n\n\tprivate toggleValue() {\n\t\tconst item = this.options[this.cursor];\n\t\tif (item.group === true) {\n\t\t\tconst group = item.value;\n\t\t\tconst groupedItems = this.getGroupItems(group);\n\t\t\tif (this.isGroupSelected(group)) {\n\t\t\t\tthis.value = this.value.filter(\n\t\t\t\t\t(v: string) => groupedItems.findIndex((i) => i.value === v) === -1\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis.value = [...this.value, ...groupedItems.map((i) => i.value)];\n\t\t\t}\n\t\t\tthis.value = Array.from(new Set(this.value));\n\t\t} else {\n\t\t\tconst selected = this.value.includes(item.value);\n\t\t\tthis.value = selected\n\t\t\t\t? this.value.filter((v: T['value']) => v !== item.value)\n\t\t\t\t: [...this.value, item.value];\n\t\t}\n\t}\n\n\tconstructor(opts: GroupMultiSelectOptions<T>) {\n\t\tsuper(opts, false);\n\t\tconst { options } = opts;\n\t\tthis.options = Object.entries(options).flatMap(([key, option]) => [\n\t\t\t{ value: key, group: true, label: key },\n\t\t\t...option.map((opt) => ({ ...opt, group: key })),\n\t\t]) as any;\n\t\tthis.value = [...(opts.initialValues ?? [])];\n\t\tthis.cursor = Math.max(\n\t\t\tthis.options.findIndex(({ value }) => value === opts.cursorAt),\n\t\t\t0\n\t\t);\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up':\n\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right':\n\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'space':\n\t\t\t\t\tthis.toggleValue();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}\n}\n","import Prompt, { PromptOptions } from './prompt';\n\ninterface MultiSelectOptions<T extends { value: any }> extends PromptOptions<MultiSelectPrompt<T>> {\n\toptions: T[];\n\tinitialValues?: T['value'][];\n\trequired?: boolean;\n\tcursorAt?: T['value'];\n}\nexport default class MultiSelectPrompt<T extends { value: any }> extends Prompt {\n\toptions: T[];\n\tcursor: number = 0;\n\n\tprivate get _value() {\n\t\treturn this.options[this.cursor].value;\n\t}\n\n\tprivate toggleAll() {\n\t\tconst allSelected = this.value.length === this.options.length;\n\t\tthis.value = allSelected ? [] : this.options.map((v) => v.value);\n\t}\n\n\tprivate toggleValue() {\n\t\tconst selected = this.value.includes(this._value);\n\t\tthis.value = selected\n\t\t\t? this.value.filter((value: T['value']) => value !== this._value)\n\t\t\t: [...this.value, this._value];\n\t}\n\n\tconstructor(opts: MultiSelectOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\t\tthis.value = [...(opts.initialValues ?? [])];\n\t\tthis.cursor = Math.max(\n\t\t\tthis.options.findIndex(({ value }) => value === opts.cursorAt),\n\t\t\t0\n\t\t);\n\t\tthis.on('key', (char) => {\n\t\t\tif (char === 'a') {\n\t\t\t\tthis.toggleAll();\n\t\t\t}\n\t\t});\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up':\n\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right':\n\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'space':\n\t\t\t\t\tthis.toggleValue();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}\n}\n","import color from 'picocolors';\nimport Prompt, { PromptOptions } from './prompt';\n\ninterface PasswordOptions extends PromptOptions<PasswordPrompt> {\n\tmask?: string;\n}\nexport default class PasswordPrompt extends Prompt {\n\tvalueWithCursor = '';\n\tprivate _mask = '•';\n\tget cursor() {\n\t\treturn this._cursor;\n\t}\n\tget masked() {\n\t\treturn this.value.replaceAll(/./g, this._mask);\n\t}\n\tconstructor({ mask, ...opts }: PasswordOptions) {\n\t\tsuper(opts);\n\t\tthis._mask = mask ?? '•';\n\n\t\tthis.on('finalize', () => {\n\t\t\tthis.valueWithCursor = this.masked;\n\t\t});\n\t\tthis.on('value', () => {\n\t\t\tif (this.cursor >= this.value.length) {\n\t\t\t\tthis.valueWithCursor = `${this.masked}${color.inverse(color.hidden('_'))}`;\n\t\t\t} else {\n\t\t\t\tconst s1 = this.masked.slice(0, this.cursor);\n\t\t\t\tconst s2 = this.masked.slice(this.cursor);\n\t\t\t\tthis.valueWithCursor = `${s1}${color.inverse(s2[0])}${s2.slice(1)}`;\n\t\t\t}\n\t\t});\n\t}\n}\n","import Prompt, { PromptOptions } from './prompt';\n\ninterface SelectOptions<T extends { value: any }> extends PromptOptions<SelectPrompt<T>> {\n\toptions: T[];\n\tinitialValue?: T['value'];\n}\nexport default class SelectPrompt<T extends { value: any }> extends Prompt {\n\toptions: T[];\n\tcursor: number = 0;\n\n\tprivate get _value() {\n\t\treturn this.options[this.cursor];\n\t}\n\n\tprivate changeValue() {\n\t\tthis.value = this._value.value;\n\t}\n\n\tconstructor(opts: SelectOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\t\tthis.cursor = this.options.findIndex(({ value }) => value === opts.initialValue);\n\t\tif (this.cursor === -1) this.cursor = 0;\n\t\tthis.changeValue();\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up':\n\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right':\n\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tthis.changeValue();\n\t\t});\n\t}\n}\n","import Prompt, { PromptOptions } from './prompt';\n\ninterface SelectKeyOptions<T extends { value: any }> extends PromptOptions<SelectKeyPrompt<T>> {\n\toptions: T[];\n}\nexport default class SelectKeyPrompt<T extends { value: any }> extends Prompt {\n\toptions: T[];\n\tcursor: number = 0;\n\n\tconstructor(opts: SelectKeyOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\t\tconst keys = this.options.map(({ value: [initial] }) => initial?.toLowerCase());\n\t\tthis.cursor = Math.max(keys.indexOf(opts.initialValue), 0);\n\n\t\tthis.on('key', (key) => {\n\t\t\tif (!keys.includes(key)) return;\n\t\t\tconst value = this.options.find(({ value: [initial] }) => initial?.toLowerCase() === key);\n\t\t\tif (value) {\n\t\t\t\tthis.value = value.value;\n\t\t\t\tthis.state = 'submit';\n\t\t\t\tthis.emit('submit');\n\t\t\t}\n\t\t});\n\t}\n}\n","import color from 'picocolors';\nimport Prompt, { PromptOptions } from './prompt';\n\nexport interface TextOptions extends PromptOptions<TextPrompt> {\n\tplaceholder?: string;\n\tdefaultValue?: string;\n}\n\nexport default class TextPrompt extends Prompt {\n\tvalueWithCursor = '';\n\tget cursor() {\n\t\treturn this._cursor;\n\t}\n\tconstructor(opts: TextOptions) {\n\t\tsuper(opts);\n\n\t\tthis.on('finalize', () => {\n\t\t\tif (!this.value) {\n\t\t\t\tthis.value = opts.defaultValue;\n\t\t\t}\n\t\t\tthis.valueWithCursor = this.value;\n\t\t});\n\t\tthis.on('value', () => {\n\t\t\tif (this.cursor >= this.value.length) {\n\t\t\t\tthis.valueWithCursor = `${this.value}${color.inverse(color.hidden('_'))}`;\n\t\t\t} else {\n\t\t\t\tconst s1 = this.value.slice(0, this.cursor);\n\t\t\t\tconst s2 = this.value.slice(this.cursor);\n\t\t\t\tthis.valueWithCursor = `${s1}${color.inverse(s2[0])}${s2.slice(1)}`;\n\t\t\t}\n\t\t});\n\t}\n}\n","import type { Key } from 'node:readline';\n\nimport { stdin, stdout } from 'node:process';\nimport * as readline from 'node:readline';\nimport { cursor } from 'sisteransi';\n\nconst isWindows = globalThis.process.platform.startsWith('win');\n\nexport function block({\n\tinput = stdin,\n\toutput = stdout,\n\toverwrite = true,\n\thideCursor = true,\n} = {}) {\n\tconst rl = readline.createInterface({\n\t\tinput,\n\t\toutput,\n\t\tprompt: '',\n\t\ttabSize: 1,\n\t});\n\treadline.emitKeypressEvents(input, rl);\n\tif (input.isTTY) input.setRawMode(true);\n\n\tconst clear = (data: Buffer, { name }: Key) => {\n\t\tconst str = String(data);\n\t\tif (str === '\\x03') {\n\t\t\tif (hideCursor) output.write(cursor.show);\n\t\t\tprocess.exit(0);\n\t\t\treturn;\n\t\t}\n\t\tif (!overwrite) return;\n\t\tlet dx = name === 'return' ? 0 : -1;\n\t\tlet dy = name === 'return' ? -1 : 0;\n\n\t\treadline.moveCursor(output, dx, dy, () => {\n\t\t\treadline.clearLine(output, 1, () => {\n\t\t\t\tinput.once('keypress', clear);\n\t\t\t});\n\t\t});\n\t};\n\tif (hideCursor) output.write(cursor.hide);\n\tinput.once('keypress', clear);\n\n\treturn () => {\n\t\tinput.off('keypress', clear);\n\t\tif (hideCursor) output.write(cursor.show);\n\n\t\t// Prevent Windows specific issues: https://github.com/natemoo-re/clack/issues/176\n\t\tif (input.isTTY && !isWindows) input.setRawMode(false);\n\n\t\t// @ts-expect-error fix for https://github.com/nodejs/node/issues/31762#issuecomment-1441223907\n\t\trl.terminal = false;\n\t\trl.close();\n\t};\n}\n"],"names":["ansiRegex","onlyFirst","pattern","regex","stripAnsi","string","eaw","module","character","x","y","codePoint","code","stringToArray","characters","len","i","text","start","end","result","eawLen","chars","char","charLen","emojiRegex","stringWidth","options","ambiguousCharacterWidth","width","eastAsianWidth","ANSI_BACKGROUND_OFFSET","wrapAnsi16","offset","wrapAnsi256","wrapAnsi16m","red","green","blue","styles","foregroundColorNames","backgroundColorNames","assembleStyles","codes","groupName","group","styleName","style","hex","matches","colorString","integer","remainder","value","ansiStyles","ESCAPES","END_CODE","ANSI_ESCAPE_BELL","ANSI_CSI","ANSI_OSC","ANSI_SGR_TERMINATOR","ANSI_ESCAPE_LINK","wrapAnsiCode","wrapAnsiHyperlink","uri","wordLengths","wrapWord","rows","word","columns","isInsideEscape","isInsideLinkEscape","visible","index","characterLength","stringVisibleTrimSpacesRight","words","last","exec","returnValue","escapeCode","escapeUrl","lengths","rowLength","remainingColumns","breaksStartingThisLine","row","pre","groups","wrapAnsi","line","f","d","r","t","e","o","diffLines","a","b","aLines","bLines","diff","cancel","isCancel","setRawMode","input","aliases","keys","Prompt","render","stdin","output","stdout","opts","trackValue","__publicField","sink","WriteStream","chunk","encoding","done","readline","resolve","reject","cursor","event","cb","arr","data","cbs","cleanup","subscriber","key","problem","lines","wrap","frame","diffLine","erase","newLines","ConfirmPrompt","confirm","n","l","GroupMultiSelectPrompt","option","opt","item","groupedItems","v","selected","s","allSelected","PasswordPrompt","mask","color","s1","s2","u$1","SelectKeyPrompt","initial","TextPrompt","isWindows","block","overwrite","hideCursor","rl","clear","name","dx","dy"],"mappings":"8NAAe,SAASA,EAAU,CAAC,UAAAC,EAAY,EAAK,EAAI,CAAA,EAAI,CAG3D,MAAMC,EAAU,CACf,0JACA,0DACF,EAAG,KAAK,GAAG,EAEV,OAAO,IAAI,OAAOA,EAASD,EAAY,OAAY,GAAG,CACvD,CCPA,MAAME,EAAQH,EAAS,EAER,SAASI,EAAUC,EAAQ,CACzC,GAAI,OAAOA,GAAW,SACrB,MAAM,IAAI,UAAU,gCAAgC,OAAOA,CAAM,IAAI,EAMtE,OAAOA,EAAO,QAAQF,EAAO,EAAE,CAChC,qICbA,IAAIG,EAAM,CAAA,EAKRC,UAAiBD,EAGnBA,EAAI,eAAiB,SAASE,EAAW,CACvC,IAAIC,EAAID,EAAU,WAAW,CAAC,EAC1BE,EAAKF,EAAU,QAAU,EAAKA,EAAU,WAAW,CAAC,EAAI,EACxDG,EAAYF,EAQhB,MAPK,QAAUA,GAAKA,GAAK,OAAY,OAAUC,GAAKA,GAAK,QACvDD,GAAK,KACLC,GAAK,KACLC,EAAaF,GAAK,GAAMC,EACxBC,GAAa,OAGAA,GAAV,OACA,OAAUA,GAAaA,GAAa,OACpC,OAAUA,GAAaA,GAAa,MAChC,IAEMA,GAAV,MACA,OAAUA,GAAaA,GAAa,OACpC,OAAUA,GAAaA,GAAa,OACpC,OAAUA,GAAaA,GAAa,OACpC,OAAUA,GAAaA,GAAa,OACpC,OAAUA,GAAaA,GAAa,OACpC,OAAUA,GAAaA,GAAa,MAChC,IAEJ,MAAUA,GAAaA,GAAa,MACpC,MAAUA,GAAaA,GAAa,MACpC,MAAUA,GAAaA,GAAa,MACpC,MAAUA,GAAaA,GAAa,MACpC,OAAUA,GAAaA,GAAa,OACpC,OAAUA,GAAaA,GAAa,OACpC,OAAUA,GAAaA,GAAa,OACpC,OAAUA,GAAaA,GAAa,OACpC,OAAUA,GAAaA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AAG,SAAW,GACdA,EAAG,OACJ,CACD","x_google_ignoreList":[0,1,2,3,4,5,6]} node_modules/@clack/core/dist/index.d.ts 0000664 00000010024 15114743311 0014171 0 ustar 00 import { Readable, Writable } from 'node:stream'; declare function isCancel(value: unknown): value is symbol; interface PromptOptions<Self extends Prompt> { render(this: Omit<Self, 'prompt'>): string | void; placeholder?: string; initialValue?: any; validate?: ((value: any) => string | void) | undefined; input?: Readable; output?: Writable; debug?: boolean; } type State = 'initial' | 'active' | 'cancel' | 'submit' | 'error'; declare class Prompt { protected input: Readable; protected output: Writable; private rl; private opts; private _track; private _render; protected _cursor: number; state: State; value: any; error: string; constructor({ render, input, output, ...opts }: PromptOptions<Prompt>, trackValue?: boolean); prompt(): Promise<string | symbol>; private subscribers; on(event: string, cb: (...args: any) => any): void; once(event: string, cb: (...args: any) => any): void; emit(event: string, ...data: any[]): void; private unsubscribe; private onKeypress; protected close(): void; private restoreCursor; private _prevFrame; private render; } interface ConfirmOptions extends PromptOptions<ConfirmPrompt> { active: string; inactive: string; initialValue?: boolean; } declare class ConfirmPrompt extends Prompt { get cursor(): 0 | 1; private get _value(); constructor(opts: ConfirmOptions); } interface GroupMultiSelectOptions<T extends { value: any; }> extends PromptOptions<GroupMultiSelectPrompt<T>> { options: Record<string, T[]>; initialValues?: T['value'][]; required?: boolean; cursorAt?: T['value']; } declare class GroupMultiSelectPrompt<T extends { value: any; }> extends Prompt { options: (T & { group: string | boolean; })[]; cursor: number; getGroupItems(group: string): T[]; isGroupSelected(group: string): boolean; private toggleValue; constructor(opts: GroupMultiSelectOptions<T>); } interface MultiSelectOptions<T extends { value: any; }> extends PromptOptions<MultiSelectPrompt<T>> { options: T[]; initialValues?: T['value'][]; required?: boolean; cursorAt?: T['value']; } declare class MultiSelectPrompt<T extends { value: any; }> extends Prompt { options: T[]; cursor: number; private get _value(); private toggleAll; private toggleValue; constructor(opts: MultiSelectOptions<T>); } interface PasswordOptions extends PromptOptions<PasswordPrompt> { mask?: string; } declare class PasswordPrompt extends Prompt { valueWithCursor: string; private _mask; get cursor(): number; get masked(): any; constructor({ mask, ...opts }: PasswordOptions); } interface SelectOptions<T extends { value: any; }> extends PromptOptions<SelectPrompt<T>> { options: T[]; initialValue?: T['value']; } declare class SelectPrompt<T extends { value: any; }> extends Prompt { options: T[]; cursor: number; private get _value(); private changeValue; constructor(opts: SelectOptions<T>); } interface SelectKeyOptions<T extends { value: any; }> extends PromptOptions<SelectKeyPrompt<T>> { options: T[]; } declare class SelectKeyPrompt<T extends { value: any; }> extends Prompt { options: T[]; cursor: number; constructor(opts: SelectKeyOptions<T>); } interface TextOptions extends PromptOptions<TextPrompt> { placeholder?: string; defaultValue?: string; } declare class TextPrompt extends Prompt { valueWithCursor: string; get cursor(): number; constructor(opts: TextOptions); } declare function block({ input, output, overwrite, hideCursor, }?: { input?: (NodeJS.ReadStream & { fd: 0; }) | undefined; output?: (NodeJS.WriteStream & { fd: 1; }) | undefined; overwrite?: boolean | undefined; hideCursor?: boolean | undefined; }): () => void; export { ConfirmPrompt, GroupMultiSelectPrompt, MultiSelectPrompt, PasswordPrompt, Prompt, SelectKeyPrompt, SelectPrompt, type State, TextPrompt, block, isCancel }; node_modules/@clack/core/dist/index.cjs.map 0000664 00000261074 15114743311 0014671 0 ustar 00 {"version":3,"file":"index.cjs","sources":["../../../node_modules/.pnpm/ansi-regex@6.1.0/node_modules/ansi-regex/index.js","../../../node_modules/.pnpm/strip-ansi@7.1.0/node_modules/strip-ansi/index.js","../../../node_modules/.pnpm/eastasianwidth@0.2.0/node_modules/eastasianwidth/eastasianwidth.js","../../../node_modules/.pnpm/emoji-regex@9.2.2/node_modules/emoji-regex/index.js","../../../node_modules/.pnpm/string-width@5.1.2/node_modules/string-width/index.js","../../../node_modules/.pnpm/ansi-styles@6.2.1/node_modules/ansi-styles/index.js","../../../node_modules/.pnpm/wrap-ansi@8.1.0/node_modules/wrap-ansi/index.js","../src/prompts/prompt.ts","../src/prompts/confirm.ts","../src/prompts/group-multiselect.ts","../src/prompts/multi-select.ts","../src/prompts/password.ts","../src/prompts/select.ts","../src/prompts/select-key.ts","../src/prompts/text.ts","../src/utils.ts"],"sourcesContent":["export default function ansiRegex({onlyFirst = false} = {}) {\n\t// Valid string terminator sequences are BEL, ESC\\, and 0x9c\n\tconst ST = '(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)';\n\tconst pattern = [\n\t\t`[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?${ST})`,\n\t\t'(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]))',\n\t].join('|');\n\n\treturn new RegExp(pattern, onlyFirst ? undefined : 'g');\n}\n","import ansiRegex from 'ansi-regex';\n\nconst regex = ansiRegex();\n\nexport default function stripAnsi(string) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof string}\\``);\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn string.replace(regex, '');\n}\n","var eaw = {};\n\nif ('undefined' == typeof module) {\n window.eastasianwidth = eaw;\n} else {\n module.exports = eaw;\n}\n\neaw.eastAsianWidth = function(character) {\n var x = character.charCodeAt(0);\n var y = (character.length == 2) ? character.charCodeAt(1) : 0;\n var codePoint = x;\n if ((0xD800 <= x && x <= 0xDBFF) && (0xDC00 <= y && y <= 0xDFFF)) {\n x &= 0x3FF;\n y &= 0x3FF;\n codePoint = (x << 10) | y;\n codePoint += 0x10000;\n }\n\n if ((0x3000 == codePoint) ||\n (0xFF01 <= codePoint && codePoint <= 0xFF60) ||\n (0xFFE0 <= codePoint && codePoint <= 0xFFE6)) {\n return 'F';\n }\n if ((0x20A9 == codePoint) ||\n (0xFF61 <= codePoint && codePoint <= 0xFFBE) ||\n (0xFFC2 <= codePoint && codePoint <= 0xFFC7) ||\n (0xFFCA <= codePoint && codePoint <= 0xFFCF) ||\n (0xFFD2 <= codePoint && codePoint <= 0xFFD7) ||\n (0xFFDA <= codePoint && codePoint <= 0xFFDC) ||\n (0xFFE8 <= codePoint && codePoint <= 0xFFEE)) {\n return 'H';\n }\n if ((0x1100 <= codePoint && codePoint <= 0x115F) ||\n (0x11A3 <= codePoint && codePoint <= 0x11A7) ||\n (0x11FA <= codePoint && codePoint <= 0x11FF) ||\n (0x2329 <= codePoint && codePoint <= 0x232A) ||\n (0x2E80 <= codePoint && codePoint <= 0x2E99) ||\n (0x2E9B <= codePoint && codePoint <= 0x2EF3) ||\n (0x2F00 <= codePoint && codePoint <= 0x2FD5) ||\n (0x2FF0 <= codePoint && codePoint <= 0x2FFB) ||\n (0x3001 <= codePoint && codePoint <= 0x303E) ||\n (0x3041 <= codePoint && codePoint <= 0x3096) ||\n (0x3099 <= codePoint && codePoint <= 0x30FF) ||\n (0x3105 <= codePoint && codePoint <= 0x312D) ||\n (0x3131 <= codePoint && codePoint <= 0x318E) ||\n (0x3190 <= codePoint && codePoint <= 0x31BA) ||\n (0x31C0 <= codePoint && codePoint <= 0x31E3) ||\n (0x31F0 <= codePoint && codePoint <= 0x321E) ||\n (0x3220 <= codePoint && codePoint <= 0x3247) ||\n (0x3250 <= codePoint && codePoint <= 0x32FE) ||\n (0x3300 <= codePoint && codePoint <= 0x4DBF) ||\n (0x4E00 <= codePoint && codePoint <= 0xA48C) ||\n (0xA490 <= codePoint && codePoint <= 0xA4C6) ||\n (0xA960 <= codePoint && codePoint <= 0xA97C) ||\n (0xAC00 <= codePoint && codePoint <= 0xD7A3) ||\n (0xD7B0 <= codePoint && codePoint <= 0xD7C6) ||\n (0xD7CB <= codePoint && codePoint <= 0xD7FB) ||\n (0xF900 <= codePoint && codePoint <= 0xFAFF) ||\n (0xFE10 <= codePoint && codePoint <= 0xFE19) ||\n (0xFE30 <= codePoint && codePoint <= 0xFE52) ||\n (0xFE54 <= codePoint && codePoint <= 0xFE66) ||\n (0xFE68 <= codePoint && codePoint <= 0xFE6B) ||\n (0x1B000 <= codePoint && codePoint <= 0x1B001) ||\n (0x1F200 <= codePoint && codePoint <= 0x1F202) ||\n (0x1F210 <= codePoint && codePoint <= 0x1F23A) ||\n (0x1F240 <= codePoint && codePoint <= 0x1F248) ||\n (0x1F250 <= codePoint && codePoint <= 0x1F251) ||\n (0x20000 <= codePoint && codePoint <= 0x2F73F) ||\n (0x2B740 <= codePoint && codePoint <= 0x2FFFD) ||\n (0x30000 <= codePoint && codePoint <= 0x3FFFD)) {\n return 'W';\n }\n if ((0x0020 <= codePoint && codePoint <= 0x007E) ||\n (0x00A2 <= codePoint && codePoint <= 0x00A3) ||\n (0x00A5 <= codePoint && codePoint <= 0x00A6) ||\n (0x00AC == codePoint) ||\n (0x00AF == codePoint) ||\n (0x27E6 <= codePoint && codePoint <= 0x27ED) ||\n (0x2985 <= codePoint && codePoint <= 0x2986)) {\n return 'Na';\n }\n if ((0x00A1 == codePoint) ||\n (0x00A4 == codePoint) ||\n (0x00A7 <= codePoint && codePoint <= 0x00A8) ||\n (0x00AA == codePoint) ||\n (0x00AD <= codePoint && codePoint <= 0x00AE) ||\n (0x00B0 <= codePoint && codePoint <= 0x00B4) ||\n (0x00B6 <= codePoint && codePoint <= 0x00BA) ||\n (0x00BC <= codePoint && codePoint <= 0x00BF) ||\n (0x00C6 == codePoint) ||\n (0x00D0 == codePoint) ||\n (0x00D7 <= codePoint && codePoint <= 0x00D8) ||\n (0x00DE <= codePoint && codePoint <= 0x00E1) ||\n (0x00E6 == codePoint) ||\n (0x00E8 <= codePoint && codePoint <= 0x00EA) ||\n (0x00EC <= codePoint && codePoint <= 0x00ED) ||\n (0x00F0 == codePoint) ||\n (0x00F2 <= codePoint && codePoint <= 0x00F3) ||\n (0x00F7 <= codePoint && codePoint <= 0x00FA) ||\n (0x00FC == codePoint) ||\n (0x00FE == codePoint) ||\n (0x0101 == codePoint) ||\n (0x0111 == codePoint) ||\n (0x0113 == codePoint) ||\n (0x011B == codePoint) ||\n (0x0126 <= codePoint && codePoint <= 0x0127) ||\n (0x012B == codePoint) ||\n (0x0131 <= codePoint && codePoint <= 0x0133) ||\n (0x0138 == codePoint) ||\n (0x013F <= codePoint && codePoint <= 0x0142) ||\n (0x0144 == codePoint) ||\n (0x0148 <= codePoint && codePoint <= 0x014B) ||\n (0x014D == codePoint) ||\n (0x0152 <= codePoint && codePoint <= 0x0153) ||\n (0x0166 <= codePoint && codePoint <= 0x0167) ||\n (0x016B == codePoint) ||\n (0x01CE == codePoint) ||\n (0x01D0 == codePoint) ||\n (0x01D2 == codePoint) ||\n (0x01D4 == codePoint) ||\n (0x01D6 == codePoint) ||\n (0x01D8 == codePoint) ||\n (0x01DA == codePoint) ||\n (0x01DC == codePoint) ||\n (0x0251 == codePoint) ||\n (0x0261 == codePoint) ||\n (0x02C4 == codePoint) ||\n (0x02C7 == codePoint) ||\n (0x02C9 <= codePoint && codePoint <= 0x02CB) ||\n (0x02CD == codePoint) ||\n (0x02D0 == codePoint) ||\n (0x02D8 <= codePoint && codePoint <= 0x02DB) ||\n (0x02DD == codePoint) ||\n (0x02DF == codePoint) ||\n (0x0300 <= codePoint && codePoint <= 0x036F) ||\n (0x0391 <= codePoint && codePoint <= 0x03A1) ||\n (0x03A3 <= codePoint && codePoint <= 0x03A9) ||\n (0x03B1 <= codePoint && codePoint <= 0x03C1) ||\n (0x03C3 <= codePoint && codePoint <= 0x03C9) ||\n (0x0401 == codePoint) ||\n (0x0410 <= codePoint && codePoint <= 0x044F) ||\n (0x0451 == codePoint) ||\n (0x2010 == codePoint) ||\n (0x2013 <= codePoint && codePoint <= 0x2016) ||\n (0x2018 <= codePoint && codePoint <= 0x2019) ||\n (0x201C <= codePoint && codePoint <= 0x201D) ||\n (0x2020 <= codePoint && codePoint <= 0x2022) ||\n (0x2024 <= codePoint && codePoint <= 0x2027) ||\n (0x2030 == codePoint) ||\n (0x2032 <= codePoint && codePoint <= 0x2033) ||\n (0x2035 == codePoint) ||\n (0x203B == codePoint) ||\n (0x203E == codePoint) ||\n (0x2074 == codePoint) ||\n (0x207F == codePoint) ||\n (0x2081 <= codePoint && codePoint <= 0x2084) ||\n (0x20AC == codePoint) ||\n (0x2103 == codePoint) ||\n (0x2105 == codePoint) ||\n (0x2109 == codePoint) ||\n (0x2113 == codePoint) ||\n (0x2116 == codePoint) ||\n (0x2121 <= codePoint && codePoint <= 0x2122) ||\n (0x2126 == codePoint) ||\n (0x212B == codePoint) ||\n (0x2153 <= codePoint && codePoint <= 0x2154) ||\n (0x215B <= codePoint && codePoint <= 0x215E) ||\n (0x2160 <= codePoint && codePoint <= 0x216B) ||\n (0x2170 <= codePoint && codePoint <= 0x2179) ||\n (0x2189 == codePoint) ||\n (0x2190 <= codePoint && codePoint <= 0x2199) ||\n (0x21B8 <= codePoint && codePoint <= 0x21B9) ||\n (0x21D2 == codePoint) ||\n (0x21D4 == codePoint) ||\n (0x21E7 == codePoint) ||\n (0x2200 == codePoint) ||\n (0x2202 <= codePoint && codePoint <= 0x2203) ||\n (0x2207 <= codePoint && codePoint <= 0x2208) ||\n (0x220B == codePoint) ||\n (0x220F == codePoint) ||\n (0x2211 == codePoint) ||\n (0x2215 == codePoint) ||\n (0x221A == codePoint) ||\n (0x221D <= codePoint && codePoint <= 0x2220) ||\n (0x2223 == codePoint) ||\n (0x2225 == codePoint) ||\n (0x2227 <= codePoint && codePoint <= 0x222C) ||\n (0x222E == codePoint) ||\n (0x2234 <= codePoint && codePoint <= 0x2237) ||\n (0x223C <= codePoint && codePoint <= 0x223D) ||\n (0x2248 == codePoint) ||\n (0x224C == codePoint) ||\n (0x2252 == codePoint) ||\n (0x2260 <= codePoint && codePoint <= 0x2261) ||\n (0x2264 <= codePoint && codePoint <= 0x2267) ||\n (0x226A <= codePoint && codePoint <= 0x226B) ||\n (0x226E <= codePoint && codePoint <= 0x226F) ||\n (0x2282 <= codePoint && codePoint <= 0x2283) ||\n (0x2286 <= codePoint && codePoint <= 0x2287) ||\n (0x2295 == codePoint) ||\n (0x2299 == codePoint) ||\n (0x22A5 == codePoint) ||\n (0x22BF == codePoint) ||\n (0x2312 == codePoint) ||\n (0x2460 <= codePoint && codePoint <= 0x24E9) ||\n (0x24EB <= codePoint && codePoint <= 0x254B) ||\n (0x2550 <= codePoint && codePoint <= 0x2573) ||\n (0x2580 <= codePoint && codePoint <= 0x258F) ||\n (0x2592 <= codePoint && codePoint <= 0x2595) ||\n (0x25A0 <= codePoint && codePoint <= 0x25A1) ||\n (0x25A3 <= codePoint && codePoint <= 0x25A9) ||\n (0x25B2 <= codePoint && codePoint <= 0x25B3) ||\n (0x25B6 <= codePoint && codePoint <= 0x25B7) ||\n (0x25BC <= codePoint && codePoint <= 0x25BD) ||\n (0x25C0 <= codePoint && codePoint <= 0x25C1) ||\n (0x25C6 <= codePoint && codePoint <= 0x25C8) ||\n (0x25CB == codePoint) ||\n (0x25CE <= codePoint && codePoint <= 0x25D1) ||\n (0x25E2 <= codePoint && codePoint <= 0x25E5) ||\n (0x25EF == codePoint) ||\n (0x2605 <= codePoint && codePoint <= 0x2606) ||\n (0x2609 == codePoint) ||\n (0x260E <= codePoint && codePoint <= 0x260F) ||\n (0x2614 <= codePoint && codePoint <= 0x2615) ||\n (0x261C == codePoint) ||\n (0x261E == codePoint) ||\n (0x2640 == codePoint) ||\n (0x2642 == codePoint) ||\n (0x2660 <= codePoint && codePoint <= 0x2661) ||\n (0x2663 <= codePoint && codePoint <= 0x2665) ||\n (0x2667 <= codePoint && codePoint <= 0x266A) ||\n (0x266C <= codePoint && codePoint <= 0x266D) ||\n (0x266F == codePoint) ||\n (0x269E <= codePoint && codePoint <= 0x269F) ||\n (0x26BE <= codePoint && codePoint <= 0x26BF) ||\n (0x26C4 <= codePoint && codePoint <= 0x26CD) ||\n (0x26CF <= codePoint && codePoint <= 0x26E1) ||\n (0x26E3 == codePoint) ||\n (0x26E8 <= codePoint && codePoint <= 0x26FF) ||\n (0x273D == codePoint) ||\n (0x2757 == codePoint) ||\n (0x2776 <= codePoint && codePoint <= 0x277F) ||\n (0x2B55 <= codePoint && codePoint <= 0x2B59) ||\n (0x3248 <= codePoint && codePoint <= 0x324F) ||\n (0xE000 <= codePoint && codePoint <= 0xF8FF) ||\n (0xFE00 <= codePoint && codePoint <= 0xFE0F) ||\n (0xFFFD == codePoint) ||\n (0x1F100 <= codePoint && codePoint <= 0x1F10A) ||\n (0x1F110 <= codePoint && codePoint <= 0x1F12D) ||\n (0x1F130 <= codePoint && codePoint <= 0x1F169) ||\n (0x1F170 <= codePoint && codePoint <= 0x1F19A) ||\n (0xE0100 <= codePoint && codePoint <= 0xE01EF) ||\n (0xF0000 <= codePoint && codePoint <= 0xFFFFD) ||\n (0x100000 <= codePoint && codePoint <= 0x10FFFD)) {\n return 'A';\n }\n\n return 'N';\n};\n\neaw.characterLength = function(character) {\n var code = this.eastAsianWidth(character);\n if (code == 'F' || code == 'W' || code == 'A') {\n return 2;\n } else {\n return 1;\n }\n};\n\n// Split a string considering surrogate-pairs.\nfunction stringToArray(string) {\n return string.match(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[^\\uD800-\\uDFFF]/g) || [];\n}\n\neaw.length = function(string) {\n var characters = stringToArray(string);\n var len = 0;\n for (var i = 0; i < characters.length; i++) {\n len = len + this.characterLength(characters[i]);\n }\n return len;\n};\n\neaw.slice = function(text, start, end) {\n textLen = eaw.length(text)\n start = start ? start : 0;\n end = end ? end : 1;\n if (start < 0) {\n start = textLen + start;\n }\n if (end < 0) {\n end = textLen + end;\n }\n var result = '';\n var eawLen = 0;\n var chars = stringToArray(text);\n for (var i = 0; i < chars.length; i++) {\n var char = chars[i];\n var charLen = eaw.length(char);\n if (eawLen >= start - (charLen == 2 ? 1 : 0)) {\n if (eawLen + charLen <= end) {\n result += char;\n } else {\n break;\n }\n }\n eawLen += charLen;\n }\n return result;\n};\n","\"use strict\";\n\nmodule.exports = function () {\n // https://mths.be/emoji\n return /\\uD83C\\uDFF4\\uDB40\\uDC67\\uDB40\\uDC62(?:\\uDB40\\uDC77\\uDB40\\uDC6C\\uDB40\\uDC73|\\uDB40\\uDC73\\uDB40\\uDC63\\uDB40\\uDC74|\\uDB40\\uDC65\\uDB40\\uDC6E\\uDB40\\uDC67)\\uDB40\\uDC7F|(?:\\uD83E\\uDDD1\\uD83C\\uDFFF\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFF\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB-\\uDFFE])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFE\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFE\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFD\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFD\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFC\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFC\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFB\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFB\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFC-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C\\uDFFB(?:\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF]))|\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFC-\\uDFFF])|[\\u2695\\u2696\\u2708]\\uFE0F|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD]))?|(?:\\uD83C[\\uDFFC-\\uDFFF])\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF]))|\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83D\\uDC68|(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\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2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])\\uFE0F|\\u200D(?:(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83D[\\uDC66\\uDC67])|\\uD83C\\uDFFF|\\uD83C\\uDFFE|\\uD83C\\uDFFD|\\uD83C\\uDFFC)?|(?:\\uD83D\\uDC69(?:\\uD83C\\uDFFB\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69])|(?:\\uD83C[\\uDFFC-\\uDFFF])\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69]))|\\uD83E\\uDDD1(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1)(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC69(?:\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFF\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\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C67])|(?:\\uD83D\\uDC41\\uFE0F\\u200D\\uD83D\\uDDE8|\\uD83E\\uDDD1(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])|\\uD83D\\uDC69(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])|\\uD83D\\uDE36\\u200D\\uD83C\\uDF2B|\\uD83C\\uDFF3\\uFE0F\\u200D\\u26A7|\\uD83D\\uDC3B\\u200D\\u2744|(?:(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC70\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD35\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD-\\uDDCF\\uDDD4\\uDDD6-\\uDDDD])(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC6F|\\uD83E[\\uDD3C\\uDDDE\\uDDDF])\\u200D[\\u2640\\u2642]|(?:\\u26F9|\\uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)(?:\\uFE0F|\\uD83C[\\uDFFB-\\uDFFF])\\u200D[\\u2640\\u2642]|\\uD83C\\uDFF4\\u200D\\u2620|(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC70\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD35\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD-\\uDDCF\\uDDD4\\uDDD6-\\uDDDD])\\u200D[\\u2640\\u2642]|[\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u2328\\u23CF\\u23ED-\\u23EF\\u23F1\\u23F2\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB\\u25FC\\u2600-\\u2604\\u260E\\u2611\\u2618\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u2692\\u2694-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A7\\u26B0\\u26B1\\u26C8\\u26CF\\u26D1\\u26D3\\u26E9\\u26F0\\u26F1\\u26F4\\u26F7\\u26F8\\u2702\\u2708\\u2709\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2733\\u2734\\u2744\\u2747\\u2763\\u27A1\\u2934\\u2935\\u2B05-\\u2B07\\u3030\\u303D\\u3297\\u3299]|\\uD83C[\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDE02\\uDE37\\uDF21\\uDF24-\\uDF2C\\uDF36\\uDF7D\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E\\uDF9F\\uDFCD\\uDFCE\\uDFD4-\\uDFDF\\uDFF5\\uDFF7]|\\uD83D[\\uDC3F\\uDCFD\\uDD49\\uDD4A\\uDD6F\\uDD70\\uDD73\\uDD76-\\uDD79\\uDD87\\uDD8A-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DDD0\\uDDE0-\\uDDFF\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6]|(?:[\\u231A\\u231B\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u25FE\\u2614\\u2615\\u2648-\\u2653\\u267F\\u2693\\u26A1\\u26AA\\u26AB\\u26BD\\u26BE\\u26C4\\u26C5\\u26CE\\u26D4\\u26EA\\u26F2\\u26F3\\u26F5\\u26FA\\u26FD\\u2705\\u270A\\u270B\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2795-\\u2797\\u27B0\\u27BF\\u2B1B\\u2B1C\\u2B50\\u2B55]|\\uD83C[\\uDC04\\uDCCF\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE1A\\uDE2F\\uDE32-\\uDE36\\uDE38-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF20\\uDF2D-\\uDF35\\uDF37-\\uDF7C\\uDF7E-\\uDF93\\uDFA0-\\uDFCA\\uDFCF-\\uDFD3\\uDFE0-\\uDFF0\\uDFF4\\uDFF8-\\uDFFF]|\\uD83D[\\uDC00-\\uDC3E\\uDC40\\uDC42-\\uDCFC\\uDCFF-\\uDD3D\\uDD4B-\\uDD4E\\uDD50-\\uDD67\\uDD7A\\uDD95\\uDD96\\uDDA4\\uDDFB-\\uDE4F\\uDE80-\\uDEC5\\uDECC\\uDED0-\\uDED2\\uDED5-\\uDED7\\uDEEB\\uDEEC\\uDEF4-\\uDEFC\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0C-\\uDD3A\\uDD3C-\\uDD45\\uDD47-\\uDD78\\uDD7A-\\uDDCB\\uDDCD-\\uDDFF\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6])|(?:[#\\*0-9\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23E9-\\u23F3\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB-\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u261D\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A1\\u26A7\\u26AA\\u26AB\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C5\\u26C8\\u26CE\\u26CF\\u26D1\\u26D3\\u26D4\\u26E9\\u26EA\\u26F0-\\u26F5\\u26F7-\\u26FA\\u26FD\\u2702\\u2705\\u2708-\\u270D\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2728\\u2733\\u2734\\u2744\\u2747\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2763\\u2764\\u2795-\\u2797\\u27A1\\u27B0\\u27BF\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B50\\u2B55\\u3030\\u303D\\u3297\\u3299]|\\uD83C[\\uDC04\\uDCCF\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE02\\uDE1A\\uDE2F\\uDE32-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF21\\uDF24-\\uDF93\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E-\\uDFF0\\uDFF3-\\uDFF5\\uDFF7-\\uDFFF]|\\uD83D[\\uDC00-\\uDCFD\\uDCFF-\\uDD3D\\uDD49-\\uDD4E\\uDD50-\\uDD67\\uDD6F\\uDD70\\uDD73-\\uDD7A\\uDD87\\uDD8A-\\uDD8D\\uDD90\\uDD95\\uDD96\\uDDA4\\uDDA5\\uDDA8\\uDDB1\\uDDB2\\uDDBC\\uDDC2-\\uDDC4\\uDDD1-\\uDDD3\\uDDDC-\\uDDDE\\uDDE1\\uDDE3\\uDDE8\\uDDEF\\uDDF3\\uDDFA-\\uDE4F\\uDE80-\\uDEC5\\uDECB-\\uDED2\\uDED5-\\uDED7\\uDEE0-\\uDEE5\\uDEE9\\uDEEB\\uDEEC\\uDEF0\\uDEF3-\\uDEFC\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0C-\\uDD3A\\uDD3C-\\uDD45\\uDD47-\\uDD78\\uDD7A-\\uDDCB\\uDDCD-\\uDDFF\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6])\\uFE0F|(?:[\\u261D\\u26F9\\u270A-\\u270D]|\\uD83C[\\uDF85\\uDFC2-\\uDFC4\\uDFC7\\uDFCA-\\uDFCC]|\\uD83D[\\uDC42\\uDC43\\uDC46-\\uDC50\\uDC66-\\uDC78\\uDC7C\\uDC81-\\uDC83\\uDC85-\\uDC87\\uDC8F\\uDC91\\uDCAA\\uDD74\\uDD75\\uDD7A\\uDD90\\uDD95\\uDD96\\uDE45-\\uDE47\\uDE4B-\\uDE4F\\uDEA3\\uDEB4-\\uDEB6\\uDEC0\\uDECC]|\\uD83E[\\uDD0C\\uDD0F\\uDD18-\\uDD1F\\uDD26\\uDD30-\\uDD39\\uDD3C-\\uDD3E\\uDD77\\uDDB5\\uDDB6\\uDDB8\\uDDB9\\uDDBB\\uDDCD-\\uDDCF\\uDDD1-\\uDDDD])/g;\n};\n","import stripAnsi from 'strip-ansi';\nimport eastAsianWidth from 'eastasianwidth';\nimport emojiRegex from 'emoji-regex';\n\nexport default function stringWidth(string, options = {}) {\n\tif (typeof string !== 'string' || string.length === 0) {\n\t\treturn 0;\n\t}\n\n\toptions = {\n\t\tambiguousIsNarrow: true,\n\t\t...options\n\t};\n\n\tstring = stripAnsi(string);\n\n\tif (string.length === 0) {\n\t\treturn 0;\n\t}\n\n\tstring = string.replace(emojiRegex(), ' ');\n\n\tconst ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2;\n\tlet width = 0;\n\n\tfor (const character of string) {\n\t\tconst codePoint = character.codePointAt(0);\n\n\t\t// Ignore control characters\n\t\tif (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore combining characters\n\t\tif (codePoint >= 0x300 && codePoint <= 0x36F) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst code = eastAsianWidth.eastAsianWidth(character);\n\t\tswitch (code) {\n\t\t\tcase 'F':\n\t\t\tcase 'W':\n\t\t\t\twidth += 2;\n\t\t\t\tbreak;\n\t\t\tcase 'A':\n\t\t\t\twidth += ambiguousCharacterWidth;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\twidth += 1;\n\t\t}\n\t}\n\n\treturn width;\n}\n","const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue: (red, green, blue) => {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue: hex => {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue: code => {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n","import stringWidth from 'string-width';\nimport stripAnsi from 'strip-ansi';\nimport ansiStyles from 'ansi-styles';\n\nconst ESCAPES = new Set([\n\t'\\u001B',\n\t'\\u009B',\n]);\n\nconst END_CODE = 39;\nconst ANSI_ESCAPE_BELL = '\\u0007';\nconst ANSI_CSI = '[';\nconst ANSI_OSC = ']';\nconst ANSI_SGR_TERMINATOR = 'm';\nconst ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;\n\nconst wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;\nconst wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`;\n\n// Calculate the length of words split on ' ', ignoring\n// the extra characters added by ansi escape codes\nconst wordLengths = string => string.split(' ').map(character => stringWidth(character));\n\n// Wrap a long word across multiple rows\n// Ansi escape codes do not count towards length\nconst wrapWord = (rows, word, columns) => {\n\tconst characters = [...word];\n\n\tlet isInsideEscape = false;\n\tlet isInsideLinkEscape = false;\n\tlet visible = stringWidth(stripAnsi(rows[rows.length - 1]));\n\n\tfor (const [index, character] of characters.entries()) {\n\t\tconst characterLength = stringWidth(character);\n\n\t\tif (visible + characterLength <= columns) {\n\t\t\trows[rows.length - 1] += character;\n\t\t} else {\n\t\t\trows.push(character);\n\t\t\tvisible = 0;\n\t\t}\n\n\t\tif (ESCAPES.has(character)) {\n\t\t\tisInsideEscape = true;\n\t\t\tisInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK);\n\t\t}\n\n\t\tif (isInsideEscape) {\n\t\t\tif (isInsideLinkEscape) {\n\t\t\t\tif (character === ANSI_ESCAPE_BELL) {\n\t\t\t\t\tisInsideEscape = false;\n\t\t\t\t\tisInsideLinkEscape = false;\n\t\t\t\t}\n\t\t\t} else if (character === ANSI_SGR_TERMINATOR) {\n\t\t\t\tisInsideEscape = false;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tvisible += characterLength;\n\n\t\tif (visible === columns && index < characters.length - 1) {\n\t\t\trows.push('');\n\t\t\tvisible = 0;\n\t\t}\n\t}\n\n\t// It's possible that the last row we copy over is only\n\t// ansi escape characters, handle this edge-case\n\tif (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {\n\t\trows[rows.length - 2] += rows.pop();\n\t}\n};\n\n// Trims spaces from a string ignoring invisible sequences\nconst stringVisibleTrimSpacesRight = string => {\n\tconst words = string.split(' ');\n\tlet last = words.length;\n\n\twhile (last > 0) {\n\t\tif (stringWidth(words[last - 1]) > 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlast--;\n\t}\n\n\tif (last === words.length) {\n\t\treturn string;\n\t}\n\n\treturn words.slice(0, last).join(' ') + words.slice(last).join('');\n};\n\n// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode\n//\n// 'hard' will never allow a string to take up more than columns characters\n//\n// 'soft' allows long words to expand past the column length\nconst exec = (string, columns, options = {}) => {\n\tif (options.trim !== false && string.trim() === '') {\n\t\treturn '';\n\t}\n\n\tlet returnValue = '';\n\tlet escapeCode;\n\tlet escapeUrl;\n\n\tconst lengths = wordLengths(string);\n\tlet rows = [''];\n\n\tfor (const [index, word] of string.split(' ').entries()) {\n\t\tif (options.trim !== false) {\n\t\t\trows[rows.length - 1] = rows[rows.length - 1].trimStart();\n\t\t}\n\n\t\tlet rowLength = stringWidth(rows[rows.length - 1]);\n\n\t\tif (index !== 0) {\n\t\t\tif (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {\n\t\t\t\t// If we start with a new word but the current row length equals the length of the columns, add a new row\n\t\t\t\trows.push('');\n\t\t\t\trowLength = 0;\n\t\t\t}\n\n\t\t\tif (rowLength > 0 || options.trim === false) {\n\t\t\t\trows[rows.length - 1] += ' ';\n\t\t\t\trowLength++;\n\t\t\t}\n\t\t}\n\n\t\t// In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns'\n\t\tif (options.hard && lengths[index] > columns) {\n\t\t\tconst remainingColumns = (columns - rowLength);\n\t\t\tconst breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);\n\t\t\tconst breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);\n\t\t\tif (breaksStartingNextLine < breaksStartingThisLine) {\n\t\t\t\trows.push('');\n\t\t\t}\n\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {\n\t\t\tif (options.wordWrap === false && rowLength < columns) {\n\t\t\t\twrapWord(rows, word, columns);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\trows.push('');\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && options.wordWrap === false) {\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\trows[rows.length - 1] += word;\n\t}\n\n\tif (options.trim !== false) {\n\t\trows = rows.map(row => stringVisibleTrimSpacesRight(row));\n\t}\n\n\tconst pre = [...rows.join('\\n')];\n\n\tfor (const [index, character] of pre.entries()) {\n\t\treturnValue += character;\n\n\t\tif (ESCAPES.has(character)) {\n\t\t\tconst {groups} = new RegExp(`(?:\\\\${ANSI_CSI}(?<code>\\\\d+)m|\\\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}};\n\t\t\tif (groups.code !== undefined) {\n\t\t\t\tconst code = Number.parseFloat(groups.code);\n\t\t\t\tescapeCode = code === END_CODE ? undefined : code;\n\t\t\t} else if (groups.uri !== undefined) {\n\t\t\t\tescapeUrl = groups.uri.length === 0 ? undefined : groups.uri;\n\t\t\t}\n\t\t}\n\n\t\tconst code = ansiStyles.codes.get(Number(escapeCode));\n\n\t\tif (pre[index + 1] === '\\n') {\n\t\t\tif (escapeUrl) {\n\t\t\t\treturnValue += wrapAnsiHyperlink('');\n\t\t\t}\n\n\t\t\tif (escapeCode && code) {\n\t\t\t\treturnValue += wrapAnsiCode(code);\n\t\t\t}\n\t\t} else if (character === '\\n') {\n\t\t\tif (escapeCode && code) {\n\t\t\t\treturnValue += wrapAnsiCode(escapeCode);\n\t\t\t}\n\n\t\t\tif (escapeUrl) {\n\t\t\t\treturnValue += wrapAnsiHyperlink(escapeUrl);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn returnValue;\n};\n\n// For each newline, invoke the method separately\nexport default function wrapAnsi(string, columns, options) {\n\treturn String(string)\n\t\t.normalize()\n\t\t.replace(/\\r\\n/g, '\\n')\n\t\t.split('\\n')\n\t\t.map(line => exec(line, columns, options))\n\t\t.join('\\n');\n}\n","import type { Key, ReadLine } from 'node:readline';\n\nimport { stdin, stdout } from 'node:process';\nimport readline from 'node:readline';\nimport { Readable, Writable } from 'node:stream';\nimport { WriteStream } from 'node:tty';\nimport { cursor, erase } from 'sisteransi';\nimport wrap from 'wrap-ansi';\n\nfunction diffLines(a: string, b: string) {\n\tif (a === b) return;\n\n\tconst aLines = a.split('\\n');\n\tconst bLines = b.split('\\n');\n\tconst diff: number[] = [];\n\n\tfor (let i = 0; i < Math.max(aLines.length, bLines.length); i++) {\n\t\tif (aLines[i] !== bLines[i]) diff.push(i);\n\t}\n\n\treturn diff;\n}\n\nconst cancel = Symbol('clack:cancel');\nexport function isCancel(value: unknown): value is symbol {\n\treturn value === cancel;\n}\n\nfunction setRawMode(input: Readable, value: boolean) {\n\tif ((input as typeof stdin).isTTY) (input as typeof stdin).setRawMode(value);\n}\n\nconst aliases = new Map([\n\t['k', 'up'],\n\t['j', 'down'],\n\t['h', 'left'],\n\t['l', 'right'],\n]);\nconst keys = new Set(['up', 'down', 'left', 'right', 'space', 'enter']);\n\nexport interface PromptOptions<Self extends Prompt> {\n\trender(this: Omit<Self, 'prompt'>): string | void;\n\tplaceholder?: string;\n\tinitialValue?: any;\n\tvalidate?: ((value: any) => string | void) | undefined;\n\tinput?: Readable;\n\toutput?: Writable;\n\tdebug?: boolean;\n}\n\nexport type State = 'initial' | 'active' | 'cancel' | 'submit' | 'error';\n\nexport default class Prompt {\n\tprotected input: Readable;\n\tprotected output: Writable;\n\tprivate rl!: ReadLine;\n\tprivate opts: Omit<PromptOptions<Prompt>, 'render' | 'input' | 'output'>;\n\tprivate _track: boolean = false;\n\tprivate _render: (context: Omit<Prompt, 'prompt'>) => string | void;\n\tprotected _cursor: number = 0;\n\n\tpublic state: State = 'initial';\n\tpublic value: any;\n\tpublic error: string = '';\n\n\tconstructor(\n\t\t{ render, input = stdin, output = stdout, ...opts }: PromptOptions<Prompt>,\n\t\ttrackValue: boolean = true\n\t) {\n\t\tthis.opts = opts;\n\t\tthis.onKeypress = this.onKeypress.bind(this);\n\t\tthis.close = this.close.bind(this);\n\t\tthis.render = this.render.bind(this);\n\t\tthis._render = render.bind(this);\n\t\tthis._track = trackValue;\n\n\t\tthis.input = input;\n\t\tthis.output = output;\n\t}\n\n\tpublic prompt() {\n\t\tconst sink = new WriteStream(0);\n\t\tsink._write = (chunk, encoding, done) => {\n\t\t\tif (this._track) {\n\t\t\t\tthis.value = this.rl.line.replace(/\\t/g, '');\n\t\t\t\tthis._cursor = this.rl.cursor;\n\t\t\t\tthis.emit('value', this.value);\n\t\t\t}\n\t\t\tdone();\n\t\t};\n\t\tthis.input.pipe(sink);\n\n\t\tthis.rl = readline.createInterface({\n\t\t\tinput: this.input,\n\t\t\toutput: sink,\n\t\t\ttabSize: 2,\n\t\t\tprompt: '',\n\t\t\tescapeCodeTimeout: 50,\n\t\t});\n\t\treadline.emitKeypressEvents(this.input, this.rl);\n\t\tthis.rl.prompt();\n\t\tif (this.opts.initialValue !== undefined && this._track) {\n\t\t\tthis.rl.write(this.opts.initialValue);\n\t\t}\n\n\t\tthis.input.on('keypress', this.onKeypress);\n\t\tsetRawMode(this.input, true);\n\t\tthis.output.on('resize', this.render);\n\n\t\tthis.render();\n\n\t\treturn new Promise<string | symbol>((resolve, reject) => {\n\t\t\tthis.once('submit', () => {\n\t\t\t\tthis.output.write(cursor.show);\n\t\t\t\tthis.output.off('resize', this.render);\n\t\t\t\tsetRawMode(this.input, false);\n\t\t\t\tresolve(this.value);\n\t\t\t});\n\t\t\tthis.once('cancel', () => {\n\t\t\t\tthis.output.write(cursor.show);\n\t\t\t\tthis.output.off('resize', this.render);\n\t\t\t\tsetRawMode(this.input, false);\n\t\t\t\tresolve(cancel);\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate subscribers = new Map<string, { cb: (...args: any) => any; once?: boolean }[]>();\n\tpublic on(event: string, cb: (...args: any) => any) {\n\t\tconst arr = this.subscribers.get(event) ?? [];\n\t\tarr.push({ cb });\n\t\tthis.subscribers.set(event, arr);\n\t}\n\tpublic once(event: string, cb: (...args: any) => any) {\n\t\tconst arr = this.subscribers.get(event) ?? [];\n\t\tarr.push({ cb, once: true });\n\t\tthis.subscribers.set(event, arr);\n\t}\n\tpublic emit(event: string, ...data: any[]) {\n\t\tconst cbs = this.subscribers.get(event) ?? [];\n\t\tconst cleanup: (() => void)[] = [];\n\t\tfor (const subscriber of cbs) {\n\t\t\tsubscriber.cb(...data);\n\t\t\tif (subscriber.once) {\n\t\t\t\tcleanup.push(() => cbs.splice(cbs.indexOf(subscriber), 1));\n\t\t\t}\n\t\t}\n\t\tfor (const cb of cleanup) {\n\t\t\tcb();\n\t\t}\n\t}\n\tprivate unsubscribe() {\n\t\tthis.subscribers.clear();\n\t}\n\n\tprivate onKeypress(char: string, key?: Key) {\n\t\tif (this.state === 'error') {\n\t\t\tthis.state = 'active';\n\t\t}\n\t\tif (key?.name && !this._track && aliases.has(key.name)) {\n\t\t\tthis.emit('cursor', aliases.get(key.name));\n\t\t}\n\t\tif (key?.name && keys.has(key.name)) {\n\t\t\tthis.emit('cursor', key.name);\n\t\t}\n\t\tif (char && (char.toLowerCase() === 'y' || char.toLowerCase() === 'n')) {\n\t\t\tthis.emit('confirm', char.toLowerCase() === 'y');\n\t\t}\n\t\tif (char === '\\t' && this.opts.placeholder) {\n\t\t\tif (!this.value) {\n\t\t\t\tthis.rl.write(this.opts.placeholder);\n\t\t\t\tthis.emit('value', this.opts.placeholder);\n\t\t\t}\n\t\t}\n\t\tif (char) {\n\t\t\tthis.emit('key', char.toLowerCase());\n\t\t}\n\n\t\tif (key?.name === 'return') {\n\t\t\tif (this.opts.validate) {\n\t\t\t\tconst problem = this.opts.validate(this.value);\n\t\t\t\tif (problem) {\n\t\t\t\t\tthis.error = problem;\n\t\t\t\t\tthis.state = 'error';\n\t\t\t\t\tthis.rl.write(this.value);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.state !== 'error') {\n\t\t\t\tthis.state = 'submit';\n\t\t\t}\n\t\t}\n\t\tif (char === '\\x03') {\n\t\t\tthis.state = 'cancel';\n\t\t}\n\t\tif (this.state === 'submit' || this.state === 'cancel') {\n\t\t\tthis.emit('finalize');\n\t\t}\n\t\tthis.render();\n\t\tif (this.state === 'submit' || this.state === 'cancel') {\n\t\t\tthis.close();\n\t\t}\n\t}\n\n\tprotected close() {\n\t\tthis.input.unpipe();\n\t\tthis.input.removeListener('keypress', this.onKeypress);\n\t\tthis.output.write('\\n');\n\t\tsetRawMode(this.input, false);\n\t\tthis.rl.close();\n\t\tthis.emit(`${this.state}`, this.value);\n\t\tthis.unsubscribe();\n\t}\n\n\tprivate restoreCursor() {\n\t\tconst lines =\n\t\t\twrap(this._prevFrame, process.stdout.columns, { hard: true }).split('\\n').length - 1;\n\t\tthis.output.write(cursor.move(-999, lines * -1));\n\t}\n\n\tprivate _prevFrame = '';\n\tprivate render() {\n\t\tconst frame = wrap(this._render(this) ?? '', process.stdout.columns, { hard: true });\n\t\tif (frame === this._prevFrame) return;\n\n\t\tif (this.state === 'initial') {\n\t\t\tthis.output.write(cursor.hide);\n\t\t} else {\n\t\t\tconst diff = diffLines(this._prevFrame, frame);\n\t\t\tthis.restoreCursor();\n\t\t\t// If a single line has changed, only update that line\n\t\t\tif (diff && diff?.length === 1) {\n\t\t\t\tconst diffLine = diff[0];\n\t\t\t\tthis.output.write(cursor.move(0, diffLine));\n\t\t\t\tthis.output.write(erase.lines(1));\n\t\t\t\tconst lines = frame.split('\\n');\n\t\t\t\tthis.output.write(lines[diffLine]);\n\t\t\t\tthis._prevFrame = frame;\n\t\t\t\tthis.output.write(cursor.move(0, lines.length - diffLine - 1));\n\t\t\t\treturn;\n\t\t\t\t// If many lines have changed, rerender everything past the first line\n\t\t\t} else if (diff && diff?.length > 1) {\n\t\t\t\tconst diffLine = diff[0];\n\t\t\t\tthis.output.write(cursor.move(0, diffLine));\n\t\t\t\tthis.output.write(erase.down());\n\t\t\t\tconst lines = frame.split('\\n');\n\t\t\t\tconst newLines = lines.slice(diffLine);\n\t\t\t\tthis.output.write(newLines.join('\\n'));\n\t\t\t\tthis._prevFrame = frame;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.output.write(erase.down());\n\t\t}\n\n\t\tthis.output.write(frame);\n\t\tif (this.state === 'initial') {\n\t\t\tthis.state = 'active';\n\t\t}\n\t\tthis._prevFrame = frame;\n\t}\n}\n","import { cursor } from 'sisteransi';\nimport Prompt, { PromptOptions } from './prompt';\n\ninterface ConfirmOptions extends PromptOptions<ConfirmPrompt> {\n\tactive: string;\n\tinactive: string;\n\tinitialValue?: boolean;\n}\nexport default class ConfirmPrompt extends Prompt {\n\tget cursor() {\n\t\treturn this.value ? 0 : 1;\n\t}\n\n\tprivate get _value() {\n\t\treturn this.cursor === 0;\n\t}\n\n\tconstructor(opts: ConfirmOptions) {\n\t\tsuper(opts, false);\n\t\tthis.value = opts.initialValue ? true : false;\n\n\t\tthis.on('value', () => {\n\t\t\tthis.value = this._value;\n\t\t});\n\n\t\tthis.on('confirm', (confirm) => {\n\t\t\tthis.output.write(cursor.move(0, -1));\n\t\t\tthis.value = confirm;\n\t\t\tthis.state = 'submit';\n\t\t\tthis.close();\n\t\t});\n\n\t\tthis.on('cursor', () => {\n\t\t\tthis.value = !this.value;\n\t\t});\n\t}\n}\n","import Prompt, { PromptOptions } from './prompt';\n\ninterface GroupMultiSelectOptions<T extends { value: any }>\n\textends PromptOptions<GroupMultiSelectPrompt<T>> {\n\toptions: Record<string, T[]>;\n\tinitialValues?: T['value'][];\n\trequired?: boolean;\n\tcursorAt?: T['value'];\n}\nexport default class GroupMultiSelectPrompt<T extends { value: any }> extends Prompt {\n\toptions: (T & { group: string | boolean })[];\n\tcursor: number = 0;\n\n\tgetGroupItems(group: string): T[] {\n\t\treturn this.options.filter((o) => o.group === group);\n\t}\n\n\tisGroupSelected(group: string) {\n\t\tconst items = this.getGroupItems(group);\n\t\treturn items.every((i) => this.value.includes(i.value));\n\t}\n\n\tprivate toggleValue() {\n\t\tconst item = this.options[this.cursor];\n\t\tif (item.group === true) {\n\t\t\tconst group = item.value;\n\t\t\tconst groupedItems = this.getGroupItems(group);\n\t\t\tif (this.isGroupSelected(group)) {\n\t\t\t\tthis.value = this.value.filter(\n\t\t\t\t\t(v: string) => groupedItems.findIndex((i) => i.value === v) === -1\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis.value = [...this.value, ...groupedItems.map((i) => i.value)];\n\t\t\t}\n\t\t\tthis.value = Array.from(new Set(this.value));\n\t\t} else {\n\t\t\tconst selected = this.value.includes(item.value);\n\t\t\tthis.value = selected\n\t\t\t\t? this.value.filter((v: T['value']) => v !== item.value)\n\t\t\t\t: [...this.value, item.value];\n\t\t}\n\t}\n\n\tconstructor(opts: GroupMultiSelectOptions<T>) {\n\t\tsuper(opts, false);\n\t\tconst { options } = opts;\n\t\tthis.options = Object.entries(options).flatMap(([key, option]) => [\n\t\t\t{ value: key, group: true, label: key },\n\t\t\t...option.map((opt) => ({ ...opt, group: key })),\n\t\t]) as any;\n\t\tthis.value = [...(opts.initialValues ?? [])];\n\t\tthis.cursor = Math.max(\n\t\t\tthis.options.findIndex(({ value }) => value === opts.cursorAt),\n\t\t\t0\n\t\t);\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up':\n\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right':\n\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'space':\n\t\t\t\t\tthis.toggleValue();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}\n}\n","import Prompt, { PromptOptions } from './prompt';\n\ninterface MultiSelectOptions<T extends { value: any }> extends PromptOptions<MultiSelectPrompt<T>> {\n\toptions: T[];\n\tinitialValues?: T['value'][];\n\trequired?: boolean;\n\tcursorAt?: T['value'];\n}\nexport default class MultiSelectPrompt<T extends { value: any }> extends Prompt {\n\toptions: T[];\n\tcursor: number = 0;\n\n\tprivate get _value() {\n\t\treturn this.options[this.cursor].value;\n\t}\n\n\tprivate toggleAll() {\n\t\tconst allSelected = this.value.length === this.options.length;\n\t\tthis.value = allSelected ? [] : this.options.map((v) => v.value);\n\t}\n\n\tprivate toggleValue() {\n\t\tconst selected = this.value.includes(this._value);\n\t\tthis.value = selected\n\t\t\t? this.value.filter((value: T['value']) => value !== this._value)\n\t\t\t: [...this.value, this._value];\n\t}\n\n\tconstructor(opts: MultiSelectOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\t\tthis.value = [...(opts.initialValues ?? [])];\n\t\tthis.cursor = Math.max(\n\t\t\tthis.options.findIndex(({ value }) => value === opts.cursorAt),\n\t\t\t0\n\t\t);\n\t\tthis.on('key', (char) => {\n\t\t\tif (char === 'a') {\n\t\t\t\tthis.toggleAll();\n\t\t\t}\n\t\t});\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up':\n\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right':\n\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'space':\n\t\t\t\t\tthis.toggleValue();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}\n}\n","import color from 'picocolors';\nimport Prompt, { PromptOptions } from './prompt';\n\ninterface PasswordOptions extends PromptOptions<PasswordPrompt> {\n\tmask?: string;\n}\nexport default class PasswordPrompt extends Prompt {\n\tvalueWithCursor = '';\n\tprivate _mask = '•';\n\tget cursor() {\n\t\treturn this._cursor;\n\t}\n\tget masked() {\n\t\treturn this.value.replaceAll(/./g, this._mask);\n\t}\n\tconstructor({ mask, ...opts }: PasswordOptions) {\n\t\tsuper(opts);\n\t\tthis._mask = mask ?? '•';\n\n\t\tthis.on('finalize', () => {\n\t\t\tthis.valueWithCursor = this.masked;\n\t\t});\n\t\tthis.on('value', () => {\n\t\t\tif (this.cursor >= this.value.length) {\n\t\t\t\tthis.valueWithCursor = `${this.masked}${color.inverse(color.hidden('_'))}`;\n\t\t\t} else {\n\t\t\t\tconst s1 = this.masked.slice(0, this.cursor);\n\t\t\t\tconst s2 = this.masked.slice(this.cursor);\n\t\t\t\tthis.valueWithCursor = `${s1}${color.inverse(s2[0])}${s2.slice(1)}`;\n\t\t\t}\n\t\t});\n\t}\n}\n","import Prompt, { PromptOptions } from './prompt';\n\ninterface SelectOptions<T extends { value: any }> extends PromptOptions<SelectPrompt<T>> {\n\toptions: T[];\n\tinitialValue?: T['value'];\n}\nexport default class SelectPrompt<T extends { value: any }> extends Prompt {\n\toptions: T[];\n\tcursor: number = 0;\n\n\tprivate get _value() {\n\t\treturn this.options[this.cursor];\n\t}\n\n\tprivate changeValue() {\n\t\tthis.value = this._value.value;\n\t}\n\n\tconstructor(opts: SelectOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\t\tthis.cursor = this.options.findIndex(({ value }) => value === opts.initialValue);\n\t\tif (this.cursor === -1) this.cursor = 0;\n\t\tthis.changeValue();\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up':\n\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right':\n\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tthis.changeValue();\n\t\t});\n\t}\n}\n","import Prompt, { PromptOptions } from './prompt';\n\ninterface SelectKeyOptions<T extends { value: any }> extends PromptOptions<SelectKeyPrompt<T>> {\n\toptions: T[];\n}\nexport default class SelectKeyPrompt<T extends { value: any }> extends Prompt {\n\toptions: T[];\n\tcursor: number = 0;\n\n\tconstructor(opts: SelectKeyOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\t\tconst keys = this.options.map(({ value: [initial] }) => initial?.toLowerCase());\n\t\tthis.cursor = Math.max(keys.indexOf(opts.initialValue), 0);\n\n\t\tthis.on('key', (key) => {\n\t\t\tif (!keys.includes(key)) return;\n\t\t\tconst value = this.options.find(({ value: [initial] }) => initial?.toLowerCase() === key);\n\t\t\tif (value) {\n\t\t\t\tthis.value = value.value;\n\t\t\t\tthis.state = 'submit';\n\t\t\t\tthis.emit('submit');\n\t\t\t}\n\t\t});\n\t}\n}\n","import color from 'picocolors';\nimport Prompt, { PromptOptions } from './prompt';\n\nexport interface TextOptions extends PromptOptions<TextPrompt> {\n\tplaceholder?: string;\n\tdefaultValue?: string;\n}\n\nexport default class TextPrompt extends Prompt {\n\tvalueWithCursor = '';\n\tget cursor() {\n\t\treturn this._cursor;\n\t}\n\tconstructor(opts: TextOptions) {\n\t\tsuper(opts);\n\n\t\tthis.on('finalize', () => {\n\t\t\tif (!this.value) {\n\t\t\t\tthis.value = opts.defaultValue;\n\t\t\t}\n\t\t\tthis.valueWithCursor = this.value;\n\t\t});\n\t\tthis.on('value', () => {\n\t\t\tif (this.cursor >= this.value.length) {\n\t\t\t\tthis.valueWithCursor = `${this.value}${color.inverse(color.hidden('_'))}`;\n\t\t\t} else {\n\t\t\t\tconst s1 = this.value.slice(0, this.cursor);\n\t\t\t\tconst s2 = this.value.slice(this.cursor);\n\t\t\t\tthis.valueWithCursor = `${s1}${color.inverse(s2[0])}${s2.slice(1)}`;\n\t\t\t}\n\t\t});\n\t}\n}\n","import type { Key } from 'node:readline';\n\nimport { stdin, stdout } from 'node:process';\nimport * as readline from 'node:readline';\nimport { cursor } from 'sisteransi';\n\nconst isWindows = globalThis.process.platform.startsWith('win');\n\nexport function block({\n\tinput = stdin,\n\toutput = stdout,\n\toverwrite = true,\n\thideCursor = true,\n} = {}) {\n\tconst rl = readline.createInterface({\n\t\tinput,\n\t\toutput,\n\t\tprompt: '',\n\t\ttabSize: 1,\n\t});\n\treadline.emitKeypressEvents(input, rl);\n\tif (input.isTTY) input.setRawMode(true);\n\n\tconst clear = (data: Buffer, { name }: Key) => {\n\t\tconst str = String(data);\n\t\tif (str === '\\x03') {\n\t\t\tif (hideCursor) output.write(cursor.show);\n\t\t\tprocess.exit(0);\n\t\t\treturn;\n\t\t}\n\t\tif (!overwrite) return;\n\t\tlet dx = name === 'return' ? 0 : -1;\n\t\tlet dy = name === 'return' ? -1 : 0;\n\n\t\treadline.moveCursor(output, dx, dy, () => {\n\t\t\treadline.clearLine(output, 1, () => {\n\t\t\t\tinput.once('keypress', clear);\n\t\t\t});\n\t\t});\n\t};\n\tif (hideCursor) output.write(cursor.hide);\n\tinput.once('keypress', clear);\n\n\treturn () => {\n\t\tinput.off('keypress', clear);\n\t\tif (hideCursor) output.write(cursor.show);\n\n\t\t// Prevent Windows specific issues: https://github.com/natemoo-re/clack/issues/176\n\t\tif (input.isTTY && !isWindows) input.setRawMode(false);\n\n\t\t// @ts-expect-error fix for https://github.com/nodejs/node/issues/31762#issuecomment-1441223907\n\t\trl.terminal = false;\n\t\trl.close();\n\t};\n}\n"],"names":["onlyFirst","pattern","string","eaw","module","character","y","codePoint","code","stringToArray","characters","len","i","text","start","end","result","eawLen","chars","char","charLen","options","emojiRegex","ambiguousCharacterWidth","width","offset","red","green","blue","codes","groupName","group","styleName","style","hex","matches","colorString","integer","remainder","value","uri","rows","word","columns","isInsideEscape","isInsideLinkEscape","visible","index","characterLength","words","last","returnValue","escapeCode","escapeUrl","lengths","rowLength","remainingColumns","breaksStartingThisLine","row","pre","groups","line","r","t","e","o","diffLines","a","b","aLines","bLines","diff","cancel","setRawMode","input","aliases","keys","Prompt","render","stdin","output","stdout","opts","trackValue","__publicField","sink","WriteStream","chunk","encoding","done","readline","resolve","reject","cursor","event","cb","arr","data","cbs","cleanup","subscriber","key","problem","lines","wrap","frame","diffLine","erase","newLines","ConfirmPrompt","confirm","n","l","GroupMultiSelectPrompt","option","opt","item","groupedItems","v","selected","s","allSelected","PasswordPrompt","mask","color","s1","s2","SelectKeyPrompt","initial","TextPrompt","isWindows","overwrite","hideCursor","rl","clear","name","dx","dy"],"mappings":"yiBAAe,SAAS,UAAU,CAAC,UAAAA,EAAY,EAAK,EAAI,CAAA,EAAI,CAG3D,MAAMC,EAAU,CACf,0JACA,0DACF,EAAG,KAAK,GAAG,EAEV,OAAO,IAAI,OAAOA,EAASD,EAAY,OAAY,GAAG,CACvD,CCPA,MAAM,MAAQ,UAAS,EAER,SAAS,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WAAAC,EAAa,EACd,EAAI,CAAC,EAAG,CACP,MAAMC,EAAK3C,aAAS,gBAAgB,CACnC,MAAAhB,EACA,OAAAM,EACA,OAAQ,GACR,QAAS,CACV,CAAC,EACDU,aAAS,mBAAmBhB,EAAO2D,CAAE,EACjC3D,EAAM,OAAOA,EAAM,WAAW,EAAI,EAEtC,MAAM4D,EAAQ,CAACrC,EAAc,CAAE,KAAAsC,CAAK,IAAW,CAE9C,GADY,OAAOtC,CAAI,IACX,IAAQ,CACfmC,GAAYpD,EAAO,MAAMa,WAAAA,OAAO,IAAI,EACxC,QAAQ,KAAK,CAAC,EACd,MACD,CACA,GAAI,CAACsC,EAAW,OAChB,IAAIK,EAAKD,IAAS,SAAW,EAAI,GAC7BE,EAAKF,IAAS,SAAW,GAAK,EAElC7C,aAAS,WAAWV,EAAQwD,EAAIC,EAAI,IAAM,CACzC/C,aAAS,UAAUV,EAAQ,EAAG,IAAM,CACnCN,EAAM,KAAK,WAAY4D,CAAK,CAC7B,CAAC,CACF,CAAC,CACF,EACA,OAAIF,GAAYpD,EAAO,MAAMa,WAAAA,OAAO,IAAI,EACxCnB,EAAM,KAAK,WAAY4D,CAAK,EAErB,IAAM,CACZ5D,EAAM,IAAI,WAAY4D,CAAK,EACvBF,GAAYpD,EAAO,MAAMa,WAAO,OAAA,IAAI,EAGpCnB,EAAM,OAAS,CAACwD,GAAWxD,EAAM,WAAW,EAAK,EAGrD2D,EAAG,SAAW,GACdA,EAAG,OACJ,CACD","x_google_ignoreList":[0,1,2,3,4,5,6]} node_modules/@clack/core/dist/index.mjs 0000664 00000105125 15114743311 0014121 0 ustar 00 import{cursor as l,erase as m}from"sisteransi";import{stdin as $,stdout as k}from"node:process";import*as f from"node:readline";import _ from"node:readline";import{WriteStream as U}from"node:tty";import c from"picocolors";function q({onlyFirst:e=!1}={}){const F=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(F,e?void 0:"g")}const J=q();function S(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(J,"")}function T(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var j={exports:{}};(function(e){var u={};e.exports=u,u.eastAsianWidth=function(t){var s=t.charCodeAt(0),C=t.length==2?t.charCodeAt(1):0,D=s;return 55296<=s&&s<=56319&&56320<=C&&C<=57343&&(s&=1023,C&=1023,D=s<<10|C,D+=65536),D==12288||65281<=D&&D<=65376||65504<=D&&D<=65510?"F":D==8361||65377<=D&&D<=65470||65474<=D&&D<=65479||65482<=D&&D<=65487||65490<=D&&D<=65495||65498<=D&&D<=65500||65512<=D&&D<=65518?"H":4352<=D&&D<=4447||4515<=D&&D<=4519||4602<=D&&D<=4607||9001<=D&&D<=9002||11904<=D&&D<=11929||11931<=D&&D<=12019||12032<=D&&D<=12245||12272<=D&&D<=12283||12289<=D&&D<=12350||12353<=D&&D<=12438||12441<=D&&D<=12543||12549<=D&&D<=12589||12593<=D&&D<=12686||12688<=D&&D<=12730||12736<=D&&D<=12771||12784<=D&&D<=12830||12832<=D&&D<=12871||12880<=D&&D<=13054||13056<=D&&D<=19903||19968<=D&&D<=42124||42128<=D&&D<=42182||43360<=D&&D<=43388||44032<=D&&D<=55203||55216<=D&&D<=55238||55243<=D&&D<=55291||63744<=D&&D<=64255||65040<=D&&D<=65049||65072<=D&&D<=65106||65108<=D&&D<=65126||65128<=D&&D<=65131||110592<=D&&D<=110593||127488<=D&&D<=127490||127504<=D&&D<=127546||127552<=D&&D<=127560||127568<=D&&D<=127569||131072<=D&&D<=194367||177984<=D&&D<=196605||196608<=D&&D<=262141?"W":32<=D&&D<=126||162<=D&&D<=163||165<=D&&D<=166||D==172||D==175||10214<=D&&D<=10221||10629<=D&&D<=10630?"Na":D==161||D==164||167<=D&&D<=168||D==170||173<=D&&D<=174||176<=D&&D<=180||182<=D&&D<=186||188<=D&&D<=191||D==198||D==208||215<=D&&D<=216||222<=D&&D<=225||D==230||232<=D&&D<=234||236<=D&&D<=237||D==240||242<=D&&D<=243||247<=D&&D<=250||D==252||D==254||D==257||D==273||D==275||D==283||294<=D&&D<=295||D==299||305<=D&&D<=307||D==312||319<=D&&D<=322||D==324||328<=D&&D<=331||D==333||338<=D&&D<=339||358<=D&&D<=359||D==363||D==462||D==464||D==466||D==468||D==470||D==472||D==474||D==476||D==593||D==609||D==708||D==711||713<=D&&D<=715||D==717||D==720||728<=D&&D<=731||D==733||D==735||768<=D&&D<=879||913<=D&&D<=929||931<=D&&D<=937||945<=D&&D<=961||963<=D&&D<=969||D==1025||1040<=D&&D<=1103||D==1105||D==8208||8211<=D&&D<=8214||8216<=D&&D<=8217||8220<=D&&D<=8221||8224<=D&&D<=8226||8228<=D&&D<=8231||D==8240||8242<=D&&D<=8243||D==8245||D==8251||D==8254||D==8308||D==8319||8321<=D&&D<=8324||D==8364||D==8451||D==8453||D==8457||D==8467||D==8470||8481<=D&&D<=8482||D==8486||D==8491||8531<=D&&D<=8532||8539<=D&&D<=8542||8544<=D&&D<=8555||8560<=D&&D<=8569||D==8585||8592<=D&&D<=8601||8632<=D&&D<=8633||D==8658||D==8660||D==8679||D==8704||8706<=D&&D<=8707||8711<=D&&D<=8712||D==8715||D==8719||D==8721||D==8725||D==8730||8733<=D&&D<=8736||D==8739||D==8741||8743<=D&&D<=8748||D==8750||8756<=D&&D<=8759||8764<=D&&D<=8765||D==8776||D==8780||D==8786||8800<=D&&D<=8801||8804<=D&&D<=8807||8810<=D&&D<=8811||8814<=D&&D<=8815||8834<=D&&D<=8835||8838<=D&&D<=8839||D==8853||D==8857||D==8869||D==8895||D==8978||9312<=D&&D<=9449||9451<=D&&D<=9547||9552<=D&&D<=9587||9600<=D&&D<=9615||9618<=D&&D<=9621||9632<=D&&D<=9633||9635<=D&&D<=9641||9650<=D&&D<=9651||9654<=D&&D<=9655||9660<=D&&D<=9661||9664<=D&&D<=9665||9670<=D&&D<=9672||D==9675||9678<=D&&D<=9681||9698<=D&&D<=9701||D==9711||9733<=D&&D<=9734||D==9737||9742<=D&&D<=9743||9748<=D&&D<=9749||D==9756||D==9758||D==9792||D==9794||9824<=D&&D<=9825||9827<=D&&D<=9829||9831<=D&&D<=9834||9836<=D&&D<=9837||D==9839||9886<=D&&D<=9887||9918<=D&&D<=9919||9924<=D&&D<=9933||9935<=D&&D<=9953||D==9955||9960<=D&&D<=9983||D==10045||D==10071||10102<=D&&D<=10111||11093<=D&&D<=11097||12872<=D&&D<=12879||57344<=D&&D<=63743||65024<=D&&D<=65039||D==65533||127232<=D&&D<=127242||127248<=D&&D<=127277||127280<=D&&D<=127337||127344<=D&&D<=127386||917760<=D&&D<=917999||983040<=D&&D<=1048573||1048576<=D&&D<=1114109?"A":"N"},u.characterLength=function(t){var s=this.eastAsianWidth(t);return s=="F"||s=="W"||s=="A"?2:1};function F(t){return t.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}u.length=function(t){for(var s=F(t),C=0,D=0;D<s.length;D++)C=C+this.characterLength(s[D]);return C},u.slice=function(t,s,C){textLen=u.length(t),s=s||0,C=C||1,s<0&&(s=textLen+s),C<0&&(C=textLen+C);for(var D="",i=0,n=F(t),E=0;E<n.length;E++){var h=n[E],o=u.length(h);if(i>=s-(o==2?1:0))if(i+o<=C)D+=h;else break;i+=o}return D}})(j);var Q=j.exports;const X=T(Q);var DD=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?: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uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\u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\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g};const uD=T(DD);function A(e,u={}){if(typeof e!="string"||e.length===0||(u={ambiguousIsNarrow:!0,...u},e=S(e),e.length===0))return 0;e=e.replace(uD()," ");const F=u.ambiguousIsNarrow?1:2;let t=0;for(const s of e){const C=s.codePointAt(0);if(C<=31||C>=127&&C<=159||C>=768&&C<=879)continue;switch(X.eastAsianWidth(s)){case"F":case"W":t+=2;break;case"A":t+=F;break;default:t+=1}}return t}const d=10,M=(e=0)=>u=>`\x1B[${u+e}m`,P=(e=0)=>u=>`\x1B[${38+e};5;${u}m`,W=(e=0)=>(u,F,t)=>`\x1B[${38+e};2;${u};${F};${t}m`,r={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(r.modifier);const FD=Object.keys(r.color),eD=Object.keys(r.bgColor);[...FD,...eD];function tD(){const e=new Map;for(const[u,F]of Object.entries(r)){for(const[t,s]of Object.entries(F))r[t]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},F[t]=r[t],e.set(s[0],s[1]);Object.defineProperty(r,u,{value:F,enumerable:!1})}return Object.defineProperty(r,"codes",{value:e,enumerable:!1}),r.color.close="\x1B[39m",r.bgColor.close="\x1B[49m",r.color.ansi=M(),r.color.ansi256=P(),r.color.ansi16m=W(),r.bgColor.ansi=M(d),r.bgColor.ansi256=P(d),r.bgColor.ansi16m=W(d),Object.defineProperties(r,{rgbToAnsi256:{value:(u,F,t)=>u===F&&F===t?u<8?16:u>248?231:Math.round((u-8)/247*24)+232:16+36*Math.round(u/255*5)+6*Math.round(F/255*5)+Math.round(t/255*5),enumerable:!1},hexToRgb:{value:u=>{const F=/[a-f\d]{6}|[a-f\d]{3}/i.exec(u.toString(16));if(!F)return[0,0,0];let[t]=F;t.length===3&&(t=[...t].map(C=>C+C).join(""));const s=Number.parseInt(t,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:u=>r.rgbToAnsi256(...r.hexToRgb(u)),enumerable:!1},ansi256ToAnsi:{value:u=>{if(u<8)return 30+u;if(u<16)return 90+(u-8);let F,t,s;if(u>=232)F=((u-232)*10+8)/255,t=F,s=F;else{u-=16;const i=u%36;F=Math.floor(u/36)/5,t=Math.floor(i/6)/5,s=i%6/5}const C=Math.max(F,t,s)*2;if(C===0)return 30;let D=30+(Math.round(s)<<2|Math.round(t)<<1|Math.round(F));return C===2&&(D+=60),D},enumerable:!1},rgbToAnsi:{value:(u,F,t)=>r.ansi256ToAnsi(r.rgbToAnsi256(u,F,t)),enumerable:!1},hexToAnsi:{value:u=>r.ansi256ToAnsi(r.hexToAnsi256(u)),enumerable:!1}}),r}const sD=tD(),g=new Set(["\x1B","\x9B"]),CD=39,b="\x07",O="[",iD="]",I="m",w=`${iD}8;;`,N=e=>`${g.values().next().value}${O}${e}${I}`,L=e=>`${g.values().next().value}${w}${e}${b}`,rD=e=>e.split(" ").map(u=>A(u)),y=(e,u,F)=>{const t=[...u];let s=!1,C=!1,D=A(S(e[e.length-1]));for(const[i,n]of t.entries()){const E=A(n);if(D+E<=F?e[e.length-1]+=n:(e.push(n),D=0),g.has(n)&&(s=!0,C=t.slice(i+1).join("").startsWith(w)),s){C?n===b&&(s=!1,C=!1):n===I&&(s=!1);continue}D+=E,D===F&&i<t.length-1&&(e.push(""),D=0)}!D&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},ED=e=>{const u=e.split(" ");let F=u.length;for(;F>0&&!(A(u[F-1])>0);)F--;return F===u.length?e:u.slice(0,F).join(" ")+u.slice(F).join("")},oD=(e,u,F={})=>{if(F.trim!==!1&&e.trim()==="")return"";let t="",s,C;const D=rD(e);let i=[""];for(const[E,h]of e.split(" ").entries()){F.trim!==!1&&(i[i.length-1]=i[i.length-1].trimStart());let o=A(i[i.length-1]);if(E!==0&&(o>=u&&(F.wordWrap===!1||F.trim===!1)&&(i.push(""),o=0),(o>0||F.trim===!1)&&(i[i.length-1]+=" ",o++)),F.hard&&D[E]>u){const B=u-o,p=1+Math.floor((D[E]-B-1)/u);Math.floor((D[E]-1)/u)<p&&i.push(""),y(i,h,u);continue}if(o+D[E]>u&&o>0&&D[E]>0){if(F.wordWrap===!1&&o<u){y(i,h,u);continue}i.push("")}if(o+D[E]>u&&F.wordWrap===!1){y(i,h,u);continue}i[i.length-1]+=h}F.trim!==!1&&(i=i.map(E=>ED(E)));const n=[...i.join(` `)];for(const[E,h]of n.entries()){if(t+=h,g.has(h)){const{groups:B}=new RegExp(`(?:\\${O}(?<code>\\d+)m|\\${w}(?<uri>.*)${b})`).exec(n.slice(E).join(""))||{groups:{}};if(B.code!==void 0){const p=Number.parseFloat(B.code);s=p===CD?void 0:p}else B.uri!==void 0&&(C=B.uri.length===0?void 0:B.uri)}const o=sD.codes.get(Number(s));n[E+1]===` `?(C&&(t+=L("")),s&&o&&(t+=N(o))):h===` `&&(s&&o&&(t+=N(s)),C&&(t+=L(C)))}return t};function R(e,u,F){return String(e).normalize().replace(/\r\n/g,` `).split(` `).map(t=>oD(t,u,F)).join(` `)}var nD=Object.defineProperty,aD=(e,u,F)=>u in e?nD(e,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):e[u]=F,a=(e,u,F)=>(aD(e,typeof u!="symbol"?u+"":u,F),F);function hD(e,u){if(e===u)return;const F=e.split(` `),t=u.split(` `),s=[];for(let C=0;C<Math.max(F.length,t.length);C++)F[C]!==t[C]&&s.push(C);return s}const V=Symbol("clack:cancel");function lD(e){return e===V}function v(e,u){e.isTTY&&e.setRawMode(u)}const z=new Map([["k","up"],["j","down"],["h","left"],["l","right"]]),xD=new Set(["up","down","left","right","space","enter"]);class x{constructor({render:u,input:F=$,output:t=k,...s},C=!0){a(this,"input"),a(this,"output"),a(this,"rl"),a(this,"opts"),a(this,"_track",!1),a(this,"_render"),a(this,"_cursor",0),a(this,"state","initial"),a(this,"value"),a(this,"error",""),a(this,"subscribers",new Map),a(this,"_prevFrame",""),this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=u.bind(this),this._track=C,this.input=F,this.output=t}prompt(){const u=new U(0);return u._write=(F,t,s)=>{this._track&&(this.value=this.rl.line.replace(/\t/g,""),this._cursor=this.rl.cursor,this.emit("value",this.value)),s()},this.input.pipe(u),this.rl=_.createInterface({input:this.input,output:u,tabSize:2,prompt:"",escapeCodeTimeout:50}),_.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on("keypress",this.onKeypress),v(this.input,!0),this.output.on("resize",this.render),this.render(),new Promise((F,t)=>{this.once("submit",()=>{this.output.write(l.show),this.output.off("resize",this.render),v(this.input,!1),F(this.value)}),this.once("cancel",()=>{this.output.write(l.show),this.output.off("resize",this.render),v(this.input,!1),F(V)})})}on(u,F){const t=this.subscribers.get(u)??[];t.push({cb:F}),this.subscribers.set(u,t)}once(u,F){const t=this.subscribers.get(u)??[];t.push({cb:F,once:!0}),this.subscribers.set(u,t)}emit(u,...F){const t=this.subscribers.get(u)??[],s=[];for(const C of t)C.cb(...F),C.once&&s.push(()=>t.splice(t.indexOf(C),1));for(const C of s)C()}unsubscribe(){this.subscribers.clear()}onKeypress(u,F){if(this.state==="error"&&(this.state="active"),F?.name&&!this._track&&z.has(F.name)&&this.emit("cursor",z.get(F.name)),F?.name&&xD.has(F.name)&&this.emit("cursor",F.name),u&&(u.toLowerCase()==="y"||u.toLowerCase()==="n")&&this.emit("confirm",u.toLowerCase()==="y"),u===" "&&this.opts.placeholder&&(this.value||(this.rl.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),u&&this.emit("key",u.toLowerCase()),F?.name==="return"){if(this.opts.validate){const t=this.opts.validate(this.value);t&&(this.error=t,this.state="error",this.rl.write(this.value))}this.state!=="error"&&(this.state="submit")}u===""&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(` `),v(this.input,!1),this.rl.close(),this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){const u=R(this._prevFrame,process.stdout.columns,{hard:!0}).split(` `).length-1;this.output.write(l.move(-999,u*-1))}render(){const u=R(this._render(this)??"",process.stdout.columns,{hard:!0});if(u!==this._prevFrame){if(this.state==="initial")this.output.write(l.hide);else{const F=hD(this._prevFrame,u);if(this.restoreCursor(),F&&F?.length===1){const t=F[0];this.output.write(l.move(0,t)),this.output.write(m.lines(1));const s=u.split(` `);this.output.write(s[t]),this._prevFrame=u,this.output.write(l.move(0,s.length-t-1));return}else if(F&&F?.length>1){const t=F[0];this.output.write(l.move(0,t)),this.output.write(m.down());const s=u.split(` `).slice(t);this.output.write(s.join(` `)),this._prevFrame=u;return}this.output.write(m.down())}this.output.write(u),this.state==="initial"&&(this.state="active"),this._prevFrame=u}}}class BD extends x{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(u){super(u,!1),this.value=!!u.initialValue,this.on("value",()=>{this.value=this._value}),this.on("confirm",F=>{this.output.write(l.move(0,-1)),this.value=F,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var cD=Object.defineProperty,AD=(e,u,F)=>u in e?cD(e,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):e[u]=F,G=(e,u,F)=>(AD(e,typeof u!="symbol"?u+"":u,F),F);class pD extends x{constructor(u){super(u,!1),G(this,"options"),G(this,"cursor",0);const{options:F}=u;this.options=Object.entries(F).flatMap(([t,s])=>[{value:t,group:!0,label:t},...s.map(C=>({...C,group:t}))]),this.value=[...u.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===u.cursorAt),0),this.on("cursor",t=>{switch(t){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case"space":this.toggleValue();break}})}getGroupItems(u){return this.options.filter(F=>F.group===u)}isGroupSelected(u){return this.getGroupItems(u).every(F=>this.value.includes(F.value))}toggleValue(){const u=this.options[this.cursor];if(u.group===!0){const F=u.value,t=this.getGroupItems(F);this.isGroupSelected(F)?this.value=this.value.filter(s=>t.findIndex(C=>C.value===s)===-1):this.value=[...this.value,...t.map(s=>s.value)],this.value=Array.from(new Set(this.value))}else{const F=this.value.includes(u.value);this.value=F?this.value.filter(t=>t!==u.value):[...this.value,u.value]}}}var fD=Object.defineProperty,gD=(e,u,F)=>u in e?fD(e,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):e[u]=F,K=(e,u,F)=>(gD(e,typeof u!="symbol"?u+"":u,F),F);let vD=class extends x{constructor(u){super(u,!1),K(this,"options"),K(this,"cursor",0),this.options=u.options,this.value=[...u.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:F})=>F===u.cursorAt),0),this.on("key",F=>{F==="a"&&this.toggleAll()}),this.on("cursor",F=>{switch(F){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case"space":this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){const u=this.value.length===this.options.length;this.value=u?[]:this.options.map(F=>F.value)}toggleValue(){const u=this.value.includes(this._value);this.value=u?this.value.filter(F=>F!==this._value):[...this.value,this._value]}};var mD=Object.defineProperty,dD=(e,u,F)=>u in e?mD(e,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):e[u]=F,Y=(e,u,F)=>(dD(e,typeof u!="symbol"?u+"":u,F),F);class bD extends x{constructor({mask:u,...F}){super(F),Y(this,"valueWithCursor",""),Y(this,"_mask","\u2022"),this._mask=u??"\u2022",this.on("finalize",()=>{this.valueWithCursor=this.masked}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${c.inverse(c.hidden("_"))}`;else{const t=this.masked.slice(0,this.cursor),s=this.masked.slice(this.cursor);this.valueWithCursor=`${t}${c.inverse(s[0])}${s.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}}var wD=Object.defineProperty,yD=(e,u,F)=>u in e?wD(e,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):e[u]=F,Z=(e,u,F)=>(yD(e,typeof u!="symbol"?u+"":u,F),F);let $D=class extends x{constructor(u){super(u,!1),Z(this,"options"),Z(this,"cursor",0),this.options=u.options,this.cursor=this.options.findIndex(({value:F})=>F===u.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on("cursor",F=>{switch(F){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}};var kD=Object.defineProperty,_D=(e,u,F)=>u in e?kD(e,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):e[u]=F,H=(e,u,F)=>(_D(e,typeof u!="symbol"?u+"":u,F),F);class SD extends x{constructor(u){super(u,!1),H(this,"options"),H(this,"cursor",0),this.options=u.options;const F=this.options.map(({value:[t]})=>t?.toLowerCase());this.cursor=Math.max(F.indexOf(u.initialValue),0),this.on("key",t=>{if(!F.includes(t))return;const s=this.options.find(({value:[C]})=>C?.toLowerCase()===t);s&&(this.value=s.value,this.state="submit",this.emit("submit"))})}}var TD=Object.defineProperty,jD=(e,u,F)=>u in e?TD(e,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):e[u]=F,MD=(e,u,F)=>(jD(e,typeof u!="symbol"?u+"":u,F),F);class PD extends x{constructor(u){super(u),MD(this,"valueWithCursor",""),this.on("finalize",()=>{this.value||(this.value=u.defaultValue),this.valueWithCursor=this.value}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.value}${c.inverse(c.hidden("_"))}`;else{const F=this.value.slice(0,this.cursor),t=this.value.slice(this.cursor);this.valueWithCursor=`${F}${c.inverse(t[0])}${t.slice(1)}`}})}get cursor(){return this._cursor}}const WD=globalThis.process.platform.startsWith("win");function OD({input:e=$,output:u=k,overwrite:F=!0,hideCursor:t=!0}={}){const s=f.createInterface({input:e,output:u,prompt:"",tabSize:1});f.emitKeypressEvents(e,s),e.isTTY&&e.setRawMode(!0);const C=(D,{name:i})=>{if(String(D)===""){t&&u.write(l.show),process.exit(0);return}if(!F)return;let n=i==="return"?0:-1,E=i==="return"?-1:0;f.moveCursor(u,n,E,()=>{f.clearLine(u,1,()=>{e.once("keypress",C)})})};return t&&u.write(l.hide),e.once("keypress",C),()=>{e.off("keypress",C),t&&u.write(l.show),e.isTTY&&!WD&&e.setRawMode(!1),s.terminal=!1,s.close()}}export{BD as ConfirmPrompt,pD as GroupMultiSelectPrompt,vD as MultiSelectPrompt,bD as PasswordPrompt,x as Prompt,SD as SelectKeyPrompt,$D as SelectPrompt,PD as TextPrompt,OD as block,lD as isCancel}; //# sourceMappingURL=index.mjs.map node_modules/@clack/core/dist/index.d.cts 0000664 00000010024 15114743311 0014334 0 ustar 00 import { Readable, Writable } from 'node:stream'; declare function isCancel(value: unknown): value is symbol; interface PromptOptions<Self extends Prompt> { render(this: Omit<Self, 'prompt'>): string | void; placeholder?: string; initialValue?: any; validate?: ((value: any) => string | void) | undefined; input?: Readable; output?: Writable; debug?: boolean; } type State = 'initial' | 'active' | 'cancel' | 'submit' | 'error'; declare class Prompt { protected input: Readable; protected output: Writable; private rl; private opts; private _track; private _render; protected _cursor: number; state: State; value: any; error: string; constructor({ render, input, output, ...opts }: PromptOptions<Prompt>, trackValue?: boolean); prompt(): Promise<string | symbol>; private subscribers; on(event: string, cb: (...args: any) => any): void; once(event: string, cb: (...args: any) => any): void; emit(event: string, ...data: any[]): void; private unsubscribe; private onKeypress; protected close(): void; private restoreCursor; private _prevFrame; private render; } interface ConfirmOptions extends PromptOptions<ConfirmPrompt> { active: string; inactive: string; initialValue?: boolean; } declare class ConfirmPrompt extends Prompt { get cursor(): 0 | 1; private get _value(); constructor(opts: ConfirmOptions); } interface GroupMultiSelectOptions<T extends { value: any; }> extends PromptOptions<GroupMultiSelectPrompt<T>> { options: Record<string, T[]>; initialValues?: T['value'][]; required?: boolean; cursorAt?: T['value']; } declare class GroupMultiSelectPrompt<T extends { value: any; }> extends Prompt { options: (T & { group: string | boolean; })[]; cursor: number; getGroupItems(group: string): T[]; isGroupSelected(group: string): boolean; private toggleValue; constructor(opts: GroupMultiSelectOptions<T>); } interface MultiSelectOptions<T extends { value: any; }> extends PromptOptions<MultiSelectPrompt<T>> { options: T[]; initialValues?: T['value'][]; required?: boolean; cursorAt?: T['value']; } declare class MultiSelectPrompt<T extends { value: any; }> extends Prompt { options: T[]; cursor: number; private get _value(); private toggleAll; private toggleValue; constructor(opts: MultiSelectOptions<T>); } interface PasswordOptions extends PromptOptions<PasswordPrompt> { mask?: string; } declare class PasswordPrompt extends Prompt { valueWithCursor: string; private _mask; get cursor(): number; get masked(): any; constructor({ mask, ...opts }: PasswordOptions); } interface SelectOptions<T extends { value: any; }> extends PromptOptions<SelectPrompt<T>> { options: T[]; initialValue?: T['value']; } declare class SelectPrompt<T extends { value: any; }> extends Prompt { options: T[]; cursor: number; private get _value(); private changeValue; constructor(opts: SelectOptions<T>); } interface SelectKeyOptions<T extends { value: any; }> extends PromptOptions<SelectKeyPrompt<T>> { options: T[]; } declare class SelectKeyPrompt<T extends { value: any; }> extends Prompt { options: T[]; cursor: number; constructor(opts: SelectKeyOptions<T>); } interface TextOptions extends PromptOptions<TextPrompt> { placeholder?: string; defaultValue?: string; } declare class TextPrompt extends Prompt { valueWithCursor: string; get cursor(): number; constructor(opts: TextOptions); } declare function block({ input, output, overwrite, hideCursor, }?: { input?: (NodeJS.ReadStream & { fd: 0; }) | undefined; output?: (NodeJS.WriteStream & { fd: 1; }) | undefined; overwrite?: boolean | undefined; hideCursor?: boolean | undefined; }): () => void; export { ConfirmPrompt, GroupMultiSelectPrompt, MultiSelectPrompt, PasswordPrompt, Prompt, SelectKeyPrompt, SelectPrompt, type State, TextPrompt, block, isCancel }; node_modules/@clack/core/dist/index.cjs 0000664 00000111124 15114743311 0014103 0 ustar 00 "use strict";const sisteransi=require("sisteransi"),node_process=require("node:process"),s$1=require("node:readline"),node_tty=require("node:tty"),i$1=require("picocolors");function _interopDefaultCompat(C){return C&&typeof C=="object"&&"default"in C?C.default:C}function _interopNamespaceCompat(C){if(C&&typeof C=="object"&&"default"in C)return C;const F=Object.create(null);if(C)for(const t in C)F[t]=C[t];return F.default=C,F}const s__default=_interopDefaultCompat(s$1),s__namespace=_interopNamespaceCompat(s$1),i__default=_interopDefaultCompat(i$1);function ansiRegex({onlyFirst:C=!1}={}){const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(t,C?void 0:"g")}const regex=ansiRegex();function stripAnsi(C){if(typeof C!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof C}\``);return C.replace(regex,"")}function getDefaultExportFromCjs(C){return C&&C.__esModule&&Object.prototype.hasOwnProperty.call(C,"default")?C.default:C}var eastasianwidth={exports:{}};(function(C){var F={};C.exports=F,F.eastAsianWidth=function(E){var x=E.charCodeAt(0),B=E.length==2?E.charCodeAt(1):0,D=x;return 55296<=x&&x<=56319&&56320<=B&&B<=57343&&(x&=1023,B&=1023,D=x<<10|B,D+=65536),D==12288||65281<=D&&D<=65376||65504<=D&&D<=65510?"F":D==8361||65377<=D&&D<=65470||65474<=D&&D<=65479||65482<=D&&D<=65487||65490<=D&&D<=65495||65498<=D&&D<=65500||65512<=D&&D<=65518?"H":4352<=D&&D<=4447||4515<=D&&D<=4519||4602<=D&&D<=4607||9001<=D&&D<=9002||11904<=D&&D<=11929||11931<=D&&D<=12019||12032<=D&&D<=12245||12272<=D&&D<=12283||12289<=D&&D<=12350||12353<=D&&D<=12438||12441<=D&&D<=12543||12549<=D&&D<=12589||12593<=D&&D<=12686||12688<=D&&D<=12730||12736<=D&&D<=12771||12784<=D&&D<=12830||12832<=D&&D<=12871||12880<=D&&D<=13054||13056<=D&&D<=19903||19968<=D&&D<=42124||42128<=D&&D<=42182||43360<=D&&D<=43388||44032<=D&&D<=55203||55216<=D&&D<=55238||55243<=D&&D<=55291||63744<=D&&D<=64255||65040<=D&&D<=65049||65072<=D&&D<=65106||65108<=D&&D<=65126||65128<=D&&D<=65131||110592<=D&&D<=110593||127488<=D&&D<=127490||127504<=D&&D<=127546||127552<=D&&D<=127560||127568<=D&&D<=127569||131072<=D&&D<=194367||177984<=D&&D<=196605||196608<=D&&D<=262141?"W":32<=D&&D<=126||162<=D&&D<=163||165<=D&&D<=166||D==172||D==175||10214<=D&&D<=10221||10629<=D&&D<=10630?"Na":D==161||D==164||167<=D&&D<=168||D==170||173<=D&&D<=174||176<=D&&D<=180||182<=D&&D<=186||188<=D&&D<=191||D==198||D==208||215<=D&&D<=216||222<=D&&D<=225||D==230||232<=D&&D<=234||236<=D&&D<=237||D==240||242<=D&&D<=243||247<=D&&D<=250||D==252||D==254||D==257||D==273||D==275||D==283||294<=D&&D<=295||D==299||305<=D&&D<=307||D==312||319<=D&&D<=322||D==324||328<=D&&D<=331||D==333||338<=D&&D<=339||358<=D&&D<=359||D==363||D==462||D==464||D==466||D==468||D==470||D==472||D==474||D==476||D==593||D==609||D==708||D==711||713<=D&&D<=715||D==717||D==720||728<=D&&D<=731||D==733||D==735||768<=D&&D<=879||913<=D&&D<=929||931<=D&&D<=937||945<=D&&D<=961||963<=D&&D<=969||D==1025||1040<=D&&D<=1103||D==1105||D==8208||8211<=D&&D<=8214||8216<=D&&D<=8217||8220<=D&&D<=8221||8224<=D&&D<=8226||8228<=D&&D<=8231||D==8240||8242<=D&&D<=8243||D==8245||D==8251||D==8254||D==8308||D==8319||8321<=D&&D<=8324||D==8364||D==8451||D==8453||D==8457||D==8467||D==8470||8481<=D&&D<=8482||D==8486||D==8491||8531<=D&&D<=8532||8539<=D&&D<=8542||8544<=D&&D<=8555||8560<=D&&D<=8569||D==8585||8592<=D&&D<=8601||8632<=D&&D<=8633||D==8658||D==8660||D==8679||D==8704||8706<=D&&D<=8707||8711<=D&&D<=8712||D==8715||D==8719||D==8721||D==8725||D==8730||8733<=D&&D<=8736||D==8739||D==8741||8743<=D&&D<=8748||D==8750||8756<=D&&D<=8759||8764<=D&&D<=8765||D==8776||D==8780||D==8786||8800<=D&&D<=8801||8804<=D&&D<=8807||8810<=D&&D<=8811||8814<=D&&D<=8815||8834<=D&&D<=8835||8838<=D&&D<=8839||D==8853||D==8857||D==8869||D==8895||D==8978||9312<=D&&D<=9449||9451<=D&&D<=9547||9552<=D&&D<=9587||9600<=D&&D<=9615||9618<=D&&D<=9621||9632<=D&&D<=9633||9635<=D&&D<=9641||9650<=D&&D<=9651||9654<=D&&D<=9655||9660<=D&&D<=9661||9664<=D&&D<=9665||9670<=D&&D<=9672||D==9675||9678<=D&&D<=9681||9698<=D&&D<=9701||D==9711||9733<=D&&D<=9734||D==9737||9742<=D&&D<=9743||9748<=D&&D<=9749||D==9756||D==9758||D==9792||D==9794||9824<=D&&D<=9825||9827<=D&&D<=9829||9831<=D&&D<=9834||9836<=D&&D<=9837||D==9839||9886<=D&&D<=9887||9918<=D&&D<=9919||9924<=D&&D<=9933||9935<=D&&D<=9953||D==9955||9960<=D&&D<=9983||D==10045||D==10071||10102<=D&&D<=10111||11093<=D&&D<=11097||12872<=D&&D<=12879||57344<=D&&D<=63743||65024<=D&&D<=65039||D==65533||127232<=D&&D<=127242||127248<=D&&D<=127277||127280<=D&&D<=127337||127344<=D&&D<=127386||917760<=D&&D<=917999||983040<=D&&D<=1048573||1048576<=D&&D<=1114109?"A":"N"},F.characterLength=function(E){var x=this.eastAsianWidth(E);return x=="F"||x=="W"||x=="A"?2:1};function t(E){return E.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}F.length=function(E){for(var x=t(E),B=0,D=0;D<x.length;D++)B=B+this.characterLength(x[D]);return B},F.slice=function(E,x,B){textLen=F.length(E),x=x||0,B=B||1,x<0&&(x=textLen+x),B<0&&(B=textLen+B);for(var D="",A=0,w=t(E),v=0;v<w.length;v++){var $=w[v],b=F.length($);if(A>=x-(b==2?1:0))if(A+b<=B)D+=$;else break;A+=b}return D}})(eastasianwidth);var eastasianwidthExports=eastasianwidth.exports;const eastAsianWidth=getDefaultExportFromCjs(eastasianwidthExports);var emojiRegex=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB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80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uD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\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g};const emojiRegex$1=getDefaultExportFromCjs(emojiRegex);function stringWidth(C,F={}){if(typeof C!="string"||C.length===0||(F={ambiguousIsNarrow:!0,...F},C=stripAnsi(C),C.length===0))return 0;C=C.replace(emojiRegex$1()," ");const t=F.ambiguousIsNarrow?1:2;let E=0;for(const x of C){const B=x.codePointAt(0);if(B<=31||B>=127&&B<=159||B>=768&&B<=879)continue;switch(eastAsianWidth.eastAsianWidth(x)){case"F":case"W":E+=2;break;case"A":E+=t;break;default:E+=1}}return E}const ANSI_BACKGROUND_OFFSET=10,wrapAnsi16=(C=0)=>F=>`\x1B[${F+C}m`,wrapAnsi256=(C=0)=>F=>`\x1B[${38+C};5;${F}m`,wrapAnsi16m=(C=0)=>(F,t,E)=>`\x1B[${38+C};2;${F};${t};${E}m`,styles={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(styles.modifier);const foregroundColorNames=Object.keys(styles.color),backgroundColorNames=Object.keys(styles.bgColor);[...foregroundColorNames,...backgroundColorNames];function assembleStyles(){const C=new Map;for(const[F,t]of Object.entries(styles)){for(const[E,x]of Object.entries(t))styles[E]={open:`\x1B[${x[0]}m`,close:`\x1B[${x[1]}m`},t[E]=styles[E],C.set(x[0],x[1]);Object.defineProperty(styles,F,{value:t,enumerable:!1})}return Object.defineProperty(styles,"codes",{value:C,enumerable:!1}),styles.color.close="\x1B[39m",styles.bgColor.close="\x1B[49m",styles.color.ansi=wrapAnsi16(),styles.color.ansi256=wrapAnsi256(),styles.color.ansi16m=wrapAnsi16m(),styles.bgColor.ansi=wrapAnsi16(ANSI_BACKGROUND_OFFSET),styles.bgColor.ansi256=wrapAnsi256(ANSI_BACKGROUND_OFFSET),styles.bgColor.ansi16m=wrapAnsi16m(ANSI_BACKGROUND_OFFSET),Object.defineProperties(styles,{rgbToAnsi256:{value:(F,t,E)=>F===t&&t===E?F<8?16:F>248?231:Math.round((F-8)/247*24)+232:16+36*Math.round(F/255*5)+6*Math.round(t/255*5)+Math.round(E/255*5),enumerable:!1},hexToRgb:{value:F=>{const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(F.toString(16));if(!t)return[0,0,0];let[E]=t;E.length===3&&(E=[...E].map(B=>B+B).join(""));const x=Number.parseInt(E,16);return[x>>16&255,x>>8&255,x&255]},enumerable:!1},hexToAnsi256:{value:F=>styles.rgbToAnsi256(...styles.hexToRgb(F)),enumerable:!1},ansi256ToAnsi:{value:F=>{if(F<8)return 30+F;if(F<16)return 90+(F-8);let t,E,x;if(F>=232)t=((F-232)*10+8)/255,E=t,x=t;else{F-=16;const A=F%36;t=Math.floor(F/36)/5,E=Math.floor(A/6)/5,x=A%6/5}const B=Math.max(t,E,x)*2;if(B===0)return 30;let D=30+(Math.round(x)<<2|Math.round(E)<<1|Math.round(t));return B===2&&(D+=60),D},enumerable:!1},rgbToAnsi:{value:(F,t,E)=>styles.ansi256ToAnsi(styles.rgbToAnsi256(F,t,E)),enumerable:!1},hexToAnsi:{value:F=>styles.ansi256ToAnsi(styles.hexToAnsi256(F)),enumerable:!1}}),styles}const ansiStyles=assembleStyles(),ESCAPES=new Set(["\x1B","\x9B"]),END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,wrapAnsiCode=C=>`${ESCAPES.values().next().value}${ANSI_CSI}${C}${ANSI_SGR_TERMINATOR}`,wrapAnsiHyperlink=C=>`${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${C}${ANSI_ESCAPE_BELL}`,wordLengths=C=>C.split(" ").map(F=>stringWidth(F)),wrapWord=(C,F,t)=>{const E=[...F];let x=!1,B=!1,D=stringWidth(stripAnsi(C[C.length-1]));for(const[A,w]of E.entries()){const v=stringWidth(w);if(D+v<=t?C[C.length-1]+=w:(C.push(w),D=0),ESCAPES.has(w)&&(x=!0,B=E.slice(A+1).join("").startsWith(ANSI_ESCAPE_LINK)),x){B?w===ANSI_ESCAPE_BELL&&(x=!1,B=!1):w===ANSI_SGR_TERMINATOR&&(x=!1);continue}D+=v,D===t&&A<E.length-1&&(C.push(""),D=0)}!D&&C[C.length-1].length>0&&C.length>1&&(C[C.length-2]+=C.pop())},stringVisibleTrimSpacesRight=C=>{const F=C.split(" ");let t=F.length;for(;t>0&&!(stringWidth(F[t-1])>0);)t--;return t===F.length?C:F.slice(0,t).join(" ")+F.slice(t).join("")},exec=(C,F,t={})=>{if(t.trim!==!1&&C.trim()==="")return"";let E="",x,B;const D=wordLengths(C);let A=[""];for(const[v,$]of C.split(" ").entries()){t.trim!==!1&&(A[A.length-1]=A[A.length-1].trimStart());let b=stringWidth(A[A.length-1]);if(v!==0&&(b>=F&&(t.wordWrap===!1||t.trim===!1)&&(A.push(""),b=0),(b>0||t.trim===!1)&&(A[A.length-1]+=" ",b++)),t.hard&&D[v]>F){const k=F-b,S=1+Math.floor((D[v]-k-1)/F);Math.floor((D[v]-1)/F)<S&&A.push(""),wrapWord(A,$,F);continue}if(b+D[v]>F&&b>0&&D[v]>0){if(t.wordWrap===!1&&b<F){wrapWord(A,$,F);continue}A.push("")}if(b+D[v]>F&&t.wordWrap===!1){wrapWord(A,$,F);continue}A[A.length-1]+=$}t.trim!==!1&&(A=A.map(v=>stringVisibleTrimSpacesRight(v)));const w=[...A.join(` `)];for(const[v,$]of w.entries()){if(E+=$,ESCAPES.has($)){const{groups:k}=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(w.slice(v).join(""))||{groups:{}};if(k.code!==void 0){const S=Number.parseFloat(k.code);x=S===END_CODE?void 0:S}else k.uri!==void 0&&(B=k.uri.length===0?void 0:k.uri)}const b=ansiStyles.codes.get(Number(x));w[v+1]===` `?(B&&(E+=wrapAnsiHyperlink("")),x&&b&&(E+=wrapAnsiCode(b))):$===` `&&(x&&b&&(E+=wrapAnsiCode(x)),B&&(E+=wrapAnsiHyperlink(B)))}return E};function wrapAnsi(C,F,t){return String(C).normalize().replace(/\r\n/g,` `).split(` `).map(E=>exec(E,F,t)).join(` `)}var f=Object.defineProperty,d=(C,F,t)=>F in C?f(C,F,{enumerable:!0,configurable:!0,writable:!0,value:t}):C[F]=t,o$3=(C,F,t)=>(d(C,typeof F!="symbol"?F+"":F,t),t);function g(C,F){if(C===F)return;const t=C.split(` `),E=F.split(` `),x=[];for(let B=0;B<Math.max(t.length,E.length);B++)t[B]!==E[B]&&x.push(B);return x}const c$1=Symbol("clack:cancel");function isCancel(C){return C===c$1}function p$1(C,F){C.isTTY&&C.setRawMode(F)}const m$1=new Map([["k","up"],["j","down"],["h","left"],["l","right"]]),y$1=new Set(["up","down","left","right","space","enter"]);class _{constructor({render:F,input:t=node_process.stdin,output:E=node_process.stdout,...x},B=!0){o$3(this,"input"),o$3(this,"output"),o$3(this,"rl"),o$3(this,"opts"),o$3(this,"_track",!1),o$3(this,"_render"),o$3(this,"_cursor",0),o$3(this,"state","initial"),o$3(this,"value"),o$3(this,"error",""),o$3(this,"subscribers",new Map),o$3(this,"_prevFrame",""),this.opts=x,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=F.bind(this),this._track=B,this.input=t,this.output=E}prompt(){const F=new node_tty.WriteStream(0);return F._write=(t,E,x)=>{this._track&&(this.value=this.rl.line.replace(/\t/g,""),this._cursor=this.rl.cursor,this.emit("value",this.value)),x()},this.input.pipe(F),this.rl=s__default.createInterface({input:this.input,output:F,tabSize:2,prompt:"",escapeCodeTimeout:50}),s__default.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on("keypress",this.onKeypress),p$1(this.input,!0),this.output.on("resize",this.render),this.render(),new Promise((t,E)=>{this.once("submit",()=>{this.output.write(sisteransi.cursor.show),this.output.off("resize",this.render),p$1(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(sisteransi.cursor.show),this.output.off("resize",this.render),p$1(this.input,!1),t(c$1)})})}on(F,t){const E=this.subscribers.get(F)??[];E.push({cb:t}),this.subscribers.set(F,E)}once(F,t){const E=this.subscribers.get(F)??[];E.push({cb:t,once:!0}),this.subscribers.set(F,E)}emit(F,...t){const E=this.subscribers.get(F)??[],x=[];for(const B of E)B.cb(...t),B.once&&x.push(()=>E.splice(E.indexOf(B),1));for(const B of x)B()}unsubscribe(){this.subscribers.clear()}onKeypress(F,t){if(this.state==="error"&&(this.state="active"),t?.name&&!this._track&&m$1.has(t.name)&&this.emit("cursor",m$1.get(t.name)),t?.name&&y$1.has(t.name)&&this.emit("cursor",t.name),F&&(F.toLowerCase()==="y"||F.toLowerCase()==="n")&&this.emit("confirm",F.toLowerCase()==="y"),F===" "&&this.opts.placeholder&&(this.value||(this.rl.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),F&&this.emit("key",F.toLowerCase()),t?.name==="return"){if(this.opts.validate){const E=this.opts.validate(this.value);E&&(this.error=E,this.state="error",this.rl.write(this.value))}this.state!=="error"&&(this.state="submit")}F===""&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(` `),p$1(this.input,!1),this.rl.close(),this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){const F=wrapAnsi(this._prevFrame,process.stdout.columns,{hard:!0}).split(` `).length-1;this.output.write(sisteransi.cursor.move(-999,F*-1))}render(){const F=wrapAnsi(this._render(this)??"",process.stdout.columns,{hard:!0});if(F!==this._prevFrame){if(this.state==="initial")this.output.write(sisteransi.cursor.hide);else{const t=g(this._prevFrame,F);if(this.restoreCursor(),t&&t?.length===1){const E=t[0];this.output.write(sisteransi.cursor.move(0,E)),this.output.write(sisteransi.erase.lines(1));const x=F.split(` `);this.output.write(x[E]),this._prevFrame=F,this.output.write(sisteransi.cursor.move(0,x.length-E-1));return}else if(t&&t?.length>1){const E=t[0];this.output.write(sisteransi.cursor.move(0,E)),this.output.write(sisteransi.erase.down());const x=F.split(` `).slice(E);this.output.write(x.join(` `)),this._prevFrame=F;return}this.output.write(sisteransi.erase.down())}this.output.write(F),this.state==="initial"&&(this.state="active"),this._prevFrame=F}}}class s extends _{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(F){super(F,!1),this.value=!!F.initialValue,this.on("value",()=>{this.value=this._value}),this.on("confirm",t=>{this.output.write(sisteransi.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var a=Object.defineProperty,n$3=(C,F,t)=>F in C?a(C,F,{enumerable:!0,configurable:!0,writable:!0,value:t}):C[F]=t,l$3=(C,F,t)=>(n$3(C,typeof F!="symbol"?F+"":F,t),t);class p extends _{constructor(F){super(F,!1),l$3(this,"options"),l$3(this,"cursor",0);const{options:t}=F;this.options=Object.entries(t).flatMap(([E,x])=>[{value:E,group:!0,label:E},...x.map(B=>({...B,group:E}))]),this.value=[...F.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:E})=>E===F.cursorAt),0),this.on("cursor",E=>{switch(E){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case"space":this.toggleValue();break}})}getGroupItems(F){return this.options.filter(t=>t.group===F)}isGroupSelected(F){return this.getGroupItems(F).every(t=>this.value.includes(t.value))}toggleValue(){const F=this.options[this.cursor];if(F.group===!0){const t=F.value,E=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter(x=>E.findIndex(B=>B.value===x)===-1):this.value=[...this.value,...E.map(x=>x.value)],this.value=Array.from(new Set(this.value))}else{const t=this.value.includes(F.value);this.value=t?this.value.filter(E=>E!==F.value):[...this.value,F.value]}}}var o$2=Object.defineProperty,r$1=(C,F,t)=>F in C?o$2(C,F,{enumerable:!0,configurable:!0,writable:!0,value:t}):C[F]=t,l$2=(C,F,t)=>(r$1(C,typeof F!="symbol"?F+"":F,t),t);let u$3=class extends _{constructor(F){super(F,!1),l$2(this,"options"),l$2(this,"cursor",0),this.options=F.options,this.value=[...F.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===F.cursorAt),0),this.on("key",t=>{t==="a"&&this.toggleAll()}),this.on("cursor",t=>{switch(t){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case"space":this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){const F=this.value.length===this.options.length;this.value=F?[]:this.options.map(t=>t.value)}toggleValue(){const F=this.value.includes(this._value);this.value=F?this.value.filter(t=>t!==this._value):[...this.value,this._value]}};var u$2=Object.defineProperty,n$2=(C,F,t)=>F in C?u$2(C,F,{enumerable:!0,configurable:!0,writable:!0,value:t}):C[F]=t,e=(C,F,t)=>(n$2(C,typeof F!="symbol"?F+"":F,t),t);class m extends _{constructor({mask:F,...t}){super(t),e(this,"valueWithCursor",""),e(this,"_mask","\u2022"),this._mask=F??"\u2022",this.on("finalize",()=>{this.valueWithCursor=this.masked}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${i__default.inverse(i__default.hidden("_"))}`;else{const E=this.masked.slice(0,this.cursor),x=this.masked.slice(this.cursor);this.valueWithCursor=`${E}${i__default.inverse(x[0])}${x.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}}var o$1=Object.defineProperty,n$1=(C,F,t)=>F in C?o$1(C,F,{enumerable:!0,configurable:!0,writable:!0,value:t}):C[F]=t,r=(C,F,t)=>(n$1(C,typeof F!="symbol"?F+"":F,t),t);let u$1=class extends _{constructor(F){super(F,!1),r(this,"options"),r(this,"cursor",0),this.options=F.options,this.cursor=this.options.findIndex(({value:t})=>t===F.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on("cursor",t=>{switch(t){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}};var u=Object.defineProperty,l$1=(C,F,t)=>F in C?u(C,F,{enumerable:!0,configurable:!0,writable:!0,value:t}):C[F]=t,i=(C,F,t)=>(l$1(C,typeof F!="symbol"?F+"":F,t),t);class c extends _{constructor(F){super(F,!1),i(this,"options"),i(this,"cursor",0),this.options=F.options;const t=this.options.map(({value:[E]})=>E?.toLowerCase());this.cursor=Math.max(t.indexOf(F.initialValue),0),this.on("key",E=>{if(!t.includes(E))return;const x=this.options.find(({value:[B]})=>B?.toLowerCase()===E);x&&(this.value=x.value,this.state="submit",this.emit("submit"))})}}var l=Object.defineProperty,h=(C,F,t)=>F in C?l(C,F,{enumerable:!0,configurable:!0,writable:!0,value:t}):C[F]=t,o=(C,F,t)=>(h(C,typeof F!="symbol"?F+"":F,t),t);class n extends _{constructor(F){super(F),o(this,"valueWithCursor",""),this.on("finalize",()=>{this.value||(this.value=F.defaultValue),this.valueWithCursor=this.value}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.value}${i__default.inverse(i__default.hidden("_"))}`;else{const t=this.value.slice(0,this.cursor),E=this.value.slice(this.cursor);this.valueWithCursor=`${t}${i__default.inverse(E[0])}${E.slice(1)}`}})}get cursor(){return this._cursor}}const y=globalThis.process.platform.startsWith("win");function block({input:C=node_process.stdin,output:F=node_process.stdout,overwrite:t=!0,hideCursor:E=!0}={}){const x=s__namespace.createInterface({input:C,output:F,prompt:"",tabSize:1});s__namespace.emitKeypressEvents(C,x),C.isTTY&&C.setRawMode(!0);const B=(D,{name:A})=>{if(String(D)===""){E&&F.write(sisteransi.cursor.show),process.exit(0);return}if(!t)return;let w=A==="return"?0:-1,v=A==="return"?-1:0;s__namespace.moveCursor(F,w,v,()=>{s__namespace.clearLine(F,1,()=>{C.once("keypress",B)})})};return E&&F.write(sisteransi.cursor.hide),C.once("keypress",B),()=>{C.off("keypress",B),E&&F.write(sisteransi.cursor.show),C.isTTY&&!y&&C.setRawMode(!1),x.terminal=!1,x.close()}}exports.ConfirmPrompt=s,exports.GroupMultiSelectPrompt=p,exports.MultiSelectPrompt=u$3,exports.PasswordPrompt=m,exports.Prompt=_,exports.SelectKeyPrompt=c,exports.SelectPrompt=u$1,exports.TextPrompt=n,exports.block=block,exports.isCancel=isCancel; //# sourceMappingURL=index.cjs.map node_modules/@clack/core/CHANGELOG.md 0000664 00000006605 15114743311 0013150 0 ustar 00 # @clack/core ## 0.3.5 ### Patch Changes - 4845f4f: Fixes a bug which kept the terminal cursor hidden after a prompt is cancelled - d7b2fb9: Adds missing `LICENSE` file. Since the `package.json` file has always included `"license": "MIT"`, please consider this a licensing clarification rather than a licensing change. ## 0.3.4 ### Patch Changes - a04e418: fix(@clack/core): keyboard input not working after await in spinner - 4f6fcf5: feat(@clack/core): allow tab completion for placeholders ## 0.3.3 ### Patch Changes - cd79076: fix: restore raw mode on unblock ## 0.3.2 ### Patch Changes - c96eda5: Enable hard line-wrapping behavior for long words without spaces ## 0.3.1 ### Patch Changes - 58a1df1: Fix line duplication bug by automatically wrapping prompts to `process.stdout.columns` ## 0.3.0 ### Minor Changes - 8a4a12f: Add `GroupMultiSelect` prompt ### Patch Changes - 8a4a12f: add `groupMultiselect` prompt ## 0.2.1 ### Patch Changes - ec812b6: fix `readline` hang on Windows ## 0.2.0 ### Minor Changes - d74dd05: Adds a `selectKey` prompt type - 54c1bc3: **Breaking Change** `multiselect` has renamed `initialValue` to `initialValues` ## 0.1.9 ### Patch Changes - 1251132: Multiselect: return `Value[]` instead of `Option[]`. - 8994382: Add a password prompt to `@clack/prompts` ## 0.1.8 ### Patch Changes - d96071c: Don't mutate `initialValue` in `multiselect`, fix parameter type for `validate()`. Credits to @banjo for the bug report and initial PR! ## 0.1.7 ### Patch Changes - 6d9e675: Add support for neovim cursor motion (`hjkl`) Thanks [@esau-morais](https://github.com/esau-morais) for the assist! ## 0.1.6 ### Patch Changes - 7fb5375: Adds a new `defaultValue` option to the text prompt, removes automatic usage of the placeholder value. ## 0.1.5 ### Patch Changes - de1314e: Support `required` option for multi-select ## 0.1.4 ### Patch Changes - ca77da1: Fix multiselect initial value logic - 8aed606: Fix `MaxListenersExceededWarning` by detaching `stdin` listeners on close ## 0.1.3 ### Patch Changes - a99c458: Support `initialValue` option for text prompt ## 0.1.2 ### Patch Changes - Allow isCancel to type guard any unknown value - 7dcad8f: Allow placeholder to be passed to TextPrompt - 2242f13: Fix multiselect returning undefined - b1341d6: Improved placeholder handling ## 0.1.1 ### Patch Changes - 4be7dbf: Ensure raw mode is unset on submit - b480679: Preserve value if validation fails ## 0.1.0 ### Minor Changes - 7015ec9: Create new prompt: multi-select ## 0.0.12 ### Patch Changes - 9d371c3: Fix rendering bug when using y/n to confirm ## 0.0.11 ### Patch Changes - 441d5b7: fix select return undefined - d20ef2a: Update keywords, URLs - fe13c2f: fix cursor missing after submit ## 0.0.10 ### Patch Changes - a0cb382: Add `main` entrypoint ## 0.0.9 ### Patch Changes - Fix node@16 issue (cannot read "createInterface" of undefined) ## 0.0.8 ### Patch Changes - a4b5e13: Bug fixes, exposes `block` utility ## 0.0.7 ### Patch Changes - Fix cursor bug ## 0.0.6 ### Patch Changes - Fix error with character check ## 0.0.5 ### Patch Changes - 491f9e0: update readme ## 0.0.4 ### Patch Changes - 7372d5c: Fix bug with line deletion ## 0.0.3 ### Patch Changes - 5605d28: Do not bundle dependencies (take II) ## 0.0.2 ### Patch Changes - 2ee67cb: don't bundle deps ## 0.0.1 ### Patch Changes - 306598e: Initial publish, still WIP node_modules/@clack/core/README.md 0000664 00000000771 15114743311 0012614 0 ustar 00 # `@clack/core` Clack contains low-level primitives for implementing your own command-line applications. Currently, `TextPrompt`, `SelectPrompt`, and `ConfirmPrompt` are exposed as well as the base `Prompt` class. Each `Prompt` accepts a `render` function. ```js import { TextPrompt, isCancel } from '@clack/core'; const p = new TextPrompt({ render() { return `What's your name?\n${this.valueWithCursor}`; }, }); const name = await p.prompt(); if (isCancel(name)) { process.exit(0); } ``` node_modules/minizlib/package.json 0000664 00000001613 15114743311 0013327 0 ustar 00 { "name": "minizlib", "version": "2.1.2", "description": "A small fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding.", "main": "index.js", "dependencies": { "minipass": "^3.0.0", "yallist": "^4.0.0" }, "scripts": { "test": "tap test/*.js --100 -J", "preversion": "npm test", "postversion": "npm publish", "postpublish": "git push origin --all; git push origin --tags" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minizlib.git" }, "keywords": [ "zlib", "gzip", "gunzip", "deflate", "inflate", "compression", "zip", "unzip" ], "author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)", "license": "MIT", "devDependencies": { "tap": "^14.6.9" }, "files": [ "index.js", "constants.js" ], "engines": { "node": ">= 8" } } node_modules/minizlib/LICENSE 0000664 00000002421 15114743311 0012044 0 ustar 00 Minizlib was created by Isaac Z. Schlueter. It is a derivative work of the Node.js project. """ Copyright Isaac Z. Schlueter and Contributors Copyright Node.js contributors. All rights reserved. Copyright Joyent, Inc. and other Node contributors. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ node_modules/minizlib/constants.js 0000664 00000007234 15114743311 0013420 0 ustar 00 // Update with any zlib constants that are added or changed in the future. // Node v6 didn't export this, so we just hard code the version and rely // on all the other hard-coded values from zlib v4736. When node v6 // support drops, we can just export the realZlibConstants object. const realZlibConstants = require('zlib').constants || /* istanbul ignore next */ { ZLIB_VERNUM: 4736 } module.exports = Object.freeze(Object.assign(Object.create(null), { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, DEFLATE: 1, INFLATE: 2, GZIP: 3, GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8, BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15, Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity, Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9, Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1, BROTLI_OPERATION_PROCESS: 0, BROTLI_OPERATION_FLUSH: 1, BROTLI_OPERATION_FINISH: 2, BROTLI_OPERATION_EMIT_METADATA: 3, BROTLI_MODE_GENERIC: 0, BROTLI_MODE_TEXT: 1, BROTLI_MODE_FONT: 2, BROTLI_DEFAULT_MODE: 0, BROTLI_MIN_QUALITY: 0, BROTLI_MAX_QUALITY: 11, BROTLI_DEFAULT_QUALITY: 11, BROTLI_MIN_WINDOW_BITS: 10, BROTLI_MAX_WINDOW_BITS: 24, BROTLI_LARGE_MAX_WINDOW_BITS: 30, BROTLI_DEFAULT_WINDOW: 22, BROTLI_MIN_INPUT_BLOCK_BITS: 16, BROTLI_MAX_INPUT_BLOCK_BITS: 24, BROTLI_PARAM_MODE: 0, BROTLI_PARAM_QUALITY: 1, BROTLI_PARAM_LGWIN: 2, BROTLI_PARAM_LGBLOCK: 3, BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, BROTLI_PARAM_SIZE_HINT: 5, BROTLI_PARAM_LARGE_WINDOW: 6, BROTLI_PARAM_NPOSTFIX: 7, BROTLI_PARAM_NDIRECT: 8, BROTLI_DECODER_RESULT_ERROR: 0, BROTLI_DECODER_RESULT_SUCCESS: 1, BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, BROTLI_DECODER_NO_ERROR: 0, BROTLI_DECODER_SUCCESS: 1, BROTLI_DECODER_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, BROTLI_DECODER_ERROR_UNREACHABLE: -31, }, realZlibConstants)) node_modules/minizlib/index.js 0000664 00000022344 15114743311 0012512 0 ustar 00 'use strict' const assert = require('assert') const Buffer = require('buffer').Buffer const realZlib = require('zlib') const constants = exports.constants = require('./constants.js') const Minipass = require('minipass') const OriginalBufferConcat = Buffer.concat const _superWrite = Symbol('_superWrite') class ZlibError extends Error { constructor (err) { super('zlib: ' + err.message) this.code = err.code this.errno = err.errno /* istanbul ignore if */ if (!this.code) this.code = 'ZLIB_ERROR' this.message = 'zlib: ' + err.message Error.captureStackTrace(this, this.constructor) } get name () { return 'ZlibError' } } // the Zlib class they all inherit from // This thing manages the queue of requests, and returns // true or false if there is anything in the queue when // you call the .write() method. const _opts = Symbol('opts') const _flushFlag = Symbol('flushFlag') const _finishFlushFlag = Symbol('finishFlushFlag') const _fullFlushFlag = Symbol('fullFlushFlag') const _handle = Symbol('handle') const _onError = Symbol('onError') const _sawError = Symbol('sawError') const _level = Symbol('level') const _strategy = Symbol('strategy') const _ended = Symbol('ended') const _defaultFullFlush = Symbol('_defaultFullFlush') class ZlibBase extends Minipass { constructor (opts, mode) { if (!opts || typeof opts !== 'object') throw new TypeError('invalid options for ZlibBase constructor') super(opts) this[_sawError] = false this[_ended] = false this[_opts] = opts this[_flushFlag] = opts.flush this[_finishFlushFlag] = opts.finishFlush // this will throw if any options are invalid for the class selected try { this[_handle] = new realZlib[mode](opts) } catch (er) { // make sure that all errors get decorated properly throw new ZlibError(er) } this[_onError] = (err) => { // no sense raising multiple errors, since we abort on the first one. if (this[_sawError]) return this[_sawError] = true // there is no way to cleanly recover. // continuing only obscures problems. this.close() this.emit('error', err) } this[_handle].on('error', er => this[_onError](new ZlibError(er))) this.once('end', () => this.close) } close () { if (this[_handle]) { this[_handle].close() this[_handle] = null this.emit('close') } } reset () { if (!this[_sawError]) { assert(this[_handle], 'zlib binding closed') return this[_handle].reset() } } flush (flushFlag) { if (this.ended) return if (typeof flushFlag !== 'number') flushFlag = this[_fullFlushFlag] this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) } end (chunk, encoding, cb) { if (chunk) this.write(chunk, encoding) this.flush(this[_finishFlushFlag]) this[_ended] = true return super.end(null, null, cb) } get ended () { return this[_ended] } write (chunk, encoding, cb) { // process the chunk using the sync process // then super.write() all the outputted chunks if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (typeof chunk === 'string') chunk = Buffer.from(chunk, encoding) if (this[_sawError]) return assert(this[_handle], 'zlib binding closed') // _processChunk tries to .close() the native handle after it's done, so we // intercept that by temporarily making it a no-op. const nativeHandle = this[_handle]._handle const originalNativeClose = nativeHandle.close nativeHandle.close = () => {} const originalClose = this[_handle].close this[_handle].close = () => {} // It also calls `Buffer.concat()` at the end, which may be convenient // for some, but which we are not interested in as it slows us down. Buffer.concat = (args) => args let result try { const flushFlag = typeof chunk[_flushFlag] === 'number' ? chunk[_flushFlag] : this[_flushFlag] result = this[_handle]._processChunk(chunk, flushFlag) // if we don't throw, reset it back how it was Buffer.concat = OriginalBufferConcat } catch (err) { // or if we do, put Buffer.concat() back before we emit error // Error events call into user code, which may call Buffer.concat() Buffer.concat = OriginalBufferConcat this[_onError](new ZlibError(err)) } finally { if (this[_handle]) { // Core zlib resets `_handle` to null after attempting to close the // native handle. Our no-op handler prevented actual closure, but we // need to restore the `._handle` property. this[_handle]._handle = nativeHandle nativeHandle.close = originalNativeClose this[_handle].close = originalClose // `_processChunk()` adds an 'error' listener. If we don't remove it // after each call, these handlers start piling up. this[_handle].removeAllListeners('error') // make sure OUR error listener is still attached tho } } if (this[_handle]) this[_handle].on('error', er => this[_onError](new ZlibError(er))) let writeReturn if (result) { if (Array.isArray(result) && result.length > 0) { // The first buffer is always `handle._outBuffer`, which would be // re-used for later invocations; so, we always have to copy that one. writeReturn = this[_superWrite](Buffer.from(result[0])) for (let i = 1; i < result.length; i++) { writeReturn = this[_superWrite](result[i]) } } else { writeReturn = this[_superWrite](Buffer.from(result)) } } if (cb) cb() return writeReturn } [_superWrite] (data) { return super.write(data) } } class Zlib extends ZlibBase { constructor (opts, mode) { opts = opts || {} opts.flush = opts.flush || constants.Z_NO_FLUSH opts.finishFlush = opts.finishFlush || constants.Z_FINISH super(opts, mode) this[_fullFlushFlag] = constants.Z_FULL_FLUSH this[_level] = opts.level this[_strategy] = opts.strategy } params (level, strategy) { if (this[_sawError]) return if (!this[_handle]) throw new Error('cannot switch params when binding is closed') // no way to test this without also not supporting params at all /* istanbul ignore if */ if (!this[_handle].params) throw new Error('not supported in this implementation') if (this[_level] !== level || this[_strategy] !== strategy) { this.flush(constants.Z_SYNC_FLUSH) assert(this[_handle], 'zlib binding closed') // .params() calls .flush(), but the latter is always async in the // core zlib. We override .flush() temporarily to intercept that and // flush synchronously. const origFlush = this[_handle].flush this[_handle].flush = (flushFlag, cb) => { this.flush(flushFlag) cb() } try { this[_handle].params(level, strategy) } finally { this[_handle].flush = origFlush } /* istanbul ignore else */ if (this[_handle]) { this[_level] = level this[_strategy] = strategy } } } } // minimal 2-byte header class Deflate extends Zlib { constructor (opts) { super(opts, 'Deflate') } } class Inflate extends Zlib { constructor (opts) { super(opts, 'Inflate') } } // gzip - bigger header, same deflate compression const _portable = Symbol('_portable') class Gzip extends Zlib { constructor (opts) { super(opts, 'Gzip') this[_portable] = opts && !!opts.portable } [_superWrite] (data) { if (!this[_portable]) return super[_superWrite](data) // we'll always get the header emitted in one first chunk // overwrite the OS indicator byte with 0xFF this[_portable] = false data[9] = 255 return super[_superWrite](data) } } class Gunzip extends Zlib { constructor (opts) { super(opts, 'Gunzip') } } // raw - no header class DeflateRaw extends Zlib { constructor (opts) { super(opts, 'DeflateRaw') } } class InflateRaw extends Zlib { constructor (opts) { super(opts, 'InflateRaw') } } // auto-detect header. class Unzip extends Zlib { constructor (opts) { super(opts, 'Unzip') } } class Brotli extends ZlibBase { constructor (opts, mode) { opts = opts || {} opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH super(opts, mode) this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH } } class BrotliCompress extends Brotli { constructor (opts) { super(opts, 'BrotliCompress') } } class BrotliDecompress extends Brotli { constructor (opts) { super(opts, 'BrotliDecompress') } } exports.Deflate = Deflate exports.Inflate = Inflate exports.Gzip = Gzip exports.Gunzip = Gunzip exports.DeflateRaw = DeflateRaw exports.InflateRaw = InflateRaw exports.Unzip = Unzip /* istanbul ignore else */ if (typeof realZlib.BrotliCompress === 'function') { exports.BrotliCompress = BrotliCompress exports.BrotliDecompress = BrotliDecompress } else { exports.BrotliCompress = exports.BrotliDecompress = class { constructor () { throw new Error('Brotli is not supported in this version of Node.js') } } } node_modules/minizlib/node_modules/minipass/package.json 0000664 00000002243 15114743311 0017627 0 ustar 00 { "name": "minipass", "version": "3.3.6", "description": "minimal implementation of a PassThrough stream", "main": "index.js", "types": "index.d.ts", "dependencies": { "yallist": "^4.0.0" }, "devDependencies": { "@types/node": "^17.0.41", "end-of-stream": "^1.4.0", "prettier": "^2.6.2", "tap": "^16.2.0", "through2": "^2.0.3", "ts-node": "^10.8.1", "typescript": "^4.7.3" }, "scripts": { "test": "tap", "preversion": "npm test", "postversion": "npm publish", "postpublish": "git push origin --follow-tags" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass.git" }, "keywords": [ "passthrough", "stream" ], "author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)", "license": "ISC", "files": [ "index.d.ts", "index.js" ], "tap": { "check-coverage": true }, "engines": { "node": ">=8" }, "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" } } node_modules/minizlib/node_modules/minipass/LICENSE 0000664 00000001423 15114743311 0016345 0 ustar 00 The ISC License Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. node_modules/minizlib/node_modules/minipass/index.d.ts 0000664 00000010200 15114743311 0017232 0 ustar 00 /// <reference types="node" /> import { EventEmitter } from 'events' import { Stream } from 'stream' declare namespace Minipass { type Encoding = BufferEncoding | 'buffer' | null interface Writable extends EventEmitter { end(): any write(chunk: any, ...args: any[]): any } interface Readable extends EventEmitter { pause(): any resume(): any pipe(): any } interface Pipe<R, W> { src: Minipass<R, W> dest: Writable opts: PipeOptions } type DualIterable<T> = Iterable<T> & AsyncIterable<T> type ContiguousData = Buffer | ArrayBufferLike | ArrayBufferView | string type BufferOrString = Buffer | string interface StringOptions { encoding: BufferEncoding objectMode?: boolean async?: boolean } interface BufferOptions { encoding?: null | 'buffer' objectMode?: boolean async?: boolean } interface ObjectModeOptions { objectMode: true async?: boolean } interface PipeOptions { end?: boolean proxyErrors?: boolean } type Options<T> = T extends string ? StringOptions : T extends Buffer ? BufferOptions : ObjectModeOptions } declare class Minipass< RType extends any = Buffer, WType extends any = RType extends Minipass.BufferOrString ? Minipass.ContiguousData : RType > extends Stream implements Minipass.DualIterable<RType> { static isStream(stream: any): stream is Minipass.Readable | Minipass.Writable readonly bufferLength: number readonly flowing: boolean readonly writable: boolean readonly readable: boolean readonly paused: boolean readonly emittedEnd: boolean readonly destroyed: boolean /** * Not technically private or readonly, but not safe to mutate. */ private readonly buffer: RType[] private readonly pipes: Minipass.Pipe<RType, WType>[] /** * Technically writable, but mutating it can change the type, * so is not safe to do in TypeScript. */ readonly objectMode: boolean async: boolean /** * Note: encoding is not actually read-only, and setEncoding(enc) * exists. However, this type definition will insist that TypeScript * programs declare the type of a Minipass stream up front, and if * that type is string, then an encoding MUST be set in the ctor. If * the type is Buffer, then the encoding must be missing, or set to * 'buffer' or null. If the type is anything else, then objectMode * must be set in the constructor options. So there is effectively * no allowed way that a TS program can set the encoding after * construction, as doing so will destroy any hope of type safety. * TypeScript does not provide many options for changing the type of * an object at run-time, which is what changing the encoding does. */ readonly encoding: Minipass.Encoding // setEncoding(encoding: Encoding): void // Options required if not reading buffers constructor( ...args: RType extends Buffer ? [] | [Minipass.Options<RType>] : [Minipass.Options<RType>] ) write(chunk: WType, cb?: () => void): boolean write(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): boolean read(size?: number): RType end(cb?: () => void): this end(chunk: any, cb?: () => void): this end(chunk: any, encoding?: Minipass.Encoding, cb?: () => void): this pause(): void resume(): void promise(): Promise<void> collect(): Promise<RType[]> concat(): RType extends Minipass.BufferOrString ? Promise<RType> : never destroy(er?: any): void pipe<W extends Minipass.Writable>(dest: W, opts?: Minipass.PipeOptions): W unpipe<W extends Minipass.Writable>(dest: W): void /** * alias for on() */ addEventHandler(event: string, listener: (...args: any[]) => any): this on(event: string, listener: (...args: any[]) => any): this on(event: 'data', listener: (chunk: RType) => any): this on(event: 'error', listener: (error: any) => any): this on( event: | 'readable' | 'drain' | 'resume' | 'end' | 'prefinish' | 'finish' | 'close', listener: () => any ): this [Symbol.iterator](): Iterator<RType> [Symbol.asyncIterator](): AsyncIterator<RType> } export = Minipass node_modules/minizlib/node_modules/minipass/index.js 0000664 00000040367 15114743311 0017017 0 ustar 00 'use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = require('events') const Stream = require('stream') const SD = require('string_decoder').StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') const DESTROYED = Symbol('destroyed') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol('asyncIterator not implemented') const ITERATOR = doIter && Symbol.iterator || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor (src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe () { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors () {} end () { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe () { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor (src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } module.exports = class Minipass extends Stream { constructor (options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this.pipes = [] this.buffer = [] this[OBJECTMODE] = options && options.objectMode || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = options && options.encoding || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = options && !!options.async || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false } get bufferLength () { return this[BUFFERLENGTH] } get encoding () { return this[ENCODING] } set encoding (enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if (this[ENCODING] && enc !== this[ENCODING] && (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this.buffer.length) this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding (enc) { this.encoding = enc } get objectMode () { return this[OBJECTMODE] } set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async'] () { return this[ASYNC] } set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } write (chunk, encoding, cb) { if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit('error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } )) return true } if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read (n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this.buffer.length > 1 && !this[OBJECTMODE]) { if (this.encoding) this.buffer = [this.buffer.join('')] else this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] } const ret = this[READ](n || null, this.buffer[0]) this[MAYBE_EMIT_END]() return ret } [READ] (n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this.buffer[0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this.buffer.length && !this[EOF]) this.emit('drain') return chunk } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME] () { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this.buffer.length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume () { return this[RESUME]() } pause () { this[FLOWING] = false this[PAUSED] = true } get destroyed () { return this[DESTROYED] } get flowing () { return this[FLOWING] } get paused () { return this[PAUSED] } [BUFFERPUSH] (chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this.buffer.push(chunk) } [BUFFERSHIFT] () { if (this.buffer.length) { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this.buffer[0].length } return this.buffer.shift() } [FLUSH] (noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) if (!noDrain && !this.buffer.length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK] (chunk) { return chunk ? (this.emit('data', chunk), this.flowing) : false } pipe (dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts)) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe (dest) { const p = this.pipes.find(p => p.dest === dest) if (p) { this.pipes.splice(this.pipes.indexOf(p), 1) p.unpipe() } } addListener (ev, fn) { return this.on(ev, fn) } on (ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this.pipes.length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd () { return this[EMITTED_END] } [MAYBE_EMIT_END] () { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this.buffer.length === 0 && this[EOF]) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit (ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data const ret = super.emit('error', data) this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA] (data) { for (const p of this.pipes) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND] () { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2] () { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this.pipes) { p.dest.write(data) } super.emit('data', data) } } for (const p of this.pipes) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect () { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat () { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) } // stream.promise().then(() => done, er => emitted error) promise () { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR] () { const next = () => { const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return Promise.resolve({ done: true }) let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next } } // for (let chunk of stream) [ITERATOR] () { const next = () => { const value = this.read() const done = value === null return { value, done } } return { next } } destroy (er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this.buffer.length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) else // if no error to emit, still reject pending promises this.emit(DESTROYED) return this } static isStream (s) { return !!s && (s instanceof Minipass || s instanceof Stream || s instanceof EE && ( typeof s.pipe === 'function' || // readable (typeof s.write === 'function' && typeof s.end === 'function') // writable )) } } node_modules/minizlib/node_modules/minipass/README.md 0000664 00000061255 15114743311 0016630 0 ustar 00 # minipass A _very_ minimal implementation of a [PassThrough stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) [It's very fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0) for objects, strings, and buffers. Supports `pipe()`ing (including multi-`pipe()` and backpressure transmission), buffering data until either a `data` event handler or `pipe()` is added (so you don't lose the first chunk), and most other cases where PassThrough is a good idea. There is a `read()` method, but it's much more efficient to consume data from this stream via `'data'` events or by calling `pipe()` into some other stream. Calling `read()` requires the buffer to be flattened in some cases, which requires copying memory. If you set `objectMode: true` in the options, then whatever is written will be emitted. Otherwise, it'll do a minimal amount of Buffer copying to ensure proper Streams semantics when `read(n)` is called. `objectMode` can also be set by doing `stream.objectMode = true`, or by writing any non-string/non-buffer data. `objectMode` cannot be set to false once it is set. This is not a `through` or `through2` stream. It doesn't transform the data, it just passes it right through. If you want to transform the data, extend the class, and override the `write()` method. Once you're done transforming the data however you want, call `super.write()` with the transform output. For some examples of streams that extend Minipass in various ways, check out: - [minizlib](http://npm.im/minizlib) - [fs-minipass](http://npm.im/fs-minipass) - [tar](http://npm.im/tar) - [minipass-collect](http://npm.im/minipass-collect) - [minipass-flush](http://npm.im/minipass-flush) - [minipass-pipeline](http://npm.im/minipass-pipeline) - [tap](http://npm.im/tap) - [tap-parser](http://npm.im/tap-parser) - [treport](http://npm.im/treport) - [minipass-fetch](http://npm.im/minipass-fetch) - [pacote](http://npm.im/pacote) - [make-fetch-happen](http://npm.im/make-fetch-happen) - [cacache](http://npm.im/cacache) - [ssri](http://npm.im/ssri) - [npm-registry-fetch](http://npm.im/npm-registry-fetch) - [minipass-json-stream](http://npm.im/minipass-json-stream) - [minipass-sized](http://npm.im/minipass-sized) ## Differences from Node.js Streams There are several things that make Minipass streams different from (and in some ways superior to) Node.js core streams. Please read these caveats if you are familiar with node-core streams and intend to use Minipass streams in your programs. You can avoid most of these differences entirely (for a very small performance penalty) by setting `{async: true}` in the constructor options. ### Timing Minipass streams are designed to support synchronous use-cases. Thus, data is emitted as soon as it is available, always. It is buffered until read, but no longer. Another way to look at it is that Minipass streams are exactly as synchronous as the logic that writes into them. This can be surprising if your code relies on `PassThrough.write()` always providing data on the next tick rather than the current one, or being able to call `resume()` and not have the entire buffer disappear immediately. However, without this synchronicity guarantee, there would be no way for Minipass to achieve the speeds it does, or support the synchronous use cases that it does. Simply put, waiting takes time. This non-deferring approach makes Minipass streams much easier to reason about, especially in the context of Promises and other flow-control mechanisms. Example: ```js const Minipass = require('minipass') const stream = new Minipass({ async: true }) stream.on('data', () => console.log('data event')) console.log('before write') stream.write('hello') console.log('after write') // output: // before write // data event // after write ``` ### Exception: Async Opt-In If you wish to have a Minipass stream with behavior that more closely mimics Node.js core streams, you can set the stream in async mode either by setting `async: true` in the constructor options, or by setting `stream.async = true` later on. ```js const Minipass = require('minipass') const asyncStream = new Minipass({ async: true }) asyncStream.on('data', () => console.log('data event')) console.log('before write') asyncStream.write('hello') console.log('after write') // output: // before write // after write // data event <-- this is deferred until the next tick ``` Switching _out_ of async mode is unsafe, as it could cause data corruption, and so is not enabled. Example: ```js const Minipass = require('minipass') const stream = new Minipass({ encoding: 'utf8' }) stream.on('data', chunk => console.log(chunk)) stream.async = true console.log('before writes') stream.write('hello') setStreamSyncAgainSomehow(stream) // <-- this doesn't actually exist! stream.write('world') console.log('after writes') // hypothetical output would be: // before writes // world // after writes // hello // NOT GOOD! ``` To avoid this problem, once set into async mode, any attempt to make the stream sync again will be ignored. ```js const Minipass = require('minipass') const stream = new Minipass({ encoding: 'utf8' }) stream.on('data', chunk => console.log(chunk)) stream.async = true console.log('before writes') stream.write('hello') stream.async = false // <-- no-op, stream already async stream.write('world') console.log('after writes') // actual output: // before writes // after writes // hello // world ``` ### No High/Low Water Marks Node.js core streams will optimistically fill up a buffer, returning `true` on all writes until the limit is hit, even if the data has nowhere to go. Then, they will not attempt to draw more data in until the buffer size dips below a minimum value. Minipass streams are much simpler. The `write()` method will return `true` if the data has somewhere to go (which is to say, given the timing guarantees, that the data is already there by the time `write()` returns). If the data has nowhere to go, then `write()` returns false, and the data sits in a buffer, to be drained out immediately as soon as anyone consumes it. Since nothing is ever buffered unnecessarily, there is much less copying data, and less bookkeeping about buffer capacity levels. ### Hazards of Buffering (or: Why Minipass Is So Fast) Since data written to a Minipass stream is immediately written all the way through the pipeline, and `write()` always returns true/false based on whether the data was fully flushed, backpressure is communicated immediately to the upstream caller. This minimizes buffering. Consider this case: ```js const {PassThrough} = require('stream') const p1 = new PassThrough({ highWaterMark: 1024 }) const p2 = new PassThrough({ highWaterMark: 1024 }) const p3 = new PassThrough({ highWaterMark: 1024 }) const p4 = new PassThrough({ highWaterMark: 1024 }) p1.pipe(p2).pipe(p3).pipe(p4) p4.on('data', () => console.log('made it through')) // this returns false and buffers, then writes to p2 on next tick (1) // p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) // p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) // p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' // on next tick (4) // p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and // 'drain' on next tick (5) // p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) // p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next // tick (7) p1.write(Buffer.alloc(2048)) // returns false ``` Along the way, the data was buffered and deferred at each stage, and multiple event deferrals happened, for an unblocked pipeline where it was perfectly safe to write all the way through! Furthermore, setting a `highWaterMark` of `1024` might lead someone reading the code to think an advisory maximum of 1KiB is being set for the pipeline. However, the actual advisory buffering level is the _sum_ of `highWaterMark` values, since each one has its own bucket. Consider the Minipass case: ```js const m1 = new Minipass() const m2 = new Minipass() const m3 = new Minipass() const m4 = new Minipass() m1.pipe(m2).pipe(m3).pipe(m4) m4.on('data', () => console.log('made it through')) // m1 is flowing, so it writes the data to m2 immediately // m2 is flowing, so it writes the data to m3 immediately // m3 is flowing, so it writes the data to m4 immediately // m4 is flowing, so it fires the 'data' event immediately, returns true // m4's write returned true, so m3 is still flowing, returns true // m3's write returned true, so m2 is still flowing, returns true // m2's write returned true, so m1 is still flowing, returns true // No event deferrals or buffering along the way! m1.write(Buffer.alloc(2048)) // returns true ``` It is extremely unlikely that you _don't_ want to buffer any data written, or _ever_ buffer data that can be flushed all the way through. Neither node-core streams nor Minipass ever fail to buffer written data, but node-core streams do a lot of unnecessary buffering and pausing. As always, the faster implementation is the one that does less stuff and waits less time to do it. ### Immediately emit `end` for empty streams (when not paused) If a stream is not paused, and `end()` is called before writing any data into it, then it will emit `end` immediately. If you have logic that occurs on the `end` event which you don't want to potentially happen immediately (for example, closing file descriptors, moving on to the next entry in an archive parse stream, etc.) then be sure to call `stream.pause()` on creation, and then `stream.resume()` once you are ready to respond to the `end` event. However, this is _usually_ not a problem because: ### Emit `end` When Asked One hazard of immediately emitting `'end'` is that you may not yet have had a chance to add a listener. In order to avoid this hazard, Minipass streams safely re-emit the `'end'` event if a new listener is added after `'end'` has been emitted. Ie, if you do `stream.on('end', someFunction)`, and the stream has already emitted `end`, then it will call the handler right away. (You can think of this somewhat like attaching a new `.then(fn)` to a previously-resolved Promise.) To prevent calling handlers multiple times who would not expect multiple ends to occur, all listeners are removed from the `'end'` event whenever it is emitted. ### Emit `error` When Asked The most recent error object passed to the `'error'` event is stored on the stream. If a new `'error'` event handler is added, and an error was previously emitted, then the event handler will be called immediately (or on `process.nextTick` in the case of async streams). This makes it much more difficult to end up trying to interact with a broken stream, if the error handler is added after an error was previously emitted. ### Impact of "immediate flow" on Tee-streams A "tee stream" is a stream piping to multiple destinations: ```js const tee = new Minipass() t.pipe(dest1) t.pipe(dest2) t.write('foo') // goes to both destinations ``` Since Minipass streams _immediately_ process any pending data through the pipeline when a new pipe destination is added, this can have surprising effects, especially when a stream comes in from some other function and may or may not have data in its buffer. ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone src.pipe(dest2) // gets nothing! ``` One solution is to create a dedicated tee-stream junction that pipes to both locations, and then pipe to _that_ instead. ```js // Safe example: tee to both places const src = new Minipass() src.write('foo') const tee = new Minipass() tee.pipe(dest1) tee.pipe(dest2) src.pipe(tee) // tee gets 'foo', pipes to both locations ``` The same caveat applies to `on('data')` event listeners. The first one added will _immediately_ receive all of the data, leaving nothing for the second: ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.on('data', handler1) // receives 'foo' right away src.on('data', handler2) // nothing to see here! ``` Using a dedicated tee-stream can be used in this case as well: ```js // Safe example: tee to both data handlers const src = new Minipass() src.write('foo') const tee = new Minipass() tee.on('data', handler1) tee.on('data', handler2) src.pipe(tee) ``` All of the hazards in this section are avoided by setting `{ async: true }` in the Minipass constructor, or by setting `stream.async = true` afterwards. Note that this does add some overhead, so should only be done in cases where you are willing to lose a bit of performance in order to avoid having to refactor program logic. ## USAGE It's a stream! Use it like a stream and it'll most likely do what you want. ```js const Minipass = require('minipass') const mp = new Minipass(options) // optional: { encoding, objectMode } mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` ### OPTIONS * `encoding` How would you like the data coming _out_ of the stream to be encoded? Accepts any values that can be passed to `Buffer.toString()`. * `objectMode` Emit data exactly as it comes in. This will be flipped on by default if you write() something other than a string or Buffer at any point. Setting `objectMode: true` will prevent setting any encoding value. * `async` Defaults to `false`. Set to `true` to defer data emission until next tick. This reduces performance slightly, but makes Minipass streams use timing behavior closer to Node core streams. See [Timing](#timing) for more details. ### API Implements the user-facing portions of Node.js's `Readable` and `Writable` streams. ### Methods * `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the base Minipass class, the same data will come out.) Returns `false` if the stream will buffer the next write, or true if it's still in "flowing" mode. * `end([chunk, [encoding]], [callback])` - Signal that you have no more data to write. This will queue an `end` event to be fired when all the data has been consumed. * `setEncoding(encoding)` - Set the encoding for data coming of the stream. This can only be done once. * `pause()` - No more data for a while, please. This also prevents `end` from being emitted for empty streams until the stream is resumed. * `resume()` - Resume the stream. If there's data in the buffer, it is all discarded. Any buffered events are immediately emitted. * `pipe(dest)` - Send all output to the stream provided. When data is emitted, it is immediately written to any and all pipe destinations. (Or written on next tick in `async` mode.) * `unpipe(dest)` - Stop piping to the destination stream. This is immediate, meaning that any asynchronously queued data will _not_ make it to the destination when running in `async` mode. * `options.end` - Boolean, end the destination stream when the source stream ends. Default `true`. * `options.proxyErrors` - Boolean, proxy `error` events from the source stream to the destination stream. Note that errors are _not_ proxied after the pipeline terminates, either due to the source emitting `'end'` or manually unpiping with `src.unpipe(dest)`. Default `false`. * `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some events are given special treatment, however. (See below under "events".) * `promise()` - Returns a Promise that resolves when the stream emits `end`, or rejects if the stream emits `error`. * `collect()` - Return a Promise that resolves on `end` with an array containing each chunk of data that was emitted, or rejects if the stream emits `error`. Note that this consumes the stream data. * `concat()` - Same as `collect()`, but concatenates the data into a single Buffer object. Will reject the returned promise if the stream is in objectMode, or if it goes into objectMode by the end of the data. * `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not provided, then consume all of it. If `n` bytes are not available, then it returns null. **Note** consuming streams in this way is less efficient, and can lead to unnecessary Buffer copying. * `destroy([er])` - Destroy the stream. If an error is provided, then an `'error'` event is emitted. If the stream has a `close()` method, and has not emitted a `'close'` event yet, then `stream.close()` will be called. Any Promises returned by `.promise()`, `.collect()` or `.concat()` will be rejected. After being destroyed, writing to the stream will emit an error. No more data will be emitted if the stream is destroyed, even if it was previously buffered. ### Properties * `bufferLength` Read-only. Total number of bytes buffered, or in the case of objectMode, the total number of objects. * `encoding` The encoding that has been set. (Setting this is equivalent to calling `setEncoding(enc)` and has the same prohibition against setting multiple times.) * `flowing` Read-only. Boolean indicating whether a chunk written to the stream will be immediately emitted. * `emittedEnd` Read-only. Boolean indicating whether the end-ish events (ie, `end`, `prefinish`, `finish`) have been emitted. Note that listening on any end-ish event will immediateyl re-emit it if it has already been emitted. * `writable` Whether the stream is writable. Default `true`. Set to `false` when `end()` * `readable` Whether the stream is readable. Default `true`. * `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written to the stream that have not yet been emitted. (It's probably a bad idea to mess with this.) * `pipes` A [yallist](http://npm.im/yallist) linked list of streams that this stream is piping into. (It's probably a bad idea to mess with this.) * `destroyed` A getter that indicates whether the stream was destroyed. * `paused` True if the stream has been explicitly paused, otherwise false. * `objectMode` Indicates whether the stream is in `objectMode`. Once set to `true`, it cannot be set to `false`. ### Events * `data` Emitted when there's data to read. Argument is the data to read. This is never emitted while not flowing. If a listener is attached, that will resume the stream. * `end` Emitted when there's no more data to read. This will be emitted immediately for empty streams when `end()` is called. If a listener is attached, and `end` was already emitted, then it will be emitted again. All listeners are removed when `end` is emitted. * `prefinish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'end'`. * `finish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'prefinish'`. * `close` An indication that an underlying resource has been released. Minipass does not emit this event, but will defer it until after `end` has been emitted, since it throws off some stream libraries otherwise. * `drain` Emitted when the internal buffer empties, and it is again suitable to `write()` into the stream. * `readable` Emitted when data is buffered and ready to be read by a consumer. * `resume` Emitted when stream changes state from buffering to flowing mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event listener is added.) ### Static Methods * `Minipass.isStream(stream)` Returns `true` if the argument is a stream, and false otherwise. To be considered a stream, the object must be either an instance of Minipass, or an EventEmitter that has either a `pipe()` method, or both `write()` and `end()` methods. (Pretty much any stream in node-land will return `true` for this.) ## EXAMPLES Here are some examples of things you can do with Minipass streams. ### simple "are you done yet" promise ```js mp.promise().then(() => { // stream is finished }, er => { // stream emitted an error }) ``` ### collecting ```js mp.collect().then(all => { // all is an array of all the data emitted // encoding is supported in this case, so // so the result will be a collection of strings if // an encoding is specified, or buffers/objects if not. // // In an async function, you may do // const data = await stream.collect() }) ``` ### collecting into a single blob This is a bit slower because it concatenates the data into one chunk for you, but if you're going to do it yourself anyway, it's convenient this way: ```js mp.concat().then(onebigchunk => { // onebigchunk is a string if the stream // had an encoding set, or a buffer otherwise. }) ``` ### iteration You can iterate over streams synchronously or asynchronously in platforms that support it. Synchronous iteration will end when the currently available data is consumed, even if the `end` event has not been reached. In string and buffer mode, the data is concatenated, so unless multiple writes are occurring in the same tick as the `read()`, sync iteration loops will generally only have a single iteration. To consume chunks in this way exactly as they have been written, with no flattening, create the stream with the `{ objectMode: true }` option. ```js const mp = new Minipass({ objectMode: true }) mp.write('a') mp.write('b') for (let letter of mp) { console.log(letter) // a, b } mp.write('c') mp.write('d') for (let letter of mp) { console.log(letter) // c, d } mp.write('e') mp.end() for (let letter of mp) { console.log(letter) // e } for (let letter of mp) { console.log(letter) // nothing } ``` Asynchronous iteration will continue until the end event is reached, consuming all of the data. ```js const mp = new Minipass({ encoding: 'utf8' }) // some source of some data let i = 5 const inter = setInterval(() => { if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // consume the data with asynchronous iteration async function consume () { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // logs `foo\n` 5 times, and then `ok` ``` ### subclass that `console.log()`s everything written into it ```js class Logger extends Minipass { write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } } someSource.pipe(new Logger()).pipe(someDest) ``` ### same thing, but using an inline anonymous class ```js // js classes are fun someSource .pipe(new (class extends Minipass { emit (ev, ...data) { // let's also log events, because debugging some weird thing console.log('EMIT', ev) return super.emit(ev, ...data) } write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } })) .pipe(someDest) ``` ### subclass that defers 'end' for some reason ```js class SlowEnd extends Minipass { emit (ev, ...args) { if (ev === 'end') { console.log('going to end, hold on a sec') setTimeout(() => { console.log('ok, ready to end now') super.emit('end', ...args) }, 100) } else { return super.emit(ev, ...args) } } } ``` ### transform that creates newline-delimited JSON ```js class NDJSONEncode extends Minipass { write (obj, cb) { try { // JSON.stringify can throw, emit an error on that return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) } catch (er) { this.emit('error', er) } } end (obj, cb) { if (typeof obj === 'function') { cb = obj obj = undefined } if (obj !== undefined) { this.write(obj) } return super.end(cb) } } ``` ### transform that parses newline-delimited JSON ```js class NDJSONDecode extends Minipass { constructor (options) { // always be in object mode, as far as Minipass is concerned super({ objectMode: true }) this._jsonBuffer = '' } write (chunk, encoding, cb) { if (typeof chunk === 'string' && typeof encoding === 'string' && encoding !== 'utf8') { chunk = Buffer.from(chunk, encoding).toString() } else if (Buffer.isBuffer(chunk)) chunk = chunk.toString() } if (typeof encoding === 'function') { cb = encoding } const jsonData = (this._jsonBuffer + chunk).split('\n') this._jsonBuffer = jsonData.pop() for (let i = 0; i < jsonData.length; i++) { try { // JSON.parse can throw, emit an error on that super.write(JSON.parse(jsonData[i])) } catch (er) { this.emit('error', er) continue } } if (cb) cb() } } ``` node_modules/minizlib/README.md 0000664 00000003601 15114743311 0012317 0 ustar 00 # minizlib A fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding. This module was created to serve the needs of [node-tar](http://npm.im/tar) and [minipass-fetch](http://npm.im/minipass-fetch). Brotli is supported in versions of node with a Brotli binding. ## How does this differ from the streams in `require('zlib')`? First, there are no convenience methods to compress or decompress a buffer. If you want those, use the built-in `zlib` module. This is only streams. That being said, Minipass streams to make it fairly easy to use as one-liners: `new zlib.Deflate().end(data).read()` will return the deflate compressed result. This module compresses and decompresses the data as fast as you feed it in. It is synchronous, and runs on the main process thread. Zlib and Brotli operations can be high CPU, but they're very fast, and doing it this way means much less bookkeeping and artificial deferral. Node's built in zlib streams are built on top of `stream.Transform`. They do the maximally safe thing with respect to consistent asynchrony, buffering, and backpressure. See [Minipass](http://npm.im/minipass) for more on the differences between Node.js core streams and Minipass streams, and the convenience methods provided by that class. ## Classes - Deflate - Inflate - Gzip - Gunzip - DeflateRaw - InflateRaw - Unzip - BrotliCompress (Node v10 and higher) - BrotliDecompress (Node v10 and higher) ## USAGE ```js const zlib = require('minizlib') const input = sourceOfCompressedData() const decode = new zlib.BrotliDecompress() const output = whereToWriteTheDecodedData() input.pipe(decode).pipe(output) ``` ## REPRODUCIBLE BUILDS To create reproducible gzip compressed files across different operating systems, set `portable: true` in the options. This causes minizlib to set the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for 'unknown'.
| ver. 1.6 |
Github
|
.
| PHP 8.1.33 | Генерация страницы: 0.37 |
proxy
|
phpinfo
|
Настройка