├── CODEOWNERS ├── pnpm-workspace.yaml ├── eslint.config.js ├── .gitignore ├── renovate.json ├── playground ├── package.json └── index.js ├── src ├── index.ts └── implementation.ts ├── .editorconfig ├── vitest.config.ts ├── tsconfig.json ├── .github ├── ISSUE_TEMPLATE │ └── ---bug-report.yml └── workflows │ ├── codeql.yml │ └── ci.yml ├── LICENCE ├── package.json ├── README.md ├── CODE_OF_CONDUCT.md └── test └── index.test.ts /CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @danielroe 2 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - playground 3 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | import antfu from '@antfu/eslint-config' 2 | 3 | export default antfu() 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | coverage 4 | .vscode 5 | .DS_Store 6 | .eslintcache 7 | *.log* 8 | *.env* 9 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "github>danielroe/renovate" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /playground/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "module", 3 | "private": true, 4 | "scripts": { 5 | "dev": "node index.js" 6 | }, 7 | "dependencies": { 8 | "glob-native": "latest" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /playground/index.js: -------------------------------------------------------------------------------- 1 | import assert from 'node:assert' 2 | import * as pkg from 'glob-native' 3 | 4 | // eslint-disable-next-line no-console 5 | console.log(pkg.welcome()) 6 | 7 | assert.strictEqual(pkg.welcome(), 'hello world') 8 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import fsp from 'node:fs/promises' 2 | import { fspGlob as _fspGlob } from './implementation' 3 | 4 | export type { GlobOptions } from './implementation' 5 | 6 | export const fspGlob = (fsp as any).glob as typeof _fspGlob ?? _fspGlob 7 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | charset = utf-8 8 | 9 | [*.js] 10 | indent_style = space 11 | indent_size = 2 12 | 13 | [{package.json,*.yml,*.cjson}] 14 | indent_style = space 15 | indent_size = 2 16 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { fileURLToPath } from 'node:url' 2 | import { defineConfig } from 'vitest/config' 3 | 4 | export default defineConfig({ 5 | resolve: { 6 | alias: { 7 | 'glob-native': fileURLToPath( 8 | new URL('./src/index.ts', import.meta.url).href, 9 | ), 10 | }, 11 | }, 12 | test: { 13 | coverage: { 14 | include: ['src'], 15 | reporter: ['text', 'json', 'html'], 16 | }, 17 | }, 18 | }) 19 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2022", 4 | "lib": [ 5 | "es2022" 6 | ], 7 | "moduleDetection": "force", 8 | "module": "preserve", 9 | "resolveJsonModule": true, 10 | "allowJs": true, 11 | "strict": true, 12 | "noImplicitOverride": true, 13 | "noUncheckedIndexedAccess": true, 14 | "noEmit": true, 15 | "esModuleInterop": true, 16 | "forceConsistentCasingInFileNames": true, 17 | "isolatedModules": true, 18 | "verbatimModuleSyntax": true, 19 | "skipLibCheck": true 20 | }, 21 | "include": [ 22 | "src", 23 | "test", 24 | "playground", 25 | "test/fixture/other" 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/---bug-report.yml: -------------------------------------------------------------------------------- 1 | name: 🐛 Bug report 2 | description: Something's not working 3 | labels: [bug] 4 | body: 5 | - type: textarea 6 | validations: 7 | required: true 8 | attributes: 9 | label: 🐛 The bug 10 | description: What isn't working? Describe what the bug is. 11 | - type: input 12 | validations: 13 | required: true 14 | attributes: 15 | label: 🛠️ To reproduce 16 | description: A reproduction of the bug via https://stackblitz.com/github/unjs/glob-native/tree/main/playground 17 | placeholder: https://stackblitz.com/[...] 18 | - type: textarea 19 | validations: 20 | required: true 21 | attributes: 22 | label: 🌈 Expected behaviour 23 | description: What did you expect to happen? Is there a section in the docs about this? 24 | - type: textarea 25 | attributes: 26 | label: ℹ️ Additional context 27 | description: Add any other context about the problem here. 28 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | name: CodeQL 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | schedule: 9 | - cron: '31 15 * * 5' 10 | 11 | jobs: 12 | analyze: 13 | name: Analyze 14 | runs-on: ubuntu-latest 15 | permissions: 16 | actions: read 17 | contents: read 18 | security-events: write 19 | 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | language: [javascript] 24 | 25 | steps: 26 | - name: Checkout 27 | uses: actions/checkout@v4 28 | 29 | - name: Initialize CodeQL 30 | uses: github/codeql-action/init@v3 31 | with: 32 | languages: ${{ matrix.language }} 33 | queries: +security-and-quality 34 | 35 | - name: Autobuild 36 | uses: github/codeql-action/autobuild@v3 37 | 38 | - name: Perform CodeQL Analysis 39 | uses: github/codeql-action/analyze@v3 40 | with: 41 | category: '/language:${{ matrix.language }}' 42 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Daniel Roe 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | push: 8 | branches: 9 | - main 10 | - renovate/* 11 | 12 | jobs: 13 | lint: 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v4 18 | - run: corepack enable 19 | - uses: actions/setup-node@v4 20 | with: 21 | node-version: 22 22 | cache: pnpm 23 | 24 | - name: 📦 Install dependencies 25 | run: pnpm install 26 | 27 | - name: 🔠 Lint project 28 | run: pnpm lint 29 | 30 | test: 31 | runs-on: ubuntu-latest 32 | 33 | steps: 34 | - uses: actions/checkout@v4 35 | - run: corepack enable 36 | - uses: actions/setup-node@v4 37 | with: 38 | node-version: 22 39 | cache: pnpm 40 | 41 | - name: 📦 Install dependencies 42 | run: pnpm install 43 | 44 | - name: 🛠 Build project 45 | run: pnpm build 46 | 47 | - name: 💪 Test types 48 | run: pnpm test:types 49 | 50 | - name: 🧪 Test project 51 | run: pnpm test:unit -- --coverage 52 | 53 | - name: 🟩 Coverage 54 | uses: codecov/codecov-action@v5 55 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "glob-native", 3 | "type": "module", 4 | "version": "0.0.1", 5 | "packageManager": "pnpm@9.15.4", 6 | "description": "", 7 | "license": "MIT", 8 | "repository": "unjs/glob-native", 9 | "sideEffects": false, 10 | "exports": { 11 | ".": "./dist/index.js" 12 | }, 13 | "main": "./dist/index.js", 14 | "module": "./dist/index.js", 15 | "types": "./dist/index.d.ts", 16 | "files": [ 17 | "dist" 18 | ], 19 | "scripts": { 20 | "build": "unbuild", 21 | "dev": "vitest dev", 22 | "lint": "eslint . --fix", 23 | "prepare": "simple-git-hooks", 24 | "prepack": "pnpm build", 25 | "prepublishOnly": "pnpm lint && pnpm test", 26 | "release": "bumpp && pnpm publish", 27 | "test": "pnpm test:unit && pnpm test:types", 28 | "test:unit": "vitest", 29 | "test:types": "tsc --noEmit" 30 | }, 31 | "dependencies": { 32 | "fdir": "^6.1.1", 33 | "picomatch": "^4.0.2" 34 | }, 35 | "devDependencies": { 36 | "@antfu/eslint-config": "latest", 37 | "@types/picomatch": "3.0.1", 38 | "@vitest/coverage-v8": "latest", 39 | "bumpp": "9.10.0", 40 | "eslint": "latest", 41 | "lint-staged": "latest", 42 | "simple-git-hooks": "latest", 43 | "typescript": "latest", 44 | "unbuild": "latest", 45 | "vite": "latest", 46 | "vitest": "latest" 47 | }, 48 | "resolutions": { 49 | "glob-native": "link:." 50 | }, 51 | "simple-git-hooks": { 52 | "pre-commit": "npx lint-staged" 53 | }, 54 | "lint-staged": { 55 | "*.{js,ts,mjs,cjs,json,.*rc}": [ 56 | "pnpm eslint --fix" 57 | ] 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # glob-native 2 | 3 | [![npm version][npm-version-src]][npm-version-href] 4 | [![npm downloads][npm-downloads-src]][npm-downloads-href] 5 | [![Github Actions][github-actions-src]][github-actions-href] 6 | [![Codecov][codecov-src]][codecov-href] 7 | 8 | > A polyfill package to replicate the functionality of the experimental `fs.glob` 9 | 10 | > [!WARNING] 11 | > This package is not yet reliable enough to use, not least because the node `fs.glob` implementation seems to have some issues that need to be reported/fixed. 12 | 13 | ## 🚧 Roadmap 14 | 15 | - [x] fsPromises.glob 16 | - [ ] fs.glob 17 | - [ ] fs.globSync 18 | 19 | ## Usage 20 | 21 | Install package: 22 | 23 | ```sh 24 | npm install glob-native 25 | ``` 26 | 27 | ```js 28 | import { fspGlob as glob } from 'glob-native' 29 | 30 | for await (const entry of glob('**/*.js')) { 31 | console.log(entry) 32 | } 33 | ``` 34 | 35 | ## 💻 Development 36 | 37 | - Clone this repository 38 | - Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` 39 | - Install dependencies using `pnpm install` 40 | - Run interactive tests using `pnpm dev` 41 | 42 | ## License 43 | 44 | Made with ❤️ 45 | 46 | Published under [MIT License](./LICENCE). 47 | 48 | 49 | 50 | [npm-version-src]: https://img.shields.io/npm/v/glob-native?style=flat-square 51 | [npm-version-href]: https://npmjs.com/package/glob-native 52 | [npm-downloads-src]: https://img.shields.io/npm/dm/glob-native?style=flat-square 53 | [npm-downloads-href]: https://npm.chart.dev/glob-native 54 | [github-actions-src]: https://img.shields.io/github/actions/workflow/status/unjs/glob-native/ci.yml?branch=main&style=flat-square 55 | [github-actions-href]: https://github.com/unjs/glob-native/actions?query=workflow%3Aci 56 | [codecov-src]: https://img.shields.io/codecov/c/gh/unjs/glob-native/main?style=flat-square 57 | [codecov-href]: https://codecov.io/gh/unjs/glob-native 58 | -------------------------------------------------------------------------------- /src/implementation.ts: -------------------------------------------------------------------------------- 1 | import process from 'node:process' 2 | import path from 'node:path' 3 | import type { Dirent } from 'node:fs' 4 | import fsp from 'node:fs/promises' 5 | 6 | import { fdir as FDir } from 'fdir' 7 | 8 | // https://nodejs.org/api/fs.html#fspromisesglobpattern-options 9 | export interface GlobOptions { 10 | /** current working directory. Default: process.cwd() */ 11 | cwd?: string 12 | /** 13 | * Function to filter out files/directories. 14 | * Return true to exclude the item, false to include it. 15 | * @default undefined 16 | */ 17 | exclude?: (path: string) => boolean 18 | /** 19 | * Whether the glob should return paths as Dirents. 20 | * @default false 21 | */ 22 | withFileTypes?: WithFileTypes 23 | } 24 | 25 | export async function *fspGlob(pattern: string | string[], options?: GlobOptions): AsyncGenerator<(WithFileTypes extends true ? Dirent : string) | undefined, void, unknown> { 26 | // Normalise options 27 | const patterns = Array.isArray(pattern) ? pattern : [pattern] 28 | const dir = options?.cwd ? path.resolve(options.cwd) : process.cwd() 29 | const withFileTypes = !!options?.withFileTypes 30 | type GlobReturn = WithFileTypes extends true ? Dirent : string 31 | 32 | // Initialise watcher 33 | const fdir = new FDir({ 34 | exclude: options?.exclude ? dirName => options.exclude!(dirName) : undefined, 35 | filters: options?.exclude ? [(filePath, _isDirectory) => !options.exclude!(path.basename(filePath))] : [], 36 | includeDirs: true, 37 | relativePaths: true, 38 | }) 39 | 40 | const files = await fdir.globWithOptions(patterns, { 41 | dot: false, 42 | cwd: dir, 43 | nonegate: true, 44 | }).crawl(dir).withPromise() 45 | 46 | const contents: Record = {} 47 | 48 | for (const file of files) { 49 | const absolutePath = path.resolve(dir, file) 50 | const relativePath = path.relative(dir, absolutePath) 51 | 52 | if (relativePath) { 53 | if (withFileTypes) { 54 | const dirname = path.dirname(absolutePath) 55 | contents[dirname] ||= await fsp.readdir(dirname, { withFileTypes: true }) 56 | yield contents[dirname].find(file => file.name === path.basename(absolutePath)) as GlobReturn 57 | } 58 | else { 59 | yield relativePath as GlobReturn 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | - Using welcoming and inclusive language 12 | - Being respectful of differing viewpoints and experiences 13 | - Gracefully accepting constructive criticism 14 | - Focusing on what is best for the community 15 | - Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | - The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | - Trolling, insulting/derogatory comments, and personal or political attacks 21 | - Public or private harassment 22 | - Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | - Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [daniel@roe.dev](mailto:daniel@roe.dev). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 44 | 45 | [homepage]: https://www.contributor-covenant.org 46 | 47 | For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq 48 | -------------------------------------------------------------------------------- /test/index.test.ts: -------------------------------------------------------------------------------- 1 | import fsp from 'node:fs/promises' 2 | import path from 'node:path' 3 | import { afterAll, beforeAll, describe, expect, it } from 'vitest' 4 | import { fspGlob } from '../src/implementation.js' 5 | 6 | const relativeFixturePath = 'node_modules/_test_fixture' 7 | const absoluteFixturePath = path.resolve(relativeFixturePath) 8 | 9 | const fixture = [ 10 | '.dot/file.js', 11 | 'dir/index.js', 12 | 'dir/README.md', 13 | 'other/file.ts', 14 | ] 15 | 16 | const cases = new Map, any>([ 17 | [ 18 | ['**/*.js', { cwd: relativeFixturePath }], 19 | ['dir/index.js'], 20 | ], 21 | [ 22 | ['**/*', { cwd: relativeFixturePath }], 23 | ['dir', 'other', 'other/file.ts', 'dir/README.md', 'dir/index.js'], 24 | ], 25 | [ 26 | // negative patterns are not supported 27 | [['**/*', '!**/*.md'], { cwd: relativeFixturePath }], 28 | ['dir', 'other', 'other/file.ts', 'dir/README.md', 'dir/index.js'], 29 | ], 30 | [ 31 | // file types 32 | [['**/*.js'], { cwd: relativeFixturePath, withFileTypes: true as const }], 33 | [expect.objectContaining({ 34 | name: 'index.js', 35 | parentPath: path.join(absoluteFixturePath, 'dir'), 36 | path: path.join(absoluteFixturePath, 'dir'), 37 | })], 38 | ], 39 | [ 40 | // exclude - note that the node behaviour doesn't entirely match the docs - it only triggers on directories 41 | [['_test_fixture/**/*.*'], { cwd: 'node_modules', exclude: path => path.endsWith('dir') }], 42 | ['_test_fixture/other/file.ts'], 43 | ], 44 | [ 45 | // exclude - note that the node behaviour doesn't entirely match the docs - it only triggers on directories 46 | [['_test_fixture/**/*.*'], { cwd: 'node_modules', exclude: path => path.endsWith('.ts') }], 47 | ['_test_fixture/dir/README.md', '_test_fixture/dir/index.js'], 48 | ], 49 | // Inconsistent implementation from polyfill 50 | // [ 51 | // // exclude - note that the node behaviour doesn't entirely match the docs - it only triggers on directories 52 | // [['fixture/**/*'], { cwd: 'test', exclude: path => path.endsWith('dir') }], 53 | // ['fixture/other', 'fixture/other/file.ts'], 54 | // ], 55 | // Buggy implementation from Node 56 | // [ 57 | // // exclude - note that the node behaviour doesn't entirely match the docs - it only triggers on directories 58 | // [['fixture/**/*'], { cwd: 'test', exclude: path => path.endsWith('.ts') }], 59 | // ['fixture/dir', 'fixture/other', 'fixture/dir/README.md', 'fixture/dir/index.js', 'fixture/other/file.ts'], 60 | // ], 61 | ]) 62 | 63 | const implementations = { 64 | native: (fsp as any).glob as typeof fspGlob, 65 | polyfill: fspGlob, 66 | } 67 | 68 | describe('fspGlob', () => { 69 | beforeAll(async () => { 70 | await fsp.rm(absoluteFixturePath, { recursive: true, force: true }) 71 | for (const file of fixture) { 72 | const filePath = path.join(absoluteFixturePath, file) 73 | await fsp.mkdir(path.dirname(filePath), { recursive: true }) 74 | await fsp.writeFile(filePath, '') 75 | } 76 | }) 77 | 78 | it.each(Object.entries(implementations))('works with %s implementation', async (name, implementation) => { 79 | for (const [args, result] of cases) { 80 | const entries = [] 81 | for await (const entry of implementation(...args)) { 82 | entries.push(entry) 83 | } 84 | expect(entries.sort()).toEqual(result.sort()) 85 | } 86 | }) 87 | 88 | afterAll(async () => { 89 | // await fsp.rm(absoluteFixturePath, { recursive: true, force: true }) 90 | }) 91 | }) 92 | --------------------------------------------------------------------------------