├── .nvmrc ├── .watchmanconfig ├── example ├── App.js ├── assets │ ├── icon.png │ ├── favicon.png │ ├── splash.png │ └── adaptive-icon.png ├── tsconfig.json ├── babel.config.js ├── package.json ├── app.json ├── metro.config.js └── src │ └── App.tsx ├── jest.setup.ts ├── .gitattributes ├── tsconfig.build.json ├── babel.config.js ├── previews ├── ccinput.gif └── ccinputlite.gif ├── .prettierrc.json ├── lefthook.yml ├── .editorconfig ├── .yarnrc.yml ├── src ├── index.tsx ├── __tests__ │ ├── CreditCardView.test.tsx │ ├── CreditCardInput.test.tsx │ └── LiteCreditCardInput.test.tsx ├── CreditCardInput.tsx ├── useCreditCardForm.tsx ├── CreditCardView.tsx └── LiteCreditCardInput.tsx ├── .github ├── branch-protection.yml ├── actions │ └── setup │ │ └── action.yml └── workflows │ └── ci.yml ├── tsconfig.json ├── .gitignore ├── LICENSE ├── package.json ├── README.md └── .yarn └── plugins └── @yarnpkg └── plugin-workspace-tools.cjs /.nvmrc: -------------------------------------------------------------------------------- 1 | v18 2 | -------------------------------------------------------------------------------- /.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /example/App.js: -------------------------------------------------------------------------------- 1 | export { default } from './src/App'; 2 | -------------------------------------------------------------------------------- /jest.setup.ts: -------------------------------------------------------------------------------- 1 | import '@testing-library/react-native/extend-expect'; 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | # specific for windows script files 3 | *.bat text eol=crlf -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig", 3 | "exclude": ["example"] 4 | } 5 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:@react-native/babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /previews/ccinput.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbycrosz/react-native-credit-card-input/HEAD/previews/ccinput.gif -------------------------------------------------------------------------------- /example/assets/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbycrosz/react-native-credit-card-input/HEAD/example/assets/icon.png -------------------------------------------------------------------------------- /previews/ccinputlite.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbycrosz/react-native-credit-card-input/HEAD/previews/ccinputlite.gif -------------------------------------------------------------------------------- /example/assets/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbycrosz/react-native-credit-card-input/HEAD/example/assets/favicon.png -------------------------------------------------------------------------------- /example/assets/splash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbycrosz/react-native-credit-card-input/HEAD/example/assets/splash.png -------------------------------------------------------------------------------- /example/assets/adaptive-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbycrosz/react-native-credit-card-input/HEAD/example/assets/adaptive-icon.png -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig", 3 | "compilerOptions": { 4 | // Avoid expo-cli auto-generating a tsconfig 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "quoteProps": "consistent", 3 | "singleQuote": true, 4 | "tabWidth": 2, 5 | "trailingComma": "es5", 6 | "useTabs": false, 7 | "singleAttributePerLine": true 8 | } 9 | -------------------------------------------------------------------------------- /lefthook.yml: -------------------------------------------------------------------------------- 1 | pre-commit: 2 | parallel: true 3 | commands: 4 | lint: 5 | glob: "*.{js,ts,jsx,tsx}" 6 | run: npx eslint {staged_files} 7 | types: 8 | glob: "*.{js,ts, jsx, tsx}" 9 | run: npx tsc --noEmit 10 | commit-msg: 11 | parallel: true 12 | commands: 13 | commitlint: 14 | run: npx commitlint --edit 15 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | 9 | indent_style = space 10 | indent_size = 2 11 | 12 | end_of_line = lf 13 | charset = utf-8 14 | trim_trailing_whitespace = true 15 | insert_final_newline = true 16 | -------------------------------------------------------------------------------- /.yarnrc.yml: -------------------------------------------------------------------------------- 1 | nodeLinker: node-modules 2 | nmHoistingLimits: workspaces 3 | 4 | plugins: 5 | - path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs 6 | spec: "@yarnpkg/plugin-interactive-tools" 7 | - path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs 8 | spec: "@yarnpkg/plugin-workspace-tools" 9 | 10 | yarnPath: .yarn/releases/yarn-3.6.1.cjs 11 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | export { default as CreditCardView } from './CreditCardView'; 2 | export { default as CreditCardInput } from './CreditCardInput'; 3 | export { default as LiteCreditCardInput } from './LiteCreditCardInput'; 4 | 5 | export { 6 | type CreditCardFormField, 7 | type CreditCardFormValues, 8 | type ValidationState, 9 | type CreditCardFormState, 10 | type CreditCardFormData, 11 | useCreditCardForm, 12 | } from './useCreditCardForm'; 13 | -------------------------------------------------------------------------------- /.github/branch-protection.yml: -------------------------------------------------------------------------------- 1 | # Branch Protection Rules for main branch 2 | # This file documents the required status checks for pull requests 3 | 4 | required_status_checks: 5 | strict: true 6 | contexts: 7 | - 'lint-and-typecheck' 8 | - 'test-coverage' 9 | - 'build' 10 | - 'build-example' 11 | 12 | required_pull_request_reviews: 13 | required_approving_review_count: 1 14 | dismiss_stale_reviews: true 15 | require_code_owner_reviews: false 16 | 17 | enforce_admins: false 18 | allow_force_pushes: false 19 | allow_deletions: false 20 | 21 | restrictions: null 22 | -------------------------------------------------------------------------------- /example/babel.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const pak = require('../package.json'); 3 | 4 | module.exports = function (api) { 5 | api.cache(true); 6 | 7 | return { 8 | presets: ['babel-preset-expo'], 9 | plugins: [ 10 | [ 11 | 'module-resolver', 12 | { 13 | extensions: ['.tsx', '.ts', '.js', '.json'], 14 | alias: { 15 | // For development, we want to alias the library to the source 16 | [pak.name]: path.join(__dirname, '..', pak.source), 17 | }, 18 | }, 19 | ], 20 | ], 21 | }; 22 | }; 23 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-credit-card-input-example", 3 | "version": "1.0.0", 4 | "main": "expo/AppEntry.js", 5 | "scripts": { 6 | "start": "expo start", 7 | "android": "expo start --android", 8 | "ios": "expo start --ios", 9 | "web": "expo start --web" 10 | }, 11 | "dependencies": { 12 | "@expo/metro-runtime": "~3.2.1", 13 | "expo": "~51.0.18", 14 | "expo-status-bar": "~1.12.1", 15 | "react": "18.2.0", 16 | "react-dom": "18.2.0", 17 | "react-native": "0.74.3", 18 | "react-native-web": "~0.19.10" 19 | }, 20 | "devDependencies": { 21 | "@babel/core": "^7.20.0", 22 | "babel-plugin-module-resolver": "^5.0.0" 23 | }, 24 | "private": true 25 | } 26 | -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "expo": { 3 | "name": "example", 4 | "slug": "example", 5 | "version": "1.0.0", 6 | "orientation": "portrait", 7 | "icon": "./assets/icon.png", 8 | "userInterfaceStyle": "light", 9 | "splash": { 10 | "image": "./assets/splash.png", 11 | "resizeMode": "contain", 12 | "backgroundColor": "#ffffff" 13 | }, 14 | "ios": { 15 | "supportsTablet": true, 16 | "bundleIdentifier": "creditcardinput.example" 17 | }, 18 | "android": { 19 | "adaptiveIcon": { 20 | "foregroundImage": "./assets/adaptive-icon.png", 21 | "backgroundColor": "#ffffff" 22 | }, 23 | "package": "creditcardinput.example" 24 | }, 25 | "web": { 26 | "favicon": "./assets/favicon.png" 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "rootDir": ".", 4 | "paths": { 5 | "react-native-credit-card-input": ["./src/index"] 6 | }, 7 | "allowUnreachableCode": false, 8 | "allowUnusedLabels": false, 9 | "esModuleInterop": true, 10 | "forceConsistentCasingInFileNames": true, 11 | "jsx": "react-jsx", 12 | "lib": ["ESNext"], 13 | "module": "ESNext", 14 | "moduleResolution": "Bundler", 15 | "noFallthroughCasesInSwitch": true, 16 | "noImplicitReturns": true, 17 | "noImplicitUseStrict": false, 18 | "noStrictGenericChecks": false, 19 | "noUncheckedIndexedAccess": true, 20 | "noUnusedLocals": true, 21 | "noUnusedParameters": true, 22 | "resolveJsonModule": true, 23 | "skipLibCheck": true, 24 | "strict": true, 25 | "target": "ESNext", 26 | "verbatimModuleSyntax": true 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /.github/actions/setup/action.yml: -------------------------------------------------------------------------------- 1 | name: Setup 2 | description: Setup Node.js and install dependencies 3 | 4 | runs: 5 | using: composite 6 | steps: 7 | - name: Setup Node.js 8 | uses: actions/setup-node@v3 9 | with: 10 | node-version-file: .nvmrc 11 | 12 | - name: Cache dependencies 13 | id: yarn-cache 14 | uses: actions/cache@v3 15 | with: 16 | path: | 17 | **/node_modules 18 | .yarn/install-state.gz 19 | key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}-${{ hashFiles('**/package.json', '!node_modules/**') }} 20 | restore-keys: | 21 | ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }} 22 | ${{ runner.os }}-yarn- 23 | 24 | - name: Install dependencies 25 | if: steps.yarn-cache.outputs.cache-hit != 'true' 26 | run: yarn install --immutable 27 | shell: bash 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # XDE 6 | .expo/ 7 | 8 | # VSCode 9 | .vscode/ 10 | jsconfig.json 11 | 12 | # Xcode 13 | # 14 | build/ 15 | *.pbxuser 16 | !default.pbxuser 17 | *.mode1v3 18 | !default.mode1v3 19 | *.mode2v3 20 | !default.mode2v3 21 | *.perspectivev3 22 | !default.perspectivev3 23 | xcuserdata 24 | *.xccheckout 25 | *.moved-aside 26 | DerivedData 27 | *.hmap 28 | *.ipa 29 | *.xcuserstate 30 | project.xcworkspace 31 | 32 | # Android/IJ 33 | # 34 | .classpath 35 | .cxx 36 | .gradle 37 | .idea 38 | .project 39 | .settings 40 | local.properties 41 | android.iml 42 | 43 | # Cocoapods 44 | # 45 | example/ios/Pods 46 | 47 | # Ruby 48 | example/vendor/ 49 | 50 | # node.js 51 | # 52 | node_modules/ 53 | npm-debug.log 54 | yarn-debug.log 55 | yarn-error.log 56 | 57 | # BUCK 58 | buck-out/ 59 | \.buckd/ 60 | android/app/libs 61 | android/keystores/debug.keystore 62 | 63 | # Yarn 64 | .yarn/* 65 | !.yarn/patches 66 | !.yarn/plugins 67 | !.yarn/releases 68 | !.yarn/sdks 69 | !.yarn/versions 70 | 71 | # Expo 72 | .expo/ 73 | 74 | # Turborepo 75 | .turbo/ 76 | 77 | # generated by bob 78 | lib/ 79 | coverage 80 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 sbycrosz 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | SOFTWARE. 21 | -------------------------------------------------------------------------------- /example/metro.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const escape = require('escape-string-regexp'); 3 | const { getDefaultConfig } = require('@expo/metro-config'); 4 | const exclusionList = require('metro-config/src/defaults/exclusionList'); 5 | const pak = require('../package.json'); 6 | 7 | const root = path.resolve(__dirname, '..'); 8 | const modules = Object.keys({ ...pak.peerDependencies }); 9 | 10 | const defaultConfig = getDefaultConfig(__dirname); 11 | 12 | /** 13 | * Metro configuration 14 | * https://facebook.github.io/metro/docs/configuration 15 | * 16 | * @type {import('metro-config').MetroConfig} 17 | */ 18 | const config = { 19 | ...defaultConfig, 20 | 21 | projectRoot: __dirname, 22 | watchFolders: [root], 23 | 24 | // We need to make sure that only one version is loaded for peerDependencies 25 | // So we block them at the root, and alias them to the versions in example's node_modules 26 | resolver: { 27 | ...defaultConfig.resolver, 28 | 29 | blacklistRE: exclusionList( 30 | modules.map( 31 | (m) => 32 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`) 33 | ) 34 | ), 35 | 36 | extraNodeModules: modules.reduce((acc, name) => { 37 | acc[name] = path.join(__dirname, 'node_modules', name); 38 | return acc; 39 | }, {}), 40 | }, 41 | }; 42 | 43 | module.exports = config; 44 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | pull_request_target: 11 | branches: 12 | - main 13 | merge_group: 14 | types: 15 | - checks_requested 16 | 17 | jobs: 18 | lint: 19 | runs-on: ubuntu-latest 20 | steps: 21 | - name: Checkout 22 | uses: actions/checkout@v3 23 | 24 | - name: Setup 25 | uses: ./.github/actions/setup 26 | 27 | - name: Lint files 28 | run: yarn lint 29 | 30 | - name: Typecheck files 31 | run: yarn typecheck 32 | 33 | test: 34 | runs-on: ubuntu-latest 35 | steps: 36 | - name: Checkout 37 | uses: actions/checkout@v3 38 | 39 | - name: Setup 40 | uses: ./.github/actions/setup 41 | 42 | - name: Run unit tests 43 | run: yarn test --maxWorkers=2 --coverage --ci 44 | 45 | build-library: 46 | runs-on: ubuntu-latest 47 | steps: 48 | - name: Checkout 49 | uses: actions/checkout@v3 50 | 51 | - name: Setup 52 | uses: ./.github/actions/setup 53 | 54 | - name: Build package 55 | run: yarn prepare 56 | 57 | build-web: 58 | runs-on: ubuntu-latest 59 | steps: 60 | - name: Checkout 61 | uses: actions/checkout@v3 62 | 63 | - name: Setup 64 | uses: ./.github/actions/setup 65 | 66 | - name: Build example for Web 67 | run: | 68 | yarn example expo export --platform web 69 | -------------------------------------------------------------------------------- /src/__tests__/CreditCardView.test.tsx: -------------------------------------------------------------------------------- 1 | import { render, screen } from '@testing-library/react-native'; 2 | import React from 'react'; 3 | import CreditCardView from '../CreditCardView'; 4 | 5 | jest.mock('react-native-flip-card', () => { 6 | const { View } = require('react-native'); 7 | const FlipCard = ({ 8 | children, 9 | flip, 10 | }: { 11 | children: React.ReactNode; 12 | flip: boolean; 13 | }) => { 14 | if (flip && children && Array.isArray(children) && children.length > 1) { 15 | return {children[1]}; 16 | } 17 | if (children && Array.isArray(children) && children.length > 0) { 18 | return {children[0]}; 19 | } 20 | return ; 21 | }; 22 | 23 | return FlipCard; 24 | }); 25 | 26 | describe('CreditCardView', () => { 27 | it('renders default placeholder by default', () => { 28 | render(); 29 | expect(screen.getByText('•••• •••• •••• ••••')).toBeTruthy(); 30 | expect(screen.getByText('••/••')).toBeTruthy(); 31 | }); 32 | 33 | it('renders supplied values when provided', () => { 34 | render( 35 | 41 | ); 42 | expect(screen.getByText('4111 1111 1111 1111')).toBeTruthy(); 43 | expect(screen.getByText('JOHN DOE')).toBeTruthy(); 44 | expect(screen.getByText('12/25')).toBeTruthy(); 45 | }); 46 | 47 | describe('Card flipping behavior', () => { 48 | it('shows front by default', () => { 49 | render(); 50 | expect(screen.getByTestId('card-front')).toBeTruthy(); 51 | expect(screen.queryByTestId('card-back')).toBeFalsy(); 52 | }); 53 | 54 | it('shows back when focusedField is cvc and not American Express', () => { 55 | render( 56 | 60 | ); 61 | expect(screen.getByTestId('card-back')).toBeTruthy(); 62 | expect(screen.queryByTestId('card-front')).toBeFalsy(); 63 | }); 64 | 65 | it('shows front when focusedField is cvc and type is American Express', () => { 66 | render( 67 | 71 | ); 72 | expect(screen.getByTestId('card-front')).toBeTruthy(); 73 | expect(screen.queryByTestId('card-back')).toBeFalsy(); 74 | }); 75 | 76 | it('displays CVC on back when card is flipped', () => { 77 | render( 78 | 83 | ); 84 | expect(screen.getByText('123')).toBeTruthy(); 85 | }); 86 | }); 87 | 88 | describe('American Express specific behavior', () => { 89 | it('shows CVC on front for American Express cards', () => { 90 | render( 91 | 95 | ); 96 | expect(screen.getByText('123')).toBeTruthy(); 97 | }); 98 | 99 | it('does not flip card for American Express when CVC is focused', () => { 100 | render( 101 | 105 | ); 106 | expect(screen.getByTestId('card-front')).toBeTruthy(); 107 | expect(screen.queryByTestId('card-back')).toBeFalsy(); 108 | }); 109 | }); 110 | }); 111 | -------------------------------------------------------------------------------- /example/src/App.tsx: -------------------------------------------------------------------------------- 1 | import { useState } from 'react'; 2 | import { 3 | Platform, 4 | ScrollView, 5 | StyleSheet, 6 | Switch, 7 | Text, 8 | View, 9 | } from 'react-native'; 10 | import { 11 | CreditCardView, 12 | CreditCardInput, 13 | LiteCreditCardInput, 14 | type CreditCardFormData, 15 | type CreditCardFormField, 16 | type ValidationState, 17 | } from 'react-native-credit-card-input'; 18 | 19 | const s = StyleSheet.create({ 20 | container: { 21 | width: '100%', 22 | maxWidth: 600, 23 | marginHorizontal: 'auto', 24 | backgroundColor: '#f0f0f0', 25 | borderRadius: 10, 26 | marginTop: 60, 27 | }, 28 | switch: { 29 | alignSelf: 'center', 30 | marginTop: 20, 31 | marginBottom: 20, 32 | }, 33 | cardView: { 34 | alignSelf: 'center', 35 | marginTop: 15, 36 | }, 37 | cardInput: { 38 | marginTop: 15, 39 | borderColor: '#fff', 40 | borderTopWidth: 1, 41 | borderBottomWidth: 1, 42 | }, 43 | infoContainer: { 44 | margin: 20, 45 | padding: 20, 46 | backgroundColor: '#dfdfdf', 47 | borderRadius: 5, 48 | }, 49 | info: { 50 | fontFamily: Platform.select({ 51 | ios: 'Courier', 52 | android: 'monospace', 53 | web: 'monospace', 54 | }), 55 | }, 56 | }); 57 | 58 | const toStatusIcon = (status?: ValidationState) => 59 | status === 'valid' ? '✅' : status === 'invalid' ? '❌' : '❓'; 60 | 61 | export default function Example() { 62 | const [useLiteInput, setUseLiteInput] = useState(false); 63 | 64 | const [focusedField, setFocusedField] = useState(); 65 | 66 | const [formData, setFormData] = useState(); 67 | 68 | return ( 69 | 70 | { 73 | setUseLiteInput(v); 74 | setFormData(undefined); 75 | }} 76 | value={useLiteInput} 77 | /> 78 | 79 | 87 | 88 | {useLiteInput ? ( 89 | 95 | ) : ( 96 | 102 | )} 103 | 104 | 105 | 106 | {formData?.valid 107 | ? '✅ Possibly valid card' 108 | : '❌ Invalid/Incomplete card'} 109 | 110 | 111 | 112 | {toStatusIcon(formData?.status.number)} 113 | {' Number\t: '} 114 | {formData?.values.number} 115 | 116 | 117 | 118 | {toStatusIcon(formData?.status.expiry)} 119 | {' Expiry\t: '} 120 | {formData?.values.expiry} 121 | 122 | 123 | 124 | {toStatusIcon(formData?.status.cvc)} 125 | {' Cvc \t: '} 126 | {formData?.values.cvc} 127 | 128 | 129 | 130 | {'ℹ️ Type \t: '} 131 | {formData?.values.type} 132 | 133 | 134 | 135 | ); 136 | } 137 | -------------------------------------------------------------------------------- /src/__tests__/CreditCardInput.test.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | render, 3 | screen, 4 | userEvent, 5 | within, 6 | } from '@testing-library/react-native'; 7 | import CreditCardInput from '../CreditCardInput'; 8 | 9 | describe('CreditCardInput', () => { 10 | let onChange: ReturnType; 11 | let user: ReturnType; 12 | let cardInput: ReturnType; 13 | 14 | beforeEach(() => { 15 | onChange = jest.fn(); 16 | 17 | user = userEvent.setup(); 18 | render( 19 | 23 | ); 24 | 25 | cardInput = within(screen.getByTestId('CARD_INPUT')); 26 | }); 27 | 28 | it('should validate and format valid credit-card information', async () => { 29 | await user.type(cardInput.getByTestId('CC_NUMBER'), '4242424242424242'); 30 | await user.type(cardInput.getByTestId('CC_EXPIRY'), '233'); 31 | await user.type(cardInput.getByTestId('CC_CVC'), '333'); 32 | 33 | expect(onChange).toHaveBeenLastCalledWith({ 34 | valid: true, 35 | status: { 36 | number: 'valid', 37 | expiry: 'valid', 38 | cvc: 'valid', 39 | }, 40 | values: { 41 | number: '4242 4242 4242 4242', 42 | expiry: '02/33', 43 | cvc: '333', 44 | type: 'visa', 45 | }, 46 | }); 47 | }); 48 | 49 | it('should ignores non number characters ', async () => { 50 | await user.type( 51 | cardInput.getByTestId('CC_NUMBER'), 52 | '--drop db "users" 4242-4242-4242-4242' 53 | ); 54 | await user.type(cardInput.getByTestId('CC_EXPIRY'), '#$!@#!@# 12/33'); 55 | await user.type(cardInput.getByTestId('CC_CVC'), 'lorem ipsum 333'); 56 | 57 | expect(onChange).toHaveBeenLastCalledWith( 58 | expect.objectContaining({ 59 | values: expect.objectContaining({ 60 | number: '4242 4242 4242 4242', 61 | expiry: '12/33', 62 | cvc: '333', 63 | }), 64 | }) 65 | ); 66 | }); 67 | 68 | it('should return validation error for invalid card information', async () => { 69 | await user.type(cardInput.getByTestId('CC_NUMBER'), '5555 5555 5555 4443'); 70 | await user.type(cardInput.getByTestId('CC_EXPIRY'), '02 / 99'); 71 | await user.type(cardInput.getByTestId('CC_CVC'), '33'); 72 | 73 | expect(onChange).toHaveBeenLastCalledWith( 74 | expect.objectContaining({ 75 | status: { 76 | number: 'invalid', // failed crc 77 | expiry: 'invalid', // too far in the future 78 | cvc: 'incomplete', // cvv is too short 79 | }, 80 | }) 81 | ); 82 | }); 83 | 84 | it('should return credit card issuer based on card number', async () => { 85 | const numberField = cardInput.getByTestId('CC_NUMBER'); 86 | 87 | await user.clear(numberField); 88 | await user.type(numberField, '4242424242424242'); 89 | expect(onChange).toHaveBeenLastCalledWith( 90 | expect.objectContaining({ 91 | values: expect.objectContaining({ type: 'visa' }), 92 | }) 93 | ); 94 | 95 | await user.clear(numberField); 96 | await user.type(numberField, '5555555555554444'); 97 | expect(onChange).toHaveBeenLastCalledWith( 98 | expect.objectContaining({ 99 | values: expect.objectContaining({ type: 'mastercard' }), 100 | }) 101 | ); 102 | 103 | await user.clear(numberField); 104 | await user.type(numberField, '371449635398431'); 105 | expect(onChange).toHaveBeenLastCalledWith( 106 | expect.objectContaining({ 107 | values: expect.objectContaining({ type: 'american-express' }), 108 | }) 109 | ); 110 | 111 | await user.clear(numberField); 112 | await user.type(numberField, '6011111111111117'); 113 | expect(onChange).toHaveBeenLastCalledWith( 114 | expect.objectContaining({ 115 | values: expect.objectContaining({ type: 'discover' }), 116 | }) 117 | ); 118 | 119 | await user.clear(numberField); 120 | await user.type(numberField, '3056930009020004'); 121 | expect(onChange).toHaveBeenLastCalledWith( 122 | expect.objectContaining({ 123 | values: expect.objectContaining({ type: 'diners-club' }), 124 | }) 125 | ); 126 | 127 | await user.clear(numberField); 128 | await user.type(numberField, '3566002020360505'); 129 | expect(onChange).toHaveBeenLastCalledWith( 130 | expect.objectContaining({ 131 | values: expect.objectContaining({ type: 'jcb' }), 132 | }) 133 | ); 134 | }); 135 | }); 136 | -------------------------------------------------------------------------------- /src/__tests__/LiteCreditCardInput.test.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | render, 3 | screen, 4 | userEvent, 5 | within, 6 | } from '@testing-library/react-native'; 7 | import LiteCreditCardInput from '../LiteCreditCardInput'; 8 | 9 | describe('LiteCreditCardInput', () => { 10 | let onChange: ReturnType; 11 | let user: ReturnType; 12 | let cardInput: ReturnType; 13 | 14 | beforeEach(() => { 15 | onChange = jest.fn(); 16 | 17 | user = userEvent.setup(); 18 | render( 19 | 23 | ); 24 | 25 | cardInput = within(screen.getByTestId('CARD_INPUT')); 26 | }); 27 | 28 | it('should validate and format valid credit-card information', async () => { 29 | await user.type(cardInput.getByTestId('CC_NUMBER'), '4242424242424242'); 30 | await user.type(cardInput.getByTestId('CC_EXPIRY'), '233'); 31 | await user.type(cardInput.getByTestId('CC_CVC'), '333'); 32 | 33 | expect(onChange).toHaveBeenLastCalledWith({ 34 | valid: true, 35 | status: { 36 | number: 'valid', 37 | expiry: 'valid', 38 | cvc: 'valid', 39 | }, 40 | values: { 41 | number: '4242 4242 4242 4242', 42 | expiry: '02/33', 43 | cvc: '333', 44 | type: 'visa', 45 | }, 46 | }); 47 | }); 48 | 49 | it('should ignores non number characters ', async () => { 50 | await user.type( 51 | cardInput.getByTestId('CC_NUMBER'), 52 | '--drop db "users" 4242-4242-4242-4242' 53 | ); 54 | await user.type(cardInput.getByTestId('CC_EXPIRY'), '#$!@#!@# 12/33'); 55 | await user.type(cardInput.getByTestId('CC_CVC'), 'lorem ipsum 333'); 56 | 57 | expect(onChange).toHaveBeenLastCalledWith( 58 | expect.objectContaining({ 59 | values: expect.objectContaining({ 60 | number: '4242 4242 4242 4242', 61 | expiry: '12/33', 62 | cvc: '333', 63 | }), 64 | }) 65 | ); 66 | }); 67 | 68 | it('should return validation error for invalid card information', async () => { 69 | await user.type(cardInput.getByTestId('CC_NUMBER'), '5555 5555 5555 4443'); 70 | await user.type(cardInput.getByTestId('CC_EXPIRY'), '02 / 99'); 71 | await user.type(cardInput.getByTestId('CC_CVC'), '33'); 72 | 73 | expect(onChange).toHaveBeenLastCalledWith( 74 | expect.objectContaining({ 75 | status: { 76 | number: 'invalid', // failed crc 77 | expiry: 'invalid', // too far in the future 78 | cvc: 'incomplete', // cvv is too short 79 | }, 80 | }) 81 | ); 82 | }); 83 | 84 | it('should return credit card issuer based on card number', async () => { 85 | const numberField = cardInput.getByTestId('CC_NUMBER'); 86 | 87 | await user.clear(numberField); 88 | await user.type(numberField, '4242424242424242'); 89 | expect(onChange).toHaveBeenLastCalledWith( 90 | expect.objectContaining({ 91 | values: expect.objectContaining({ type: 'visa' }), 92 | }) 93 | ); 94 | 95 | await user.clear(numberField); 96 | await user.type(numberField, '5555555555554444'); 97 | expect(onChange).toHaveBeenLastCalledWith( 98 | expect.objectContaining({ 99 | values: expect.objectContaining({ type: 'mastercard' }), 100 | }) 101 | ); 102 | 103 | await user.clear(numberField); 104 | await user.type(numberField, '371449635398431'); 105 | expect(onChange).toHaveBeenLastCalledWith( 106 | expect.objectContaining({ 107 | values: expect.objectContaining({ type: 'american-express' }), 108 | }) 109 | ); 110 | 111 | await user.clear(numberField); 112 | await user.type(numberField, '6011111111111117'); 113 | expect(onChange).toHaveBeenLastCalledWith( 114 | expect.objectContaining({ 115 | values: expect.objectContaining({ type: 'discover' }), 116 | }) 117 | ); 118 | 119 | await user.clear(numberField); 120 | await user.type(numberField, '3056930009020004'); 121 | expect(onChange).toHaveBeenLastCalledWith( 122 | expect.objectContaining({ 123 | values: expect.objectContaining({ type: 'diners-club' }), 124 | }) 125 | ); 126 | 127 | await user.clear(numberField); 128 | await user.type(numberField, '3566002020360505'); 129 | expect(onChange).toHaveBeenLastCalledWith( 130 | expect.objectContaining({ 131 | values: expect.objectContaining({ type: 'jcb' }), 132 | }) 133 | ); 134 | }); 135 | }); 136 | -------------------------------------------------------------------------------- /src/CreditCardInput.tsx: -------------------------------------------------------------------------------- 1 | import { useEffect, useRef } from 'react'; 2 | import { 3 | StyleSheet, 4 | Text, 5 | TextInput, 6 | View, 7 | type TextStyle, 8 | type ViewStyle, 9 | } from 'react-native'; 10 | import { 11 | useCreditCardForm, 12 | type CreditCardFormData, 13 | type CreditCardFormField, 14 | } from './useCreditCardForm'; 15 | 16 | interface Props { 17 | autoFocus?: boolean; 18 | style?: ViewStyle; 19 | labelStyle?: TextStyle; 20 | inputStyle?: TextStyle; 21 | placeholderColor?: string; 22 | labels?: { 23 | number: string; 24 | expiry: string; 25 | cvc: string; 26 | }; 27 | placeholders?: { 28 | number: string; 29 | expiry: string; 30 | cvc: string; 31 | }; 32 | onChange: (formData: CreditCardFormData) => void; 33 | onFocusField?: (field: CreditCardFormField) => void; 34 | testID?: string; 35 | } 36 | 37 | const s = StyleSheet.create({ 38 | container: { 39 | paddingVertical: 15, 40 | paddingHorizontal: 15, 41 | }, 42 | icon: { 43 | width: 48, 44 | height: 40, 45 | resizeMode: 'contain', 46 | }, 47 | numberInput: {}, 48 | extraContainer: { 49 | flexDirection: 'row', 50 | marginTop: 15, 51 | }, 52 | expiryInputContainer: { 53 | flex: 1, 54 | marginRight: 5, 55 | }, 56 | cvcInputContainer: { 57 | flex: 1, 58 | marginLeft: 5, 59 | }, 60 | input: { 61 | height: 40, 62 | fontSize: 16, 63 | borderBottomColor: 'darkgray', 64 | borderBottomWidth: 1, 65 | // @ts-expect-error outlineWidth is used to hide the text-input outline on react-native-web 66 | outlineWidth: 0, 67 | }, 68 | inputLabel: { 69 | fontSize: 14, 70 | fontWeight: 600, 71 | }, 72 | }); 73 | 74 | const CreditCardInput = (props: Props) => { 75 | const { 76 | autoFocus, 77 | style, 78 | labelStyle, 79 | inputStyle, 80 | placeholderColor = 'darkgray', 81 | labels = { 82 | number: 'CARD NUMBER', 83 | expiry: 'EXPIRY', 84 | cvc: 'CVC/CVV', 85 | }, 86 | placeholders = { 87 | number: '1234 5678 1234 5678', 88 | expiry: 'MM/YY', 89 | cvc: 'CVC', 90 | }, 91 | onChange, 92 | onFocusField = () => {}, 93 | testID, 94 | } = props; 95 | 96 | const { values, onChangeValue } = useCreditCardForm(onChange); 97 | 98 | const numberInput = useRef(null); 99 | 100 | useEffect(() => { 101 | if (autoFocus) numberInput.current?.focus(); 102 | }, [autoFocus]); 103 | 104 | return ( 105 | 109 | 110 | {labels.number} 111 | onChangeValue('number', v)} 120 | onFocus={() => onFocusField('number')} 121 | autoCorrect={false} 122 | underlineColorAndroid={'transparent'} 123 | testID="CC_NUMBER" 124 | /> 125 | 126 | 127 | 128 | 129 | {labels.expiry} 130 | onChangeValue('expiry', v)} 138 | onFocus={() => onFocusField('expiry')} 139 | autoCorrect={false} 140 | underlineColorAndroid={'transparent'} 141 | testID="CC_EXPIRY" 142 | /> 143 | 144 | 145 | 146 | {labels.cvc} 147 | onChangeValue('cvc', v)} 155 | onFocus={() => onFocusField('cvc')} 156 | autoCorrect={false} 157 | underlineColorAndroid={'transparent'} 158 | testID="CC_CVC" 159 | /> 160 | 161 | 162 | 163 | ); 164 | }; 165 | 166 | export default CreditCardInput; 167 | -------------------------------------------------------------------------------- /src/useCreditCardForm.tsx: -------------------------------------------------------------------------------- 1 | import { useCallback, useState } from 'react'; 2 | import cardValidator from 'card-validator'; 3 | 4 | export type CreditCardIssuer = 5 | | 'visa' 6 | | 'mastercard' 7 | | 'american-express' 8 | | 'diners-club' 9 | | 'discover' 10 | | 'jcb'; 11 | 12 | export type CreditCardFormField = 'number' | 'expiry' | 'cvc'; 13 | 14 | export type CreditCardFormValues = { 15 | number: string; 16 | expiry: string; 17 | cvc: string; 18 | type?: CreditCardIssuer; 19 | }; 20 | 21 | export type ValidationState = 'incomplete' | 'invalid' | 'valid'; 22 | 23 | export type CreditCardFormState = { 24 | number: ValidationState; 25 | expiry: ValidationState; 26 | cvc: ValidationState; 27 | }; 28 | 29 | export type CreditCardFormData = { 30 | valid: boolean; 31 | values: CreditCardFormValues; 32 | status: CreditCardFormState; 33 | }; 34 | 35 | // --- Utilities 36 | 37 | const toStatus = (validation: { 38 | isValid: boolean; 39 | isPotentiallyValid: boolean; 40 | }): ValidationState => { 41 | return validation.isValid 42 | ? 'valid' 43 | : validation.isPotentiallyValid 44 | ? 'incomplete' 45 | : 'invalid'; 46 | }; 47 | 48 | const removeNonNumber = (string = '') => string.replace(/[^\d]/g, ''); 49 | 50 | const limitLength = (string = '', maxLength: number) => 51 | string.slice(0, maxLength); 52 | 53 | const addGaps = (string = '', gaps: number[]) => { 54 | const offsets = [0].concat(gaps).concat([string.length]); 55 | 56 | return offsets 57 | .map((end, index) => { 58 | if (index === 0) return ''; 59 | const start = offsets[index - 1] || 0; 60 | return string.slice(start, end); 61 | }) 62 | .filter((part) => part !== '') 63 | .join(' '); 64 | }; 65 | 66 | const formatCardNumber = ( 67 | number: string, 68 | maxLength: number, 69 | gaps: number[] 70 | ) => { 71 | const numberSanitized = removeNonNumber(number); 72 | const lengthSanitized = limitLength(numberSanitized, maxLength); 73 | const formatted = addGaps(lengthSanitized, gaps); 74 | return formatted; 75 | }; 76 | 77 | const formatCardExpiry = (expiry: string) => { 78 | const sanitized = limitLength(removeNonNumber(expiry), 4); 79 | if (sanitized.match(/^[2-9]$/)) { 80 | return `0${sanitized}`; 81 | } 82 | if (sanitized.length > 2) { 83 | return `${sanitized.substr(0, 2)}/${sanitized.substr(2, sanitized.length)}`; 84 | } 85 | return sanitized; 86 | }; 87 | 88 | const formatCardCVC = (cvc: string, cvcMaxLength: number) => { 89 | return limitLength(removeNonNumber(cvc), cvcMaxLength); 90 | }; 91 | 92 | export const useCreditCardForm = ( 93 | onChange: (formData: CreditCardFormData) => void 94 | ) => { 95 | const [formState, setFormState] = useState({ 96 | number: 'incomplete', 97 | expiry: 'incomplete', 98 | cvc: 'incomplete', 99 | }); 100 | 101 | const [values, setValues] = useState({ 102 | number: '', 103 | expiry: '', 104 | cvc: '', 105 | type: undefined, 106 | }); 107 | 108 | const onChangeValue = useCallback( 109 | (field: CreditCardFormField, value: string) => { 110 | const newValues = { 111 | ...values, 112 | [field]: value, 113 | }; 114 | 115 | const numberValidation = cardValidator.number(newValues.number); 116 | 117 | // When card issuer cant be detected, use these default (3 digit CVC, 16 digit card number with spaces every 4 digit) 118 | const cvcMaxLength = numberValidation.card?.code.size || 3; 119 | const cardNumberGaps = numberValidation.card?.gaps || [4, 8, 12]; 120 | const cardNumberMaxLength = 121 | // Credit card number can vary. Use the longest possible as maximum (otherwise fallback to 16) 122 | Math.max(...(numberValidation.card?.lengths || [16])); 123 | 124 | const newFormattedValues = { 125 | number: formatCardNumber( 126 | newValues.number, 127 | cardNumberMaxLength, 128 | cardNumberGaps 129 | ), 130 | expiry: formatCardExpiry(newValues.expiry), 131 | cvc: formatCardCVC(newValues.cvc, cvcMaxLength), 132 | type: numberValidation.card?.type as CreditCardIssuer, 133 | }; 134 | 135 | const newFormState = { 136 | number: toStatus(cardValidator.number(newFormattedValues.number)), 137 | expiry: toStatus( 138 | cardValidator.expirationDate(newFormattedValues.expiry) 139 | ), 140 | cvc: toStatus(cardValidator.cvv(newFormattedValues.cvc, cvcMaxLength)), 141 | }; 142 | 143 | setValues(newFormattedValues); 144 | setFormState(newFormState); 145 | 146 | onChange({ 147 | valid: 148 | newFormState.number === 'valid' && 149 | newFormState.expiry === 'valid' && 150 | newFormState.cvc === 'valid', 151 | values: newFormattedValues, 152 | status: newFormState, 153 | }); 154 | }, 155 | [values, onChange] 156 | ); 157 | 158 | return { 159 | values, 160 | status: formState, 161 | onChangeValue, 162 | }; 163 | }; 164 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-credit-card-input", 3 | "version": "1.0.0", 4 | "description": "React native credit card input component", 5 | "source": "./src/index.tsx", 6 | "main": "./lib/commonjs/index.cjs", 7 | "module": "./lib/module/index.mjs", 8 | "types": "./lib/typescript/src/index.d.ts", 9 | "exports": { 10 | ".": { 11 | "types": "./lib/typescript/src/index.d.ts", 12 | "import": "./lib/module/index.mjs", 13 | "require": "./lib/commonjs/index.cjs" 14 | } 15 | }, 16 | "files": [ 17 | "src", 18 | "lib", 19 | "android", 20 | "ios", 21 | "cpp", 22 | "*.podspec", 23 | "!ios/build", 24 | "!android/build", 25 | "!android/gradle", 26 | "!android/gradlew", 27 | "!android/gradlew.bat", 28 | "!android/local.properties", 29 | "!**/__tests__", 30 | "!**/__fixtures__", 31 | "!**/__mocks__", 32 | "!**/.*" 33 | ], 34 | "scripts": { 35 | "example": "yarn workspace react-native-credit-card-input-example", 36 | "test": "jest", 37 | "typecheck": "tsc --noEmit", 38 | "lint": "eslint \"**/*.{js,ts,tsx}\"", 39 | "clean": "del-cli lib", 40 | "prepare": "bob build", 41 | "release": "release-it" 42 | }, 43 | "keywords": [ 44 | "react-native", 45 | "ios", 46 | "android" 47 | ], 48 | "repository": { 49 | "type": "git", 50 | "url": "git+https://github.com/sbycrosz/react-native-credit-card-input.git" 51 | }, 52 | "author": "sbycrosz (https://github.com/sbycrosz)", 53 | "license": "MIT", 54 | "bugs": { 55 | "url": "https://github.com/sbycrosz/react-native-credit-card-input/issues" 56 | }, 57 | "homepage": "https://github.com/sbycrosz/react-native-credit-card-input#readme", 58 | "publishConfig": { 59 | "registry": "https://registry.npmjs.org/" 60 | }, 61 | "devDependencies": { 62 | "@commitlint/config-conventional": "^17.0.2", 63 | "@evilmartians/lefthook": "^1.5.0", 64 | "@react-native/eslint-config": "^0.73.1", 65 | "@release-it/conventional-changelog": "^5.0.0", 66 | "@testing-library/react-native": "^12.5.1", 67 | "@types/jest": "^29.5.5", 68 | "@types/react": "^18.2.44", 69 | "@types/react-native-flip-card": "^3.5.7", 70 | "commitlint": "^17.0.2", 71 | "del-cli": "^5.1.0", 72 | "eslint": "^8.51.0", 73 | "eslint-config-prettier": "^9.0.0", 74 | "eslint-plugin-prettier": "^5.0.1", 75 | "jest": "^29.7.0", 76 | "prettier": "3.3.2", 77 | "react": "18.2.0", 78 | "react-native": "0.74.3", 79 | "react-native-builder-bob": "^0.25.0", 80 | "react-test-renderer": "^18.3.1", 81 | "release-it": "^15.0.0", 82 | "typescript": "^5.2.2" 83 | }, 84 | "resolutions": { 85 | "@types/react": "^18.2.44" 86 | }, 87 | "peerDependencies": { 88 | "react": "*", 89 | "react-native": "*" 90 | }, 91 | "workspaces": [ 92 | "example" 93 | ], 94 | "packageManager": "yarn@3.6.1", 95 | "jest": { 96 | "preset": "react-native", 97 | "modulePathIgnorePatterns": [ 98 | "/example/node_modules", 99 | "/lib/" 100 | ], 101 | "setupFilesAfterEnv": [ 102 | "/jest.setup.ts" 103 | ], 104 | "collectCoverageFrom": [ 105 | "src/**/*.{ts,tsx}", 106 | "!src/**/*.d.ts", 107 | "!src/**/__tests__/**", 108 | "!src/**/index.tsx" 109 | ], 110 | "coverageThreshold": { 111 | "global": { 112 | "branches": 80, 113 | "functions": 80, 114 | "lines": 80, 115 | "statements": 80 116 | } 117 | } 118 | }, 119 | "commitlint": { 120 | "extends": [ 121 | "@commitlint/config-conventional" 122 | ] 123 | }, 124 | "release-it": { 125 | "git": { 126 | "commitMessage": "chore: release ${version}", 127 | "tagName": "v${version}" 128 | }, 129 | "npm": { 130 | "publish": true 131 | }, 132 | "github": { 133 | "release": true 134 | }, 135 | "plugins": { 136 | "@release-it/conventional-changelog": { 137 | "preset": "angular" 138 | } 139 | } 140 | }, 141 | "eslintConfig": { 142 | "root": true, 143 | "extends": [ 144 | "@react-native", 145 | "prettier" 146 | ], 147 | "rules": { 148 | "react/react-in-jsx-scope": "off", 149 | "prettier/prettier": [ 150 | "error", 151 | { 152 | "quoteProps": "consistent", 153 | "singleQuote": true, 154 | "tabWidth": 2, 155 | "trailingComma": "es5", 156 | "useTabs": false, 157 | "singleAttributePerLine": true 158 | } 159 | ] 160 | } 161 | }, 162 | "eslintIgnore": [ 163 | "node_modules/", 164 | "lib/" 165 | ], 166 | "react-native-builder-bob": { 167 | "source": "src", 168 | "output": "lib", 169 | "targets": [ 170 | [ 171 | "commonjs", 172 | { 173 | "esm": true 174 | } 175 | ], 176 | [ 177 | "module", 178 | { 179 | "esm": true 180 | } 181 | ], 182 | [ 183 | "typescript", 184 | { 185 | "project": "tsconfig.build.json" 186 | } 187 | ] 188 | ] 189 | }, 190 | "create-react-native-library": { 191 | "type": "library", 192 | "version": "0.38.1" 193 | }, 194 | "dependencies": { 195 | "card-validator": "^10.0.0", 196 | "react-native-flip-card": "^3.5.7" 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /src/CreditCardView.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | Image, 3 | ImageBackground, 4 | Platform, 5 | StyleSheet, 6 | Text, 7 | View, 8 | type ImageSourcePropType, 9 | type ViewStyle, 10 | } from 'react-native'; 11 | import FlipCard from 'react-native-flip-card'; 12 | import Icons from './Icons'; 13 | import { useMemo } from 'react'; 14 | import type { CreditCardIssuer } from './useCreditCardForm'; 15 | 16 | const CARD_SIZE = { width: 300, height: 190 }; 17 | 18 | const s = StyleSheet.create({ 19 | cardContainer: {}, 20 | cardFace: { 21 | backgroundColor: '#444', 22 | borderRadius: 10, 23 | }, 24 | cardMagneticStripe: { 25 | position: 'absolute', 26 | left: 0, 27 | right: 0, 28 | top: 30, 29 | height: 40, 30 | backgroundColor: '#000', 31 | }, 32 | icon: { 33 | position: 'absolute', 34 | top: 15, 35 | right: 15, 36 | width: 60, 37 | height: 40, 38 | resizeMode: 'contain', 39 | }, 40 | baseText: { 41 | color: 'rgba(255, 255, 255, 0.5)', 42 | backgroundColor: 'transparent', 43 | }, 44 | placeholder: { 45 | color: 'rgba(255, 255, 255, 0.5)', 46 | }, 47 | focusedField: { 48 | fontWeight: 'bold', 49 | color: 'rgba(255, 255, 255, 1)', 50 | }, 51 | number: { 52 | fontSize: 21, 53 | position: 'absolute', 54 | top: 95, 55 | left: 28, 56 | }, 57 | name: { 58 | fontSize: 16, 59 | position: 'absolute', 60 | bottom: 20, 61 | left: 25, 62 | right: 100, 63 | }, 64 | expiryLabel: { 65 | fontSize: 9, 66 | position: 'absolute', 67 | bottom: 40, 68 | left: 218, 69 | }, 70 | expiry: { 71 | fontSize: 16, 72 | position: 'absolute', 73 | bottom: 20, 74 | left: 220, 75 | }, 76 | amexCVC: { 77 | fontSize: 16, 78 | position: 'absolute', 79 | top: 73, 80 | right: 30, 81 | }, 82 | cvc: { 83 | fontSize: 16, 84 | position: 'absolute', 85 | top: 80, 86 | right: 30, 87 | }, 88 | }); 89 | 90 | interface Props { 91 | focusedField?: 'name' | 'number' | 'expiry' | 'cvc'; 92 | type?: CreditCardIssuer; 93 | name?: string; 94 | number?: string; 95 | expiry?: string; 96 | cvc?: string; 97 | 98 | placeholders?: { 99 | number: string; 100 | expiry: string; 101 | cvc: string; 102 | name: string; 103 | }; 104 | style?: ViewStyle; 105 | 106 | fontFamily?: string; 107 | imageFront?: ImageSourcePropType; 108 | imageBack?: ImageSourcePropType; 109 | } 110 | 111 | const CreditCardView = (props: Props) => { 112 | const { 113 | focusedField, 114 | type, 115 | name, 116 | number, 117 | expiry, 118 | cvc, 119 | placeholders = { 120 | number: '•••• •••• •••• ••••', 121 | name: '', 122 | expiry: '••/••', 123 | cvc: '•••', 124 | }, 125 | imageFront, 126 | imageBack, 127 | fontFamily = Platform.select({ 128 | ios: 'Courier', 129 | android: 'monospace', 130 | web: 'monospace', 131 | }), 132 | style, 133 | } = props; 134 | 135 | const isAmex = type === 'american-express'; 136 | const shouldShowCardBack = !isAmex && focusedField === 'cvc'; 137 | 138 | const cardIcon = useMemo(() => { 139 | if (type && Icons[type]) return Icons[type]; 140 | return null; 141 | }, [type]); 142 | 143 | return ( 144 | 145 | 153 | 157 | {!!cardIcon && ( 158 | 162 | )} 163 | 164 | 173 | {!number ? placeholders.number : number} 174 | 175 | 176 | 186 | {!name ? placeholders.name : name.toUpperCase()} 187 | 188 | 189 | 198 | MONTH/YEAR 199 | 200 | 209 | {!expiry ? placeholders.expiry : expiry} 210 | 211 | 212 | {isAmex && ( 213 | 222 | {!cvc ? placeholders.cvc : cvc} 223 | 224 | )} 225 | 226 | 227 | 231 | 232 | 240 | {!cvc ? placeholders.cvc : cvc} 241 | 242 | 243 | 244 | 245 | ); 246 | }; 247 | 248 | export default CreditCardView; 249 | -------------------------------------------------------------------------------- /src/LiteCreditCardInput.tsx: -------------------------------------------------------------------------------- 1 | import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; 2 | import { 3 | Image, 4 | LayoutAnimation, 5 | StyleSheet, 6 | TextInput, 7 | TouchableOpacity, 8 | View, 9 | type TextStyle, 10 | type ViewStyle, 11 | } from 'react-native'; 12 | import Icons from './Icons'; 13 | import { 14 | useCreditCardForm, 15 | type CreditCardFormData, 16 | type CreditCardFormField, 17 | } from './useCreditCardForm'; 18 | 19 | interface Props { 20 | autoFocus?: boolean; 21 | style?: ViewStyle; 22 | inputStyle?: TextStyle; 23 | placeholderColor?: string; 24 | placeholders?: { 25 | number: string; 26 | expiry: string; 27 | cvc: string; 28 | }; 29 | onChange: (formData: CreditCardFormData) => void; 30 | onFocusField?: (field: CreditCardFormField) => void; 31 | testID?: string; 32 | } 33 | 34 | const s = StyleSheet.create({ 35 | container: { 36 | paddingVertical: 10, 37 | paddingHorizontal: 15, 38 | flexDirection: 'row', 39 | alignItems: 'center', 40 | overflow: 'hidden', 41 | }, 42 | icon: { 43 | width: 48, 44 | height: 40, 45 | resizeMode: 'contain', 46 | }, 47 | expanded: { 48 | flex: 1, 49 | }, 50 | hidden: { 51 | width: 0, 52 | }, 53 | leftPart: { 54 | overflow: 'hidden', 55 | }, 56 | rightPart: { 57 | overflow: 'hidden', 58 | flexDirection: 'row', 59 | }, 60 | last4: { 61 | flex: 1, 62 | justifyContent: 'center', 63 | }, 64 | numberInput: { 65 | width: 1000, 66 | }, 67 | expiryInput: { 68 | width: 80, 69 | }, 70 | cvcInput: { 71 | width: 80, 72 | }, 73 | last4Input: { 74 | width: 60, 75 | marginLeft: 20, 76 | }, 77 | input: { 78 | height: 40, 79 | fontSize: 16, 80 | // @ts-expect-error outlineWidth is used to hide the text-input outline on react-native-web 81 | outlineWidth: 0, 82 | }, 83 | }); 84 | 85 | const LiteCreditCardInput = (props: Props) => { 86 | const { 87 | autoFocus = false, 88 | style, 89 | inputStyle, 90 | placeholderColor = 'darkgray', 91 | placeholders = { 92 | number: '1234 5678 1234 5678', 93 | expiry: 'MM/YY', 94 | cvc: 'CVC', 95 | }, 96 | onChange, 97 | onFocusField = () => {}, 98 | testID, 99 | } = props; 100 | 101 | const _onChange = (formData: CreditCardFormData): void => { 102 | // Focus next field when number/expiry field become valid 103 | if (status.number !== 'valid' && formData.status.number === 'valid') { 104 | toggleFormState(); 105 | expiryInput.current?.focus(); 106 | } 107 | 108 | if (status.expiry !== 'valid' && formData.status.expiry === 'valid') { 109 | cvcInput.current?.focus(); 110 | } 111 | 112 | onChange(formData); 113 | }; 114 | 115 | const { values, status, onChangeValue } = useCreditCardForm(_onChange); 116 | 117 | const [showRightPart, setShowRightPart] = useState(false); 118 | 119 | const toggleFormState = useCallback(() => { 120 | LayoutAnimation.easeInEaseOut(); 121 | setShowRightPart((v) => !v); 122 | }, []); 123 | 124 | const numberInput = useRef(null); 125 | const expiryInput = useRef(null); 126 | const cvcInput = useRef(null); 127 | 128 | useEffect(() => { 129 | if (autoFocus) numberInput.current?.focus(); 130 | }, [autoFocus]); 131 | 132 | const cardIcon = useMemo(() => { 133 | if (values.type && Icons[values.type]) return Icons[values.type]; 134 | return Icons.placeholder; 135 | }, [values.type]); 136 | 137 | return ( 138 | 142 | 143 | 144 | onChangeValue('number', v)} 153 | onFocus={() => onFocusField('number')} 154 | autoCorrect={false} 155 | underlineColorAndroid={'transparent'} 156 | testID="CC_NUMBER" 157 | /> 158 | 159 | 160 | 161 | 165 | 169 | 170 | 171 | 172 | 177 | 178 | 188 | 189 | 190 | 191 | 192 | onChangeValue('expiry', v)} 201 | onFocus={() => onFocusField('expiry')} 202 | autoCorrect={false} 203 | underlineColorAndroid={'transparent'} 204 | testID="CC_EXPIRY" 205 | /> 206 | 207 | 208 | 209 | onChangeValue('cvc', v)} 218 | onFocus={() => onFocusField('cvc')} 219 | autoCorrect={false} 220 | underlineColorAndroid={'transparent'} 221 | testID="CC_CVC" 222 | /> 223 | 224 | 225 | 226 | ); 227 | }; 228 | 229 | export default LiteCreditCardInput; 230 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # React Native Credit Card Input - Finally updated in 2024! 3 | [Example on Expo Snack](https://snack.expo.io/@sbycrosz/react-native-credit-card-example) - Easy (and good looking) credit-card input for your React Native Project 💳 💳 4 | 5 | 6 |

