diff --git a/.gitattributes b/.gitattributes index dbd44bf..6313b56 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1 @@ -# Auto detect text files and enforce LF as linebreaks * text=auto eol=lf diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..9cff13e --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @phanect diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 6c3a2d4..94badf3 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,13 +3,28 @@ updates: - package-ecosystem: "npm" directory: "/" schedule: - interval: "daily" + interval: "weekly" assignees: - "phanect" + groups: + compatible: + applies-to: "version-updates" + update-types: + - "minor" + - "patch" - package-ecosystem: "github-actions" directory: "/" schedule: - interval: "daily" + interval: "weekly" assignees: - "phanect" + groups: + security: + applies-to: "security-updates" + patterns: + - "*" + normal: + applies-to: "version-updates" + patterns: + - "*" diff --git a/.github/workflows/actions.yml b/.github/workflows/actions.yml new file mode 100644 index 0000000..a081954 --- /dev/null +++ b/.github/workflows/actions.yml @@ -0,0 +1,83 @@ +name: GitHub Actions + +on: + pull_request: + branches: + - main + push: + branches: + - main + release: + types: + - published + +permissions: + contents: read + +jobs: + build-lint: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + - uses: jdx/mise-action@c37c93293d6b742fc901e1406b8f764f6fb19dac # v2.4.4 + with: + install: true + cache: true + + - run: mise lint + - run: mise build + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: dist + path: dist + if-no-files-found: error + retention-days: 1 + include-hidden-files: true + + test: + name: test on Node.js v${{ matrix.node-version }} + runs-on: ubuntu-latest + timeout-minutes: 5 + strategy: + matrix: + node-version: + - 20 + - 22 + - 24 + env: + # Override Node.js version over mise.toml + MISE_NODE_VERSION: ${{ matrix.node-version }} + steps: + + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + - uses: jdx/mise-action@c37c93293d6b742fc901e1406b8f764f6fb19dac # v2.4.4 + with: + install: true + cache: true + + - run: mise test + + publish: + needs: + - build-lint + - test + if: github.event_name == 'release' + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + - uses: jdx/mise-action@c37c93293d6b742fc901e1406b8f764f6fb19dac # v2.4.4 + with: + install: true + cache: true + + - uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0 + with: + name: dist + path: dist + + - name: Set npm auth token + run: echo "//registry.npmjs.org/:_authToken=${{secrets.NPM_AUTH_TOKEN}}" > ~/.npmrc + - run: mise release diff --git a/.github/workflows/workflow.yaml b/.github/workflows/workflow.yaml deleted file mode 100644 index a28ab7b..0000000 --- a/.github/workflows/workflow.yaml +++ /dev/null @@ -1,50 +0,0 @@ -name: GitHub Actions - -on: - pull_request: - branches: - - main - push: - branches: - - main - release: - types: - - published - -jobs: - build: - runs-on: ubuntu-latest - strategy: - matrix: - node-version: - - 18 - - 20 - - 22 - steps: - - uses: actions/checkout@v4 - - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v4 - with: - node-version: ${{ matrix.node-version }} - - - run: npm install - - run: npm run build - - run: npm test - - run: npm run lint - - publish: - needs: build - if: github.event_name == 'release' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: 20 - - - run: npm install - - run: npm run build - - - name: Set npm auth token - run: echo "//registry.npmjs.org/:_authToken=${{secrets.NPM_AUTH_TOKEN}}" > ~/.npmrc - - run: npm run release diff --git a/.gitignore b/.gitignore index 8ce1d1d..5e7520f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,18 +1,7 @@ # -# Project-Specific +# Generic # -# Built files -dist/ - -# -# System -# - -# Logs -logs/ -*.log - # PIDs *.pid *.seed @@ -22,24 +11,84 @@ pids # File manager configs .directory Thumbs.db -*.DS_Store +.DS_Store + +# Build directory +build/ +dist/ + +# tmp files +temp/ +tmp/ + +# Logs +logs/ +*.log + +# Archives +*.zip +*.tar.gz +*.tar.xz +*.tar +*.tgz + +# dotenv +.env +.env.* +!.env.example + +# SQLite DB +*.db +*.db-journal + +# mise +mise.local.toml # # JavaScript # -# NPM / Yarn +# NPM / package managers node_modules/ .npm/ .yarn-integrity +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* + # Lockfiles are not required for npm packages +pnpm-lock.yaml package-lock.json yarn.lock +bun.lockb +npm-shrinkwrap.json -# tarballs packed by `npm pack` -*.tgz - -# Others +# Node.js .node_repl_history + +# TypeScript +*.tsbuildinfo + +# Frameworks +.next/ +.nuxt/ +out/ +.svelte-kit/ +.astro/ + +# Platforms +.wrangler/ +.dev.vars +worker-configuration.d.ts + +.vercel/ +.netlify/ + +# Vite +vite.config.js.timestamp-* +vite.config.ts.timestamp-* + +# ESLint .eslintcache diff --git a/.npmignore b/.npmignore index 3088814..b60af40 100644 --- a/.npmignore +++ b/.npmignore @@ -1,11 +1,16 @@ +# TODO Remove this file if the project is not an npm package /.github/ +/.vscode/ /dist/*.d.mts /dist/*.d.cts -/test/ +src/ +test/ +tests/ +*.config.js +*.config.mjs +*.config.ts *.tgz .editorconfig -.eslintrc.cjs -.gitarrtibutes +.gitattributes .gitignore -build.config.* tsconfig.json diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..46f2b23 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,8 @@ +{ + "recommendations": [ + "dbaeumer.vscode-eslint", + "EditorConfig.EditorConfig", + "hverlin.mise-vscode", + "tamasfe.even-better-toml" + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..92027ef --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,39 @@ +{ + "javascript.preferences.importModuleSpecifierEnding": "js", + "javascript.preferences.quoteStyle": "double", + "typescript.preferences.preferTypeOnlyAutoImports": true, + + "eslint.useFlatConfig": true, + "eslint.validate": [ + "javascript", + "typescript", + "javascriptreact", + "typescriptreact", + "vue", + "svelte", + "astro", + "html", + "json", + "jsonc", + "json5", + ], + + "editor.formatOnSave": true, + "editor.formatOnPaste": true, + "editor.defaultFormatter": "dbaeumer.vscode-eslint", + "editor.codeActionsOnSave": { + "source.fixAll": "never" + }, + "eslint.format.enable": true, + "eslint.codeActionsOnSave.mode": "problems", + "eslint.codeActionsOnSave.rules": [ + "@stylistic/arrow-parens", + "@stylistic/quotes", + "@stylistic/semi", + "@stylistic/space-before-blocks", + "@stylistic/space-before-function-paren", + "@stylistic/space-in-parens" + ], + + "prettier.enable": false +} diff --git a/LICENSE b/LICENSE deleted file mode 100644 index e2ce6f5..0000000 --- a/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2020 Jumpei Ogawa (https://phanective.org) - -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. diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 212bf38..448cce2 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,21 @@ @phanect's personal utility library for JavaScript & TypeScript +## Development + +### Prerequisites + +- [mise](https://mise.jdx.dev) + +### Build + +Run the following commands: + +```sh +mise install +mise build +``` + ## License -MIT +Licensed under the [Apache License 2.0](./LICENSE.txt). diff --git a/biome.jsonc b/biome.jsonc deleted file mode 100644 index 704227a..0000000 --- a/biome.jsonc +++ /dev/null @@ -1,4 +0,0 @@ -{ - "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", - "extends": ["@phanect/configs/biome"] -} diff --git a/build.config.ts b/build.config.ts deleted file mode 100644 index 7467145..0000000 --- a/build.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineBuildConfig } from "unbuild"; - -export default defineBuildConfig({ - entries: ["./src/universal.ts", "./src/nodejs.ts"], - declaration: true, - rollup: { - emitCJS: true, - }, -}); diff --git a/eslint.config.ts b/eslint.config.ts new file mode 100644 index 0000000..b5d0097 --- /dev/null +++ b/eslint.config.ts @@ -0,0 +1,31 @@ +import { core, nodejs, unbundled } from "@phanect/lint"; +import type { Linter } from "eslint"; + +const configs: Linter.Config[] = [ + { + ignores: [ + "./**/dist/**", + ], + }, + + ...core, + ...unbundled, + + ...nodejs.map((config) => ({ + ...config, + files: [ "./src/nodejs/**/*.ts" ], + })), + + { + // Do not add `files: [ "*" ],` here. + + languageOptions: { + parserOptions: { + projectService: true, + tsconfigRootDir: import.meta.dirname, + }, + }, + }, +]; + +export default configs; diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..89a056c --- /dev/null +++ b/mise.toml @@ -0,0 +1,50 @@ +[tools] +node = { version = "24" } + +[tasks] + [tasks.build] + run = "tsdown" + env = { NODE_ENV = "production" } + + [tasks.lint] + run = [ + "tsc --noEmit", + "eslint" + ] + + [tasks.fix] + run = "eslint --fix" + + [tasks.test] + run = "vitest run" + + [tasks.clean] + run = "git clean -dX --exclude=\"!mise.local.toml\" --force" + + [tasks.refresh] + depends = [ "clean" ] + run = [ + "rm --force ./pnpm-lock.yaml", + "corepack enable", + "corepack up", + "mise install" + ] + + [tasks.release] + run = "npm publish --access public --non-interactive" + +[hooks] +postinstall = [ + "corepack enable", + "pnpm install", +] + +[env] +_.path = "./node_modules/.bin" + +[settings] +jobs = 8 + +# Required for hooks as of 2025.10 +# https://mise.jdx.dev/hooks.html +experimental = true diff --git a/package.json b/package.json index d54d760..45bf29e 100644 --- a/package.json +++ b/package.json @@ -1,44 +1,44 @@ { "name": "@phanect/utils", - "version": "1.5.0", + "version": "2.0.0", "description": "@phanect's personal utility library for JavaScript & TypeScript", + "repository": { + "type": "git", + "url": "git+https://github.com/phanect/utils.git" + }, "author": "Jumpei Ogawa (https://phanective.org)", - "license": "MIT", + "license": "Apache-2.0", "type": "module", "main": "./dist/universal.cjs", - "module": "./dist/universal.mjs", + "module": "./dist/universal.js", "types": "./dist/universal.d.ts", "exports": { ".": { "import": { - "default": "./dist/universal.mjs", - "types": "./dist/universal.d.ts" + "types": "./dist/universal.d.ts", + "default": "./dist/universal.js" }, "require": "./dist/universal.cjs" }, "./nodejs": { - "import": "./dist/nodejs.mjs", - "require": "./dist/nodejs.cjs", - "types": "./dist/nodejs.d.ts" + "types": "./dist/nodejs.d.ts", + "import": "./dist/nodejs.js", + "require": "./dist/nodejs.cjs" } }, - "scripts": { - "build": "unbuild", - "lint": "tsc --noEmit && biome check", - "fix": "biome check --write", - "release": "npm publish --access public --non-interactive", - "test": "vitest run" - }, "devDependencies": { - "@biomejs/biome": "^1.8.3", "@phanect/configs": "latest", + "@phanect/lint": "latest", "@types/node": "^22.1.0", + "eslint": "^9.21.0", + "jiti": "^2.4.2", + "tsdown": "0.15.6", "typescript": "^5.3.3", - "unbuild": "^2.0.0", "vitest": "^2.0.2" }, "engines": { - "node": ">=18.x", - "npm": ">=10.x" - } + "node": "^20.11.0 || ^22.16.0 || >=24.0.0", + "pnpm": ">=10.x" + }, + "packageManager": "pnpm@10.18.2+sha512.9fb969fa749b3ade6035e0f109f0b8a60b5d08a1a87fdf72e337da90dcc93336e2280ca4e44f2358a649b83c17959e9993e777c2080879f3801e6f0d999ad3dd" } diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..cb8238f --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,3 @@ +onlyBuiltDependencies: + - esbuild + - unrs-resolver diff --git a/src/nodejs.ts b/src/nodejs.ts index 0060f7f..a97b7ab 100644 --- a/src/nodejs.ts +++ b/src/nodejs.ts @@ -1,2 +1 @@ -export { cmd } from "./nodejs/cmd.ts"; export { loadJSON } from "./nodejs/load-json.ts"; diff --git a/src/nodejs/cmd.ts b/src/nodejs/cmd.ts deleted file mode 100644 index ab9a8da..0000000 --- a/src/nodejs/cmd.ts +++ /dev/null @@ -1,168 +0,0 @@ -import type { Buffer } from "node:buffer"; -import { exec as execCallback } from "node:child_process"; - -type CmdParams = Parameters; -type CommandString = CmdParams[0]; -type CmdOptions = CmdParams[1] & { - output?: boolean; - printCommand?: boolean; -}; - -type CmdCallback = Exclude; -type CmdCallbackParams = Parameters; -type CmdStdOut = CmdCallbackParams[1]; -type CmdStdErr = CmdCallbackParams[2]; - -type CmdReturn = { - stdout: CmdStdOut; - stderr: CmdStdErr; - child: ReturnType; -}; - -type Queued = { - processId: number; - text: string | unknown; - target: "stdout" | "stderr"; - isCommand: boolean; -}; - -/** - * Run multiple commands asynchronously, but show their output sequentially. - * @param commands - Command(s) to run. - * @param options - Options. Same as Node.js's `child_process.exec()`'s + some additional options - * @param options.output - Print output if `true`. If `false`, no command output is printed and you have to print them manually from the return value. `true` by default. - * @param options.printCommand - Print command string before running the command. `true` by default. - * @returns Array of command output and child process object. - */ -export const cmd = async ( - commands: CommandString | CommandString[], - options?: CmdOptions, -): Promise => { - // Default options - const { output = true, printCommand = true } = options ?? {}; - /** Current command ID to be allowed to pring log */ - let currentProcessId = 0; - /** Queue of the texts waiting to be printed. */ - let queue: Queued[] = []; - const returnValues: CmdReturn[] = []; - - const log = (queued: Queued): void => { - const logger = queued.target === "stdout" ? console.info : console.error; - const prefix = - (queued.isCommand ? (0 < queued.processId ? "\n" : "") + ">>> " : "") + - `[${queued.processId}]`; - const trailingLineBreaks = queued.isCommand ? "\n\n" : "\n"; - - if (typeof queued.text === "string" || !!queued.text?.toString) { - logger( - queued.text - .toString() - .trim() // strip leading & trailing linebreaks - .split("\n") - .map((line) => `${prefix} ${line}`) - .join("\n") + trailingLineBreaks, - ); - } else { - logger(prefix, queued.text, trailingLineBreaks); - } - }; - - type AddToPrintQueueOptions = Omit & { - isCommand?: Queued["isCommand"] | undefined; - }; - - const addToPrintQueue = ( - text: string | Buffer | unknown, - { target, processId, isCommand = false }: AddToPrintQueueOptions, - ): void => { - const _text = - typeof text === "string" || !text?.toString ? text : text.toString(); - - if (processId <= currentProcessId) { - log({ - processId, - text: _text, - target, - isCommand, - }); - } else { - queue.push({ - processId, - text: _text, - target, - isCommand, - }); - } - }; - const dumpFromQueue = (processId: number): void => { - for (const queued of queue) { - if (queued.processId <= processId) { - log(queued); - } - } - queue = []; - }; - const nextProcess = (): void => { - currentProcessId++; - dumpFromQueue(currentProcessId); - }; - - const promises: Promise[] = ( - Array.isArray(commands) ? commands : [commands] - ).map( - (command, i) => - new Promise((resolve, reject) => { - try { - if (printCommand !== false) { - addToPrintQueue(command, { - target: "stdout", - processId: i, - isCommand: true, - }); - } - - // TODO use "error" event to print error, and "close" to resolve instead of callback. - // https://nodejs.org/docs/latest-v20.x/api/child_process.html#event-error - // https://nodejs.org/docs/latest-v20.x/api/child_process.html#event-close - - const child = execCallback( - command, - options, - (err, stdout, stderr) => { - if (err) { - reject(err); - return; - } - - resolve({ stdout, stderr, child }); - }, - ); - - if (output !== false) { - child.stdout?.on("data", (data: string | Buffer | unknown): void => - addToPrintQueue(data, { - target: "stdout", - processId: i, - }), - ); - - child.stderr?.on("data", (data: string | Buffer | unknown): void => - addToPrintQueue(data, { - target: "stderr", - processId: i, - }), - ); - } - } catch (err) { - reject(err); - } - }), - ); - - for (const promise of promises) { - returnValues.push(await promise); - nextProcess(); - } - - return Array.isArray(commands) ? returnValues : returnValues[0]; -}; diff --git a/src/nodejs/load-json.ts b/src/nodejs/load-json.ts index c45cd48..28a165a 100644 --- a/src/nodejs/load-json.ts +++ b/src/nodejs/load-json.ts @@ -1,23 +1,19 @@ -import type { ObjectEncodingOptions } from "node:fs"; import { readFile, stat } from "node:fs/promises"; +import type { ObjectEncodingOptions } from "node:fs"; -export const loadJSON = async ( +export const loadJSON = async >( jsonPath: string, options?: ObjectEncodingOptions, ): Promise => { - try { - if (!(await stat(jsonPath)).isFile()) { - throw new Error(`"${jsonPath}" does not exist of not a regular file.`); - } + if (!(await stat(jsonPath)).isFile()) { + throw new Error(`"${ jsonPath }" does not exist or not a regular file.`); + } - const jsonString = await readFile(jsonPath, { - ...options, - encoding: options?.encoding ?? "utf8", - }); - const loadedJSON: JsonObject = JSON.parse(jsonString); + const jsonString = await readFile(jsonPath, { + ...options, + encoding: options?.encoding ?? "utf8", + }); + const loadedJSON = JSON.parse(jsonString) as JsonObject; - return loadedJSON; - } catch (err) { - return Promise.reject(err); - } + return loadedJSON; }; diff --git a/src/nodejs/tsconfig.json b/src/nodejs/tsconfig.json new file mode 100644 index 0000000..1c53588 --- /dev/null +++ b/src/nodejs/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": [ + "@phanect/configs/ts/nodejs", + "@phanect/configs/ts/addons/npm" + ], + "include": [ + "./**/*.ts", + "./**/*.js" + ] +} diff --git a/src/universal/get-last-element-of.ts b/src/universal/get-last-element-of.ts index 4b1758e..bc0ddfc 100644 --- a/src/universal/get-last-element-of.ts +++ b/src/universal/get-last-element-of.ts @@ -1,11 +1,11 @@ export function getLastElementOf( arr: T[], - options?: { withIndex?: false }, + options?: { withIndex?: false; }, ): T | undefined; export function getLastElementOf( arr: T[], - options: { withIndex: true }, -): { el: T; index: number } | undefined; + options: { withIndex: true; }, +): { el: T; index: number; } | undefined; /** * @param arr - The array to get the last element. @@ -19,7 +19,7 @@ export function getLastElementOf( options: { withIndex?: boolean; } = {}, -): T | { el: T; index: number } | undefined { +): T | { el: T; index: number; } | undefined { if (arr.length <= 0) { return undefined; } diff --git a/src/universal/npm-package-exists.ts b/src/universal/npm-package-exists.ts index 97af56e..46934c1 100644 --- a/src/universal/npm-package-exists.ts +++ b/src/universal/npm-package-exists.ts @@ -1,7 +1,7 @@ import { trimLines } from "./trim-lines.ts"; export const npmPackageExists = async (pkgName: string): Promise => { - const res = await fetch(`https://registry.npmjs.com/${pkgName}`); + const res = await fetch(`https://registry.npmjs.com/${ pkgName }`); if (res.status < 400) { return true; @@ -10,24 +10,24 @@ export const npmPackageExists = async (pkgName: string): Promise => { } else if (400 <= res.status && res.status < 500) { throw new Error( trimLines(` - [ERROR] Package name "${pkgName}" may be invalid. + [ERROR] Package name "${ pkgName }" may be invalid. Could not check if npm package exists. - HTTP ${res.status} ${res.statusText} https://registry.npmjs.com/${pkgName} + HTTP ${ res.status } ${ res.statusText } https://registry.npmjs.com/${ pkgName } `), ); } else if (500 <= res.status) { throw new Error( trimLines(` [ERROR] registry.npmjs.com may be down. See: https://status.npmjs.org - Could not check if npm package "${pkgName}" exists. - HTTP ${res.status} ${res.statusText} https://registry.npmjs.com/${pkgName} + Could not check if npm package "${ pkgName }" exists. + HTTP ${ res.status } ${ res.statusText } https://registry.npmjs.com/${ pkgName } `), ); } else { throw new Error( trimLines(` - [ERROR] Unexpected HTTP Status Code ${res.status} ${res.statusText} while checking https://registry.npmjs.com/${pkgName} + [ERROR] Unexpected HTTP Status Code ${ res.status } ${ res.statusText } while checking https://registry.npmjs.com/${ pkgName } `), ); } diff --git a/src/universal/sort-objects.ts b/src/universal/sort-objects.ts index 4d9fb82..a1b06de 100644 --- a/src/universal/sort-objects.ts +++ b/src/universal/sort-objects.ts @@ -1,13 +1,13 @@ /** * Sort array of the objects by the keys in the alphabetical order. - * @param objects - Aarray of objects. + * @param objects - Array of objects. * @returns - Sorted array of the objects. */ -/* biome-ignore lint/suspicious/noExplicitAny: - * `{ [key: string]: unknown }` is not acceptable and we must use `any` here. +/* eslint-disable-next-line @typescript-eslint/no-explicit-any -- + * `{ [key: string]: unknown }` is not acceptable and we must use `any` here. * See: https://github.com/microsoft/TypeScript/wiki/Breaking-Changes/83af27fca396d172b4d895d480b10c3bacf89112#-k-string-unknown--is-no-longer-a-wildcard-assignment-target */ -export const sortObjects = ( +export const sortObjects = >( objects: T[], ): T[] => objects.sort((obj1, obj2) => { @@ -18,13 +18,9 @@ export const sortObjects = ( for (const key of keys) { if (!(key in obj1 && key in obj2) || obj1[key] === obj2[key]) { // continue - } - // if the values are not comparable, false is returned. - else if ((obj1[key] as Comparable) < (obj2[key] as Comparable)) { + } else if ((obj1[key] as Comparable) < (obj2[key] as Comparable)) { // false if if not comparable return -1; - } - // if the values are not comparable, false is returned. - else if ((obj1[key] as Comparable) > (obj2[key] as Comparable)) { + } else if ((obj1[key] as Comparable) > (obj2[key] as Comparable)) { // false if if not comparable return 1; } else { // continue diff --git a/test/cmd.test.ts b/test/cmd.test.ts deleted file mode 100644 index 46e1f23..0000000 --- a/test/cmd.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { join } from "node:path"; -import { fileURLToPath } from "node:url"; -import { afterEach, describe, expect, test, vi } from "vitest"; -import { cmd } from "../src/nodejs.ts"; -import { deindent } from "../src/universal.ts"; - -const __dirname = fileURLToPath(new URL(".", import.meta.url)); - -describe("Mock tests", () => { - afterEach(() => { - vi.restoreAllMocks(); - }); - - test("cmd", async () => { - let output = ""; - - vi.spyOn(console, "info").mockImplementation((printed) => { - output = output + printed; - return output; - }); - vi.spyOn(console, "error").mockImplementation((printed) => { - output = output + printed; - return output; - }); - - await cmd([ - `bash ${join(__dirname, "fixtures/cmd/command1.sh")}`, - `bash ${join(__dirname, "fixtures/cmd/command2.sh")}`, - ]); - - expect(output).toStrictEqual( - deindent(` - >>> [0] bash ${join(join(__dirname, "fixtures/cmd/command1.sh"))} - - [0] Command 1 started. - [0] This message is printed after three seconds, but it should be shown before the output of command 2. - - >>> [1] bash ${join(__dirname, "fixtures/cmd/command2.sh")} - - [1] Command 2 executed. - `).trim() + "\n", - ); - }); -}); diff --git a/test/fixtures/load-json/fixture.json b/test/fixtures/load-json/fixture.json index e8b37fe..65b645f 100644 --- a/test/fixtures/load-json/fixture.json +++ b/test/fixtures/load-json/fixture.json @@ -1,4 +1,4 @@ { "foo": "bar", - "boo": ["a", "b", "c"] + "boo": [ "a", "b", "c" ] } diff --git a/test/nodejs/load-json.test.ts b/test/nodejs/load-json.test.ts index 66d8699..b3edce0 100644 --- a/test/nodejs/load-json.test.ts +++ b/test/nodejs/load-json.test.ts @@ -9,6 +9,6 @@ test("loadJSON", async () => { expect(obj).toStrictEqual({ foo: "bar", - boo: ["a", "b", "c"], + boo: [ "a", "b", "c" ], }); }); diff --git a/test/universal/get-last-element-of.test.ts b/test/universal/get-last-element-of.test.ts index 20647d0..f6224b5 100644 --- a/test/universal/get-last-element-of.test.ts +++ b/test/universal/get-last-element-of.test.ts @@ -2,11 +2,11 @@ import { expect, test } from "vitest"; import { getLastElementOf } from "../../src/universal.ts"; test("getLastElementOf (without index)", () => { - const lastElement = getLastElementOf(["a", "b", "c"]); + const lastElement = getLastElementOf([ "a", "b", "c" ]); expect(lastElement).toStrictEqual("c"); - const lastElementExplicitlyWithoutIndex = getLastElementOf(["a", "b", "c"], { + const lastElementExplicitlyWithoutIndex = getLastElementOf([ "a", "b", "c" ], { withIndex: false, }); @@ -14,7 +14,7 @@ test("getLastElementOf (without index)", () => { }); test("getLastElementOf (with index)", () => { - const lastElement = getLastElementOf(["a", "b", "c"], { withIndex: true }); + const lastElement = getLastElementOf([ "a", "b", "c" ], { withIndex: true }); expect(lastElement).toStrictEqual({ el: "c", index: 2 }); }); diff --git a/tsconfig.json b/tsconfig.json index e9153d0..4c0b5bd 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,8 +1,17 @@ { "extends": [ - "@phanect/configs/tsconfig/frontend", - "@phanect/configs/tsconfig/addons/npm" + "@phanect/configs/ts", + "@phanect/configs/ts/addons/npm" ], - "include": ["**/*.ts", "**/*.js"], - "exclude": ["dist", "node_modules"] + "include": [ + "**/*.ts", + "**/*.tsx", + "**/*.js", + "**/*.mjs", + "**/*.jsx" + ], + "exclude": [ + "dist", + "node_modules" + ] } diff --git a/tsdown.config.ts b/tsdown.config.ts new file mode 100644 index 0000000..daf8a6d --- /dev/null +++ b/tsdown.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from "tsdown"; + +export default defineConfig({ + entry: [ + "./src/universal.ts", + "./src/nodejs.ts", + ], + + format: [ "esm", "cjs" ], + dts: true, + sourcemap: true, + + treeshake: false, + minify: false, + clean: true, +});