7 | 8 | 9 |

10 | 11 | Code: 12 | 13 | ```ts 14 | 15 | // or 16 | 17 | ``` 18 | 19 | # Features 20 | * Skeuomorphic credit-card 💳 21 | * Lite version for smaller screens / compact layout 22 | * Credit-card input validations & formatting while you're typing 23 | * Form is fully navigatable using keypad 24 | * Works on both Android, iOS **and Web!** 25 | 26 | # Usage 27 | 28 | ```bash 29 | yarn add react-native-credit-card-input 30 | ``` 31 | 32 | then add these lines in your react-native codebase 33 | 34 | ```js 35 | import { CreditCardInput, LiteCreditCardInput } from "react-native-credit-card-input"; 36 | 37 | 38 | // or 39 | 40 | 41 | // Note: You'll need to enable LayoutAnimation on android to see LiteCreditCardInput's animations 42 | // UIManager.setLayoutAnimationEnabledExperimental(true); 43 | 44 | ``` 45 | 46 | And then on your onChange handler: 47 | 48 | ```js 49 | _onChange => form => console.log(form); 50 | 51 | // will print: 52 | { 53 | valid: true, // will be true once all fields are "valid" (time to enable the submit button) 54 | values: { // will be in the sanitized and formatted form 55 | number: "4242 4242", 56 | expiry: "06/19", 57 | cvc: "300", 58 | type: "visa", // will be one of [null, "visa", "master-card", "american-express", "diners-club", "discover", "jcb", "unionpay", "maestro"] 59 | }, 60 | status: { // will be one of ["incomplete", "invalid", and "valid"] 61 | number: "incomplete", 62 | expiry: "incomplete", 63 | cvc: "incomplete", 64 | }, 65 | }; 66 | 67 | ``` 68 | 69 | # Example 70 | 71 | [Expo Snack](https://snack.expo.io/@sbycrosz/react-native-credit-card-example) 72 | 73 | Or run it locally 74 | 75 | ```bash 76 | yarn install 77 | 78 | yarn example ios 79 | # or 80 | yarn example android 81 | # or 82 | yarn example web 83 | ``` 84 | 85 | # Should I used this in my project? 86 | 87 | - Yes, if you need a quick credit card input component for your project or proof of concept. 88 | - Yes, if the current UI/component fit your use case 89 | - Otherwise, you're probably better off using [your favorite form library](https://react-hook-form.com/) and implementing the validation with the [card-validator](https://www.npmjs.com/package/card-validator) package! 90 | 91 | 92 | # Components 93 | 94 | ## LiteCreditCardInput 95 | | Prop | Type | Description | 96 | |--------------------|-------------------------------------------|---------------------------------------------------------------| 97 | | `autoFocus` | `boolean` | Optional. Specifies if the input should auto-focus. | 98 | | `style` | `ViewStyle` | Optional. Custom style for the component's container. | 99 | | `inputStyle` | `TextStyle` | Optional. Custom style for the input fields. | 100 | | `placeholderColor` | `string` | Optional. Color for the placeholder text. | 101 | | `placeholders` | `{ number: string; expiry: string; cvc: string; }` | Optional. Custom placeholders for the input fields. | 102 | | `onChange` | `(formData: CreditCardFormData) => void` | Required. Callback function called when form data changes. | 103 | | `onFocusField` | `(field: CreditCardFormField) => void` | Optional. Callback function called when a field gains focus. | 104 | 105 | ## CreditCardInput 106 | | Prop | Type | Description | 107 | |--------------------|-------------------------------------------|---------------------------------------------------------------| 108 | | `autoFocus` | `boolean` | Optional. Specifies if the input should auto-focus. | 109 | | `style` | `ViewStyle` | Optional. Custom style for the component's container. | 110 | | `labelStyle` | `TextStyle` | Optional. Custom style for the labels. | 111 | | `inputStyle` | `TextStyle` | Optional. Custom style for the input fields. | 112 | | `placeholderColor` | `string` | Optional. Color for the placeholder text. | 113 | | `labels` | `{ number: string; expiry: string; cvc: string; }` | Optional. Custom labels for the input fields. | 114 | | `placeholders` | `{ number: string; expiry: string; cvc: string; }` | Optional. Custom placeholders for the input fields. | 115 | | `onChange` | `(formData: CreditCardFormData) => void` | Required. Callback function called when form data changes. | 116 | | `onFocusField` | `(field: CreditCardFormField) => void` | Optional. Callback function called when a field gains focus. | 117 | 118 | 119 | ## CardView 120 | 121 | | Prop | Type | Description | 122 | |-------------------|-----------------------------------------------------------|----------------------------------------------------------------| 123 | | `focusedField` | `'name' \| 'number' \| 'expiry' \| 'cvc'` | Optional. Specifies which field is currently focused. | 124 | | `type` | `CreditCardIssuer` | Optional. Specifies the type of the credit card issuer. | 125 | | `name` | `string` | Optional. The name on the credit card. | 126 | | `number` | `string` | Optional. The credit card number. | 127 | | `expiry` | `string` | Optional. The expiry date of the credit card. | 128 | | `cvc` | `string` | Optional. The CVC code of the credit card. | 129 | | `placeholders` | `{ number: string; expiry: string; cvc: string; name: string; }` | Optional. Custom placeholders for the input fields. | 130 | | `style` | `ViewStyle` | Optional. Custom style for the component's container. | 131 | | `fontFamily` | `string` | Optional. Custom font family for the text. | 132 | | `imageFront` | `ImageSourcePropType` | Optional. Image source for the front of the credit card. | 133 | | `imageBack` | `ImageSourcePropType` | Optional. Image source for the back of the credit card. | 134 | -------------------------------------------------------------------------------- /.yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | //prettier-ignore 3 | module.exports = { 4 | name: "@yarnpkg/plugin-workspace-tools", 5 | factory: function (require) { 6 | var plugin=(()=>{var yr=Object.create;var we=Object.defineProperty;var _r=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var br=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty;var W=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var q=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),Cr=(e,r)=>{for(var t in r)we(e,t,{get:r[t],enumerable:!0})},Je=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of Er(r))!xr.call(e,s)&&s!==t&&we(e,s,{get:()=>r[s],enumerable:!(n=_r(r,s))||n.enumerable});return e};var Be=(e,r,t)=>(t=e!=null?yr(br(e)):{},Je(r||!e||!e.__esModule?we(t,"default",{value:e,enumerable:!0}):t,e)),wr=e=>Je(we({},"__esModule",{value:!0}),e);var ve=q(ee=>{"use strict";ee.isInteger=e=>typeof e=="number"?Number.isInteger(e):typeof e=="string"&&e.trim()!==""?Number.isInteger(Number(e)):!1;ee.find=(e,r)=>e.nodes.find(t=>t.type===r);ee.exceedsLimit=(e,r,t=1,n)=>n===!1||!ee.isInteger(e)||!ee.isInteger(r)?!1:(Number(r)-Number(e))/Number(t)>=n;ee.escapeNode=(e,r=0,t)=>{let n=e.nodes[r];!n||(t&&n.type===t||n.type==="open"||n.type==="close")&&n.escaped!==!0&&(n.value="\\"+n.value,n.escaped=!0)};ee.encloseBrace=e=>e.type!=="brace"?!1:e.commas>>0+e.ranges>>0===0?(e.invalid=!0,!0):!1;ee.isInvalidBrace=e=>e.type!=="brace"?!1:e.invalid===!0||e.dollar?!0:e.commas>>0+e.ranges>>0===0||e.open!==!0||e.close!==!0?(e.invalid=!0,!0):!1;ee.isOpenOrClose=e=>e.type==="open"||e.type==="close"?!0:e.open===!0||e.close===!0;ee.reduce=e=>e.reduce((r,t)=>(t.type==="text"&&r.push(t.value),t.type==="range"&&(t.type="text"),r),[]);ee.flatten=(...e)=>{let r=[],t=n=>{for(let s=0;s{"use strict";var tt=ve();rt.exports=(e,r={})=>{let t=(n,s={})=>{let i=r.escapeInvalid&&tt.isInvalidBrace(s),a=n.invalid===!0&&r.escapeInvalid===!0,c="";if(n.value)return(i||a)&&tt.isOpenOrClose(n)?"\\"+n.value:n.value;if(n.value)return n.value;if(n.nodes)for(let p of n.nodes)c+=t(p);return c};return t(e)}});var st=q((Vn,nt)=>{"use strict";nt.exports=function(e){return typeof e=="number"?e-e===0:typeof e=="string"&&e.trim()!==""?Number.isFinite?Number.isFinite(+e):isFinite(+e):!1}});var ht=q((Jn,pt)=>{"use strict";var at=st(),le=(e,r,t)=>{if(at(e)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(r===void 0||e===r)return String(e);if(at(r)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let n={relaxZeros:!0,...t};typeof n.strictZeros=="boolean"&&(n.relaxZeros=n.strictZeros===!1);let s=String(n.relaxZeros),i=String(n.shorthand),a=String(n.capture),c=String(n.wrap),p=e+":"+r+"="+s+i+a+c;if(le.cache.hasOwnProperty(p))return le.cache[p].result;let m=Math.min(e,r),h=Math.max(e,r);if(Math.abs(m-h)===1){let y=e+"|"+r;return n.capture?`(${y})`:n.wrap===!1?y:`(?:${y})`}let R=ft(e)||ft(r),f={min:e,max:r,a:m,b:h},$=[],_=[];if(R&&(f.isPadded=R,f.maxLen=String(f.max).length),m<0){let y=h<0?Math.abs(h):1;_=it(y,Math.abs(m),f,n),m=f.a=0}return h>=0&&($=it(m,h,f,n)),f.negatives=_,f.positives=$,f.result=Sr(_,$,n),n.capture===!0?f.result=`(${f.result})`:n.wrap!==!1&&$.length+_.length>1&&(f.result=`(?:${f.result})`),le.cache[p]=f,f.result};function Sr(e,r,t){let n=Pe(e,r,"-",!1,t)||[],s=Pe(r,e,"",!1,t)||[],i=Pe(e,r,"-?",!0,t)||[];return n.concat(i).concat(s).join("|")}function vr(e,r){let t=1,n=1,s=ut(e,t),i=new Set([r]);for(;e<=s&&s<=r;)i.add(s),t+=1,s=ut(e,t);for(s=ct(r+1,n)-1;e1&&c.count.pop(),c.count.push(h.count[0]),c.string=c.pattern+lt(c.count),a=m+1;continue}t.isPadded&&(R=Lr(m,t,n)),h.string=R+h.pattern+lt(h.count),i.push(h),a=m+1,c=h}return i}function Pe(e,r,t,n,s){let i=[];for(let a of e){let{string:c}=a;!n&&!ot(r,"string",c)&&i.push(t+c),n&&ot(r,"string",c)&&i.push(t+c)}return i}function $r(e,r){let t=[];for(let n=0;nr?1:r>e?-1:0}function ot(e,r,t){return e.some(n=>n[r]===t)}function ut(e,r){return Number(String(e).slice(0,-r)+"9".repeat(r))}function ct(e,r){return e-e%Math.pow(10,r)}function lt(e){let[r=0,t=""]=e;return t||r>1?`{${r+(t?","+t:"")}}`:""}function kr(e,r,t){return`[${e}${r-e===1?"":"-"}${r}]`}function ft(e){return/^-?(0+)\d/.test(e)}function Lr(e,r,t){if(!r.isPadded)return e;let n=Math.abs(r.maxLen-String(e).length),s=t.relaxZeros!==!1;switch(n){case 0:return"";case 1:return s?"0?":"0";case 2:return s?"0{0,2}":"00";default:return s?`0{0,${n}}`:`0{${n}}`}}le.cache={};le.clearCache=()=>le.cache={};pt.exports=le});var Ue=q((es,Et)=>{"use strict";var Or=W("util"),At=ht(),dt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Nr=e=>r=>e===!0?Number(r):String(r),Me=e=>typeof e=="number"||typeof e=="string"&&e!=="",Ae=e=>Number.isInteger(+e),De=e=>{let r=`${e}`,t=-1;if(r[0]==="-"&&(r=r.slice(1)),r==="0")return!1;for(;r[++t]==="0";);return t>0},Ir=(e,r,t)=>typeof e=="string"||typeof r=="string"?!0:t.stringify===!0,Br=(e,r,t)=>{if(r>0){let n=e[0]==="-"?"-":"";n&&(e=e.slice(1)),e=n+e.padStart(n?r-1:r,"0")}return t===!1?String(e):e},gt=(e,r)=>{let t=e[0]==="-"?"-":"";for(t&&(e=e.slice(1),r--);e.length{e.negatives.sort((a,c)=>ac?1:0),e.positives.sort((a,c)=>ac?1:0);let t=r.capture?"":"?:",n="",s="",i;return e.positives.length&&(n=e.positives.join("|")),e.negatives.length&&(s=`-(${t}${e.negatives.join("|")})`),n&&s?i=`${n}|${s}`:i=n||s,r.wrap?`(${t}${i})`:i},mt=(e,r,t,n)=>{if(t)return At(e,r,{wrap:!1,...n});let s=String.fromCharCode(e);if(e===r)return s;let i=String.fromCharCode(r);return`[${s}-${i}]`},Rt=(e,r,t)=>{if(Array.isArray(e)){let n=t.wrap===!0,s=t.capture?"":"?:";return n?`(${s}${e.join("|")})`:e.join("|")}return At(e,r,t)},yt=(...e)=>new RangeError("Invalid range arguments: "+Or.inspect(...e)),_t=(e,r,t)=>{if(t.strictRanges===!0)throw yt([e,r]);return[]},Mr=(e,r)=>{if(r.strictRanges===!0)throw new TypeError(`Expected step "${e}" to be a number`);return[]},Dr=(e,r,t=1,n={})=>{let s=Number(e),i=Number(r);if(!Number.isInteger(s)||!Number.isInteger(i)){if(n.strictRanges===!0)throw yt([e,r]);return[]}s===0&&(s=0),i===0&&(i=0);let a=s>i,c=String(e),p=String(r),m=String(t);t=Math.max(Math.abs(t),1);let h=De(c)||De(p)||De(m),R=h?Math.max(c.length,p.length,m.length):0,f=h===!1&&Ir(e,r,n)===!1,$=n.transform||Nr(f);if(n.toRegex&&t===1)return mt(gt(e,R),gt(r,R),!0,n);let _={negatives:[],positives:[]},y=T=>_[T<0?"negatives":"positives"].push(Math.abs(T)),E=[],S=0;for(;a?s>=i:s<=i;)n.toRegex===!0&&t>1?y(s):E.push(Br($(s,S),R,f)),s=a?s-t:s+t,S++;return n.toRegex===!0?t>1?Pr(_,n):Rt(E,null,{wrap:!1,...n}):E},Ur=(e,r,t=1,n={})=>{if(!Ae(e)&&e.length>1||!Ae(r)&&r.length>1)return _t(e,r,n);let s=n.transform||(f=>String.fromCharCode(f)),i=`${e}`.charCodeAt(0),a=`${r}`.charCodeAt(0),c=i>a,p=Math.min(i,a),m=Math.max(i,a);if(n.toRegex&&t===1)return mt(p,m,!1,n);let h=[],R=0;for(;c?i>=a:i<=a;)h.push(s(i,R)),i=c?i-t:i+t,R++;return n.toRegex===!0?Rt(h,null,{wrap:!1,options:n}):h},$e=(e,r,t,n={})=>{if(r==null&&Me(e))return[e];if(!Me(e)||!Me(r))return _t(e,r,n);if(typeof t=="function")return $e(e,r,1,{transform:t});if(dt(t))return $e(e,r,0,t);let s={...n};return s.capture===!0&&(s.wrap=!0),t=t||s.step||1,Ae(t)?Ae(e)&&Ae(r)?Dr(e,r,t,s):Ur(e,r,Math.max(Math.abs(t),1),s):t!=null&&!dt(t)?Mr(t,s):$e(e,r,1,t)};Et.exports=$e});var Ct=q((ts,xt)=>{"use strict";var Gr=Ue(),bt=ve(),qr=(e,r={})=>{let t=(n,s={})=>{let i=bt.isInvalidBrace(s),a=n.invalid===!0&&r.escapeInvalid===!0,c=i===!0||a===!0,p=r.escapeInvalid===!0?"\\":"",m="";if(n.isOpen===!0||n.isClose===!0)return p+n.value;if(n.type==="open")return c?p+n.value:"(";if(n.type==="close")return c?p+n.value:")";if(n.type==="comma")return n.prev.type==="comma"?"":c?n.value:"|";if(n.value)return n.value;if(n.nodes&&n.ranges>0){let h=bt.reduce(n.nodes),R=Gr(...h,{...r,wrap:!1,toRegex:!0});if(R.length!==0)return h.length>1&&R.length>1?`(${R})`:R}if(n.nodes)for(let h of n.nodes)m+=t(h,n);return m};return t(e)};xt.exports=qr});var vt=q((rs,St)=>{"use strict";var Kr=Ue(),wt=He(),he=ve(),fe=(e="",r="",t=!1)=>{let n=[];if(e=[].concat(e),r=[].concat(r),!r.length)return e;if(!e.length)return t?he.flatten(r).map(s=>`{${s}}`):r;for(let s of e)if(Array.isArray(s))for(let i of s)n.push(fe(i,r,t));else for(let i of r)t===!0&&typeof i=="string"&&(i=`{${i}}`),n.push(Array.isArray(i)?fe(s,i,t):s+i);return he.flatten(n)},Wr=(e,r={})=>{let t=r.rangeLimit===void 0?1e3:r.rangeLimit,n=(s,i={})=>{s.queue=[];let a=i,c=i.queue;for(;a.type!=="brace"&&a.type!=="root"&&a.parent;)a=a.parent,c=a.queue;if(s.invalid||s.dollar){c.push(fe(c.pop(),wt(s,r)));return}if(s.type==="brace"&&s.invalid!==!0&&s.nodes.length===2){c.push(fe(c.pop(),["{}"]));return}if(s.nodes&&s.ranges>0){let R=he.reduce(s.nodes);if(he.exceedsLimit(...R,r.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let f=Kr(...R,r);f.length===0&&(f=wt(s,r)),c.push(fe(c.pop(),f)),s.nodes=[];return}let p=he.encloseBrace(s),m=s.queue,h=s;for(;h.type!=="brace"&&h.type!=="root"&&h.parent;)h=h.parent,m=h.queue;for(let R=0;R{"use strict";Ht.exports={MAX_LENGTH:1024*64,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:` 7 | `,CHAR_NO_BREAK_SPACE:"\xA0",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:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var Nt=q((ss,Ot)=>{"use strict";var jr=He(),{MAX_LENGTH:Tt,CHAR_BACKSLASH:Ge,CHAR_BACKTICK:Fr,CHAR_COMMA:Qr,CHAR_DOT:Xr,CHAR_LEFT_PARENTHESES:Zr,CHAR_RIGHT_PARENTHESES:Yr,CHAR_LEFT_CURLY_BRACE:zr,CHAR_RIGHT_CURLY_BRACE:Vr,CHAR_LEFT_SQUARE_BRACKET:kt,CHAR_RIGHT_SQUARE_BRACKET:Lt,CHAR_DOUBLE_QUOTE:Jr,CHAR_SINGLE_QUOTE:en,CHAR_NO_BREAK_SPACE:tn,CHAR_ZERO_WIDTH_NOBREAK_SPACE:rn}=$t(),nn=(e,r={})=>{if(typeof e!="string")throw new TypeError("Expected a string");let t=r||{},n=typeof t.maxLength=="number"?Math.min(Tt,t.maxLength):Tt;if(e.length>n)throw new SyntaxError(`Input length (${e.length}), exceeds max characters (${n})`);let s={type:"root",input:e,nodes:[]},i=[s],a=s,c=s,p=0,m=e.length,h=0,R=0,f,$={},_=()=>e[h++],y=E=>{if(E.type==="text"&&c.type==="dot"&&(c.type="text"),c&&c.type==="text"&&E.type==="text"){c.value+=E.value;return}return a.nodes.push(E),E.parent=a,E.prev=c,c=E,E};for(y({type:"bos"});h0){if(a.ranges>0){a.ranges=0;let E=a.nodes.shift();a.nodes=[E,{type:"text",value:jr(a)}]}y({type:"comma",value:f}),a.commas++;continue}if(f===Xr&&R>0&&a.commas===0){let E=a.nodes;if(R===0||E.length===0){y({type:"text",value:f});continue}if(c.type==="dot"){if(a.range=[],c.value+=f,c.type="range",a.nodes.length!==3&&a.nodes.length!==5){a.invalid=!0,a.ranges=0,c.type="text";continue}a.ranges++,a.args=[];continue}if(c.type==="range"){E.pop();let S=E[E.length-1];S.value+=c.value+f,c=S,a.ranges--;continue}y({type:"dot",value:f});continue}y({type:"text",value:f})}do if(a=i.pop(),a.type!=="root"){a.nodes.forEach(T=>{T.nodes||(T.type==="open"&&(T.isOpen=!0),T.type==="close"&&(T.isClose=!0),T.nodes||(T.type="text"),T.invalid=!0)});let E=i[i.length-1],S=E.nodes.indexOf(a);E.nodes.splice(S,1,...a.nodes)}while(i.length>0);return y({type:"eos"}),s};Ot.exports=nn});var Pt=q((as,Bt)=>{"use strict";var It=He(),sn=Ct(),an=vt(),on=Nt(),Z=(e,r={})=>{let t=[];if(Array.isArray(e))for(let n of e){let s=Z.create(n,r);Array.isArray(s)?t.push(...s):t.push(s)}else t=[].concat(Z.create(e,r));return r&&r.expand===!0&&r.nodupes===!0&&(t=[...new Set(t)]),t};Z.parse=(e,r={})=>on(e,r);Z.stringify=(e,r={})=>It(typeof e=="string"?Z.parse(e,r):e,r);Z.compile=(e,r={})=>(typeof e=="string"&&(e=Z.parse(e,r)),sn(e,r));Z.expand=(e,r={})=>{typeof e=="string"&&(e=Z.parse(e,r));let t=an(e,r);return r.noempty===!0&&(t=t.filter(Boolean)),r.nodupes===!0&&(t=[...new Set(t)]),t};Z.create=(e,r={})=>e===""||e.length<3?[e]:r.expand!==!0?Z.compile(e,r):Z.expand(e,r);Bt.exports=Z});var me=q((is,qt)=>{"use strict";var un=W("path"),se="\\\\/",Mt=`[^${se}]`,ie="\\.",cn="\\+",ln="\\?",Te="\\/",fn="(?=.)",Dt="[^/]",qe=`(?:${Te}|$)`,Ut=`(?:^|${Te})`,Ke=`${ie}{1,2}${qe}`,pn=`(?!${ie})`,hn=`(?!${Ut}${Ke})`,dn=`(?!${ie}{0,1}${qe})`,gn=`(?!${Ke})`,An=`[^.${Te}]`,mn=`${Dt}*?`,Gt={DOT_LITERAL:ie,PLUS_LITERAL:cn,QMARK_LITERAL:ln,SLASH_LITERAL:Te,ONE_CHAR:fn,QMARK:Dt,END_ANCHOR:qe,DOTS_SLASH:Ke,NO_DOT:pn,NO_DOTS:hn,NO_DOT_SLASH:dn,NO_DOTS_SLASH:gn,QMARK_NO_DOT:An,STAR:mn,START_ANCHOR:Ut},Rn={...Gt,SLASH_LITERAL:`[${se}]`,QMARK:Mt,STAR:`${Mt}*?`,DOTS_SLASH:`${ie}{1,2}(?:[${se}]|$)`,NO_DOT:`(?!${ie})`,NO_DOTS:`(?!(?:^|[${se}])${ie}{1,2}(?:[${se}]|$))`,NO_DOT_SLASH:`(?!${ie}{0,1}(?:[${se}]|$))`,NO_DOTS_SLASH:`(?!${ie}{1,2}(?:[${se}]|$))`,QMARK_NO_DOT:`[^.${se}]`,START_ANCHOR:`(?:^|[${se}])`,END_ANCHOR:`(?:[${se}]|$)`},yn={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"};qt.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:yn,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,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,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,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,CHAR_NO_BREAK_SPACE:160,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,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:un.sep,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===!0?Rn:Gt}}});var Re=q(Q=>{"use strict";var _n=W("path"),En=process.platform==="win32",{REGEX_BACKSLASH:bn,REGEX_REMOVE_BACKSLASH:xn,REGEX_SPECIAL_CHARS:Cn,REGEX_SPECIAL_CHARS_GLOBAL:wn}=me();Q.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Q.hasRegexChars=e=>Cn.test(e);Q.isRegexChar=e=>e.length===1&&Q.hasRegexChars(e);Q.escapeRegex=e=>e.replace(wn,"\\$1");Q.toPosixSlashes=e=>e.replace(bn,"/");Q.removeBackslashes=e=>e.replace(xn,r=>r==="\\"?"":r);Q.supportsLookbehinds=()=>{let e=process.version.slice(1).split(".").map(Number);return e.length===3&&e[0]>=9||e[0]===8&&e[1]>=10};Q.isWindows=e=>e&&typeof e.windows=="boolean"?e.windows:En===!0||_n.sep==="\\";Q.escapeLast=(e,r,t)=>{let n=e.lastIndexOf(r,t);return n===-1?e:e[n-1]==="\\"?Q.escapeLast(e,r,n-1):`${e.slice(0,n)}\\${e.slice(n)}`};Q.removePrefix=(e,r={})=>{let t=e;return t.startsWith("./")&&(t=t.slice(2),r.prefix="./"),t};Q.wrapOutput=(e,r={},t={})=>{let n=t.contains?"":"^",s=t.contains?"":"$",i=`${n}(?:${e})${s}`;return r.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var Yt=q((us,Zt)=>{"use strict";var Kt=Re(),{CHAR_ASTERISK:We,CHAR_AT:Sn,CHAR_BACKWARD_SLASH:ye,CHAR_COMMA:vn,CHAR_DOT:je,CHAR_EXCLAMATION_MARK:Fe,CHAR_FORWARD_SLASH:Xt,CHAR_LEFT_CURLY_BRACE:Qe,CHAR_LEFT_PARENTHESES:Xe,CHAR_LEFT_SQUARE_BRACKET:Hn,CHAR_PLUS:$n,CHAR_QUESTION_MARK:Wt,CHAR_RIGHT_CURLY_BRACE:Tn,CHAR_RIGHT_PARENTHESES:jt,CHAR_RIGHT_SQUARE_BRACKET:kn}=me(),Ft=e=>e===Xt||e===ye,Qt=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)},Ln=(e,r)=>{let t=r||{},n=e.length-1,s=t.parts===!0||t.scanToEnd===!0,i=[],a=[],c=[],p=e,m=-1,h=0,R=0,f=!1,$=!1,_=!1,y=!1,E=!1,S=!1,T=!1,L=!1,z=!1,I=!1,re=0,K,g,v={value:"",depth:0,isGlob:!1},k=()=>m>=n,l=()=>p.charCodeAt(m+1),H=()=>(K=g,p.charCodeAt(++m));for(;m0&&(B=p.slice(0,h),p=p.slice(h),R-=h),w&&_===!0&&R>0?(w=p.slice(0,R),o=p.slice(R)):_===!0?(w="",o=p):w=p,w&&w!==""&&w!=="/"&&w!==p&&Ft(w.charCodeAt(w.length-1))&&(w=w.slice(0,-1)),t.unescape===!0&&(o&&(o=Kt.removeBackslashes(o)),w&&T===!0&&(w=Kt.removeBackslashes(w)));let u={prefix:B,input:e,start:h,base:w,glob:o,isBrace:f,isBracket:$,isGlob:_,isExtglob:y,isGlobstar:E,negated:L,negatedExtglob:z};if(t.tokens===!0&&(u.maxDepth=0,Ft(g)||a.push(v),u.tokens=a),t.parts===!0||t.tokens===!0){let P;for(let b=0;b{"use strict";var ke=me(),Y=Re(),{MAX_LENGTH:Le,POSIX_REGEX_SOURCE:On,REGEX_NON_SPECIAL_CHARS:Nn,REGEX_SPECIAL_CHARS_BACKREF:In,REPLACEMENTS:zt}=ke,Bn=(e,r)=>{if(typeof r.expandRange=="function")return r.expandRange(...e,r);e.sort();let t=`[${e.join("-")}]`;try{new RegExp(t)}catch{return e.map(s=>Y.escapeRegex(s)).join("..")}return t},de=(e,r)=>`Missing ${e}: "${r}" - use "\\\\${r}" to match literal characters`,Vt=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=zt[e]||e;let t={...r},n=typeof t.maxLength=="number"?Math.min(Le,t.maxLength):Le,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:t.prepend||""},a=[i],c=t.capture?"":"?:",p=Y.isWindows(r),m=ke.globChars(p),h=ke.extglobChars(m),{DOT_LITERAL:R,PLUS_LITERAL:f,SLASH_LITERAL:$,ONE_CHAR:_,DOTS_SLASH:y,NO_DOT:E,NO_DOT_SLASH:S,NO_DOTS_SLASH:T,QMARK:L,QMARK_NO_DOT:z,STAR:I,START_ANCHOR:re}=m,K=A=>`(${c}(?:(?!${re}${A.dot?y:R}).)*?)`,g=t.dot?"":E,v=t.dot?L:z,k=t.bash===!0?K(t):I;t.capture&&(k=`(${k})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let l={input:e,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:a};e=Y.removePrefix(e,l),s=e.length;let H=[],w=[],B=[],o=i,u,P=()=>l.index===s-1,b=l.peek=(A=1)=>e[l.index+A],V=l.advance=()=>e[++l.index]||"",J=()=>e.slice(l.index+1),X=(A="",O=0)=>{l.consumed+=A,l.index+=O},Ee=A=>{l.output+=A.output!=null?A.output:A.value,X(A.value)},mr=()=>{let A=1;for(;b()==="!"&&(b(2)!=="("||b(3)==="?");)V(),l.start++,A++;return A%2===0?!1:(l.negated=!0,l.start++,!0)},be=A=>{l[A]++,B.push(A)},oe=A=>{l[A]--,B.pop()},C=A=>{if(o.type==="globstar"){let O=l.braces>0&&(A.type==="comma"||A.type==="brace"),d=A.extglob===!0||H.length&&(A.type==="pipe"||A.type==="paren");A.type!=="slash"&&A.type!=="paren"&&!O&&!d&&(l.output=l.output.slice(0,-o.output.length),o.type="star",o.value="*",o.output=k,l.output+=o.output)}if(H.length&&A.type!=="paren"&&(H[H.length-1].inner+=A.value),(A.value||A.output)&&Ee(A),o&&o.type==="text"&&A.type==="text"){o.value+=A.value,o.output=(o.output||"")+A.value;return}A.prev=o,a.push(A),o=A},xe=(A,O)=>{let d={...h[O],conditions:1,inner:""};d.prev=o,d.parens=l.parens,d.output=l.output;let x=(t.capture?"(":"")+d.open;be("parens"),C({type:A,value:O,output:l.output?"":_}),C({type:"paren",extglob:!0,value:V(),output:x}),H.push(d)},Rr=A=>{let O=A.close+(t.capture?")":""),d;if(A.type==="negate"){let x=k;A.inner&&A.inner.length>1&&A.inner.includes("/")&&(x=K(t)),(x!==k||P()||/^\)+$/.test(J()))&&(O=A.close=`)$))${x}`),A.inner.includes("*")&&(d=J())&&/^\.[^\\/.]+$/.test(d)&&(O=A.close=`)${d})${x})`),A.prev.type==="bos"&&(l.negatedExtglob=!0)}C({type:"paren",extglob:!0,value:u,output:O}),oe("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let A=!1,O=e.replace(In,(d,x,M,j,G,Ie)=>j==="\\"?(A=!0,d):j==="?"?x?x+j+(G?L.repeat(G.length):""):Ie===0?v+(G?L.repeat(G.length):""):L.repeat(M.length):j==="."?R.repeat(M.length):j==="*"?x?x+j+(G?k:""):k:x?d:`\\${d}`);return A===!0&&(t.unescape===!0?O=O.replace(/\\/g,""):O=O.replace(/\\+/g,d=>d.length%2===0?"\\\\":d?"\\":"")),O===e&&t.contains===!0?(l.output=e,l):(l.output=Y.wrapOutput(O,l,r),l)}for(;!P();){if(u=V(),u==="\0")continue;if(u==="\\"){let d=b();if(d==="/"&&t.bash!==!0||d==="."||d===";")continue;if(!d){u+="\\",C({type:"text",value:u});continue}let x=/^\\+/.exec(J()),M=0;if(x&&x[0].length>2&&(M=x[0].length,l.index+=M,M%2!==0&&(u+="\\")),t.unescape===!0?u=V():u+=V(),l.brackets===0){C({type:"text",value:u});continue}}if(l.brackets>0&&(u!=="]"||o.value==="["||o.value==="[^")){if(t.posix!==!1&&u===":"){let d=o.value.slice(1);if(d.includes("[")&&(o.posix=!0,d.includes(":"))){let x=o.value.lastIndexOf("["),M=o.value.slice(0,x),j=o.value.slice(x+2),G=On[j];if(G){o.value=M+G,l.backtrack=!0,V(),!i.output&&a.indexOf(o)===1&&(i.output=_);continue}}}(u==="["&&b()!==":"||u==="-"&&b()==="]")&&(u=`\\${u}`),u==="]"&&(o.value==="["||o.value==="[^")&&(u=`\\${u}`),t.posix===!0&&u==="!"&&o.value==="["&&(u="^"),o.value+=u,Ee({value:u});continue}if(l.quotes===1&&u!=='"'){u=Y.escapeRegex(u),o.value+=u,Ee({value:u});continue}if(u==='"'){l.quotes=l.quotes===1?0:1,t.keepQuotes===!0&&C({type:"text",value:u});continue}if(u==="("){be("parens"),C({type:"paren",value:u});continue}if(u===")"){if(l.parens===0&&t.strictBrackets===!0)throw new SyntaxError(de("opening","("));let d=H[H.length-1];if(d&&l.parens===d.parens+1){Rr(H.pop());continue}C({type:"paren",value:u,output:l.parens?")":"\\)"}),oe("parens");continue}if(u==="["){if(t.nobracket===!0||!J().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(de("closing","]"));u=`\\${u}`}else be("brackets");C({type:"bracket",value:u});continue}if(u==="]"){if(t.nobracket===!0||o&&o.type==="bracket"&&o.value.length===1){C({type:"text",value:u,output:`\\${u}`});continue}if(l.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(de("opening","["));C({type:"text",value:u,output:`\\${u}`});continue}oe("brackets");let d=o.value.slice(1);if(o.posix!==!0&&d[0]==="^"&&!d.includes("/")&&(u=`/${u}`),o.value+=u,Ee({value:u}),t.literalBrackets===!1||Y.hasRegexChars(d))continue;let x=Y.escapeRegex(o.value);if(l.output=l.output.slice(0,-o.value.length),t.literalBrackets===!0){l.output+=x,o.value=x;continue}o.value=`(${c}${x}|${o.value})`,l.output+=o.value;continue}if(u==="{"&&t.nobrace!==!0){be("braces");let d={type:"brace",value:u,output:"(",outputIndex:l.output.length,tokensIndex:l.tokens.length};w.push(d),C(d);continue}if(u==="}"){let d=w[w.length-1];if(t.nobrace===!0||!d){C({type:"text",value:u,output:u});continue}let x=")";if(d.dots===!0){let M=a.slice(),j=[];for(let G=M.length-1;G>=0&&(a.pop(),M[G].type!=="brace");G--)M[G].type!=="dots"&&j.unshift(M[G].value);x=Bn(j,t),l.backtrack=!0}if(d.comma!==!0&&d.dots!==!0){let M=l.output.slice(0,d.outputIndex),j=l.tokens.slice(d.tokensIndex);d.value=d.output="\\{",u=x="\\}",l.output=M;for(let G of j)l.output+=G.output||G.value}C({type:"brace",value:u,output:x}),oe("braces"),w.pop();continue}if(u==="|"){H.length>0&&H[H.length-1].conditions++,C({type:"text",value:u});continue}if(u===","){let d=u,x=w[w.length-1];x&&B[B.length-1]==="braces"&&(x.comma=!0,d="|"),C({type:"comma",value:u,output:d});continue}if(u==="/"){if(o.type==="dot"&&l.index===l.start+1){l.start=l.index+1,l.consumed="",l.output="",a.pop(),o=i;continue}C({type:"slash",value:u,output:$});continue}if(u==="."){if(l.braces>0&&o.type==="dot"){o.value==="."&&(o.output=R);let d=w[w.length-1];o.type="dots",o.output+=u,o.value+=u,d.dots=!0;continue}if(l.braces+l.parens===0&&o.type!=="bos"&&o.type!=="slash"){C({type:"text",value:u,output:R});continue}C({type:"dot",value:u,output:R});continue}if(u==="?"){if(!(o&&o.value==="(")&&t.noextglob!==!0&&b()==="("&&b(2)!=="?"){xe("qmark",u);continue}if(o&&o.type==="paren"){let x=b(),M=u;if(x==="<"&&!Y.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(o.value==="("&&!/[!=<:]/.test(x)||x==="<"&&!/<([!=]|\w+>)/.test(J()))&&(M=`\\${u}`),C({type:"text",value:u,output:M});continue}if(t.dot!==!0&&(o.type==="slash"||o.type==="bos")){C({type:"qmark",value:u,output:z});continue}C({type:"qmark",value:u,output:L});continue}if(u==="!"){if(t.noextglob!==!0&&b()==="("&&(b(2)!=="?"||!/[!=<:]/.test(b(3)))){xe("negate",u);continue}if(t.nonegate!==!0&&l.index===0){mr();continue}}if(u==="+"){if(t.noextglob!==!0&&b()==="("&&b(2)!=="?"){xe("plus",u);continue}if(o&&o.value==="("||t.regex===!1){C({type:"plus",value:u,output:f});continue}if(o&&(o.type==="bracket"||o.type==="paren"||o.type==="brace")||l.parens>0){C({type:"plus",value:u});continue}C({type:"plus",value:f});continue}if(u==="@"){if(t.noextglob!==!0&&b()==="("&&b(2)!=="?"){C({type:"at",extglob:!0,value:u,output:""});continue}C({type:"text",value:u});continue}if(u!=="*"){(u==="$"||u==="^")&&(u=`\\${u}`);let d=Nn.exec(J());d&&(u+=d[0],l.index+=d[0].length),C({type:"text",value:u});continue}if(o&&(o.type==="globstar"||o.star===!0)){o.type="star",o.star=!0,o.value+=u,o.output=k,l.backtrack=!0,l.globstar=!0,X(u);continue}let A=J();if(t.noextglob!==!0&&/^\([^?]/.test(A)){xe("star",u);continue}if(o.type==="star"){if(t.noglobstar===!0){X(u);continue}let d=o.prev,x=d.prev,M=d.type==="slash"||d.type==="bos",j=x&&(x.type==="star"||x.type==="globstar");if(t.bash===!0&&(!M||A[0]&&A[0]!=="/")){C({type:"star",value:u,output:""});continue}let G=l.braces>0&&(d.type==="comma"||d.type==="brace"),Ie=H.length&&(d.type==="pipe"||d.type==="paren");if(!M&&d.type!=="paren"&&!G&&!Ie){C({type:"star",value:u,output:""});continue}for(;A.slice(0,3)==="/**";){let Ce=e[l.index+4];if(Ce&&Ce!=="/")break;A=A.slice(3),X("/**",3)}if(d.type==="bos"&&P()){o.type="globstar",o.value+=u,o.output=K(t),l.output=o.output,l.globstar=!0,X(u);continue}if(d.type==="slash"&&d.prev.type!=="bos"&&!j&&P()){l.output=l.output.slice(0,-(d.output+o.output).length),d.output=`(?:${d.output}`,o.type="globstar",o.output=K(t)+(t.strictSlashes?")":"|$)"),o.value+=u,l.globstar=!0,l.output+=d.output+o.output,X(u);continue}if(d.type==="slash"&&d.prev.type!=="bos"&&A[0]==="/"){let Ce=A[1]!==void 0?"|$":"";l.output=l.output.slice(0,-(d.output+o.output).length),d.output=`(?:${d.output}`,o.type="globstar",o.output=`${K(t)}${$}|${$}${Ce})`,o.value+=u,l.output+=d.output+o.output,l.globstar=!0,X(u+V()),C({type:"slash",value:"/",output:""});continue}if(d.type==="bos"&&A[0]==="/"){o.type="globstar",o.value+=u,o.output=`(?:^|${$}|${K(t)}${$})`,l.output=o.output,l.globstar=!0,X(u+V()),C({type:"slash",value:"/",output:""});continue}l.output=l.output.slice(0,-o.output.length),o.type="globstar",o.output=K(t),o.value+=u,l.output+=o.output,l.globstar=!0,X(u);continue}let O={type:"star",value:u,output:k};if(t.bash===!0){O.output=".*?",(o.type==="bos"||o.type==="slash")&&(O.output=g+O.output),C(O);continue}if(o&&(o.type==="bracket"||o.type==="paren")&&t.regex===!0){O.output=u,C(O);continue}(l.index===l.start||o.type==="slash"||o.type==="dot")&&(o.type==="dot"?(l.output+=S,o.output+=S):t.dot===!0?(l.output+=T,o.output+=T):(l.output+=g,o.output+=g),b()!=="*"&&(l.output+=_,o.output+=_)),C(O)}for(;l.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(de("closing","]"));l.output=Y.escapeLast(l.output,"["),oe("brackets")}for(;l.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(de("closing",")"));l.output=Y.escapeLast(l.output,"("),oe("parens")}for(;l.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(de("closing","}"));l.output=Y.escapeLast(l.output,"{"),oe("braces")}if(t.strictSlashes!==!0&&(o.type==="star"||o.type==="bracket")&&C({type:"maybe_slash",value:"",output:`${$}?`}),l.backtrack===!0){l.output="";for(let A of l.tokens)l.output+=A.output!=null?A.output:A.value,A.suffix&&(l.output+=A.suffix)}return l};Vt.fastpaths=(e,r)=>{let t={...r},n=typeof t.maxLength=="number"?Math.min(Le,t.maxLength):Le,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=zt[e]||e;let i=Y.isWindows(r),{DOT_LITERAL:a,SLASH_LITERAL:c,ONE_CHAR:p,DOTS_SLASH:m,NO_DOT:h,NO_DOTS:R,NO_DOTS_SLASH:f,STAR:$,START_ANCHOR:_}=ke.globChars(i),y=t.dot?R:h,E=t.dot?f:h,S=t.capture?"":"?:",T={negated:!1,prefix:""},L=t.bash===!0?".*?":$;t.capture&&(L=`(${L})`);let z=g=>g.noglobstar===!0?L:`(${S}(?:(?!${_}${g.dot?m:a}).)*?)`,I=g=>{switch(g){case"*":return`${y}${p}${L}`;case".*":return`${a}${p}${L}`;case"*.*":return`${y}${L}${a}${p}${L}`;case"*/*":return`${y}${L}${c}${p}${E}${L}`;case"**":return y+z(t);case"**/*":return`(?:${y}${z(t)}${c})?${E}${p}${L}`;case"**/*.*":return`(?:${y}${z(t)}${c})?${E}${L}${a}${p}${L}`;case"**/.*":return`(?:${y}${z(t)}${c})?${a}${p}${L}`;default:{let v=/^(.*?)\.(\w+)$/.exec(g);if(!v)return;let k=I(v[1]);return k?k+a+v[2]:void 0}}},re=Y.removePrefix(e,T),K=I(re);return K&&t.strictSlashes!==!0&&(K+=`${c}?`),K};Jt.exports=Vt});var rr=q((ls,tr)=>{"use strict";var Pn=W("path"),Mn=Yt(),Ze=er(),Ye=Re(),Dn=me(),Un=e=>e&&typeof e=="object"&&!Array.isArray(e),D=(e,r,t=!1)=>{if(Array.isArray(e)){let h=e.map(f=>D(f,r,t));return f=>{for(let $ of h){let _=$(f);if(_)return _}return!1}}let n=Un(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let s=r||{},i=Ye.isWindows(r),a=n?D.compileRe(e,r):D.makeRe(e,r,!1,!0),c=a.state;delete a.state;let p=()=>!1;if(s.ignore){let h={...r,ignore:null,onMatch:null,onResult:null};p=D(s.ignore,h,t)}let m=(h,R=!1)=>{let{isMatch:f,match:$,output:_}=D.test(h,a,r,{glob:e,posix:i}),y={glob:e,state:c,regex:a,posix:i,input:h,output:_,match:$,isMatch:f};return typeof s.onResult=="function"&&s.onResult(y),f===!1?(y.isMatch=!1,R?y:!1):p(h)?(typeof s.onIgnore=="function"&&s.onIgnore(y),y.isMatch=!1,R?y:!1):(typeof s.onMatch=="function"&&s.onMatch(y),R?y:!0)};return t&&(m.state=c),m};D.test=(e,r,t,{glob:n,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return{isMatch:!1,output:""};let i=t||{},a=i.format||(s?Ye.toPosixSlashes:null),c=e===n,p=c&&a?a(e):e;return c===!1&&(p=a?a(e):e,c=p===n),(c===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?c=D.matchBase(e,r,t,s):c=r.exec(p)),{isMatch:Boolean(c),match:c,output:p}};D.matchBase=(e,r,t,n=Ye.isWindows(t))=>(r instanceof RegExp?r:D.makeRe(r,t)).test(Pn.basename(e));D.isMatch=(e,r,t)=>D(r,t)(e);D.parse=(e,r)=>Array.isArray(e)?e.map(t=>D.parse(t,r)):Ze(e,{...r,fastpaths:!1});D.scan=(e,r)=>Mn(e,r);D.compileRe=(e,r,t=!1,n=!1)=>{if(t===!0)return e.output;let s=r||{},i=s.contains?"":"^",a=s.contains?"":"$",c=`${i}(?:${e.output})${a}`;e&&e.negated===!0&&(c=`^(?!${c}).*$`);let p=D.toRegex(c,r);return n===!0&&(p.state=e),p};D.makeRe=(e,r={},t=!1,n=!1)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let s={negated:!1,fastpaths:!0};return r.fastpaths!==!1&&(e[0]==="."||e[0]==="*")&&(s.output=Ze.fastpaths(e,r)),s.output||(s=Ze(e,r)),D.compileRe(s,r,t,n)};D.toRegex=(e,r)=>{try{let t=r||{};return new RegExp(e,t.flags||(t.nocase?"i":""))}catch(t){if(r&&r.debug===!0)throw t;return/$^/}};D.constants=Dn;tr.exports=D});var sr=q((fs,nr)=>{"use strict";nr.exports=rr()});var cr=q((ps,ur)=>{"use strict";var ir=W("util"),or=Pt(),ae=sr(),ze=Re(),ar=e=>e===""||e==="./",N=(e,r,t)=>{r=[].concat(r),e=[].concat(e);let n=new Set,s=new Set,i=new Set,a=0,c=h=>{i.add(h.output),t&&t.onResult&&t.onResult(h)};for(let h=0;h!n.has(h));if(t&&m.length===0){if(t.failglob===!0)throw new Error(`No matches found for "${r.join(", ")}"`);if(t.nonull===!0||t.nullglob===!0)return t.unescape?r.map(h=>h.replace(/\\/g,"")):r}return m};N.match=N;N.matcher=(e,r)=>ae(e,r);N.isMatch=(e,r,t)=>ae(r,t)(e);N.any=N.isMatch;N.not=(e,r,t={})=>{r=[].concat(r).map(String);let n=new Set,s=[],a=N(e,r,{...t,onResult:c=>{t.onResult&&t.onResult(c),s.push(c.output)}});for(let c of s)a.includes(c)||n.add(c);return[...n]};N.contains=(e,r,t)=>{if(typeof e!="string")throw new TypeError(`Expected a string: "${ir.inspect(e)}"`);if(Array.isArray(r))return r.some(n=>N.contains(e,n,t));if(typeof r=="string"){if(ar(e)||ar(r))return!1;if(e.includes(r)||e.startsWith("./")&&e.slice(2).includes(r))return!0}return N.isMatch(e,r,{...t,contains:!0})};N.matchKeys=(e,r,t)=>{if(!ze.isObject(e))throw new TypeError("Expected the first argument to be an object");let n=N(Object.keys(e),r,t),s={};for(let i of n)s[i]=e[i];return s};N.some=(e,r,t)=>{let n=[].concat(e);for(let s of[].concat(r)){let i=ae(String(s),t);if(n.some(a=>i(a)))return!0}return!1};N.every=(e,r,t)=>{let n=[].concat(e);for(let s of[].concat(r)){let i=ae(String(s),t);if(!n.every(a=>i(a)))return!1}return!0};N.all=(e,r,t)=>{if(typeof e!="string")throw new TypeError(`Expected a string: "${ir.inspect(e)}"`);return[].concat(r).every(n=>ae(n,t)(e))};N.capture=(e,r,t)=>{let n=ze.isWindows(t),i=ae.makeRe(String(e),{...t,capture:!0}).exec(n?ze.toPosixSlashes(r):r);if(i)return i.slice(1).map(a=>a===void 0?"":a)};N.makeRe=(...e)=>ae.makeRe(...e);N.scan=(...e)=>ae.scan(...e);N.parse=(e,r)=>{let t=[];for(let n of[].concat(e||[]))for(let s of or(String(n),r))t.push(ae.parse(s,r));return t};N.braces=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a string");return r&&r.nobrace===!0||!/\{.*\}/.test(e)?[e]:or(e,r)};N.braceExpand=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a string");return N.braces(e,{...r,expand:!0})};ur.exports=N});var fr=q((hs,lr)=>{"use strict";lr.exports=(e,...r)=>new Promise(t=>{t(e(...r))})});var hr=q((ds,Ve)=>{"use strict";var Gn=fr(),pr=e=>{if(e<1)throw new TypeError("Expected `concurrency` to be a number from 1 and up");let r=[],t=0,n=()=>{t--,r.length>0&&r.shift()()},s=(c,p,...m)=>{t++;let h=Gn(c,...m);p(h),h.then(n,n)},i=(c,p,...m)=>{tnew Promise(m=>i(c,m,...p));return Object.defineProperties(a,{activeCount:{get:()=>t},pendingCount:{get:()=>r.length}}),a};Ve.exports=pr;Ve.exports.default=pr});var jn={};Cr(jn,{default:()=>Wn});var Se=W("@yarnpkg/cli"),ne=W("@yarnpkg/core"),et=W("@yarnpkg/core"),ue=W("clipanion"),ce=class extends Se.BaseCommand{constructor(){super(...arguments);this.json=ue.Option.Boolean("--json",!1,{description:"Format the output as an NDJSON stream"});this.production=ue.Option.Boolean("--production",!1,{description:"Only install regular dependencies by omitting dev dependencies"});this.all=ue.Option.Boolean("-A,--all",!1,{description:"Install the entire project"});this.workspaces=ue.Option.Rest()}async execute(){let t=await ne.Configuration.find(this.context.cwd,this.context.plugins),{project:n,workspace:s}=await ne.Project.find(t,this.context.cwd),i=await ne.Cache.find(t);await n.restoreInstallState({restoreResolutions:!1});let a;if(this.all)a=new Set(n.workspaces);else if(this.workspaces.length===0){if(!s)throw new Se.WorkspaceRequiredError(n.cwd,this.context.cwd);a=new Set([s])}else a=new Set(this.workspaces.map(p=>n.getWorkspaceByIdent(et.structUtils.parseIdent(p))));for(let p of a)for(let m of this.production?["dependencies"]:ne.Manifest.hardDependencies)for(let h of p.manifest.getForScope(m).values()){let R=n.tryWorkspaceByDescriptor(h);R!==null&&a.add(R)}for(let p of n.workspaces)a.has(p)?this.production&&p.manifest.devDependencies.clear():(p.manifest.installConfig=p.manifest.installConfig||{},p.manifest.installConfig.selfReferences=!1,p.manifest.dependencies.clear(),p.manifest.devDependencies.clear(),p.manifest.peerDependencies.clear(),p.manifest.scripts.clear());return(await ne.StreamReport.start({configuration:t,json:this.json,stdout:this.context.stdout,includeLogs:!0},async p=>{await n.install({cache:i,report:p,persistProject:!1})})).exitCode()}};ce.paths=[["workspaces","focus"]],ce.usage=ue.Command.Usage({category:"Workspace-related commands",description:"install a single workspace and its dependencies",details:"\n This command will run an install as if the specified workspaces (and all other workspaces they depend on) were the only ones in the project. If no workspaces are explicitly listed, the active one will be assumed.\n\n Note that this command is only very moderately useful when using zero-installs, since the cache will contain all the packages anyway - meaning that the only difference between a full install and a focused install would just be a few extra lines in the `.pnp.cjs` file, at the cost of introducing an extra complexity.\n\n If the `-A,--all` flag is set, the entire project will be installed. Combine with `--production` to replicate the old `yarn install --production`.\n "});var Ne=W("@yarnpkg/cli"),ge=W("@yarnpkg/core"),_e=W("@yarnpkg/core"),F=W("@yarnpkg/core"),gr=W("@yarnpkg/plugin-git"),U=W("clipanion"),Oe=Be(cr()),Ar=Be(hr()),te=Be(W("typanion")),pe=class extends Ne.BaseCommand{constructor(){super(...arguments);this.recursive=U.Option.Boolean("-R,--recursive",!1,{description:"Find packages via dependencies/devDependencies instead of using the workspaces field"});this.from=U.Option.Array("--from",[],{description:"An array of glob pattern idents from which to base any recursion"});this.all=U.Option.Boolean("-A,--all",!1,{description:"Run the command on all workspaces of a project"});this.verbose=U.Option.Boolean("-v,--verbose",!1,{description:"Prefix each output line with the name of the originating workspace"});this.parallel=U.Option.Boolean("-p,--parallel",!1,{description:"Run the commands in parallel"});this.interlaced=U.Option.Boolean("-i,--interlaced",!1,{description:"Print the output of commands in real-time instead of buffering it"});this.jobs=U.Option.String("-j,--jobs",{description:"The maximum number of parallel tasks that the execution will be limited to; or `unlimited`",validator:te.isOneOf([te.isEnum(["unlimited"]),te.applyCascade(te.isNumber(),[te.isInteger(),te.isAtLeast(1)])])});this.topological=U.Option.Boolean("-t,--topological",!1,{description:"Run the command after all workspaces it depends on (regular) have finished"});this.topologicalDev=U.Option.Boolean("--topological-dev",!1,{description:"Run the command after all workspaces it depends on (regular + dev) have finished"});this.include=U.Option.Array("--include",[],{description:"An array of glob pattern idents; only matching workspaces will be traversed"});this.exclude=U.Option.Array("--exclude",[],{description:"An array of glob pattern idents; matching workspaces won't be traversed"});this.publicOnly=U.Option.Boolean("--no-private",{description:"Avoid running the command on private workspaces"});this.since=U.Option.String("--since",{description:"Only include workspaces that have been changed since the specified ref.",tolerateBoolean:!0});this.commandName=U.Option.String();this.args=U.Option.Proxy()}async execute(){let t=await ge.Configuration.find(this.context.cwd,this.context.plugins),{project:n,workspace:s}=await ge.Project.find(t,this.context.cwd);if(!this.all&&!s)throw new Ne.WorkspaceRequiredError(n.cwd,this.context.cwd);await n.restoreInstallState();let i=this.cli.process([this.commandName,...this.args]),a=i.path.length===1&&i.path[0]==="run"&&typeof i.scriptName<"u"?i.scriptName:null;if(i.path.length===0)throw new U.UsageError("Invalid subcommand name for iteration - use the 'run' keyword if you wish to execute a script");let c=this.all?n.topLevelWorkspace:s,p=this.since?Array.from(await gr.gitUtils.fetchChangedWorkspaces({ref:this.since,project:n})):[c,...this.from.length>0?c.getRecursiveWorkspaceChildren():[]],m=g=>Oe.default.isMatch(F.structUtils.stringifyIdent(g.locator),this.from),h=this.from.length>0?p.filter(m):p,R=new Set([...h,...h.map(g=>[...this.recursive?this.since?g.getRecursiveWorkspaceDependents():g.getRecursiveWorkspaceDependencies():g.getRecursiveWorkspaceChildren()]).flat()]),f=[],$=!1;if(a!=null&&a.includes(":")){for(let g of n.workspaces)if(g.manifest.scripts.has(a)&&($=!$,$===!1))break}for(let g of R)a&&!g.manifest.scripts.has(a)&&!$&&!(await ge.scriptUtils.getWorkspaceAccessibleBinaries(g)).has(a)||a===process.env.npm_lifecycle_event&&g.cwd===s.cwd||this.include.length>0&&!Oe.default.isMatch(F.structUtils.stringifyIdent(g.locator),this.include)||this.exclude.length>0&&Oe.default.isMatch(F.structUtils.stringifyIdent(g.locator),this.exclude)||this.publicOnly&&g.manifest.private===!0||f.push(g);let _=this.parallel?this.jobs==="unlimited"?1/0:Number(this.jobs)||Math.ceil(F.nodeUtils.availableParallelism()/2):1,y=_===1?!1:this.parallel,E=y?this.interlaced:!0,S=(0,Ar.default)(_),T=new Map,L=new Set,z=0,I=null,re=!1,K=await _e.StreamReport.start({configuration:t,stdout:this.context.stdout,includePrefix:!1},async g=>{let v=async(k,{commandIndex:l})=>{if(re)return-1;!y&&this.verbose&&l>1&&g.reportSeparator();let H=qn(k,{configuration:t,verbose:this.verbose,commandIndex:l}),[w,B]=dr(g,{prefix:H,interlaced:E}),[o,u]=dr(g,{prefix:H,interlaced:E});try{this.verbose&&g.reportInfo(null,`${H} Process started`);let P=Date.now(),b=await this.cli.run([this.commandName,...this.args],{cwd:k.cwd,stdout:w,stderr:o})||0;w.end(),o.end(),await B,await u;let V=Date.now();if(this.verbose){let J=t.get("enableTimers")?`, completed in ${F.formatUtils.pretty(t,V-P,F.formatUtils.Type.DURATION)}`:"";g.reportInfo(null,`${H} Process exited (exit code ${b})${J}`)}return b===130&&(re=!0,I=b),b}catch(P){throw w.end(),o.end(),await B,await u,P}};for(let k of f)T.set(k.anchoredLocator.locatorHash,k);for(;T.size>0&&!g.hasErrors();){let k=[];for(let[w,B]of T){if(L.has(B.anchoredDescriptor.descriptorHash))continue;let o=!0;if(this.topological||this.topologicalDev){let u=this.topologicalDev?new Map([...B.manifest.dependencies,...B.manifest.devDependencies]):B.manifest.dependencies;for(let P of u.values()){let b=n.tryWorkspaceByDescriptor(P);if(o=b===null||!T.has(b.anchoredLocator.locatorHash),!o)break}}if(!!o&&(L.add(B.anchoredDescriptor.descriptorHash),k.push(S(async()=>{let u=await v(B,{commandIndex:++z});return T.delete(w),L.delete(B.anchoredDescriptor.descriptorHash),u})),!y))break}if(k.length===0){let w=Array.from(T.values()).map(B=>F.structUtils.prettyLocator(t,B.anchoredLocator)).join(", ");g.reportError(_e.MessageName.CYCLIC_DEPENDENCIES,`Dependency cycle detected (${w})`);return}let H=(await Promise.all(k)).find(w=>w!==0);I===null&&(I=typeof H<"u"?1:I),(this.topological||this.topologicalDev)&&typeof H<"u"&&g.reportError(_e.MessageName.UNNAMED,"The command failed for workspaces that are depended upon by other workspaces; can't satisfy the dependency graph")}});return I!==null?I:K.exitCode()}};pe.paths=[["workspaces","foreach"]],pe.usage=U.Command.Usage({category:"Workspace-related commands",description:"run a command on all workspaces",details:"\n This command will run a given sub-command on current and all its descendant workspaces. Various flags can alter the exact behavior of the command:\n\n - If `-p,--parallel` is set, the commands will be ran in parallel; they'll by default be limited to a number of parallel tasks roughly equal to half your core number, but that can be overridden via `-j,--jobs`, or disabled by setting `-j unlimited`.\n\n - If `-p,--parallel` and `-i,--interlaced` are both set, Yarn will print the lines from the output as it receives them. If `-i,--interlaced` wasn't set, it would instead buffer the output from each process and print the resulting buffers only after their source processes have exited.\n\n - If `-t,--topological` is set, Yarn will only run the command after all workspaces that it depends on through the `dependencies` field have successfully finished executing. If `--topological-dev` is set, both the `dependencies` and `devDependencies` fields will be considered when figuring out the wait points.\n\n - If `-A,--all` is set, Yarn will run the command on all the workspaces of a project. By default yarn runs the command only on current and all its descendant workspaces.\n\n - If `-R,--recursive` is set, Yarn will find workspaces to run the command on by recursively evaluating `dependencies` and `devDependencies` fields, instead of looking at the `workspaces` fields.\n\n - If `--from` is set, Yarn will use the packages matching the 'from' glob as the starting point for any recursive search.\n\n - If `--since` is set, Yarn will only run the command on workspaces that have been modified since the specified ref. By default Yarn will use the refs specified by the `changesetBaseRefs` configuration option.\n\n - The command may apply to only some workspaces through the use of `--include` which acts as a whitelist. The `--exclude` flag will do the opposite and will be a list of packages that mustn't execute the script. Both flags accept glob patterns (if valid Idents and supported by [micromatch](https://github.com/micromatch/micromatch)). Make sure to escape the patterns, to prevent your own shell from trying to expand them.\n\n Adding the `-v,--verbose` flag will cause Yarn to print more information; in particular the name of the workspace that generated the output will be printed at the front of each line.\n\n If the command is `run` and the script being run does not exist the child workspace will be skipped without error.\n ",examples:[["Publish current and all descendant packages","yarn workspaces foreach npm publish --tolerate-republish"],["Run build script on current and all descendant packages","yarn workspaces foreach run build"],["Run build script on current and all descendant packages in parallel, building package dependencies first","yarn workspaces foreach -pt run build"],["Run build script on several packages and all their dependencies, building dependencies first","yarn workspaces foreach -ptR --from '{workspace-a,workspace-b}' run build"]]});function dr(e,{prefix:r,interlaced:t}){let n=e.createStreamReporter(r),s=new F.miscUtils.DefaultStream;s.pipe(n,{end:!1}),s.on("finish",()=>{n.end()});let i=new Promise(c=>{n.on("finish",()=>{c(s.active)})});if(t)return[s,i];let a=new F.miscUtils.BufferStream;return a.pipe(s,{end:!1}),a.on("finish",()=>{s.end()}),[a,i]}function qn(e,{configuration:r,commandIndex:t,verbose:n}){if(!n)return null;let i=`[${F.structUtils.stringifyIdent(e.locator)}]:`,a=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],c=a[t%a.length];return F.formatUtils.pretty(r,i,c)}var Kn={commands:[ce,pe]},Wn=Kn;return wr(jn);})(); 8 | /*! 9 | * fill-range 10 | * 11 | * Copyright (c) 2014-present, Jon Schlinkert. 12 | * Licensed under the MIT License. 13 | */ 14 | /*! 15 | * is-number 16 | * 17 | * Copyright (c) 2014-present, Jon Schlinkert. 18 | * Released under the MIT License. 19 | */ 20 | /*! 21 | * to-regex-range 22 | * 23 | * Copyright (c) 2015-present, Jon Schlinkert. 24 | * Released under the MIT License. 25 | */ 26 | return plugin; 27 | } 28 | }; 29 | --------------------------------------------------------------------------------