From c08d8a6f848afd0930dd2c8a203f6c4db792b95b Mon Sep 17 00:00:00 2001 From: Francois Picalausa Date: Sun, 7 Jan 2024 16:33:13 +0900 Subject: [PATCH 1/7] feat: handle unknown authors --- README.md | 26 ++- action.yml | 8 + package-lock.json | 433 ++++++++++++++++++++++++------------- src/cli.ts | 4 +- src/commitComment.test.ts | 8 +- src/commitComments.ts | 18 +- src/index.ts | 9 + src/readBranches.ts | 126 ++++++----- src/removeStaleBranches.ts | 32 ++- src/types.ts | 9 +- 10 files changed, 435 insertions(+), 238 deletions(-) diff --git a/README.md b/README.md index 42958f1..940ee15 100644 --- a/README.md +++ b/README.md @@ -17,18 +17,20 @@ Without setting `dry_run: true`, this action will remove branches. Consider sett ## Inputs -| Input | Defaults | Description | -|-----------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `github-token` | `${{ secrets.GITHUB_TOKEN }}` | PAT for GitHub API authentication. | -| `dry-run` | `false` | Flag that prevents this action from doing any modification to the repository. | -| `exempt-organization` | (not set) | Name of a Github organization. Branches for which the latest commiter belongs to this organization will be exempt from cleanup. | -| `exempt-branches-regex` | `^(main\|master)$` | Regular expression defining branches name that are exempt from cleanup. | -| `exempt-authors-regex` | (not set) | Regular expression defining authors who are exempt from cleanup. | -| `exempt-protected-branches` | true | Whether protected branches are exempted | -| `stale-branch-message` | `@{author} Your branch [{branchName}]({branchUrl}) hasn't been updated in the last 60 days and is marked as stale. It will be removed in a week.\r\nIf you want to keep this branch around, delete this comment or add new commits to this branch.` | Template for commit comments notifying the author that their branch will be removed. | -| `days-before-branch-stale` | 90 | Number of days since the last commit before a branch is considered stale. Once stale, this action will leave a comment on the last commit, marking the branch as stale. | -| `days-before-branch-delete` | 7 | Number of days before a stale branch is removed. Set to 0 to remove immediately. | -| `operations-per-run` | 10 | Maximum number of stale branches to look at in any run of this action. | +| Input | Defaults | Description | +|-----------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `github-token` | `${{ secrets.GITHUB_TOKEN }}` | PAT for GitHub API authentication. | +| `dry-run` | `false` | Flag that prevents this action from doing any modification to the repository. | +| `exempt-organization` | (not set) | Name of a Github organization. Branches for which the latest commiter belongs to this organization will be exempt from cleanup. | +| `exempt-branches-regex` | `^(main\|master)$` | Regular expression defining branches name that are exempt from cleanup. | +| `exempt-authors-regex` | (not set) | Regular expression defining authors who are exempt from cleanup. | +| `exempt-protected-branches` | `true` | Whether protected branches are exempted | +| `stale-branch-message` | `@{author} Your branch [{branchName}]({branchUrl}) hasn't been updated in the last 60 days and is marked as stale. It will be removed in a week.\r\nIf you want to keep this branch around, delete this comment or add new commits to this branch.` | Template for commit comments notifying the author that their branch will be removed. | +| `days-before-branch-stale` | `90` | Number of days since the last commit before a branch is considered stale. Once stale, this action will leave a comment on the last commit, marking the branch as stale. | +| `days-before-branch-delete` | `7` | Number of days before a stale branch is removed. Set to 0 to remove immediately. | +| `operations-per-run` | `10` | Maximum number of stale branches to look at in any run of this action. | +| `ignore-unknown-authors` | `false` | Whether to abort early when a commit author cannot be identified. By default, stop early since this may indicate that the token used to run the action doesn't have the right privileges. Set to true and define a default recipient instead if not a concern. | +| `default-recipient` | (not set) | When `ignore-unknown-authors` is `true`, use this login as the author to notify when the branch becomes stale. | ## Example usage diff --git a/action.yml b/action.yml index 559c7eb..49930aa 100644 --- a/action.yml +++ b/action.yml @@ -43,3 +43,11 @@ inputs: description: "Maximum number of stale branches to look at in any run of this action." default: "10" required: false + ignore-unknown-authors: + description: "Whether to abort early when a commit author cannot be identified. By default, stop early since this may indicate that the token used to run the action doesn't have the right privileges. Set to true and define a default recipient instead if not a concern." + default: "false" + required: false + default-recipient: + description: "A string corresponding to the username to be tagged on stale branches from unknown authors" + default: "" + required: false diff --git a/package-lock.json b/package-lock.json index 33d2771..c41049e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -66,17 +66,89 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", - "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", + "version": "7.23.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", + "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==", "dev": true, "dependencies": { - "@babel/highlight": "^7.18.6" + "@babel/highlight": "^7.23.4", + "chalk": "^2.4.2" }, "engines": { "node": ">=6.9.0" } }, + "node_modules/@babel/code-frame/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/code-frame/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/code-frame/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/code-frame/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "node_modules/@babel/code-frame/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/code-frame/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/code-frame/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/@babel/compat-data": { "version": "7.20.1", "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.20.1.tgz", @@ -123,13 +195,14 @@ "dev": true }, "node_modules/@babel/generator": { - "version": "7.20.4", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.20.4.tgz", - "integrity": "sha512-luCf7yk/cm7yab6CAW1aiFnmEfBJplb/JojV56MYEK7ziWfGmFlTfmL9Ehwfy4gFhbjBfWO1wj7/TuSbVNEEtA==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz", + "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==", "dev": true, "dependencies": { - "@babel/types": "^7.20.2", + "@babel/types": "^7.23.6", "@jridgewell/gen-mapping": "^0.3.2", + "@jridgewell/trace-mapping": "^0.3.17", "jsesc": "^2.5.1" }, "engines": { @@ -169,34 +242,34 @@ } }, "node_modules/@babel/helper-environment-visitor": { - "version": "7.18.9", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz", - "integrity": "sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", + "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-function-name": { - "version": "7.19.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.19.0.tgz", - "integrity": "sha512-WAwHBINyrpqywkUH0nTnNgI5ina5TFn85HKS0pbPDfxFfhyR/aNQEn4hGi1P1JyT//I0t4OgXUlofzWILRvS5w==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", + "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", "dev": true, "dependencies": { - "@babel/template": "^7.18.10", - "@babel/types": "^7.19.0" + "@babel/template": "^7.22.15", + "@babel/types": "^7.23.0" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-hoist-variables": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz", - "integrity": "sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", + "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", "dev": true, "dependencies": { - "@babel/types": "^7.18.6" + "@babel/types": "^7.22.5" }, "engines": { "node": ">=6.9.0" @@ -255,30 +328,30 @@ } }, "node_modules/@babel/helper-split-export-declaration": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz", - "integrity": "sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==", + "version": "7.22.6", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", + "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", "dev": true, "dependencies": { - "@babel/types": "^7.18.6" + "@babel/types": "^7.22.5" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-string-parser": { - "version": "7.19.4", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.19.4.tgz", - "integrity": "sha512-nHtDoQcuqFmwYNYPz3Rah5ph2p8PFeFCsZk9A/48dPc/rGocJ5J3hAAZ7pb76VWX3fZKu+uEr/FhH5jLx7umrw==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", + "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.19.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", - "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", "dev": true, "engines": { "node": ">=6.9.0" @@ -308,13 +381,13 @@ } }, "node_modules/@babel/highlight": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", - "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", + "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==", "dev": true, "dependencies": { - "@babel/helper-validator-identifier": "^7.18.6", - "chalk": "^2.0.0", + "@babel/helper-validator-identifier": "^7.22.20", + "chalk": "^2.4.2", "js-tokens": "^4.0.0" }, "engines": { @@ -393,9 +466,9 @@ } }, "node_modules/@babel/parser": { - "version": "7.20.3", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.20.3.tgz", - "integrity": "sha512-OP/s5a94frIPXwjzEcv5S/tpQfc6XhxYUnmWpgdqMWGgYCuErA3SzozaRAMQgSZWKeTJxht9aWAkUY+0UzvOFg==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.6.tgz", + "integrity": "sha512-Z2uID7YJ7oNvAI20O9X0bblw7Qqs8Q2hFy0R9tAfnfLkp5MW0UH9eUvnDSnFwKZ0AvgS1ucqR4KzvVHgnke1VQ==", "dev": true, "bin": { "parser": "bin/babel-parser.js" @@ -582,34 +655,34 @@ } }, "node_modules/@babel/template": { - "version": "7.18.10", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.18.10.tgz", - "integrity": "sha512-TI+rCtooWHr3QJ27kJxfjutghu44DLnasDMwpDqCXVTal9RLp3RSYNh4NdBrRP2cQAoG9A8juOQl6P6oZG4JxA==", + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", + "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", "dev": true, "dependencies": { - "@babel/code-frame": "^7.18.6", - "@babel/parser": "^7.18.10", - "@babel/types": "^7.18.10" + "@babel/code-frame": "^7.22.13", + "@babel/parser": "^7.22.15", + "@babel/types": "^7.22.15" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/traverse": { - "version": "7.20.1", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.20.1.tgz", - "integrity": "sha512-d3tN8fkVJwFLkHkBN479SOsw4DMZnz8cdbL/gvuDuzy3TS6Nfw80HuQqhw1pITbIruHyh7d1fMA47kWzmcUEGA==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.18.6", - "@babel/generator": "^7.20.1", - "@babel/helper-environment-visitor": "^7.18.9", - "@babel/helper-function-name": "^7.19.0", - "@babel/helper-hoist-variables": "^7.18.6", - "@babel/helper-split-export-declaration": "^7.18.6", - "@babel/parser": "^7.20.1", - "@babel/types": "^7.20.0", - "debug": "^4.1.0", + "version": "7.23.7", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.7.tgz", + "integrity": "sha512-tY3mM8rH9jM0YHFGyfC0/xf+SB5eKUu7HPj7/k3fpi9dAlsMc5YbQvDi0Sh2QTPXqMhyaAtzAr807TIyfQrmyg==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.23.5", + "@babel/generator": "^7.23.6", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.23.0", + "@babel/helper-hoist-variables": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/parser": "^7.23.6", + "@babel/types": "^7.23.6", + "debug": "^4.3.1", "globals": "^11.1.0" }, "engines": { @@ -617,13 +690,13 @@ } }, "node_modules/@babel/types": { - "version": "7.20.2", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.20.2.tgz", - "integrity": "sha512-FnnvsNWgZCr232sqtXggapvlkk/tuwR/qhGzcmxI0GXLCjmPYQPzio2FbdlWuY6y1sHFfQKk+rRbUZ9VStQMog==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.6.tgz", + "integrity": "sha512-+uarb83brBzPKN38NX1MkB6vb6+mwvR6amUulqAE7ccQw1pEl+bCia9TbdG1lsnFP7lZySvUn37CHyXQdfTwzg==", "dev": true, "dependencies": { - "@babel/helper-string-parser": "^7.19.4", - "@babel/helper-validator-identifier": "^7.19.1", + "@babel/helper-string-parser": "^7.23.4", + "@babel/helper-validator-identifier": "^7.22.20", "to-fast-properties": "^2.0.0" }, "engines": { @@ -2713,9 +2786,9 @@ } }, "node_modules/jest-snapshot/node_modules/semver": { - "version": "7.3.8", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", - "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, "dependencies": { "lru-cache": "^6.0.0" @@ -2860,9 +2933,9 @@ "dev": true }, "node_modules/json5": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", - "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", "dev": true, "bin": { "json5": "lib/cli.js" @@ -3340,9 +3413,9 @@ } }, "node_modules/semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", "dev": true, "bin": { "semver": "bin/semver.js" @@ -3610,9 +3683,9 @@ } }, "node_modules/ts-jest/node_modules/semver": { - "version": "7.3.7", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", - "integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, "dependencies": { "lru-cache": "^6.0.0" @@ -3951,12 +4024,71 @@ } }, "@babel/code-frame": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", - "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", + "version": "7.23.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", + "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==", "dev": true, "requires": { - "@babel/highlight": "^7.18.6" + "@babel/highlight": "^7.23.4", + "chalk": "^2.4.2" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } } }, "@babel/compat-data": { @@ -3997,13 +4129,14 @@ } }, "@babel/generator": { - "version": "7.20.4", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.20.4.tgz", - "integrity": "sha512-luCf7yk/cm7yab6CAW1aiFnmEfBJplb/JojV56MYEK7ziWfGmFlTfmL9Ehwfy4gFhbjBfWO1wj7/TuSbVNEEtA==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz", + "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==", "dev": true, "requires": { - "@babel/types": "^7.20.2", + "@babel/types": "^7.23.6", "@jridgewell/gen-mapping": "^0.3.2", + "@jridgewell/trace-mapping": "^0.3.17", "jsesc": "^2.5.1" }, "dependencies": { @@ -4033,28 +4166,28 @@ } }, "@babel/helper-environment-visitor": { - "version": "7.18.9", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz", - "integrity": "sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", + "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", "dev": true }, "@babel/helper-function-name": { - "version": "7.19.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.19.0.tgz", - "integrity": "sha512-WAwHBINyrpqywkUH0nTnNgI5ina5TFn85HKS0pbPDfxFfhyR/aNQEn4hGi1P1JyT//I0t4OgXUlofzWILRvS5w==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", + "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", "dev": true, "requires": { - "@babel/template": "^7.18.10", - "@babel/types": "^7.19.0" + "@babel/template": "^7.22.15", + "@babel/types": "^7.23.0" } }, "@babel/helper-hoist-variables": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz", - "integrity": "sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", + "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", "dev": true, "requires": { - "@babel/types": "^7.18.6" + "@babel/types": "^7.22.5" } }, "@babel/helper-module-imports": { @@ -4098,24 +4231,24 @@ } }, "@babel/helper-split-export-declaration": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz", - "integrity": "sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==", + "version": "7.22.6", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", + "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", "dev": true, "requires": { - "@babel/types": "^7.18.6" + "@babel/types": "^7.22.5" } }, "@babel/helper-string-parser": { - "version": "7.19.4", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.19.4.tgz", - "integrity": "sha512-nHtDoQcuqFmwYNYPz3Rah5ph2p8PFeFCsZk9A/48dPc/rGocJ5J3hAAZ7pb76VWX3fZKu+uEr/FhH5jLx7umrw==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", + "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==", "dev": true }, "@babel/helper-validator-identifier": { - "version": "7.19.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", - "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", "dev": true }, "@babel/helper-validator-option": { @@ -4136,13 +4269,13 @@ } }, "@babel/highlight": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", - "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", + "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==", "dev": true, "requires": { - "@babel/helper-validator-identifier": "^7.18.6", - "chalk": "^2.0.0", + "@babel/helper-validator-identifier": "^7.22.20", + "chalk": "^2.4.2", "js-tokens": "^4.0.0" }, "dependencies": { @@ -4205,9 +4338,9 @@ } }, "@babel/parser": { - "version": "7.20.3", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.20.3.tgz", - "integrity": "sha512-OP/s5a94frIPXwjzEcv5S/tpQfc6XhxYUnmWpgdqMWGgYCuErA3SzozaRAMQgSZWKeTJxht9aWAkUY+0UzvOFg==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.6.tgz", + "integrity": "sha512-Z2uID7YJ7oNvAI20O9X0bblw7Qqs8Q2hFy0R9tAfnfLkp5MW0UH9eUvnDSnFwKZ0AvgS1ucqR4KzvVHgnke1VQ==", "dev": true }, "@babel/plugin-syntax-async-generators": { @@ -4337,42 +4470,42 @@ } }, "@babel/template": { - "version": "7.18.10", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.18.10.tgz", - "integrity": "sha512-TI+rCtooWHr3QJ27kJxfjutghu44DLnasDMwpDqCXVTal9RLp3RSYNh4NdBrRP2cQAoG9A8juOQl6P6oZG4JxA==", + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", + "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", "dev": true, "requires": { - "@babel/code-frame": "^7.18.6", - "@babel/parser": "^7.18.10", - "@babel/types": "^7.18.10" + "@babel/code-frame": "^7.22.13", + "@babel/parser": "^7.22.15", + "@babel/types": "^7.22.15" } }, "@babel/traverse": { - "version": "7.20.1", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.20.1.tgz", - "integrity": "sha512-d3tN8fkVJwFLkHkBN479SOsw4DMZnz8cdbL/gvuDuzy3TS6Nfw80HuQqhw1pITbIruHyh7d1fMA47kWzmcUEGA==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.18.6", - "@babel/generator": "^7.20.1", - "@babel/helper-environment-visitor": "^7.18.9", - "@babel/helper-function-name": "^7.19.0", - "@babel/helper-hoist-variables": "^7.18.6", - "@babel/helper-split-export-declaration": "^7.18.6", - "@babel/parser": "^7.20.1", - "@babel/types": "^7.20.0", - "debug": "^4.1.0", + "version": "7.23.7", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.7.tgz", + "integrity": "sha512-tY3mM8rH9jM0YHFGyfC0/xf+SB5eKUu7HPj7/k3fpi9dAlsMc5YbQvDi0Sh2QTPXqMhyaAtzAr807TIyfQrmyg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.23.5", + "@babel/generator": "^7.23.6", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.23.0", + "@babel/helper-hoist-variables": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/parser": "^7.23.6", + "@babel/types": "^7.23.6", + "debug": "^4.3.1", "globals": "^11.1.0" } }, "@babel/types": { - "version": "7.20.2", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.20.2.tgz", - "integrity": "sha512-FnnvsNWgZCr232sqtXggapvlkk/tuwR/qhGzcmxI0GXLCjmPYQPzio2FbdlWuY6y1sHFfQKk+rRbUZ9VStQMog==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.6.tgz", + "integrity": "sha512-+uarb83brBzPKN38NX1MkB6vb6+mwvR6amUulqAE7ccQw1pEl+bCia9TbdG1lsnFP7lZySvUn37CHyXQdfTwzg==", "dev": true, "requires": { - "@babel/helper-string-parser": "^7.19.4", - "@babel/helper-validator-identifier": "^7.19.1", + "@babel/helper-string-parser": "^7.23.4", + "@babel/helper-validator-identifier": "^7.22.20", "to-fast-properties": "^2.0.0" } }, @@ -6004,9 +6137,9 @@ }, "dependencies": { "semver": { - "version": "7.3.8", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", - "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, "requires": { "lru-cache": "^6.0.0" @@ -6118,9 +6251,9 @@ "dev": true }, "json5": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", - "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", "dev": true }, "kleur": { @@ -6462,9 +6595,9 @@ "dev": true }, "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", "dev": true }, "shebang-command": { @@ -6648,9 +6781,9 @@ }, "dependencies": { "semver": { - "version": "7.3.7", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", - "integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, "requires": { "lru-cache": "^6.0.0" diff --git a/src/cli.ts b/src/cli.ts index bd06a08..4f93250 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -10,7 +10,7 @@ let octokit = new Octokit({ const timer = setTimeout(() => {}, 120000); removeStaleBranches(octokit, { - isDryRun: false, + isDryRun: true, daysBeforeBranchStale: 60, daysBeforeBranchDelete: 7, staleCommentMessage: @@ -19,6 +19,8 @@ removeStaleBranches(octokit, { operationsPerRun: 10, githubToken: process.env.GITHUB_TOKEN || "", exemptProtectedBranches: true, + ignoreUnknownAuthors: false, + defaultRecipient: null, repo: { owner: "github", repo: "octocat", diff --git a/src/commitComment.test.ts b/src/commitComment.test.ts index 8e7965e..06f9a23 100644 --- a/src/commitComment.test.ts +++ b/src/commitComment.test.ts @@ -6,16 +6,20 @@ describe("Commit comments", () => { "@{author} Your branch [{branchName}]({branchUrl}) hasn't been updated in the last 60 days and is marked as stale. It will be removed in a week.\r\nIf you want to keep this branch around, delete this comment or add new commits to this branch.", { date: Date.now(), - username: "theusername", - belongsToOrganization: false, branchName: "the-branch", prefix: "origin", commitId: "123456", + author: { + username: "theusername", + email: "foo-bar@example.org", + belongsToOrganization: false, + }, isProtected: false, }, { daysBeforeBranchStale: 5, daysBeforeBranchDelete: 10, + defaultRecipient: "", }, { repo: "octocat", diff --git a/src/commitComments.ts b/src/commitComments.ts index 37aab00..9a91552 100644 --- a/src/commitComments.ts +++ b/src/commitComments.ts @@ -31,20 +31,22 @@ export class TaggedCommitComments { static formatCommentMessage( messageTemplate: string, branch: Branch, - config: Pick, + config: Pick< + Params, + "daysBeforeBranchStale" | "daysBeforeBranchDelete" | "defaultRecipient" + >, repo: Repo ) { - const serverUrl = process.env.GITHUB_SERVER_URL ?? "https://github.com" - const username = branch.username || "(Unknown user)"; + const serverUrl = process.env.GITHUB_SERVER_URL ?? "https://github.com"; + const username = + branch.author?.username || config.defaultRecipient || "(Unknown user)"; return messageTemplate .replace(/[{]branchName[}]/g, branch.branchName) .replace( /[{]branchUrl[}]/g, - `${serverUrl}/${encodeURIComponent( - repo.owner - )}/${encodeURIComponent(repo.repo)}/tree/${encodeURIComponent( - branch.branchName - )}` + `${serverUrl}/${encodeURIComponent(repo.owner)}/${encodeURIComponent( + repo.repo + )}/tree/${encodeURIComponent(branch.branchName)}` ) .replace(/[{]repoOwner[}]/g, repo.owner) .replace(/[{]repoName[}]/g, repo.repo) diff --git a/src/index.ts b/src/index.ts index 83330f9..4f247b6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -34,6 +34,13 @@ async function run(): Promise { core.getInput("operations-per-run", { required: false }) ); + const defaultRecipient = + core.getInput("default-recipient", { required: false }) ?? ""; + + const ignoreUnknownAuthors = core.getBooleanInput("ignore-unknown-authors", { + required: false, + }); + return removeStaleBranches(octokit, { isDryRun, repo: github.context.repo, @@ -45,6 +52,8 @@ async function run(): Promise { protectedOrganizationName, exemptProtectedBranches, operationsPerRun, + defaultRecipient, + ignoreUnknownAuthors, }); } diff --git a/src/readBranches.ts b/src/readBranches.ts index c94ccdd..e52e3d9 100644 --- a/src/readBranches.ts +++ b/src/readBranches.ts @@ -21,8 +21,9 @@ const GRAPHQL_QUERY = `query ($repo: String!, $owner: String!, $after: String) { target { ... on Commit { oid + authoredDate author { - date + email user { login } @@ -58,8 +59,9 @@ const GRAPHQL_QUERY_WITH_ORG = `query ($repo: String!, $owner: String!, $organiz target { ... on Commit { oid + authoredDate author { - date + email user { login organization(login: $organization) { @@ -79,70 +81,72 @@ const GRAPHQL_QUERY_WITH_ORG = `query ($repo: String!, $owner: String!, $organiz } }`; -type PageInfo = { endCursor: string | null, hasNextPage: boolean, hasPreviousPage: boolean, startCursor: string | null }; +type PageInfo = { + endCursor: string | null; + hasNextPage: boolean; + hasPreviousPage: boolean; + startCursor: string | null; +}; type Page = { - edges: E[], - nodes: N[], - pageInfo: PageInfo, - totalCount: number -} + edges: E[]; + nodes: N[]; + pageInfo: PageInfo; + totalCount: number; +}; type GitObjectID = string; -type Blob = {} -type Tag = {} -type Tree = {} +type Blob = {}; +type Tag = {}; +type Tree = {}; -type GitTimeStamp = string; +type ISOTimeStamp = string; type Organization = { - id: unknown -} + id: unknown; +}; type User = { - email: string - login: string - organization: Organization | null -} + email: string; + login: string; + organization: Organization | null; +}; type GitActor = { - email: string | null, - name: string | null - user: User | null, - date: GitTimeStamp -} + email: string | null; + name: string | null; + user: User | null; +}; type Commit = { - author: GitActor -} + author: GitActor | null; +}; type GitOject = { - id: unknown - oid: GitObjectID -} & (Commit | Blob | Tag | Tree) - + id: unknown; + authoredDate: ISOTimeStamp; + oid: GitObjectID; +} & (Commit | Blob | Tag | Tree); type Ref = { - id: unknown, - name: string, - prefix: string - refUpdateRule: unknown | null - target: GitOject -} + id: unknown; + name: string; + prefix: string; + refUpdateRule: unknown | null; + target: GitOject; +}; type RefEdge = { - cursor: string, - node: Ref -} - - -type RefConnection = Page + cursor: string; + node: Ref; +}; +type RefConnection = Page; type Repository = { - refs: RefConnection -} + refs: RefConnection; +}; export async function* readBranches( octokit: Octokit, @@ -150,7 +154,12 @@ export async function* readBranches( repo: Repo, organization?: string ): AsyncGenerator { - let pagination: PageInfo = { hasNextPage: true, endCursor: null, hasPreviousPage: false, startCursor: null }; + let pagination: PageInfo = { + hasNextPage: true, + endCursor: null, + hasPreviousPage: false, + startCursor: null, + }; while (pagination.hasNextPage) { const params = { @@ -164,30 +173,33 @@ export async function* readBranches( repository: { refs: { edges, pageInfo }, }, - } = await octokit.graphql<{repository: Repository}>( + } = await octokit.graphql<{ repository: Repository }>( organization ? GRAPHQL_QUERY_WITH_ORG : GRAPHQL_QUERY, params ); for (let i = 0; i < edges.length; ++i) { const ref = edges[i]; - const { - name, - prefix, - refUpdateRule, - } = ref.node; - - const { oid, author: { date, user } } = ref.node.target as (GitOject & Commit) + const { name, prefix, refUpdateRule } = ref.node; + + const { oid, authoredDate, author } = ref.node.target as GitOject & + Commit; + + let branchAuthor: Branch["author"] = null; + if (author) { + branchAuthor = { + username: author.user?.login ?? null, + email: author.email, + belongsToOrganization: Boolean(author.user?.organization?.id), + }; + } - const login = user ? user.login : null; - const organization = user?.organization?.id; yield { - date: Date.parse(date), + date: Date.parse(authoredDate), branchName: name, prefix, commitId: oid, - username: login, - belongsToOrganization: Boolean(organization), + author: branchAuthor, isProtected: refUpdateRule !== null, }; } diff --git a/src/removeStaleBranches.ts b/src/removeStaleBranches.ts index 2507836..787b554 100644 --- a/src/removeStaleBranches.ts +++ b/src/removeStaleBranches.ts @@ -23,7 +23,7 @@ async function processBranch( ) { console.log( "-> branch was last updated by " + - (branch.username || "(unknown user)") + + (branch.author?.username || branch.author?.email || "(unknown user)") + " on " + formatISO(branch.date) ); @@ -120,18 +120,22 @@ async function planBranchAction( commitComments: TaggedCommitComments, params: Params ): Promise { - if (params.protectedOrganizationName && branch.belongsToOrganization) { + if ( + branch.author && + params.protectedOrganizationName && + branch.author.belongsToOrganization + ) { return skip( - `author ${branch.username} belongs to protected organization ${params.protectedOrganizationName}` + `author ${branch.author.username} belongs to protected organization ${params.protectedOrganizationName}` ); } if ( filters.authorsRegex && - branch.username && - filters.authorsRegex.test(branch.username) + branch.author?.username && + filters.authorsRegex.test(branch.author.username) ) { - return skip(`author ${branch.username} is exempted`); + return skip(`author ${branch.author.username} is exempted`); } if (filters.branchRegex && filters.branchRegex.test(branch.branchName)) { @@ -215,6 +219,13 @@ export async function removeStaleBranches( const commitComments = new TaggedCommitComments(repo, octokit, headers); let operations = 0; + if (params.ignoreUnknownAuthors && !params.defaultRecipient) { + console.error( + "When ignoring unknown authors, you must specify a default recipient" + ); + return; + } + if (params.isDryRun) { console.log("Running in dry-run mode. No branch will be removed."); } @@ -240,6 +251,15 @@ export async function removeStaleBranches( repo, params.protectedOrganizationName )) { + if (!branch.author && !params.ignoreUnknownAuthors) { + console.error( + "🛑 Failed to find author associated with branch " + + branch.branchName + + ". Use ignore-unknown-authors if this is expected." + ); + throw new Error("Failed to find author for branch"); + } + const plan = await planBranchAction( now.getTime(), branch, diff --git a/src/types.ts b/src/types.ts index 9e49132..0dc6f81 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,10 +1,13 @@ export type Branch = { date: number; - belongsToOrganization: boolean; branchName: string; prefix: string; commitId: string; - username: string | null; + author: { + username: string | null; + email: string | null; + belongsToOrganization: boolean; + } | null; isProtected: boolean; }; @@ -25,4 +28,6 @@ export type Params = { exemptProtectedBranches: boolean; operationsPerRun: number; repo: Repo; + ignoreUnknownAuthors: boolean; + defaultRecipient: string | null; }; From 164497f7f9385c12aef3ad6593785ac085a066da Mon Sep 17 00:00:00 2001 From: Francois Picalausa Date: Sun, 7 Jan 2024 16:37:16 +0900 Subject: [PATCH 2/7] docs: fix documentation on building --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 940ee15..2d46ce8 100644 --- a/README.md +++ b/README.md @@ -90,4 +90,4 @@ To start, install dependencies with `npm install`. The source files live under ` You can run the tool locally with `ts-node src/cli.ts` 🖥️ -To deploy you changes, start a PR. Don't forget to run `npm build` and include changes to the `dist` dir in your commit. +To deploy you changes, start a PR. Don't forget to run `npm run build` and include changes to the `dist` dir in your commit. From bc4c06ba49d7445d0cf2d7531c8425d69c92bfb6 Mon Sep 17 00:00:00 2001 From: Francois Picalausa Date: Sun, 7 Jan 2024 16:37:28 +0900 Subject: [PATCH 3/7] dist: rebuild dist --- dist/commitComments.d.ts | 2 +- dist/index.js | 8695 +++++++++++++++++++------------------- dist/types.d.ts | 9 +- 3 files changed, 4372 insertions(+), 4334 deletions(-) diff --git a/dist/commitComments.d.ts b/dist/commitComments.d.ts index f9489ec..13a2ca5 100644 --- a/dist/commitComments.d.ts +++ b/dist/commitComments.d.ts @@ -17,7 +17,7 @@ export declare class TaggedCommitComments { private readonly octokit; private readonly headers; constructor(repo: Repo, octokit: Octokit, headers: any); - static formatCommentMessage(messageTemplate: string, branch: Branch, config: Pick, repo: Repo): string; + static formatCommentMessage(messageTemplate: string, branch: Branch, config: Pick, repo: Repo): string; getCommitCommentsWithTag({ commentTag, commitSHA, }: Commit & CommentTag): Promise<{ html_url: string; url: string; diff --git a/dist/index.js b/dist/index.js index 2047bca..189667f 100644 --- a/dist/index.js +++ b/dist/index.js @@ -5745,43 +5745,6 @@ module.exports = exports.default; /***/ }), -/***/ 8493: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = getUTCISOWeek; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(3061)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(1478)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var MILLISECONDS_IN_WEEK = 604800000; - -function getUTCISOWeek(dirtyDate) { - (0, _index4.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var diff = (0, _index2.default)(date).getTime() - (0, _index3.default)(date).getTime(); // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - - return Math.round(diff / MILLISECONDS_IN_WEEK) + 1; -} - -module.exports = exports.default; - -/***/ }), - /***/ 7170: /***/ ((module, exports, __nccwpck_require__) => { @@ -5827,7 +5790,7 @@ module.exports = exports.default; /***/ }), -/***/ 8761: +/***/ 8493: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -5836,13 +5799,13 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = getUTCWeek; +exports["default"] = getUTCISOWeek; var _index = _interopRequireDefault(__nccwpck_require__(6477)); -var _index2 = _interopRequireDefault(__nccwpck_require__(2258)); +var _index2 = _interopRequireDefault(__nccwpck_require__(3061)); -var _index3 = _interopRequireDefault(__nccwpck_require__(2629)); +var _index3 = _interopRequireDefault(__nccwpck_require__(1478)); var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); @@ -5850,10 +5813,10 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de var MILLISECONDS_IN_WEEK = 604800000; -function getUTCWeek(dirtyDate, options) { +function getUTCISOWeek(dirtyDate) { (0, _index4.default)(1, arguments); var date = (0, _index.default)(dirtyDate); - var diff = (0, _index2.default)(date, options).getTime() - (0, _index3.default)(date, options).getTime(); // Round the number of days to the nearest integer + var diff = (0, _index2.default)(date).getTime() - (0, _index3.default)(date).getTime(); // Round the number of days to the nearest integer // because the number of milliseconds in a week is not constant // (e.g. it's different in the week of the daylight saving time clock shift) @@ -5922,6 +5885,43 @@ module.exports = exports.default; /***/ }), +/***/ 8761: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = getUTCWeek; + +var _index = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(2258)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(2629)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var MILLISECONDS_IN_WEEK = 604800000; + +function getUTCWeek(dirtyDate, options) { + (0, _index4.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + var diff = (0, _index2.default)(date, options).getTime() - (0, _index3.default)(date, options).getTime(); // Round the number of days to the nearest integer + // because the number of milliseconds in a week is not constant + // (e.g. it's different in the week of the daylight saving time clock shift) + + return Math.round(diff / MILLISECONDS_IN_WEEK) + 1; +} + +module.exports = exports.default; + +/***/ }), + /***/ 2509: /***/ ((__unused_webpack_module, exports) => { @@ -6162,38 +6162,6 @@ module.exports = exports.default; /***/ }), -/***/ 3061: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfUTCISOWeek; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function startOfUTCISOWeek(dirtyDate) { - (0, _index2.default)(1, arguments); - var weekStartsOn = 1; - var date = (0, _index.default)(dirtyDate); - var day = date.getUTCDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - date.setUTCDate(date.getUTCDate() - diff); - date.setUTCHours(0, 0, 0, 0); - return date; -} - -module.exports = exports.default; - -/***/ }), - /***/ 1478: /***/ ((module, exports, __nccwpck_require__) => { @@ -6227,7 +6195,7 @@ module.exports = exports.default; /***/ }), -/***/ 2258: +/***/ 3061: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -6236,29 +6204,17 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = startOfUTCWeek; +exports["default"] = startOfUTCISOWeek; var _index = _interopRequireDefault(__nccwpck_require__(6477)); var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); - -var _index4 = __nccwpck_require__(9307); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function startOfUTCWeek(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - +function startOfUTCISOWeek(dirtyDate) { (0, _index2.default)(1, arguments); - var defaultOptions = (0, _index4.getDefaultOptions)(); - var weekStartsOn = (0, _index3.default)((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN - - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); - } - + var weekStartsOn = 1; var date = (0, _index.default)(dirtyDate); var day = date.getUTCDay(); var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; @@ -6312,6 +6268,50 @@ module.exports = exports.default; /***/ }), +/***/ 2258: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfUTCWeek; + +var _index = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); + +var _index4 = __nccwpck_require__(9307); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function startOfUTCWeek(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + + (0, _index2.default)(1, arguments); + var defaultOptions = (0, _index4.getDefaultOptions)(); + var weekStartsOn = (0, _index3.default)((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + + var date = (0, _index.default)(dirtyDate); + var day = date.getUTCDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setUTCDate(date.getUTCDate() - diff); + date.setUTCHours(0, 0, 0, 0); + return date; +} + +module.exports = exports.default; + +/***/ }), + /***/ 1985: /***/ ((module, exports) => { @@ -6341,7 +6341,7 @@ module.exports = exports.default; /***/ }), -/***/ 6211: +/***/ 1727: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -6350,141 +6350,50 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = add; +exports["default"] = addBusinessDays; -var _index = _interopRequireDefault(__nccwpck_require__(6227)); +var _index = _interopRequireDefault(__nccwpck_require__(403)); -var _index2 = _interopRequireDefault(__nccwpck_require__(2995)); +var _index2 = _interopRequireDefault(__nccwpck_require__(6477)); -var _index3 = _interopRequireDefault(__nccwpck_require__(6477)); +var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); -var _index5 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index5 = _interopRequireDefault(__nccwpck_require__(5852)); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _index6 = _interopRequireDefault(__nccwpck_require__(6308)); -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name add - * @category Common Helpers - * @summary Add the specified years, months, weeks, days, hours, minutes and seconds to the given date. + * @name addBusinessDays + * @category Day Helpers + * @summary Add the specified number of business days (mon - fri) to the given date. * * @description - * Add the specified years, months, weeks, days, hours, minutes and seconds to the given date. + * Add the specified number of business days (mon - fri) to the given date, ignoring weekends. * * @param {Date|Number} date - the date to be changed - * @param {Duration} duration - the object with years, months, weeks, days, hours, minutes and seconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * - * | Key | Description | - * |----------------|------------------------------------| - * | years | Amount of years to be added | - * | months | Amount of months to be added | - * | weeks | Amount of weeks to be added | - * | days | Amount of days to be added | - * | hours | Amount of hours to be added | - * | minutes | Amount of minutes to be added | - * | seconds | Amount of seconds to be added | - * - * All values default to 0 - * - * @returns {Date} the new date with the seconds added + * @param {Number} amount - the amount of business days to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the business days added * @throws {TypeError} 2 arguments required * * @example - * // Add the following duration to 1 September 2014, 10:19:50 - * const result = add(new Date(2014, 8, 1, 10, 19, 50), { - * years: 2, - * months: 9, - * weeks: 1, - * days: 7, - * hours: 5, - * minutes: 9, - * seconds: 30, - * }) - * //=> Thu Jun 15 2017 15:29:20 + * // Add 10 business days to 1 September 2014: + * const result = addBusinessDays(new Date(2014, 8, 1), 10) + * //=> Mon Sep 15 2014 00:00:00 (skipped weekend days) */ -function add(dirtyDate, duration) { +function addBusinessDays(dirtyDate, dirtyAmount) { (0, _index4.default)(2, arguments); - if (!duration || _typeof(duration) !== 'object') return new Date(NaN); - var years = duration.years ? (0, _index5.default)(duration.years) : 0; - var months = duration.months ? (0, _index5.default)(duration.months) : 0; - var weeks = duration.weeks ? (0, _index5.default)(duration.weeks) : 0; - var days = duration.days ? (0, _index5.default)(duration.days) : 0; - var hours = duration.hours ? (0, _index5.default)(duration.hours) : 0; - var minutes = duration.minutes ? (0, _index5.default)(duration.minutes) : 0; - var seconds = duration.seconds ? (0, _index5.default)(duration.seconds) : 0; // Add years and months - - var date = (0, _index3.default)(dirtyDate); - var dateWithMonths = months || years ? (0, _index2.default)(date, months + years * 12) : date; // Add weeks and days - - var dateWithDays = days || weeks ? (0, _index.default)(dateWithMonths, days + weeks * 7) : dateWithMonths; // Add days, hours, minutes and seconds - - var minutesToAdd = minutes + hours * 60; - var secondsToAdd = seconds + minutesToAdd * 60; - var msToAdd = secondsToAdd * 1000; - var finalDate = new Date(dateWithDays.getTime() + msToAdd); - return finalDate; -} - -module.exports = exports.default; - -/***/ }), - -/***/ 1727: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = addBusinessDays; - -var _index = _interopRequireDefault(__nccwpck_require__(403)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); - -var _index5 = _interopRequireDefault(__nccwpck_require__(5852)); - -var _index6 = _interopRequireDefault(__nccwpck_require__(6308)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @name addBusinessDays - * @category Day Helpers - * @summary Add the specified number of business days (mon - fri) to the given date. - * - * @description - * Add the specified number of business days (mon - fri) to the given date, ignoring weekends. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of business days to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the business days added - * @throws {TypeError} 2 arguments required - * - * @example - * // Add 10 business days to 1 September 2014: - * const result = addBusinessDays(new Date(2014, 8, 1), 10) - * //=> Mon Sep 15 2014 00:00:00 (skipped weekend days) - */ -function addBusinessDays(dirtyDate, dirtyAmount) { - (0, _index4.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var startedOnWeekend = (0, _index.default)(date); - var amount = (0, _index3.default)(dirtyAmount); - if (isNaN(amount)) return new Date(NaN); - var hours = date.getHours(); - var sign = amount < 0 ? -1 : 1; - var fullWeeks = (0, _index3.default)(amount / 5); - date.setDate(date.getDate() + fullWeeks * 7); // Get remaining days not part of a full week + var date = (0, _index2.default)(dirtyDate); + var startedOnWeekend = (0, _index.default)(date); + var amount = (0, _index3.default)(dirtyAmount); + if (isNaN(amount)) return new Date(NaN); + var hours = date.getHours(); + var sign = amount < 0 ? -1 : 1; + var fullWeeks = (0, _index3.default)(amount / 5); + date.setDate(date.getDate() + fullWeeks * 7); // Get remaining days not part of a full week var restDays = Math.abs(amount % 5); // Loops over remaining days @@ -7043,6 +6952,97 @@ module.exports = exports.default; /***/ }), +/***/ 6211: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = add; + +var _index = _interopRequireDefault(__nccwpck_require__(6227)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(2995)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); + +var _index5 = _interopRequireDefault(__nccwpck_require__(1985)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * @name add + * @category Common Helpers + * @summary Add the specified years, months, weeks, days, hours, minutes and seconds to the given date. + * + * @description + * Add the specified years, months, weeks, days, hours, minutes and seconds to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Duration} duration - the object with years, months, weeks, days, hours, minutes and seconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * + * | Key | Description | + * |----------------|------------------------------------| + * | years | Amount of years to be added | + * | months | Amount of months to be added | + * | weeks | Amount of weeks to be added | + * | days | Amount of days to be added | + * | hours | Amount of hours to be added | + * | minutes | Amount of minutes to be added | + * | seconds | Amount of seconds to be added | + * + * All values default to 0 + * + * @returns {Date} the new date with the seconds added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add the following duration to 1 September 2014, 10:19:50 + * const result = add(new Date(2014, 8, 1, 10, 19, 50), { + * years: 2, + * months: 9, + * weeks: 1, + * days: 7, + * hours: 5, + * minutes: 9, + * seconds: 30, + * }) + * //=> Thu Jun 15 2017 15:29:20 + */ +function add(dirtyDate, duration) { + (0, _index4.default)(2, arguments); + if (!duration || _typeof(duration) !== 'object') return new Date(NaN); + var years = duration.years ? (0, _index5.default)(duration.years) : 0; + var months = duration.months ? (0, _index5.default)(duration.months) : 0; + var weeks = duration.weeks ? (0, _index5.default)(duration.weeks) : 0; + var days = duration.days ? (0, _index5.default)(duration.days) : 0; + var hours = duration.hours ? (0, _index5.default)(duration.hours) : 0; + var minutes = duration.minutes ? (0, _index5.default)(duration.minutes) : 0; + var seconds = duration.seconds ? (0, _index5.default)(duration.seconds) : 0; // Add years and months + + var date = (0, _index3.default)(dirtyDate); + var dateWithMonths = months || years ? (0, _index2.default)(date, months + years * 12) : date; // Add weeks and days + + var dateWithDays = days || weeks ? (0, _index.default)(dateWithMonths, days + weeks * 7) : dateWithMonths; // Add days, hours, minutes and seconds + + var minutesToAdd = minutes + hours * 60; + var secondsToAdd = seconds + minutesToAdd * 60; + var msToAdd = secondsToAdd * 1000; + var finalDate = new Date(dateWithDays.getTime() + msToAdd); + return finalDate; +} + +module.exports = exports.default; + +/***/ }), + /***/ 2282: /***/ ((module, exports, __nccwpck_require__) => { @@ -9796,7 +9796,7 @@ module.exports = exports.default; /***/ }), -/***/ 1920: +/***/ 9731: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -9805,46 +9805,53 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = endOfISOWeek; +exports["default"] = endOfISOWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(5218)); +var _index = _interopRequireDefault(__nccwpck_require__(6991)); -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(6307)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name endOfISOWeek - * @category ISO Week Helpers - * @summary Return the end of an ISO week for the given date. + * @name endOfISOWeekYear + * @category ISO Week-Numbering Year Helpers + * @summary Return the end of an ISO week-numbering year for the given date. * * @description - * Return the end of an ISO week for the given date. + * Return the end of an ISO week-numbering year, + * which always starts 3 days before the year's first Thursday. * The result will be in the local timezone. * * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * * @param {Date|Number} date - the original date - * @returns {Date} the end of an ISO week + * @returns {Date} the end of an ISO week-numbering year * @throws {TypeError} 1 argument required * * @example - * // The end of an ISO week for 2 September 2014 11:55:00: - * const result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 23:59:59.999 + * // The end of an ISO week-numbering year for 2 July 2005: + * const result = endOfISOWeekYear(new Date(2005, 6, 2)) + * //=> Sun Jan 01 2006 23:59:59.999 */ -function endOfISOWeek(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate, { - weekStartsOn: 1 - }); +function endOfISOWeekYear(dirtyDate) { + (0, _index3.default)(1, arguments); + var year = (0, _index.default)(dirtyDate); + var fourthOfJanuaryOfNextYear = new Date(0); + fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); + fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); + var date = (0, _index2.default)(fourthOfJanuaryOfNextYear); + date.setMilliseconds(date.getMilliseconds() - 1); + return date; } module.exports = exports.default; /***/ }), -/***/ 9731: +/***/ 1920: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -9853,46 +9860,39 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = endOfISOWeekYear; - -var _index = _interopRequireDefault(__nccwpck_require__(6991)); +exports["default"] = endOfISOWeek; -var _index2 = _interopRequireDefault(__nccwpck_require__(6307)); +var _index = _interopRequireDefault(__nccwpck_require__(5218)); -var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name endOfISOWeekYear - * @category ISO Week-Numbering Year Helpers - * @summary Return the end of an ISO week-numbering year for the given date. + * @name endOfISOWeek + * @category ISO Week Helpers + * @summary Return the end of an ISO week for the given date. * * @description - * Return the end of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. + * Return the end of an ISO week for the given date. * The result will be in the local timezone. * * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * * @param {Date|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year + * @returns {Date} the end of an ISO week * @throws {TypeError} 1 argument required * * @example - * // The end of an ISO week-numbering year for 2 July 2005: - * const result = endOfISOWeekYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 23:59:59.999 + * // The end of an ISO week for 2 September 2014 11:55:00: + * const result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Sun Sep 07 2014 23:59:59.999 */ -function endOfISOWeekYear(dirtyDate) { - (0, _index3.default)(1, arguments); - var year = (0, _index.default)(dirtyDate); - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var date = (0, _index2.default)(fourthOfJanuaryOfNextYear); - date.setMilliseconds(date.getMilliseconds() - 1); - return date; +function endOfISOWeek(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate, { + weekStartsOn: 1 + }); } module.exports = exports.default; @@ -10339,7 +10339,7 @@ module.exports = exports.default; /***/ }), -/***/ 2168: +/***/ 7128: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -10348,438 +10348,418 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = format; +exports["default"] = formatDistanceStrict; -var _index = _interopRequireDefault(__nccwpck_require__(9920)); +var _index = __nccwpck_require__(9307); -var _index2 = _interopRequireDefault(__nccwpck_require__(7923)); +var _index2 = _interopRequireDefault(__nccwpck_require__(7032)); -var _index3 = _interopRequireDefault(__nccwpck_require__(6477)); +var _index3 = _interopRequireDefault(__nccwpck_require__(9818)); -var _index4 = _interopRequireDefault(__nccwpck_require__(9257)); +var _index4 = _interopRequireDefault(__nccwpck_require__(6477)); -var _index5 = _interopRequireDefault(__nccwpck_require__(8387)); +var _index5 = _interopRequireDefault(__nccwpck_require__(7934)); -var _index6 = _interopRequireDefault(__nccwpck_require__(7032)); - -var _index7 = __nccwpck_require__(2509); - -var _index8 = _interopRequireDefault(__nccwpck_require__(1985)); - -var _index9 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index6 = _interopRequireDefault(__nccwpck_require__(2631)); -var _index10 = __nccwpck_require__(9307); +var _index7 = _interopRequireDefault(__nccwpck_require__(618)); -var _index11 = _interopRequireDefault(__nccwpck_require__(618)); +var _index8 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -// This RegExp consists of three parts separated by `|`: -// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token -// (one of the certain letters followed by `o`) -// - (\w)\1* matches any sequences of the same letter -// - '' matches two quote characters in a row -// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), -// except a single quote symbol, which ends the sequence. -// Two quote characters do not end the sequence. -// If there is no matching single quote -// then the sequence will continue until the end of the string. -// - . matches any single character unmatched by previous parts of the RegExps -var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also -// sequences of symbols P, p, and the combinations like `PPPPPPPppppp` - -var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; -var escapedStringRegExp = /^'([^]*?)'?$/; -var doubleQuoteRegExp = /''/g; -var unescapedLatinCharacterRegExp = /[a-zA-Z]/; +var MILLISECONDS_IN_MINUTE = 1000 * 60; +var MINUTES_IN_DAY = 60 * 24; +var MINUTES_IN_MONTH = MINUTES_IN_DAY * 30; +var MINUTES_IN_YEAR = MINUTES_IN_DAY * 365; /** - * @name format + * @name formatDistanceStrict * @category Common Helpers - * @summary Format the date. + * @summary Return the distance between the given dates in words. * * @description - * Return the formatted date string in the given format. The result may vary by locale. - * - * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. - * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * Return the distance between the given dates in words, using strict units. + * This is like `formatDistance`, but does not use helpers like 'almost', 'over', + * 'less than' and the like. * - * The characters wrapped between two single quotes characters (') are escaped. - * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. - * (see the last example) + * | Distance between dates | Result | + * |------------------------|---------------------| + * | 0 ... 59 secs | [0..59] seconds | + * | 1 ... 59 mins | [1..59] minutes | + * | 1 ... 23 hrs | [1..23] hours | + * | 1 ... 29 days | [1..29] days | + * | 1 ... 11 months | [1..11] months | + * | 1 ... N years | [1..N] years | * - * Format of the string is based on Unicode Technical Standard #35: - * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table - * with a few additions (see note 7 below the table). + * @param {Date|Number} date - the date + * @param {Date|Number} baseDate - the date to compare with + * @param {Object} [options] - an object with options. + * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first + * @param {'second'|'minute'|'hour'|'day'|'month'|'year'} [options.unit] - if specified, will force a unit + * @param {'floor'|'ceil'|'round'} [options.roundingMethod='round'] - which way to round partial units + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @returns {String} the distance in words + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `date` must not be Invalid Date + * @throws {RangeError} `baseDate` must not be Invalid Date + * @throws {RangeError} `options.roundingMethod` must be 'floor', 'ceil' or 'round' + * @throws {RangeError} `options.unit` must be 'second', 'minute', 'hour', 'day', 'month' or 'year' + * @throws {RangeError} `options.locale` must contain `formatDistance` property * - * Accepted patterns: - * | Unit | Pattern | Result examples | Notes | - * |---------------------------------|---------|-----------------------------------|-------| - * | Era | G..GGG | AD, BC | | - * | | GGGG | Anno Domini, Before Christ | 2 | - * | | GGGGG | A, B | | - * | Calendar year | y | 44, 1, 1900, 2017 | 5 | - * | | yo | 44th, 1st, 0th, 17th | 5,7 | - * | | yy | 44, 01, 00, 17 | 5 | - * | | yyy | 044, 001, 1900, 2017 | 5 | - * | | yyyy | 0044, 0001, 1900, 2017 | 5 | - * | | yyyyy | ... | 3,5 | - * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 | - * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 | - * | | YY | 44, 01, 00, 17 | 5,8 | - * | | YYY | 044, 001, 1900, 2017 | 5 | - * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 | - * | | YYYYY | ... | 3,5 | - * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 | - * | | RR | -43, 00, 01, 1900, 2017 | 5,7 | - * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 | - * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 | - * | | RRRRR | ... | 3,5,7 | - * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 | - * | | uu | -43, 01, 1900, 2017 | 5 | - * | | uuu | -043, 001, 1900, 2017 | 5 | - * | | uuuu | -0043, 0001, 1900, 2017 | 5 | - * | | uuuuu | ... | 3,5 | - * | Quarter (formatting) | Q | 1, 2, 3, 4 | | - * | | Qo | 1st, 2nd, 3rd, 4th | 7 | - * | | QQ | 01, 02, 03, 04 | | - * | | QQQ | Q1, Q2, Q3, Q4 | | - * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | - * | | QQQQQ | 1, 2, 3, 4 | 4 | - * | Quarter (stand-alone) | q | 1, 2, 3, 4 | | - * | | qo | 1st, 2nd, 3rd, 4th | 7 | - * | | qq | 01, 02, 03, 04 | | - * | | qqq | Q1, Q2, Q3, Q4 | | - * | | qqqq | 1st quarter, 2nd quarter, ... | 2 | - * | | qqqqq | 1, 2, 3, 4 | 4 | - * | Month (formatting) | M | 1, 2, ..., 12 | | - * | | Mo | 1st, 2nd, ..., 12th | 7 | - * | | MM | 01, 02, ..., 12 | | - * | | MMM | Jan, Feb, ..., Dec | | - * | | MMMM | January, February, ..., December | 2 | - * | | MMMMM | J, F, ..., D | | - * | Month (stand-alone) | L | 1, 2, ..., 12 | | - * | | Lo | 1st, 2nd, ..., 12th | 7 | - * | | LL | 01, 02, ..., 12 | | - * | | LLL | Jan, Feb, ..., Dec | | - * | | LLLL | January, February, ..., December | 2 | - * | | LLLLL | J, F, ..., D | | - * | Local week of year | w | 1, 2, ..., 53 | | - * | | wo | 1st, 2nd, ..., 53th | 7 | - * | | ww | 01, 02, ..., 53 | | - * | ISO week of year | I | 1, 2, ..., 53 | 7 | - * | | Io | 1st, 2nd, ..., 53th | 7 | - * | | II | 01, 02, ..., 53 | 7 | - * | Day of month | d | 1, 2, ..., 31 | | - * | | do | 1st, 2nd, ..., 31st | 7 | - * | | dd | 01, 02, ..., 31 | | - * | Day of year | D | 1, 2, ..., 365, 366 | 9 | - * | | Do | 1st, 2nd, ..., 365th, 366th | 7 | - * | | DD | 01, 02, ..., 365, 366 | 9 | - * | | DDD | 001, 002, ..., 365, 366 | | - * | | DDDD | ... | 3 | - * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | | - * | | EEEE | Monday, Tuesday, ..., Sunday | 2 | - * | | EEEEE | M, T, W, T, F, S, S | | - * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | - * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 | - * | | io | 1st, 2nd, ..., 7th | 7 | - * | | ii | 01, 02, ..., 07 | 7 | - * | | iii | Mon, Tue, Wed, ..., Sun | 7 | - * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 | - * | | iiiii | M, T, W, T, F, S, S | 7 | - * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 | - * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | | - * | | eo | 2nd, 3rd, ..., 1st | 7 | - * | | ee | 02, 03, ..., 01 | | - * | | eee | Mon, Tue, Wed, ..., Sun | | - * | | eeee | Monday, Tuesday, ..., Sunday | 2 | - * | | eeeee | M, T, W, T, F, S, S | | - * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | - * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | | - * | | co | 2nd, 3rd, ..., 1st | 7 | - * | | cc | 02, 03, ..., 01 | | - * | | ccc | Mon, Tue, Wed, ..., Sun | | - * | | cccc | Monday, Tuesday, ..., Sunday | 2 | - * | | ccccc | M, T, W, T, F, S, S | | - * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | - * | AM, PM | a..aa | AM, PM | | - * | | aaa | am, pm | | - * | | aaaa | a.m., p.m. | 2 | - * | | aaaaa | a, p | | - * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | | - * | | bbb | am, pm, noon, midnight | | - * | | bbbb | a.m., p.m., noon, midnight | 2 | - * | | bbbbb | a, p, n, mi | | - * | Flexible day period | B..BBB | at night, in the morning, ... | | - * | | BBBB | at night, in the morning, ... | 2 | - * | | BBBBB | at night, in the morning, ... | | - * | Hour [1-12] | h | 1, 2, ..., 11, 12 | | - * | | ho | 1st, 2nd, ..., 11th, 12th | 7 | - * | | hh | 01, 02, ..., 11, 12 | | - * | Hour [0-23] | H | 0, 1, 2, ..., 23 | | - * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 | - * | | HH | 00, 01, 02, ..., 23 | | - * | Hour [0-11] | K | 1, 2, ..., 11, 0 | | - * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 | - * | | KK | 01, 02, ..., 11, 00 | | - * | Hour [1-24] | k | 24, 1, 2, ..., 23 | | - * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 | - * | | kk | 24, 01, 02, ..., 23 | | - * | Minute | m | 0, 1, ..., 59 | | - * | | mo | 0th, 1st, ..., 59th | 7 | - * | | mm | 00, 01, ..., 59 | | - * | Second | s | 0, 1, ..., 59 | | - * | | so | 0th, 1st, ..., 59th | 7 | - * | | ss | 00, 01, ..., 59 | | - * | Fraction of second | S | 0, 1, ..., 9 | | - * | | SS | 00, 01, ..., 99 | | - * | | SSS | 000, 001, ..., 999 | | - * | | SSSS | ... | 3 | - * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | | - * | | XX | -0800, +0530, Z | | - * | | XXX | -08:00, +05:30, Z | | - * | | XXXX | -0800, +0530, Z, +123456 | 2 | - * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | - * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | | - * | | xx | -0800, +0530, +0000 | | - * | | xxx | -08:00, +05:30, +00:00 | 2 | - * | | xxxx | -0800, +0530, +0000, +123456 | | - * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | - * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | | - * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 | - * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 | - * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 | - * | Seconds timestamp | t | 512969520 | 7 | - * | | tt | ... | 3,7 | - * | Milliseconds timestamp | T | 512969520900 | 7 | - * | | TT | ... | 3,7 | - * | Long localized date | P | 04/29/1453 | 7 | - * | | PP | Apr 29, 1453 | 7 | - * | | PPP | April 29th, 1453 | 7 | - * | | PPPP | Friday, April 29th, 1453 | 2,7 | - * | Long localized time | p | 12:00 AM | 7 | - * | | pp | 12:00:00 AM | 7 | - * | | ppp | 12:00:00 AM GMT+2 | 7 | - * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 | - * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 | - * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 | - * | | PPPppp | April 29th, 1453 at ... | 7 | - * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 | - * Notes: - * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale - * are the same as "stand-alone" units, but are different in some languages. - * "Formatting" units are declined according to the rules of the language - * in the context of a date. "Stand-alone" units are always nominative singular: + * @example + * // What is the distance between 2 July 2014 and 1 January 2015? + * const result = formatDistanceStrict(new Date(2014, 6, 2), new Date(2015, 0, 2)) + * //=> '6 months' * - * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` + * @example + * // What is the distance between 1 January 2015 00:00:15 + * // and 1 January 2015 00:00:00? + * const result = formatDistanceStrict( + * new Date(2015, 0, 1, 0, 0, 15), + * new Date(2015, 0, 1, 0, 0, 0) + * ) + * //=> '15 seconds' * - * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` + * @example + * // What is the distance from 1 January 2016 + * // to 1 January 2015, with a suffix? + * const result = formatDistanceStrict(new Date(2015, 0, 1), new Date(2016, 0, 1), { + * addSuffix: true + * }) + * //=> '1 year ago' * - * 2. Any sequence of the identical letters is a pattern, unless it is escaped by - * the single quote characters (see below). - * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`) - * the output will be the same as default pattern for this unit, usually - * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units - * are marked with "2" in the last column of the table. - * - * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'` - * - * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'` - * - * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'` - * - * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'` - * - * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'` - * - * 3. Some patterns could be unlimited length (such as `yyyyyyyy`). - * The output will be padded with zeros to match the length of the pattern. - * - * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'` - * - * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. - * These tokens represent the shortest form of the quarter. - * - * 5. The main difference between `y` and `u` patterns are B.C. years: - * - * | Year | `y` | `u` | - * |------|-----|-----| - * | AC 1 | 1 | 1 | - * | BC 1 | 1 | 0 | - * | BC 2 | 2 | -1 | - * - * Also `yy` always returns the last two digits of a year, - * while `uu` pads single digit years to 2 characters and returns other years unchanged: - * - * | Year | `yy` | `uu` | - * |------|------|------| - * | 1 | 01 | 01 | - * | 14 | 14 | 14 | - * | 376 | 76 | 376 | - * | 1453 | 53 | 1453 | - * - * The same difference is true for local and ISO week-numbering years (`Y` and `R`), - * except local week-numbering years are dependent on `options.weekStartsOn` - * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear} - * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}). - * - * 6. Specific non-location timezones are currently unavailable in `date-fns`, - * so right now these tokens fall back to GMT timezones. - * - * 7. These patterns are not in the Unicode Technical Standard #35: - * - `i`: ISO day of week - * - `I`: ISO week of year - * - `R`: ISO week-numbering year - * - `t`: seconds timestamp - * - `T`: milliseconds timestamp - * - `o`: ordinal number modifier - * - `P`: long localized date - * - `p`: long localized time - * - * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. - * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * - * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month. - * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * - * @param {Date|Number} date - the original date - * @param {String} format - the string of tokens - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is - * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; - * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; - * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @returns {String} the formatted date string - * @throws {TypeError} 2 arguments required - * @throws {RangeError} `date` must not be Invalid Date - * @throws {RangeError} `options.locale` must contain `localize` property - * @throws {RangeError} `options.locale` must contain `formatLong` property - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 - * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} format string contains an unescaped latin alphabet character + * @example + * // What is the distance from 1 January 2016 + * // to 1 January 2015, in minutes? + * const result = formatDistanceStrict(new Date(2016, 0, 1), new Date(2015, 0, 1), { + * unit: 'minute' + * }) + * //=> '525600 minutes' * * @example - * // Represent 11 February 2014 in middle-endian format: - * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy') - * //=> '02/11/2014' + * // What is the distance from 1 January 2015 + * // to 28 January 2015, in months, rounded up? + * const result = formatDistanceStrict(new Date(2015, 0, 28), new Date(2015, 0, 1), { + * unit: 'month', + * roundingMethod: 'ceil' + * }) + * //=> '1 month' * * @example - * // Represent 2 July 2014 in Esperanto: + * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? * import { eoLocale } from 'date-fns/locale/eo' - * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", { + * const result = formatDistanceStrict(new Date(2016, 7, 1), new Date(2015, 0, 1), { * locale: eoLocale * }) - * //=> '2-a de julio 2014' - * - * @example - * // Escape string by single quote characters: - * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'") - * //=> "3 o'clock" + * //=> '1 jaro' */ -function format(dirtyDate, dirtyFormatStr, options) { - var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; +function formatDistanceStrict(dirtyDate, dirtyBaseDate, options) { + var _ref, _options$locale, _options$roundingMeth; - (0, _index9.default)(2, arguments); - var formatStr = String(dirtyFormatStr); - var defaultOptions = (0, _index10.getDefaultOptions)(); - var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : _index11.default; - var firstWeekContainsDate = (0, _index8.default)((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN + (0, _index8.default)(2, arguments); + var defaultOptions = (0, _index.getDefaultOptions)(); + var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : _index7.default; - if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { - throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); + if (!locale.formatDistance) { + throw new RangeError('locale must contain localize.formatDistance property'); } - var weekStartsOn = (0, _index8.default)((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + var comparison = (0, _index3.default)(dirtyDate, dirtyBaseDate); - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + if (isNaN(comparison)) { + throw new RangeError('Invalid time value'); } - if (!locale.localize) { - throw new RangeError('locale must contain localize property'); - } + var localizeOptions = (0, _index6.default)((0, _index5.default)(options), { + addSuffix: Boolean(options === null || options === void 0 ? void 0 : options.addSuffix), + comparison: comparison + }); + var dateLeft; + var dateRight; - if (!locale.formatLong) { - throw new RangeError('locale must contain formatLong property'); + if (comparison > 0) { + dateLeft = (0, _index4.default)(dirtyBaseDate); + dateRight = (0, _index4.default)(dirtyDate); + } else { + dateLeft = (0, _index4.default)(dirtyDate); + dateRight = (0, _index4.default)(dirtyBaseDate); } - var originalDate = (0, _index3.default)(dirtyDate); + var roundingMethod = String((_options$roundingMeth = options === null || options === void 0 ? void 0 : options.roundingMethod) !== null && _options$roundingMeth !== void 0 ? _options$roundingMeth : 'round'); + var roundingMethodFn; - if (!(0, _index.default)(originalDate)) { - throw new RangeError('Invalid time value'); - } // Convert the date in system timezone to the same date in UTC+00:00 timezone. - // This ensures that when UTC functions will be implemented, locales will be compatible with them. - // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376 + if (roundingMethod === 'floor') { + roundingMethodFn = Math.floor; + } else if (roundingMethod === 'ceil') { + roundingMethodFn = Math.ceil; + } else if (roundingMethod === 'round') { + roundingMethodFn = Math.round; + } else { + throw new RangeError("roundingMethod must be 'floor', 'ceil' or 'round'"); + } + var milliseconds = dateRight.getTime() - dateLeft.getTime(); + var minutes = milliseconds / MILLISECONDS_IN_MINUTE; + var timezoneOffset = (0, _index2.default)(dateRight) - (0, _index2.default)(dateLeft); // Use DST-normalized difference in minutes for years, months and days; + // use regular difference in minutes for hours, minutes and seconds. - var timezoneOffset = (0, _index6.default)(originalDate); - var utcDate = (0, _index2.default)(originalDate, timezoneOffset); - var formatterOptions = { - firstWeekContainsDate: firstWeekContainsDate, - weekStartsOn: weekStartsOn, - locale: locale, - _originalDate: originalDate - }; - var result = formatStr.match(longFormattingTokensRegExp).map(function (substring) { - var firstCharacter = substring[0]; + var dstNormalizedMinutes = (milliseconds - timezoneOffset) / MILLISECONDS_IN_MINUTE; + var defaultUnit = options === null || options === void 0 ? void 0 : options.unit; + var unit; - if (firstCharacter === 'p' || firstCharacter === 'P') { - var longFormatter = _index5.default[firstCharacter]; - return longFormatter(substring, locale.formatLong); + if (!defaultUnit) { + if (minutes < 1) { + unit = 'second'; + } else if (minutes < 60) { + unit = 'minute'; + } else if (minutes < MINUTES_IN_DAY) { + unit = 'hour'; + } else if (dstNormalizedMinutes < MINUTES_IN_MONTH) { + unit = 'day'; + } else if (dstNormalizedMinutes < MINUTES_IN_YEAR) { + unit = 'month'; + } else { + unit = 'year'; } + } else { + unit = String(defaultUnit); + } // 0 up to 60 seconds - return substring; - }).join('').match(formattingTokensRegExp).map(function (substring) { - // Replace two single quote characters with one single quote character - if (substring === "''") { - return "'"; - } - var firstCharacter = substring[0]; + if (unit === 'second') { + var seconds = roundingMethodFn(milliseconds / 1000); + return locale.formatDistance('xSeconds', seconds, localizeOptions); // 1 up to 60 mins + } else if (unit === 'minute') { + var roundedMinutes = roundingMethodFn(minutes); + return locale.formatDistance('xMinutes', roundedMinutes, localizeOptions); // 1 up to 24 hours + } else if (unit === 'hour') { + var hours = roundingMethodFn(minutes / 60); + return locale.formatDistance('xHours', hours, localizeOptions); // 1 up to 30 days + } else if (unit === 'day') { + var days = roundingMethodFn(dstNormalizedMinutes / MINUTES_IN_DAY); + return locale.formatDistance('xDays', days, localizeOptions); // 1 up to 12 months + } else if (unit === 'month') { + var months = roundingMethodFn(dstNormalizedMinutes / MINUTES_IN_MONTH); + return months === 12 && defaultUnit !== 'month' ? locale.formatDistance('xYears', 1, localizeOptions) : locale.formatDistance('xMonths', months, localizeOptions); // 1 year up to max Date + } else if (unit === 'year') { + var years = roundingMethodFn(dstNormalizedMinutes / MINUTES_IN_YEAR); + return locale.formatDistance('xYears', years, localizeOptions); + } - if (firstCharacter === "'") { - return cleanEscapedString(substring); - } + throw new RangeError("unit must be 'second', 'minute', 'hour', 'day', 'month' or 'year'"); +} - var formatter = _index4.default[firstCharacter]; +module.exports = exports.default; - if (formatter) { - if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && (0, _index7.isProtectedWeekYearToken)(substring)) { - (0, _index7.throwProtectedError)(substring, dirtyFormatStr, String(dirtyDate)); - } +/***/ }), - if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && (0, _index7.isProtectedDayOfYearToken)(substring)) { - (0, _index7.throwProtectedError)(substring, dirtyFormatStr, String(dirtyDate)); - } +/***/ 4741: +/***/ ((module, exports, __nccwpck_require__) => { - return formatter(utcDate, substring, locale.localize, formatterOptions); - } +"use strict"; - if (firstCharacter.match(unescapedLatinCharacterRegExp)) { - throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); - } - return substring; - }).join(''); - return result; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = formatDistanceToNowStrict; + +var _index = _interopRequireDefault(__nccwpck_require__(7128)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name formatDistanceToNowStrict + * @category Common Helpers + * @summary Return the distance between the given date and now in words. + * @pure false + * + * @description + * Return the distance between the given dates in words, using strict units. + * This is like `formatDistance`, but does not use helpers like 'almost', 'over', + * 'less than' and the like. + * + * | Distance between dates | Result | + * |------------------------|---------------------| + * | 0 ... 59 secs | [0..59] seconds | + * | 1 ... 59 mins | [1..59] minutes | + * | 1 ... 23 hrs | [1..23] hours | + * | 1 ... 29 days | [1..29] days | + * | 1 ... 11 months | [1..11] months | + * | 1 ... N years | [1..N] years | + * + * @param {Date|Number} date - the given date + * @param {Object} [options] - an object with options. + * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first + * @param {'second'|'minute'|'hour'|'day'|'month'|'year'} [options.unit] - if specified, will force a unit + * @param {'floor'|'ceil'|'round'} [options.roundingMethod='round'] - which way to round partial units + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @returns {String} the distance in words + * @throws {TypeError} 1 argument required + * @throws {RangeError} `date` must not be Invalid Date + * @throws {RangeError} `options.locale` must contain `formatDistance` property + * + * @example + * // If today is 1 January 2015, what is the distance to 2 July 2014? + * const result = formatDistanceToNowStrict( + * new Date(2014, 6, 2) + * ) + * //=> '6 months' + * + * @example + * // If now is 1 January 2015 00:00:00, + * // what is the distance to 1 January 2015 00:00:15, including seconds? + * const result = formatDistanceToNowStrict( + * new Date(2015, 0, 1, 0, 0, 15) + * ) + * //=> '15 seconds' + * + * @example + * // If today is 1 January 2015, + * // what is the distance to 1 January 2016, with a suffix? + * const result = formatDistanceToNowStrict( + * new Date(2016, 0, 1), + * {addSuffix: true} + * ) + * //=> 'in 1 year' + * + * @example + * // If today is 28 January 2015, + * // what is the distance to 1 January 2015, in months, rounded up?? + * const result = formatDistanceToNowStrict(new Date(2015, 0, 1), { + * unit: 'month', + * roundingMethod: 'ceil' + * }) + * //=> '1 month' + * + * @example + * // If today is 1 January 2015, + * // what is the distance to 1 January 2016 in Esperanto? + * const eoLocale = require('date-fns/locale/eo') + * const result = formatDistanceToNowStrict( + * new Date(2016, 0, 1), + * {locale: eoLocale} + * ) + * //=> '1 jaro' + */ +function formatDistanceToNowStrict(dirtyDate, options) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate, Date.now(), options); } -function cleanEscapedString(input) { - var matched = input.match(escapedStringRegExp); +module.exports = exports.default; - if (!matched) { - return input; - } +/***/ }), - return matched[1].replace(doubleQuoteRegExp, "'"); +/***/ 1163: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = formatDistanceToNow; + +var _index = _interopRequireDefault(__nccwpck_require__(8149)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name formatDistanceToNow + * @category Common Helpers + * @summary Return the distance between the given date and now in words. + * @pure false + * + * @description + * Return the distance between the given date and now in words. + * + * | Distance to now | Result | + * |-------------------------------------------------------------------|---------------------| + * | 0 ... 30 secs | less than a minute | + * | 30 secs ... 1 min 30 secs | 1 minute | + * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | + * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | + * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | + * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | + * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | + * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | + * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | + * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | + * | 1 yr ... 1 yr 3 months | about 1 year | + * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | + * | 1 yr 9 months ... 2 yrs | almost 2 years | + * | N yrs ... N yrs 3 months | about N years | + * | N yrs 3 months ... N yrs 9 months | over N years | + * | N yrs 9 months ... N+1 yrs | almost N+1 years | + * + * With `options.includeSeconds == true`: + * | Distance to now | Result | + * |---------------------|----------------------| + * | 0 secs ... 5 secs | less than 5 seconds | + * | 5 secs ... 10 secs | less than 10 seconds | + * | 10 secs ... 20 secs | less than 20 seconds | + * | 20 secs ... 40 secs | half a minute | + * | 40 secs ... 60 secs | less than a minute | + * | 60 secs ... 90 secs | 1 minute | + * + * > ⚠️ Please note that this function is not present in the FP submodule as + * > it uses `Date.now()` internally hence impure and can't be safely curried. + * + * @param {Date|Number} date - the given date + * @param {Object} [options] - the object with options + * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed + * @param {Boolean} [options.addSuffix=false] - result specifies if now is earlier or later than the passed date + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @returns {String} the distance in words + * @throws {TypeError} 1 argument required + * @throws {RangeError} `date` must not be Invalid Date + * @throws {RangeError} `options.locale` must contain `formatDistance` property + * + * @example + * // If today is 1 January 2015, what is the distance to 2 July 2014? + * const result = formatDistanceToNow( + * new Date(2014, 6, 2) + * ) + * //=> '6 months' + * + * @example + * // If now is 1 January 2015 00:00:00, + * // what is the distance to 1 January 2015 00:00:15, including seconds? + * const result = formatDistanceToNow( + * new Date(2015, 0, 1, 0, 0, 15), + * {includeSeconds: true} + * ) + * //=> 'less than 20 seconds' + * + * @example + * // If today is 1 January 2015, + * // what is the distance to 1 January 2016, with a suffix? + * const result = formatDistanceToNow( + * new Date(2016, 0, 1), + * {addSuffix: true} + * ) + * //=> 'in about 1 year' + * + * @example + * // If today is 1 January 2015, + * // what is the distance to 1 August 2016 in Esperanto? + * const eoLocale = require('date-fns/locale/eo') + * const result = formatDistanceToNow( + * new Date(2016, 7, 1), + * {locale: eoLocale} + * ) + * //=> 'pli ol 1 jaro' + */ +function formatDistanceToNow(dirtyDate, options) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate, Date.now(), options); } module.exports = exports.default; @@ -11004,7 +10984,7 @@ module.exports = exports.default; /***/ }), -/***/ 7128: +/***/ 8917: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -11013,213 +10993,115 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = formatDistanceStrict; +exports["default"] = formatDuration; var _index = __nccwpck_require__(9307); -var _index2 = _interopRequireDefault(__nccwpck_require__(7032)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(9818)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index5 = _interopRequireDefault(__nccwpck_require__(7934)); - -var _index6 = _interopRequireDefault(__nccwpck_require__(2631)); - -var _index7 = _interopRequireDefault(__nccwpck_require__(618)); - -var _index8 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(618)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var MILLISECONDS_IN_MINUTE = 1000 * 60; -var MINUTES_IN_DAY = 60 * 24; -var MINUTES_IN_MONTH = MINUTES_IN_DAY * 30; -var MINUTES_IN_YEAR = MINUTES_IN_DAY * 365; +var defaultFormat = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds']; /** - * @name formatDistanceStrict + * @name formatDuration * @category Common Helpers - * @summary Return the distance between the given dates in words. + * @summary Formats a duration in human-readable format * * @description - * Return the distance between the given dates in words, using strict units. - * This is like `formatDistance`, but does not use helpers like 'almost', 'over', - * 'less than' and the like. - * - * | Distance between dates | Result | - * |------------------------|---------------------| - * | 0 ... 59 secs | [0..59] seconds | - * | 1 ... 59 mins | [1..59] minutes | - * | 1 ... 23 hrs | [1..23] hours | - * | 1 ... 29 days | [1..29] days | - * | 1 ... 11 months | [1..11] months | - * | 1 ... N years | [1..N] years | + * Return human-readable duration string i.e. "9 months 2 days" * - * @param {Date|Number} date - the date - * @param {Date|Number} baseDate - the date to compare with + * @param {Duration} duration - the duration to format * @param {Object} [options] - an object with options. - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {'second'|'minute'|'hour'|'day'|'month'|'year'} [options.unit] - if specified, will force a unit - * @param {'floor'|'ceil'|'round'} [options.roundingMethod='round'] - which way to round partial units + * @param {string[]} [options.format=['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds']] - the array of units to format + * @param {boolean} [options.zero=false] - should zeros be included in the output? + * @param {string} [options.delimiter=' '] - delimiter string * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @returns {String} the distance in words - * @throws {TypeError} 2 arguments required - * @throws {RangeError} `date` must not be Invalid Date - * @throws {RangeError} `baseDate` must not be Invalid Date - * @throws {RangeError} `options.roundingMethod` must be 'floor', 'ceil' or 'round' - * @throws {RangeError} `options.unit` must be 'second', 'minute', 'hour', 'day', 'month' or 'year' - * @throws {RangeError} `options.locale` must contain `formatDistance` property - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * const result = formatDistanceStrict(new Date(2014, 6, 2), new Date(2015, 0, 2)) - * //=> '6 months' + * @returns {string} the formatted date string + * @throws {TypeError} 1 argument required * * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00? - * const result = formatDistanceStrict( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0) - * ) - * //=> '15 seconds' + * // Format full duration + * formatDuration({ + * years: 2, + * months: 9, + * weeks: 1, + * days: 7, + * hours: 5, + * minutes: 9, + * seconds: 30 + * }) + * //=> '2 years 9 months 1 week 7 days 5 hours 9 minutes 30 seconds' * * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * const result = formatDistanceStrict(new Date(2015, 0, 1), new Date(2016, 0, 1), { - * addSuffix: true - * }) - * //=> '1 year ago' + * // Format partial duration + * formatDuration({ months: 9, days: 2 }) + * //=> '9 months 2 days' * * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, in minutes? - * const result = formatDistanceStrict(new Date(2016, 0, 1), new Date(2015, 0, 1), { - * unit: 'minute' - * }) - * //=> '525600 minutes' + * // Customize the format + * formatDuration( + * { + * years: 2, + * months: 9, + * weeks: 1, + * days: 7, + * hours: 5, + * minutes: 9, + * seconds: 30 + * }, + * { format: ['months', 'weeks'] } + * ) === '9 months 1 week' * * @example - * // What is the distance from 1 January 2015 - * // to 28 January 2015, in months, rounded up? - * const result = formatDistanceStrict(new Date(2015, 0, 28), new Date(2015, 0, 1), { - * unit: 'month', - * roundingMethod: 'ceil' - * }) - * //=> '1 month' + * // Customize the zeros presence + * formatDuration({ years: 0, months: 9 }) + * //=> '9 months' + * formatDuration({ years: 0, months: 9 }, { zero: true }) + * //=> '0 years 9 months' * * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * import { eoLocale } from 'date-fns/locale/eo' - * const result = formatDistanceStrict(new Date(2016, 7, 1), new Date(2015, 0, 1), { - * locale: eoLocale - * }) - * //=> '1 jaro' + * // Customize the delimiter + * formatDuration({ years: 2, months: 9, weeks: 3 }, { delimiter: ', ' }) + * //=> '2 years, 9 months, 3 weeks' */ -function formatDistanceStrict(dirtyDate, dirtyBaseDate, options) { - var _ref, _options$locale, _options$roundingMeth; - - (0, _index8.default)(2, arguments); - var defaultOptions = (0, _index.getDefaultOptions)(); - var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : _index7.default; - - if (!locale.formatDistance) { - throw new RangeError('locale must contain localize.formatDistance property'); - } - - var comparison = (0, _index3.default)(dirtyDate, dirtyBaseDate); - - if (isNaN(comparison)) { - throw new RangeError('Invalid time value'); - } - - var localizeOptions = (0, _index6.default)((0, _index5.default)(options), { - addSuffix: Boolean(options === null || options === void 0 ? void 0 : options.addSuffix), - comparison: comparison - }); - var dateLeft; - var dateRight; +function formatDuration(duration, options) { + var _ref, _options$locale, _options$format, _options$zero, _options$delimiter; - if (comparison > 0) { - dateLeft = (0, _index4.default)(dirtyBaseDate); - dateRight = (0, _index4.default)(dirtyDate); - } else { - dateLeft = (0, _index4.default)(dirtyDate); - dateRight = (0, _index4.default)(dirtyBaseDate); + if (arguments.length < 1) { + throw new TypeError("1 argument required, but only ".concat(arguments.length, " present")); } - var roundingMethod = String((_options$roundingMeth = options === null || options === void 0 ? void 0 : options.roundingMethod) !== null && _options$roundingMeth !== void 0 ? _options$roundingMeth : 'round'); - var roundingMethodFn; + var defaultOptions = (0, _index.getDefaultOptions)(); + var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : _index2.default; + var format = (_options$format = options === null || options === void 0 ? void 0 : options.format) !== null && _options$format !== void 0 ? _options$format : defaultFormat; + var zero = (_options$zero = options === null || options === void 0 ? void 0 : options.zero) !== null && _options$zero !== void 0 ? _options$zero : false; + var delimiter = (_options$delimiter = options === null || options === void 0 ? void 0 : options.delimiter) !== null && _options$delimiter !== void 0 ? _options$delimiter : ' '; - if (roundingMethod === 'floor') { - roundingMethodFn = Math.floor; - } else if (roundingMethod === 'ceil') { - roundingMethodFn = Math.ceil; - } else if (roundingMethod === 'round') { - roundingMethodFn = Math.round; - } else { - throw new RangeError("roundingMethod must be 'floor', 'ceil' or 'round'"); + if (!locale.formatDistance) { + return ''; } - var milliseconds = dateRight.getTime() - dateLeft.getTime(); - var minutes = milliseconds / MILLISECONDS_IN_MINUTE; - var timezoneOffset = (0, _index2.default)(dateRight) - (0, _index2.default)(dateLeft); // Use DST-normalized difference in minutes for years, months and days; - // use regular difference in minutes for hours, minutes and seconds. - - var dstNormalizedMinutes = (milliseconds - timezoneOffset) / MILLISECONDS_IN_MINUTE; - var defaultUnit = options === null || options === void 0 ? void 0 : options.unit; - var unit; + var result = format.reduce(function (acc, unit) { + var token = "x".concat(unit.replace(/(^.)/, function (m) { + return m.toUpperCase(); + })); + var value = duration[unit]; - if (!defaultUnit) { - if (minutes < 1) { - unit = 'second'; - } else if (minutes < 60) { - unit = 'minute'; - } else if (minutes < MINUTES_IN_DAY) { - unit = 'hour'; - } else if (dstNormalizedMinutes < MINUTES_IN_MONTH) { - unit = 'day'; - } else if (dstNormalizedMinutes < MINUTES_IN_YEAR) { - unit = 'month'; - } else { - unit = 'year'; + if (typeof value === 'number' && (zero || duration[unit])) { + return acc.concat(locale.formatDistance(token, value)); } - } else { - unit = String(defaultUnit); - } // 0 up to 60 seconds - - if (unit === 'second') { - var seconds = roundingMethodFn(milliseconds / 1000); - return locale.formatDistance('xSeconds', seconds, localizeOptions); // 1 up to 60 mins - } else if (unit === 'minute') { - var roundedMinutes = roundingMethodFn(minutes); - return locale.formatDistance('xMinutes', roundedMinutes, localizeOptions); // 1 up to 24 hours - } else if (unit === 'hour') { - var hours = roundingMethodFn(minutes / 60); - return locale.formatDistance('xHours', hours, localizeOptions); // 1 up to 30 days - } else if (unit === 'day') { - var days = roundingMethodFn(dstNormalizedMinutes / MINUTES_IN_DAY); - return locale.formatDistance('xDays', days, localizeOptions); // 1 up to 12 months - } else if (unit === 'month') { - var months = roundingMethodFn(dstNormalizedMinutes / MINUTES_IN_MONTH); - return months === 12 && defaultUnit !== 'month' ? locale.formatDistance('xYears', 1, localizeOptions) : locale.formatDistance('xMonths', months, localizeOptions); // 1 year up to max Date - } else if (unit === 'year') { - var years = roundingMethodFn(dstNormalizedMinutes / MINUTES_IN_YEAR); - return locale.formatDistance('xYears', years, localizeOptions); - } - - throw new RangeError("unit must be 'second', 'minute', 'hour', 'day', 'month' or 'year'"); + return acc; + }, []).join(delimiter); + return result; } module.exports = exports.default; /***/ }), -/***/ 1163: +/***/ 5296: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -11228,110 +11110,109 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = formatDistanceToNow; +exports["default"] = formatISO9075; -var _index = _interopRequireDefault(__nccwpck_require__(8149)); +var _index = _interopRequireDefault(__nccwpck_require__(6477)); -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(9920)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(8620)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name formatDistanceToNow + * @name formatISO9075 * @category Common Helpers - * @summary Return the distance between the given date and now in words. - * @pure false + * @summary Format the date according to the ISO 9075 standard (https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_get-format). * * @description - * Return the distance between the given date and now in words. - * - * | Distance to now | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance to now | Result | - * |---------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `Date.now()` internally hence impure and can't be safely curried. + * Return the formatted date string in ISO 9075 format. Options may be passed to control the parts and notations of the date. * - * @param {Date|Number} date - the given date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result specifies if now is earlier or later than the passed date - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @returns {String} the distance in words + * @param {Date|Number} date - the original date + * @param {Object} [options] - an object with options. + * @param {'extended'|'basic'} [options.format='extended'] - if 'basic', hide delimiters between date and time values. + * @param {'complete'|'date'|'time'} [options.representation='complete'] - format date, time, or both. + * @returns {String} the formatted date string * @throws {TypeError} 1 argument required * @throws {RangeError} `date` must not be Invalid Date - * @throws {RangeError} `options.locale` must contain `formatDistance` property + * @throws {RangeError} `options.format` must be 'extended' or 'basic' + * @throws {RangeError} `options.representation` must be 'date', 'time' or 'complete' * * @example - * // If today is 1 January 2015, what is the distance to 2 July 2014? - * const result = formatDistanceToNow( - * new Date(2014, 6, 2) - * ) - * //=> '6 months' + * // Represent 18 September 2019 in ISO 9075 format: + * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52)) + * //=> '2019-09-18 19:00:52' * * @example - * // If now is 1 January 2015 00:00:00, - * // what is the distance to 1 January 2015 00:00:15, including seconds? - * const result = formatDistanceToNow( - * new Date(2015, 0, 1, 0, 0, 15), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' + * // Represent 18 September 2019 in ISO 9075, short format: + * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' }) + * //=> '20190918 190052' * * @example - * // If today is 1 January 2015, - * // what is the distance to 1 January 2016, with a suffix? - * const result = formatDistanceToNow( - * new Date(2016, 0, 1), - * {addSuffix: true} - * ) - * //=> 'in about 1 year' + * // Represent 18 September 2019 in ISO 9075 format, date only: + * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' }) + * //=> '2019-09-18' * * @example - * // If today is 1 January 2015, - * // what is the distance to 1 August 2016 in Esperanto? - * const eoLocale = require('date-fns/locale/eo') - * const result = formatDistanceToNow( - * new Date(2016, 7, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' + * // Represent 18 September 2019 in ISO 9075 format, time only: + * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' }) + * //=> '19:00:52' */ -function formatDistanceToNow(dirtyDate, options) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate, Date.now(), options); +function formatISO9075(dirtyDate, options) { + var _options$format, _options$representati; + + if (arguments.length < 1) { + throw new TypeError("1 argument required, but only ".concat(arguments.length, " present")); + } + + var originalDate = (0, _index.default)(dirtyDate); + + if (!(0, _index2.default)(originalDate)) { + throw new RangeError('Invalid time value'); + } + + var format = String((_options$format = options === null || options === void 0 ? void 0 : options.format) !== null && _options$format !== void 0 ? _options$format : 'extended'); + var representation = String((_options$representati = options === null || options === void 0 ? void 0 : options.representation) !== null && _options$representati !== void 0 ? _options$representati : 'complete'); + + if (format !== 'extended' && format !== 'basic') { + throw new RangeError("format must be 'extended' or 'basic'"); + } + + if (representation !== 'date' && representation !== 'time' && representation !== 'complete') { + throw new RangeError("representation must be 'date', 'time', or 'complete'"); + } + + var result = ''; + var dateDelimiter = format === 'extended' ? '-' : ''; + var timeDelimiter = format === 'extended' ? ':' : ''; // Representation is either 'date' or 'complete' + + if (representation !== 'time') { + var day = (0, _index3.default)(originalDate.getDate(), 2); + var month = (0, _index3.default)(originalDate.getMonth() + 1, 2); + var year = (0, _index3.default)(originalDate.getFullYear(), 4); // yyyyMMdd or yyyy-MM-dd. + + result = "".concat(year).concat(dateDelimiter).concat(month).concat(dateDelimiter).concat(day); + } // Representation is either 'time' or 'complete' + + + if (representation !== 'date') { + var hour = (0, _index3.default)(originalDate.getHours(), 2); + var minute = (0, _index3.default)(originalDate.getMinutes(), 2); + var second = (0, _index3.default)(originalDate.getSeconds(), 2); // If there's also date, separate it with time with a space + + var separator = result === '' ? '' : ' '; // HHmmss or HH:mm:ss. + + result = "".concat(result).concat(separator).concat(hour).concat(timeDelimiter).concat(minute).concat(timeDelimiter).concat(second); + } + + return result; } module.exports = exports.default; /***/ }), -/***/ 4741: +/***/ 2448: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -11340,98 +11221,63 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = formatDistanceToNowStrict; - -var _index = _interopRequireDefault(__nccwpck_require__(7128)); +exports["default"] = formatISODuration; -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + /** - * @name formatDistanceToNowStrict + * @name formatISODuration * @category Common Helpers - * @summary Return the distance between the given date and now in words. - * @pure false + * @summary Format a duration object according as ISO 8601 duration string * * @description - * Return the distance between the given dates in words, using strict units. - * This is like `formatDistance`, but does not use helpers like 'almost', 'over', - * 'less than' and the like. - * - * | Distance between dates | Result | - * |------------------------|---------------------| - * | 0 ... 59 secs | [0..59] seconds | - * | 1 ... 59 mins | [1..59] minutes | - * | 1 ... 23 hrs | [1..23] hours | - * | 1 ... 29 days | [1..29] days | - * | 1 ... 11 months | [1..11] months | - * | 1 ... N years | [1..N] years | - * - * @param {Date|Number} date - the given date - * @param {Object} [options] - an object with options. - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {'second'|'minute'|'hour'|'day'|'month'|'year'} [options.unit] - if specified, will force a unit - * @param {'floor'|'ceil'|'round'} [options.roundingMethod='round'] - which way to round partial units - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @returns {String} the distance in words - * @throws {TypeError} 1 argument required - * @throws {RangeError} `date` must not be Invalid Date - * @throws {RangeError} `options.locale` must contain `formatDistance` property - * - * @example - * // If today is 1 January 2015, what is the distance to 2 July 2014? - * const result = formatDistanceToNowStrict( - * new Date(2014, 6, 2) - * ) - * //=> '6 months' + * Format a duration object according to the ISO 8601 duration standard (https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm) * - * @example - * // If now is 1 January 2015 00:00:00, - * // what is the distance to 1 January 2015 00:00:15, including seconds? - * const result = formatDistanceToNowStrict( - * new Date(2015, 0, 1, 0, 0, 15) - * ) - * //=> '15 seconds' + * @param {Duration} duration - the duration to format * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 January 2016, with a suffix? - * const result = formatDistanceToNowStrict( - * new Date(2016, 0, 1), - * {addSuffix: true} - * ) - * //=> 'in 1 year' + * @returns {String} The ISO 8601 duration string + * @throws {TypeError} Requires 1 argument + * @throws {Error} Argument must be an object * * @example - * // If today is 28 January 2015, - * // what is the distance to 1 January 2015, in months, rounded up?? - * const result = formatDistanceToNowStrict(new Date(2015, 0, 1), { - * unit: 'month', - * roundingMethod: 'ceil' + * // Format the given duration as ISO 8601 string + * const result = formatISODuration({ + * years: 39, + * months: 2, + * days: 20, + * hours: 7, + * minutes: 5, + * seconds: 0 * }) - * //=> '1 month' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 January 2016 in Esperanto? - * const eoLocale = require('date-fns/locale/eo') - * const result = formatDistanceToNowStrict( - * new Date(2016, 0, 1), - * {locale: eoLocale} - * ) - * //=> '1 jaro' + * //=> 'P39Y2M20DT0H0M0S' */ -function formatDistanceToNowStrict(dirtyDate, options) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate, Date.now(), options); +function formatISODuration(duration) { + (0, _index.default)(1, arguments); + if (_typeof(duration) !== 'object') throw new Error('Duration must be an object'); + var _duration$years = duration.years, + years = _duration$years === void 0 ? 0 : _duration$years, + _duration$months = duration.months, + months = _duration$months === void 0 ? 0 : _duration$months, + _duration$days = duration.days, + days = _duration$days === void 0 ? 0 : _duration$days, + _duration$hours = duration.hours, + hours = _duration$hours === void 0 ? 0 : _duration$hours, + _duration$minutes = duration.minutes, + minutes = _duration$minutes === void 0 ? 0 : _duration$minutes, + _duration$seconds = duration.seconds, + seconds = _duration$seconds === void 0 ? 0 : _duration$seconds; + return "P".concat(years, "Y").concat(months, "M").concat(days, "DT").concat(hours, "H").concat(minutes, "M").concat(seconds, "S"); } module.exports = exports.default; /***/ }), -/***/ 8917: +/***/ 3385: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -11440,165 +11286,48 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = formatDuration; +exports["default"] = formatISO; -var _index = __nccwpck_require__(9307); +var _index = _interopRequireDefault(__nccwpck_require__(6477)); -var _index2 = _interopRequireDefault(__nccwpck_require__(618)); +var _index2 = _interopRequireDefault(__nccwpck_require__(8620)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var defaultFormat = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds']; /** - * @name formatDuration + * @name formatISO * @category Common Helpers - * @summary Formats a duration in human-readable format + * @summary Format the date according to the ISO 8601 standard (https://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003169814.htm). * * @description - * Return human-readable duration string i.e. "9 months 2 days" + * Return the formatted date string in ISO 8601 format. Options may be passed to control the parts and notations of the date. * - * @param {Duration} duration - the duration to format + * @param {Date|Number} date - the original date * @param {Object} [options] - an object with options. - * @param {string[]} [options.format=['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds']] - the array of units to format - * @param {boolean} [options.zero=false] - should zeros be included in the output? - * @param {string} [options.delimiter=' '] - delimiter string - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @returns {string} the formatted date string + * @param {'extended'|'basic'} [options.format='extended'] - if 'basic', hide delimiters between date and time values. + * @param {'complete'|'date'|'time'} [options.representation='complete'] - format date, time with local time zone, or both. + * @returns {String} the formatted date string (in local time zone) * @throws {TypeError} 1 argument required + * @throws {RangeError} `date` must not be Invalid Date + * @throws {RangeError} `options.format` must be 'extended' or 'basic' + * @throws {RangeError} `options.representation` must be 'date', 'time' or 'complete' * * @example - * // Format full duration - * formatDuration({ - * years: 2, - * months: 9, - * weeks: 1, - * days: 7, - * hours: 5, - * minutes: 9, - * seconds: 30 - * }) - * //=> '2 years 9 months 1 week 7 days 5 hours 9 minutes 30 seconds' + * // Represent 18 September 2019 in ISO 8601 format (local time zone is UTC): + * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52)) + * //=> '2019-09-18T19:00:52Z' * * @example - * // Format partial duration - * formatDuration({ months: 9, days: 2 }) - * //=> '9 months 2 days' + * // Represent 18 September 2019 in ISO 8601, short format (local time zone is UTC): + * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' }) + * //=> '20190918T190052' * * @example - * // Customize the format - * formatDuration( - * { - * years: 2, - * months: 9, - * weeks: 1, - * days: 7, - * hours: 5, - * minutes: 9, - * seconds: 30 - * }, - * { format: ['months', 'weeks'] } - * ) === '9 months 1 week' - * - * @example - * // Customize the zeros presence - * formatDuration({ years: 0, months: 9 }) - * //=> '9 months' - * formatDuration({ years: 0, months: 9 }, { zero: true }) - * //=> '0 years 9 months' - * - * @example - * // Customize the delimiter - * formatDuration({ years: 2, months: 9, weeks: 3 }, { delimiter: ', ' }) - * //=> '2 years, 9 months, 3 weeks' - */ - -function formatDuration(duration, options) { - var _ref, _options$locale, _options$format, _options$zero, _options$delimiter; - - if (arguments.length < 1) { - throw new TypeError("1 argument required, but only ".concat(arguments.length, " present")); - } - - var defaultOptions = (0, _index.getDefaultOptions)(); - var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : _index2.default; - var format = (_options$format = options === null || options === void 0 ? void 0 : options.format) !== null && _options$format !== void 0 ? _options$format : defaultFormat; - var zero = (_options$zero = options === null || options === void 0 ? void 0 : options.zero) !== null && _options$zero !== void 0 ? _options$zero : false; - var delimiter = (_options$delimiter = options === null || options === void 0 ? void 0 : options.delimiter) !== null && _options$delimiter !== void 0 ? _options$delimiter : ' '; - - if (!locale.formatDistance) { - return ''; - } - - var result = format.reduce(function (acc, unit) { - var token = "x".concat(unit.replace(/(^.)/, function (m) { - return m.toUpperCase(); - })); - var value = duration[unit]; - - if (typeof value === 'number' && (zero || duration[unit])) { - return acc.concat(locale.formatDistance(token, value)); - } - - return acc; - }, []).join(delimiter); - return result; -} - -module.exports = exports.default; - -/***/ }), - -/***/ 3385: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = formatISO; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(8620)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @name formatISO - * @category Common Helpers - * @summary Format the date according to the ISO 8601 standard (https://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003169814.htm). - * - * @description - * Return the formatted date string in ISO 8601 format. Options may be passed to control the parts and notations of the date. - * - * @param {Date|Number} date - the original date - * @param {Object} [options] - an object with options. - * @param {'extended'|'basic'} [options.format='extended'] - if 'basic', hide delimiters between date and time values. - * @param {'complete'|'date'|'time'} [options.representation='complete'] - format date, time with local time zone, or both. - * @returns {String} the formatted date string (in local time zone) - * @throws {TypeError} 1 argument required - * @throws {RangeError} `date` must not be Invalid Date - * @throws {RangeError} `options.format` must be 'extended' or 'basic' - * @throws {RangeError} `options.representation` must be 'date', 'time' or 'complete' - * - * @example - * // Represent 18 September 2019 in ISO 8601 format (local time zone is UTC): - * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52)) - * //=> '2019-09-18T19:00:52Z' - * - * @example - * // Represent 18 September 2019 in ISO 8601, short format (local time zone is UTC): - * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' }) - * //=> '20190918T190052' - * - * @example - * // Represent 18 September 2019 in ISO 8601 format, date only: - * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' }) - * //=> '2019-09-18' + * // Represent 18 September 2019 in ISO 8601 format, date only: + * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' }) + * //=> '2019-09-18' * * @example * // Represent 18 September 2019 in ISO 8601 format, time only (local time zone is UTC): @@ -11673,7 +11402,7 @@ module.exports = exports.default; /***/ }), -/***/ 5296: +/***/ 4182: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -11682,7 +11411,7 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = formatISO9075; +exports["default"] = formatRFC3339; var _index = _interopRequireDefault(__nccwpck_require__(6477)); @@ -11690,51 +11419,46 @@ var _index2 = _interopRequireDefault(__nccwpck_require__(9920)); var _index3 = _interopRequireDefault(__nccwpck_require__(8620)); +var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name formatISO9075 + * @name formatRFC3339 * @category Common Helpers - * @summary Format the date according to the ISO 9075 standard (https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_get-format). + * @summary Format the date according to the RFC 3339 standard (https://tools.ietf.org/html/rfc3339#section-5.6). * * @description - * Return the formatted date string in ISO 9075 format. Options may be passed to control the parts and notations of the date. + * Return the formatted date string in RFC 3339 format. Options may be passed to control the parts and notations of the date. * * @param {Date|Number} date - the original date * @param {Object} [options] - an object with options. - * @param {'extended'|'basic'} [options.format='extended'] - if 'basic', hide delimiters between date and time values. - * @param {'complete'|'date'|'time'} [options.representation='complete'] - format date, time, or both. + * @param {0|1|2|3} [options.fractionDigits=0] - number of digits after the decimal point after seconds * @returns {String} the formatted date string * @throws {TypeError} 1 argument required * @throws {RangeError} `date` must not be Invalid Date - * @throws {RangeError} `options.format` must be 'extended' or 'basic' - * @throws {RangeError} `options.representation` must be 'date', 'time' or 'complete' - * - * @example - * // Represent 18 September 2019 in ISO 9075 format: - * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52)) - * //=> '2019-09-18 19:00:52' + * @throws {RangeError} `options.fractionDigits` must be between 0 and 3 * * @example - * // Represent 18 September 2019 in ISO 9075, short format: - * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' }) - * //=> '20190918 190052' + * // Represent 18 September 2019 in RFC 3339 format: + * const result = formatRFC3339(new Date(2019, 8, 18, 19, 0, 52)) + * //=> '2019-09-18T19:00:52Z' * * @example - * // Represent 18 September 2019 in ISO 9075 format, date only: - * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' }) - * //=> '2019-09-18' + * // Represent 18 September 2019 in RFC 3339 format, 2 digits of second fraction: + * const result = formatRFC3339(new Date(2019, 8, 18, 19, 0, 52, 234), { fractionDigits: 2 }) + * //=> '2019-09-18T19:00:52.23Z' * * @example - * // Represent 18 September 2019 in ISO 9075 format, time only: - * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' }) - * //=> '19:00:52' + * // Represent 18 September 2019 in RFC 3339 format, 3 digits of second fraction + * const result = formatRFC3339(new Date(2019, 8, 18, 19, 0, 52, 234), { fractionDigits: 3 }) + * //=> '2019-09-18T19:00:52.234Z' */ -function formatISO9075(dirtyDate, options) { - var _options$format, _options$representati; +function formatRFC3339(dirtyDate, options) { + var _options$fractionDigi; if (arguments.length < 1) { - throw new TypeError("1 argument required, but only ".concat(arguments.length, " present")); + throw new TypeError("1 arguments required, but only ".concat(arguments.length, " present")); } var originalDate = (0, _index.default)(dirtyDate); @@ -11743,48 +11467,48 @@ function formatISO9075(dirtyDate, options) { throw new RangeError('Invalid time value'); } - var format = String((_options$format = options === null || options === void 0 ? void 0 : options.format) !== null && _options$format !== void 0 ? _options$format : 'extended'); - var representation = String((_options$representati = options === null || options === void 0 ? void 0 : options.representation) !== null && _options$representati !== void 0 ? _options$representati : 'complete'); - - if (format !== 'extended' && format !== 'basic') { - throw new RangeError("format must be 'extended' or 'basic'"); - } + var fractionDigits = Number((_options$fractionDigi = options === null || options === void 0 ? void 0 : options.fractionDigits) !== null && _options$fractionDigi !== void 0 ? _options$fractionDigi : 0); // Test if fractionDigits is between 0 and 3 _and_ is not NaN - if (representation !== 'date' && representation !== 'time' && representation !== 'complete') { - throw new RangeError("representation must be 'date', 'time', or 'complete'"); + if (!(fractionDigits >= 0 && fractionDigits <= 3)) { + throw new RangeError('fractionDigits must be between 0 and 3 inclusively'); } - var result = ''; - var dateDelimiter = format === 'extended' ? '-' : ''; - var timeDelimiter = format === 'extended' ? ':' : ''; // Representation is either 'date' or 'complete' - - if (representation !== 'time') { - var day = (0, _index3.default)(originalDate.getDate(), 2); - var month = (0, _index3.default)(originalDate.getMonth() + 1, 2); - var year = (0, _index3.default)(originalDate.getFullYear(), 4); // yyyyMMdd or yyyy-MM-dd. - - result = "".concat(year).concat(dateDelimiter).concat(month).concat(dateDelimiter).concat(day); - } // Representation is either 'time' or 'complete' + var day = (0, _index3.default)(originalDate.getDate(), 2); + var month = (0, _index3.default)(originalDate.getMonth() + 1, 2); + var year = originalDate.getFullYear(); + var hour = (0, _index3.default)(originalDate.getHours(), 2); + var minute = (0, _index3.default)(originalDate.getMinutes(), 2); + var second = (0, _index3.default)(originalDate.getSeconds(), 2); + var fractionalSecond = ''; + if (fractionDigits > 0) { + var milliseconds = originalDate.getMilliseconds(); + var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, fractionDigits - 3)); + fractionalSecond = '.' + (0, _index3.default)(fractionalSeconds, fractionDigits); + } - if (representation !== 'date') { - var hour = (0, _index3.default)(originalDate.getHours(), 2); - var minute = (0, _index3.default)(originalDate.getMinutes(), 2); - var second = (0, _index3.default)(originalDate.getSeconds(), 2); // If there's also date, separate it with time with a space + var offset = ''; + var tzOffset = originalDate.getTimezoneOffset(); - var separator = result === '' ? '' : ' '; // HHmmss or HH:mm:ss. + if (tzOffset !== 0) { + var absoluteOffset = Math.abs(tzOffset); + var hourOffset = (0, _index3.default)((0, _index4.default)(absoluteOffset / 60), 2); + var minuteOffset = (0, _index3.default)(absoluteOffset % 60, 2); // If less than 0, the sign is +, because it is ahead of time. - result = "".concat(result).concat(separator).concat(hour).concat(timeDelimiter).concat(minute).concat(timeDelimiter).concat(second); + var sign = tzOffset < 0 ? '+' : '-'; + offset = "".concat(sign).concat(hourOffset, ":").concat(minuteOffset); + } else { + offset = 'Z'; } - return result; + return "".concat(year, "-").concat(month, "-").concat(day, "T").concat(hour, ":").concat(minute, ":").concat(second).concat(fractionalSecond).concat(offset); } module.exports = exports.default; /***/ }), -/***/ 2448: +/***/ 402: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -11793,207 +11517,36 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = formatISODuration; +exports["default"] = formatRFC7231; -var _index = _interopRequireDefault(__nccwpck_require__(2063)); +var _index = _interopRequireDefault(__nccwpck_require__(6477)); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _index2 = _interopRequireDefault(__nccwpck_require__(9920)); -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } +var _index3 = _interopRequireDefault(__nccwpck_require__(8620)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; /** - * @name formatISODuration + * @name formatRFC7231 * @category Common Helpers - * @summary Format a duration object according as ISO 8601 duration string + * @summary Format the date according to the RFC 7231 standard (https://tools.ietf.org/html/rfc7231#section-7.1.1.1). * * @description - * Format a duration object according to the ISO 8601 duration standard (https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm) - * - * @param {Duration} duration - the duration to format + * Return the formatted date string in RFC 7231 format. + * The result will always be in UTC timezone. * - * @returns {String} The ISO 8601 duration string - * @throws {TypeError} Requires 1 argument - * @throws {Error} Argument must be an object + * @param {Date|Number} date - the original date + * @returns {String} the formatted date string + * @throws {TypeError} 1 argument required + * @throws {RangeError} `date` must not be Invalid Date * * @example - * // Format the given duration as ISO 8601 string - * const result = formatISODuration({ - * years: 39, - * months: 2, - * days: 20, - * hours: 7, - * minutes: 5, - * seconds: 0 - * }) - * //=> 'P39Y2M20DT0H0M0S' - */ -function formatISODuration(duration) { - (0, _index.default)(1, arguments); - if (_typeof(duration) !== 'object') throw new Error('Duration must be an object'); - var _duration$years = duration.years, - years = _duration$years === void 0 ? 0 : _duration$years, - _duration$months = duration.months, - months = _duration$months === void 0 ? 0 : _duration$months, - _duration$days = duration.days, - days = _duration$days === void 0 ? 0 : _duration$days, - _duration$hours = duration.hours, - hours = _duration$hours === void 0 ? 0 : _duration$hours, - _duration$minutes = duration.minutes, - minutes = _duration$minutes === void 0 ? 0 : _duration$minutes, - _duration$seconds = duration.seconds, - seconds = _duration$seconds === void 0 ? 0 : _duration$seconds; - return "P".concat(years, "Y").concat(months, "M").concat(days, "DT").concat(hours, "H").concat(minutes, "M").concat(seconds, "S"); -} - -module.exports = exports.default; - -/***/ }), - -/***/ 4182: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = formatRFC3339; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(9920)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(8620)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @name formatRFC3339 - * @category Common Helpers - * @summary Format the date according to the RFC 3339 standard (https://tools.ietf.org/html/rfc3339#section-5.6). - * - * @description - * Return the formatted date string in RFC 3339 format. Options may be passed to control the parts and notations of the date. - * - * @param {Date|Number} date - the original date - * @param {Object} [options] - an object with options. - * @param {0|1|2|3} [options.fractionDigits=0] - number of digits after the decimal point after seconds - * @returns {String} the formatted date string - * @throws {TypeError} 1 argument required - * @throws {RangeError} `date` must not be Invalid Date - * @throws {RangeError} `options.fractionDigits` must be between 0 and 3 - * - * @example - * // Represent 18 September 2019 in RFC 3339 format: - * const result = formatRFC3339(new Date(2019, 8, 18, 19, 0, 52)) - * //=> '2019-09-18T19:00:52Z' - * - * @example - * // Represent 18 September 2019 in RFC 3339 format, 2 digits of second fraction: - * const result = formatRFC3339(new Date(2019, 8, 18, 19, 0, 52, 234), { fractionDigits: 2 }) - * //=> '2019-09-18T19:00:52.23Z' - * - * @example - * // Represent 18 September 2019 in RFC 3339 format, 3 digits of second fraction - * const result = formatRFC3339(new Date(2019, 8, 18, 19, 0, 52, 234), { fractionDigits: 3 }) - * //=> '2019-09-18T19:00:52.234Z' - */ -function formatRFC3339(dirtyDate, options) { - var _options$fractionDigi; - - if (arguments.length < 1) { - throw new TypeError("1 arguments required, but only ".concat(arguments.length, " present")); - } - - var originalDate = (0, _index.default)(dirtyDate); - - if (!(0, _index2.default)(originalDate)) { - throw new RangeError('Invalid time value'); - } - - var fractionDigits = Number((_options$fractionDigi = options === null || options === void 0 ? void 0 : options.fractionDigits) !== null && _options$fractionDigi !== void 0 ? _options$fractionDigi : 0); // Test if fractionDigits is between 0 and 3 _and_ is not NaN - - if (!(fractionDigits >= 0 && fractionDigits <= 3)) { - throw new RangeError('fractionDigits must be between 0 and 3 inclusively'); - } - - var day = (0, _index3.default)(originalDate.getDate(), 2); - var month = (0, _index3.default)(originalDate.getMonth() + 1, 2); - var year = originalDate.getFullYear(); - var hour = (0, _index3.default)(originalDate.getHours(), 2); - var minute = (0, _index3.default)(originalDate.getMinutes(), 2); - var second = (0, _index3.default)(originalDate.getSeconds(), 2); - var fractionalSecond = ''; - - if (fractionDigits > 0) { - var milliseconds = originalDate.getMilliseconds(); - var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, fractionDigits - 3)); - fractionalSecond = '.' + (0, _index3.default)(fractionalSeconds, fractionDigits); - } - - var offset = ''; - var tzOffset = originalDate.getTimezoneOffset(); - - if (tzOffset !== 0) { - var absoluteOffset = Math.abs(tzOffset); - var hourOffset = (0, _index3.default)((0, _index4.default)(absoluteOffset / 60), 2); - var minuteOffset = (0, _index3.default)(absoluteOffset % 60, 2); // If less than 0, the sign is +, because it is ahead of time. - - var sign = tzOffset < 0 ? '+' : '-'; - offset = "".concat(sign).concat(hourOffset, ":").concat(minuteOffset); - } else { - offset = 'Z'; - } - - return "".concat(year, "-").concat(month, "-").concat(day, "T").concat(hour, ":").concat(minute, ":").concat(second).concat(fractionalSecond).concat(offset); -} - -module.exports = exports.default; - -/***/ }), - -/***/ 402: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = formatRFC7231; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(9920)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(8620)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; -/** - * @name formatRFC7231 - * @category Common Helpers - * @summary Format the date according to the RFC 7231 standard (https://tools.ietf.org/html/rfc7231#section-7.1.1.1). - * - * @description - * Return the formatted date string in RFC 7231 format. - * The result will always be in UTC timezone. - * - * @param {Date|Number} date - the original date - * @returns {String} the formatted date string - * @throws {TypeError} 1 argument required - * @throws {RangeError} `date` must not be Invalid Date - * - * @example - * // Represent 18 September 2019 in RFC 7231 format: - * const result = formatRFC7231(new Date(2019, 8, 18, 19, 0, 52)) - * //=> 'Wed, 18 Sep 2019 19:00:52 GMT' + * // Represent 18 September 2019 in RFC 7231 format: + * const result = formatRFC7231(new Date(2019, 8, 18, 19, 0, 52)) + * //=> 'Wed, 18 Sep 2019 19:00:52 GMT' */ function formatRFC7231(dirtyDate) { @@ -12151,7 +11704,7 @@ module.exports = exports.default; /***/ }), -/***/ 4897: +/***/ 2168: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -12160,184 +11713,445 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = fromUnixTime; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(1985)); +exports["default"] = format; -var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index = _interopRequireDefault(__nccwpck_require__(9920)); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _index2 = _interopRequireDefault(__nccwpck_require__(7923)); -/** - * @name fromUnixTime - * @category Timestamp Helpers - * @summary Create a date from a Unix timestamp. - * - * @description - * Create a date from a Unix timestamp (in seconds). Decimal values will be discarded. - * - * @param {Number} unixTime - the given Unix timestamp (in seconds) - * @returns {Date} the date - * @throws {TypeError} 1 argument required - * - * @example - * // Create the date 29 February 2012 11:45:05: - * const result = fromUnixTime(1330515905) - * //=> Wed Feb 29 2012 11:45:05 - */ -function fromUnixTime(dirtyUnixTime) { - (0, _index3.default)(1, arguments); - var unixTime = (0, _index2.default)(dirtyUnixTime); - return (0, _index.default)(unixTime * 1000); -} +var _index3 = _interopRequireDefault(__nccwpck_require__(6477)); -module.exports = exports.default; +var _index4 = _interopRequireDefault(__nccwpck_require__(9257)); -/***/ }), +var _index5 = _interopRequireDefault(__nccwpck_require__(8387)); -/***/ 7626: -/***/ ((module, exports, __nccwpck_require__) => { +var _index6 = _interopRequireDefault(__nccwpck_require__(7032)); -"use strict"; +var _index7 = __nccwpck_require__(2509); +var _index8 = _interopRequireDefault(__nccwpck_require__(1985)); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = getDate; +var _index9 = _interopRequireDefault(__nccwpck_require__(2063)); -var _index = _interopRequireDefault(__nccwpck_require__(6477)); +var _index10 = __nccwpck_require__(9307); -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index11 = _interopRequireDefault(__nccwpck_require__(618)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// This RegExp consists of three parts separated by `|`: +// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token +// (one of the certain letters followed by `o`) +// - (\w)\1* matches any sequences of the same letter +// - '' matches two quote characters in a row +// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), +// except a single quote symbol, which ends the sequence. +// Two quote characters do not end the sequence. +// If there is no matching single quote +// then the sequence will continue until the end of the string. +// - . matches any single character unmatched by previous parts of the RegExps +var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also +// sequences of symbols P, p, and the combinations like `PPPPPPPppppp` + +var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; +var escapedStringRegExp = /^'([^]*?)'?$/; +var doubleQuoteRegExp = /''/g; +var unescapedLatinCharacterRegExp = /[a-zA-Z]/; /** - * @name getDate - * @category Day Helpers - * @summary Get the day of the month of the given date. + * @name format + * @category Common Helpers + * @summary Format the date. * * @description - * Get the day of the month of the given date. + * Return the formatted date string in the given format. The result may vary by locale. * - * @param {Date|Number} date - the given date - * @returns {Number} the day of month - * @throws {TypeError} 1 argument required + * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. + * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md * - * @example - * // Which day of the month is 29 February 2012? - * const result = getDate(new Date(2012, 1, 29)) - * //=> 29 - */ -function getDate(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var dayOfMonth = date.getDate(); - return dayOfMonth; -} - -module.exports = exports.default; - -/***/ }), - -/***/ 9361: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = getDay; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @name getDay - * @category Weekday Helpers - * @summary Get the day of the week of the given date. + * The characters wrapped between two single quotes characters (') are escaped. + * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. + * (see the last example) * - * @description - * Get the day of the week of the given date. + * Format of the string is based on Unicode Technical Standard #35: + * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table + * with a few additions (see note 7 below the table). * - * @param {Date|Number} date - the given date - * @returns {0|1|2|3|4|5|6} the day of week, 0 represents Sunday - * @throws {TypeError} 1 argument required + * Accepted patterns: + * | Unit | Pattern | Result examples | Notes | + * |---------------------------------|---------|-----------------------------------|-------| + * | Era | G..GGG | AD, BC | | + * | | GGGG | Anno Domini, Before Christ | 2 | + * | | GGGGG | A, B | | + * | Calendar year | y | 44, 1, 1900, 2017 | 5 | + * | | yo | 44th, 1st, 0th, 17th | 5,7 | + * | | yy | 44, 01, 00, 17 | 5 | + * | | yyy | 044, 001, 1900, 2017 | 5 | + * | | yyyy | 0044, 0001, 1900, 2017 | 5 | + * | | yyyyy | ... | 3,5 | + * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 | + * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 | + * | | YY | 44, 01, 00, 17 | 5,8 | + * | | YYY | 044, 001, 1900, 2017 | 5 | + * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 | + * | | YYYYY | ... | 3,5 | + * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 | + * | | RR | -43, 00, 01, 1900, 2017 | 5,7 | + * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 | + * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 | + * | | RRRRR | ... | 3,5,7 | + * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 | + * | | uu | -43, 01, 1900, 2017 | 5 | + * | | uuu | -043, 001, 1900, 2017 | 5 | + * | | uuuu | -0043, 0001, 1900, 2017 | 5 | + * | | uuuuu | ... | 3,5 | + * | Quarter (formatting) | Q | 1, 2, 3, 4 | | + * | | Qo | 1st, 2nd, 3rd, 4th | 7 | + * | | QQ | 01, 02, 03, 04 | | + * | | QQQ | Q1, Q2, Q3, Q4 | | + * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | + * | | QQQQQ | 1, 2, 3, 4 | 4 | + * | Quarter (stand-alone) | q | 1, 2, 3, 4 | | + * | | qo | 1st, 2nd, 3rd, 4th | 7 | + * | | qq | 01, 02, 03, 04 | | + * | | qqq | Q1, Q2, Q3, Q4 | | + * | | qqqq | 1st quarter, 2nd quarter, ... | 2 | + * | | qqqqq | 1, 2, 3, 4 | 4 | + * | Month (formatting) | M | 1, 2, ..., 12 | | + * | | Mo | 1st, 2nd, ..., 12th | 7 | + * | | MM | 01, 02, ..., 12 | | + * | | MMM | Jan, Feb, ..., Dec | | + * | | MMMM | January, February, ..., December | 2 | + * | | MMMMM | J, F, ..., D | | + * | Month (stand-alone) | L | 1, 2, ..., 12 | | + * | | Lo | 1st, 2nd, ..., 12th | 7 | + * | | LL | 01, 02, ..., 12 | | + * | | LLL | Jan, Feb, ..., Dec | | + * | | LLLL | January, February, ..., December | 2 | + * | | LLLLL | J, F, ..., D | | + * | Local week of year | w | 1, 2, ..., 53 | | + * | | wo | 1st, 2nd, ..., 53th | 7 | + * | | ww | 01, 02, ..., 53 | | + * | ISO week of year | I | 1, 2, ..., 53 | 7 | + * | | Io | 1st, 2nd, ..., 53th | 7 | + * | | II | 01, 02, ..., 53 | 7 | + * | Day of month | d | 1, 2, ..., 31 | | + * | | do | 1st, 2nd, ..., 31st | 7 | + * | | dd | 01, 02, ..., 31 | | + * | Day of year | D | 1, 2, ..., 365, 366 | 9 | + * | | Do | 1st, 2nd, ..., 365th, 366th | 7 | + * | | DD | 01, 02, ..., 365, 366 | 9 | + * | | DDD | 001, 002, ..., 365, 366 | | + * | | DDDD | ... | 3 | + * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | | + * | | EEEE | Monday, Tuesday, ..., Sunday | 2 | + * | | EEEEE | M, T, W, T, F, S, S | | + * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | + * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 | + * | | io | 1st, 2nd, ..., 7th | 7 | + * | | ii | 01, 02, ..., 07 | 7 | + * | | iii | Mon, Tue, Wed, ..., Sun | 7 | + * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 | + * | | iiiii | M, T, W, T, F, S, S | 7 | + * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 | + * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | | + * | | eo | 2nd, 3rd, ..., 1st | 7 | + * | | ee | 02, 03, ..., 01 | | + * | | eee | Mon, Tue, Wed, ..., Sun | | + * | | eeee | Monday, Tuesday, ..., Sunday | 2 | + * | | eeeee | M, T, W, T, F, S, S | | + * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | + * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | | + * | | co | 2nd, 3rd, ..., 1st | 7 | + * | | cc | 02, 03, ..., 01 | | + * | | ccc | Mon, Tue, Wed, ..., Sun | | + * | | cccc | Monday, Tuesday, ..., Sunday | 2 | + * | | ccccc | M, T, W, T, F, S, S | | + * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | + * | AM, PM | a..aa | AM, PM | | + * | | aaa | am, pm | | + * | | aaaa | a.m., p.m. | 2 | + * | | aaaaa | a, p | | + * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | | + * | | bbb | am, pm, noon, midnight | | + * | | bbbb | a.m., p.m., noon, midnight | 2 | + * | | bbbbb | a, p, n, mi | | + * | Flexible day period | B..BBB | at night, in the morning, ... | | + * | | BBBB | at night, in the morning, ... | 2 | + * | | BBBBB | at night, in the morning, ... | | + * | Hour [1-12] | h | 1, 2, ..., 11, 12 | | + * | | ho | 1st, 2nd, ..., 11th, 12th | 7 | + * | | hh | 01, 02, ..., 11, 12 | | + * | Hour [0-23] | H | 0, 1, 2, ..., 23 | | + * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 | + * | | HH | 00, 01, 02, ..., 23 | | + * | Hour [0-11] | K | 1, 2, ..., 11, 0 | | + * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 | + * | | KK | 01, 02, ..., 11, 00 | | + * | Hour [1-24] | k | 24, 1, 2, ..., 23 | | + * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 | + * | | kk | 24, 01, 02, ..., 23 | | + * | Minute | m | 0, 1, ..., 59 | | + * | | mo | 0th, 1st, ..., 59th | 7 | + * | | mm | 00, 01, ..., 59 | | + * | Second | s | 0, 1, ..., 59 | | + * | | so | 0th, 1st, ..., 59th | 7 | + * | | ss | 00, 01, ..., 59 | | + * | Fraction of second | S | 0, 1, ..., 9 | | + * | | SS | 00, 01, ..., 99 | | + * | | SSS | 000, 001, ..., 999 | | + * | | SSSS | ... | 3 | + * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | | + * | | XX | -0800, +0530, Z | | + * | | XXX | -08:00, +05:30, Z | | + * | | XXXX | -0800, +0530, Z, +123456 | 2 | + * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | + * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | | + * | | xx | -0800, +0530, +0000 | | + * | | xxx | -08:00, +05:30, +00:00 | 2 | + * | | xxxx | -0800, +0530, +0000, +123456 | | + * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | + * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | | + * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 | + * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 | + * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 | + * | Seconds timestamp | t | 512969520 | 7 | + * | | tt | ... | 3,7 | + * | Milliseconds timestamp | T | 512969520900 | 7 | + * | | TT | ... | 3,7 | + * | Long localized date | P | 04/29/1453 | 7 | + * | | PP | Apr 29, 1453 | 7 | + * | | PPP | April 29th, 1453 | 7 | + * | | PPPP | Friday, April 29th, 1453 | 2,7 | + * | Long localized time | p | 12:00 AM | 7 | + * | | pp | 12:00:00 AM | 7 | + * | | ppp | 12:00:00 AM GMT+2 | 7 | + * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 | + * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 | + * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 | + * | | PPPppp | April 29th, 1453 at ... | 7 | + * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 | + * Notes: + * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale + * are the same as "stand-alone" units, but are different in some languages. + * "Formatting" units are declined according to the rules of the language + * in the context of a date. "Stand-alone" units are always nominative singular: * - * @example - * // Which day of the week is 29 February 2012? - * const result = getDay(new Date(2012, 1, 29)) - * //=> 3 - */ -function getDay(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var day = date.getDay(); - return day; -} - -module.exports = exports.default; - -/***/ }), - -/***/ 7468: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = getDayOfYear; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(8225)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(3086)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @name getDayOfYear - * @category Day Helpers - * @summary Get the day of the year of the given date. + * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` * - * @description - * Get the day of the year of the given date. + * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` * - * @param {Date|Number} date - the given date - * @returns {Number} the day of year - * @throws {TypeError} 1 argument required + * 2. Any sequence of the identical letters is a pattern, unless it is escaped by + * the single quote characters (see below). + * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`) + * the output will be the same as default pattern for this unit, usually + * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units + * are marked with "2" in the last column of the table. * - * @example - * // Which day of the year is 2 July 2014? - * const result = getDayOfYear(new Date(2014, 6, 2)) - * //=> 183 - */ -function getDayOfYear(dirtyDate) { - (0, _index4.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var diff = (0, _index3.default)(date, (0, _index2.default)(date)); - var dayOfYear = diff + 1; - return dayOfYear; + * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'` + * + * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'` + * + * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'` + * + * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'` + * + * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'` + * + * 3. Some patterns could be unlimited length (such as `yyyyyyyy`). + * The output will be padded with zeros to match the length of the pattern. + * + * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'` + * + * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. + * These tokens represent the shortest form of the quarter. + * + * 5. The main difference between `y` and `u` patterns are B.C. years: + * + * | Year | `y` | `u` | + * |------|-----|-----| + * | AC 1 | 1 | 1 | + * | BC 1 | 1 | 0 | + * | BC 2 | 2 | -1 | + * + * Also `yy` always returns the last two digits of a year, + * while `uu` pads single digit years to 2 characters and returns other years unchanged: + * + * | Year | `yy` | `uu` | + * |------|------|------| + * | 1 | 01 | 01 | + * | 14 | 14 | 14 | + * | 376 | 76 | 376 | + * | 1453 | 53 | 1453 | + * + * The same difference is true for local and ISO week-numbering years (`Y` and `R`), + * except local week-numbering years are dependent on `options.weekStartsOn` + * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear} + * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}). + * + * 6. Specific non-location timezones are currently unavailable in `date-fns`, + * so right now these tokens fall back to GMT timezones. + * + * 7. These patterns are not in the Unicode Technical Standard #35: + * - `i`: ISO day of week + * - `I`: ISO week of year + * - `R`: ISO week-numbering year + * - `t`: seconds timestamp + * - `T`: milliseconds timestamp + * - `o`: ordinal number modifier + * - `P`: long localized date + * - `p`: long localized time + * + * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. + * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month. + * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * @param {Date|Number} date - the original date + * @param {String} format - the string of tokens + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is + * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @returns {String} the formatted date string + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `date` must not be Invalid Date + * @throws {RangeError} `options.locale` must contain `localize` property + * @throws {RangeError} `options.locale` must contain `formatLong` property + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} format string contains an unescaped latin alphabet character + * + * @example + * // Represent 11 February 2014 in middle-endian format: + * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy') + * //=> '02/11/2014' + * + * @example + * // Represent 2 July 2014 in Esperanto: + * import { eoLocale } from 'date-fns/locale/eo' + * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", { + * locale: eoLocale + * }) + * //=> '2-a de julio 2014' + * + * @example + * // Escape string by single quote characters: + * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'") + * //=> "3 o'clock" + */ + +function format(dirtyDate, dirtyFormatStr, options) { + var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; + + (0, _index9.default)(2, arguments); + var formatStr = String(dirtyFormatStr); + var defaultOptions = (0, _index10.getDefaultOptions)(); + var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : _index11.default; + var firstWeekContainsDate = (0, _index8.default)((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN + + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); + } + + var weekStartsOn = (0, _index8.default)((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + + if (!locale.localize) { + throw new RangeError('locale must contain localize property'); + } + + if (!locale.formatLong) { + throw new RangeError('locale must contain formatLong property'); + } + + var originalDate = (0, _index3.default)(dirtyDate); + + if (!(0, _index.default)(originalDate)) { + throw new RangeError('Invalid time value'); + } // Convert the date in system timezone to the same date in UTC+00:00 timezone. + // This ensures that when UTC functions will be implemented, locales will be compatible with them. + // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376 + + + var timezoneOffset = (0, _index6.default)(originalDate); + var utcDate = (0, _index2.default)(originalDate, timezoneOffset); + var formatterOptions = { + firstWeekContainsDate: firstWeekContainsDate, + weekStartsOn: weekStartsOn, + locale: locale, + _originalDate: originalDate + }; + var result = formatStr.match(longFormattingTokensRegExp).map(function (substring) { + var firstCharacter = substring[0]; + + if (firstCharacter === 'p' || firstCharacter === 'P') { + var longFormatter = _index5.default[firstCharacter]; + return longFormatter(substring, locale.formatLong); + } + + return substring; + }).join('').match(formattingTokensRegExp).map(function (substring) { + // Replace two single quote characters with one single quote character + if (substring === "''") { + return "'"; + } + + var firstCharacter = substring[0]; + + if (firstCharacter === "'") { + return cleanEscapedString(substring); + } + + var formatter = _index4.default[firstCharacter]; + + if (formatter) { + if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && (0, _index7.isProtectedWeekYearToken)(substring)) { + (0, _index7.throwProtectedError)(substring, dirtyFormatStr, String(dirtyDate)); + } + + if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && (0, _index7.isProtectedDayOfYearToken)(substring)) { + (0, _index7.throwProtectedError)(substring, dirtyFormatStr, String(dirtyDate)); + } + + return formatter(utcDate, substring, locale.localize, formatterOptions); + } + + if (firstCharacter.match(unescapedLatinCharacterRegExp)) { + throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); + } + + return substring; + }).join(''); + return result; +} + +function cleanEscapedString(input) { + var matched = input.match(escapedStringRegExp); + + if (!matched) { + return input; + } + + return matched[1].replace(doubleQuoteRegExp, "'"); } module.exports = exports.default; /***/ }), -/***/ 7573: +/***/ 4897: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -12346,47 +12160,44 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = getDaysInMonth; +exports["default"] = fromUnixTime; var _index = _interopRequireDefault(__nccwpck_require__(6477)); -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(1985)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name getDaysInMonth - * @category Month Helpers - * @summary Get the number of days in a month of the given date. + * @name fromUnixTime + * @category Timestamp Helpers + * @summary Create a date from a Unix timestamp. * * @description - * Get the number of days in a month of the given date. + * Create a date from a Unix timestamp (in seconds). Decimal values will be discarded. * - * @param {Date|Number} date - the given date - * @returns {Number} the number of days in a month + * @param {Number} unixTime - the given Unix timestamp (in seconds) + * @returns {Date} the date * @throws {TypeError} 1 argument required * * @example - * // How many days are in February 2000? - * const result = getDaysInMonth(new Date(2000, 1)) - * //=> 29 + * // Create the date 29 February 2012 11:45:05: + * const result = fromUnixTime(1330515905) + * //=> Wed Feb 29 2012 11:45:05 */ -function getDaysInMonth(dirtyDate) { - (0, _index2.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var year = date.getFullYear(); - var monthIndex = date.getMonth(); - var lastDayOfMonth = new Date(0); - lastDayOfMonth.setFullYear(year, monthIndex + 1, 0); - lastDayOfMonth.setHours(0, 0, 0, 0); - return lastDayOfMonth.getDate(); +function fromUnixTime(dirtyUnixTime) { + (0, _index3.default)(1, arguments); + var unixTime = (0, _index2.default)(dirtyUnixTime); + return (0, _index.default)(unixTime * 1000); } module.exports = exports.default; /***/ }), -/***/ 2784: +/***/ 7626: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -12395,30 +12206,219 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = getDaysInYear; +exports["default"] = getDate; var _index = _interopRequireDefault(__nccwpck_require__(6477)); -var _index2 = _interopRequireDefault(__nccwpck_require__(74)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name getDaysInYear - * @category Year Helpers - * @summary Get the number of days in a year of the given date. + * @name getDate + * @category Day Helpers + * @summary Get the day of the month of the given date. * * @description - * Get the number of days in a year of the given date. + * Get the day of the month of the given date. * * @param {Date|Number} date - the given date - * @returns {Number} the number of days in a year + * @returns {Number} the day of month * @throws {TypeError} 1 argument required * * @example - * // How many days are in 2012? + * // Which day of the month is 29 February 2012? + * const result = getDate(new Date(2012, 1, 29)) + * //=> 29 + */ +function getDate(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + var dayOfMonth = date.getDate(); + return dayOfMonth; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 7468: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = getDayOfYear; + +var _index = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(8225)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(3086)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name getDayOfYear + * @category Day Helpers + * @summary Get the day of the year of the given date. + * + * @description + * Get the day of the year of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the day of year + * @throws {TypeError} 1 argument required + * + * @example + * // Which day of the year is 2 July 2014? + * const result = getDayOfYear(new Date(2014, 6, 2)) + * //=> 183 + */ +function getDayOfYear(dirtyDate) { + (0, _index4.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + var diff = (0, _index3.default)(date, (0, _index2.default)(date)); + var dayOfYear = diff + 1; + return dayOfYear; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 9361: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = getDay; + +var _index = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name getDay + * @category Weekday Helpers + * @summary Get the day of the week of the given date. + * + * @description + * Get the day of the week of the given date. + * + * @param {Date|Number} date - the given date + * @returns {0|1|2|3|4|5|6} the day of week, 0 represents Sunday + * @throws {TypeError} 1 argument required + * + * @example + * // Which day of the week is 29 February 2012? + * const result = getDay(new Date(2012, 1, 29)) + * //=> 3 + */ +function getDay(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + var day = date.getDay(); + return day; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 7573: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = getDaysInMonth; + +var _index = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name getDaysInMonth + * @category Month Helpers + * @summary Get the number of days in a month of the given date. + * + * @description + * Get the number of days in a month of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the number of days in a month + * @throws {TypeError} 1 argument required + * + * @example + * // How many days are in February 2000? + * const result = getDaysInMonth(new Date(2000, 1)) + * //=> 29 + */ +function getDaysInMonth(dirtyDate) { + (0, _index2.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + var year = date.getFullYear(); + var monthIndex = date.getMonth(); + var lastDayOfMonth = new Date(0); + lastDayOfMonth.setFullYear(year, monthIndex + 1, 0); + lastDayOfMonth.setHours(0, 0, 0, 0); + return lastDayOfMonth.getDate(); +} + +module.exports = exports.default; + +/***/ }), + +/***/ 2784: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = getDaysInYear; + +var _index = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(74)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name getDaysInYear + * @category Year Helpers + * @summary Get the number of days in a year of the given date. + * + * @description + * Get the number of days in a year of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the number of days in a year + * @throws {TypeError} 1 argument required + * + * @example + * // How many days are in 2012? * const result = getDaysInYear(new Date(2012, 0, 1)) * //=> 366 */ @@ -12630,62 +12630,6 @@ module.exports = exports.default; /***/ }), -/***/ 9894: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = getISOWeek; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(6307)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(776)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var MILLISECONDS_IN_WEEK = 604800000; -/** - * @name getISOWeek - * @category ISO Week Helpers - * @summary Get the ISO week of the given date. - * - * @description - * Get the ISO week of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|Number} date - the given date - * @returns {Number} the ISO week - * @throws {TypeError} 1 argument required - * - * @example - * // Which week of the ISO-week numbering year is 2 January 2005? - * const result = getISOWeek(new Date(2005, 0, 2)) - * //=> 53 - */ - -function getISOWeek(dirtyDate) { - (0, _index4.default)(1, arguments); - var date = (0, _index.default)(dirtyDate); - var diff = (0, _index2.default)(date).getTime() - (0, _index3.default)(date).getTime(); // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - - return Math.round(diff / MILLISECONDS_IN_WEEK) + 1; -} - -module.exports = exports.default; - -/***/ }), - /***/ 6991: /***/ ((module, exports, __nccwpck_require__) => { @@ -12751,7 +12695,7 @@ module.exports = exports.default; /***/ }), -/***/ 3283: +/***/ 9894: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -12760,11 +12704,67 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = getISOWeeksInYear; +exports["default"] = getISOWeek; -var _index = _interopRequireDefault(__nccwpck_require__(776)); +var _index = _interopRequireDefault(__nccwpck_require__(6477)); -var _index2 = _interopRequireDefault(__nccwpck_require__(7195)); +var _index2 = _interopRequireDefault(__nccwpck_require__(6307)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(776)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var MILLISECONDS_IN_WEEK = 604800000; +/** + * @name getISOWeek + * @category ISO Week Helpers + * @summary Get the ISO week of the given date. + * + * @description + * Get the ISO week of the given date. + * + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} date - the given date + * @returns {Number} the ISO week + * @throws {TypeError} 1 argument required + * + * @example + * // Which week of the ISO-week numbering year is 2 January 2005? + * const result = getISOWeek(new Date(2005, 0, 2)) + * //=> 53 + */ + +function getISOWeek(dirtyDate) { + (0, _index4.default)(1, arguments); + var date = (0, _index.default)(dirtyDate); + var diff = (0, _index2.default)(date).getTime() - (0, _index3.default)(date).getTime(); // Round the number of days to the nearest integer + // because the number of milliseconds in a week is not constant + // (e.g. it's different in the week of the daylight saving time clock shift) + + return Math.round(diff / MILLISECONDS_IN_WEEK) + 1; +} + +module.exports = exports.default; + +/***/ }), + +/***/ 3283: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = getISOWeeksInYear; + +var _index = _interopRequireDefault(__nccwpck_require__(776)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(7195)); var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); @@ -13198,81 +13198,6 @@ module.exports = exports.default; /***/ }), -/***/ 81: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = getWeek; - -var _index = _interopRequireDefault(__nccwpck_require__(9813)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(8014)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var MILLISECONDS_IN_WEEK = 604800000; -/** - * @name getWeek - * @category Week Helpers - * @summary Get the local week index of the given date. - * - * @description - * Get the local week index of the given date. - * The exact calculation depends on the values of - * `options.weekStartsOn` (which is the index of the first day of the week) - * and `options.firstWeekContainsDate` (which is the day of January, which is always in - * the first week of the week-numbering year) - * - * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering - * - * @param {Date|Number} date - the given date - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year - * @returns {Number} the week - * @throws {TypeError} 1 argument required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 - * - * @example - * // Which week of the local week numbering year is 2 January 2005 with default options? - * const result = getWeek(new Date(2005, 0, 2)) - * //=> 2 - * - * // Which week of the local week numbering year is 2 January 2005, - * // if Monday is the first day of the week, - * // and the first week of the year always contains 4 January? - * const result = getWeek(new Date(2005, 0, 2), { - * weekStartsOn: 1, - * firstWeekContainsDate: 4 - * }) - * //=> 53 - */ - -function getWeek(dirtyDate, options) { - (0, _index4.default)(1, arguments); - var date = (0, _index3.default)(dirtyDate); - var diff = (0, _index.default)(date, options).getTime() - (0, _index2.default)(date, options).getTime(); // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - - return Math.round(diff / MILLISECONDS_IN_WEEK) + 1; -} - -module.exports = exports.default; - -/***/ }), - /***/ 9229: /***/ ((module, exports, __nccwpck_require__) => { @@ -13440,6 +13365,81 @@ module.exports = exports.default; /***/ }), +/***/ 81: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = getWeek; + +var _index = _interopRequireDefault(__nccwpck_require__(9813)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(8014)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var MILLISECONDS_IN_WEEK = 604800000; +/** + * @name getWeek + * @category Week Helpers + * @summary Get the local week index of the given date. + * + * @description + * Get the local week index of the given date. + * The exact calculation depends on the values of + * `options.weekStartsOn` (which is the index of the first day of the week) + * and `options.firstWeekContainsDate` (which is the day of January, which is always in + * the first week of the week-numbering year) + * + * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering + * + * @param {Date|Number} date - the given date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year + * @returns {Number} the week + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * + * @example + * // Which week of the local week numbering year is 2 January 2005 with default options? + * const result = getWeek(new Date(2005, 0, 2)) + * //=> 2 + * + * // Which week of the local week numbering year is 2 January 2005, + * // if Monday is the first day of the week, + * // and the first week of the year always contains 4 January? + * const result = getWeek(new Date(2005, 0, 2), { + * weekStartsOn: 1, + * firstWeekContainsDate: 4 + * }) + * //=> 53 + */ + +function getWeek(dirtyDate, options) { + (0, _index4.default)(1, arguments); + var date = (0, _index3.default)(dirtyDate); + var diff = (0, _index.default)(date, options).getTime() - (0, _index2.default)(date, options).getTime(); // Round the number of days to the nearest integer + // because the number of milliseconds in a week is not constant + // (e.g. it's different in the week of the daylight saving time clock shift) + + return Math.round(diff / MILLISECONDS_IN_WEEK) + 1; +} + +module.exports = exports.default; + +/***/ }), + /***/ 9482: /***/ ((module, exports, __nccwpck_require__) => { @@ -15945,7 +15945,7 @@ module.exports = exports.default; /***/ }), -/***/ 1982: +/***/ 3858: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -15954,148 +15954,40 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = intlFormat; +exports["default"] = intlFormatDistance; -var _index = _interopRequireDefault(__nccwpck_require__(2063)); +var _index = __nccwpck_require__(5756); + +var _index2 = _interopRequireDefault(__nccwpck_require__(3086)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(5536)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(2342)); + +var _index5 = _interopRequireDefault(__nccwpck_require__(1633)); + +var _index6 = _interopRequireDefault(__nccwpck_require__(5237)); + +var _index7 = _interopRequireDefault(__nccwpck_require__(8740)); + +var _index8 = _interopRequireDefault(__nccwpck_require__(3842)); + +var _index9 = _interopRequireDefault(__nccwpck_require__(9448)); + +var _index10 = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index11 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name intlFormat + * @name intlFormatDistance * @category Common Helpers - * @summary Format the date with Intl.DateTimeFormat (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat). - * + * @summary Formats distance between two dates in a human-readable format * @description - * Return the formatted date string in the given format. - * The method uses [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) inside. - * formatOptions are the same as [`Intl.DateTimeFormat` options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#using_options) + * The function calculates the difference between two dates and formats it as a human-readable string. * - * > ⚠️ Please note that before Node version 13.0.0, only the locale data for en-US is available by default. - * - * @param {Date|Number} argument - the original date. - * @param {Object} [formatOptions] - an object with options. - * @param {'lookup'|'best fit'} [formatOptions.localeMatcher='best fit'] - locale selection algorithm. - * @param {'narrow'|'short'|'long'} [formatOptions.weekday] - representation the days of the week. - * @param {'narrow'|'short'|'long'} [formatOptions.era] - representation of eras. - * @param {'numeric'|'2-digit'} [formatOptions.year] - representation of years. - * @param {'numeric'|'2-digit'|'narrow'|'short'|'long'} [formatOptions.month='numeric'] - representation of month. - * @param {'numeric'|'2-digit'} [formatOptions.day='numeric'] - representation of day. - * @param {'numeric'|'2-digit'} [formatOptions.hour='numeric'] - representation of hours. - * @param {'numeric'|'2-digit'} [formatOptions.minute] - representation of minutes. - * @param {'numeric'|'2-digit'} [formatOptions.second] - representation of seconds. - * @param {'short'|'long'} [formatOptions.timeZoneName] - representation of names of time zones. - * @param {'basic'|'best fit'} [formatOptions.formatMatcher='best fit'] - format selection algorithm. - * @param {Boolean} [formatOptions.hour12] - determines whether to use 12-hour time format. - * @param {String} [formatOptions.timeZone] - the time zone to use. - * @param {Object} [localeOptions] - an object with locale. - * @param {String|String[]} [localeOptions.locale] - the locale code - * @returns {String} the formatted date string. - * @throws {TypeError} 1 argument required. - * @throws {RangeError} `date` must not be Invalid Date - * - * @example - * // Represent 10 October 2019 in German. - * // Convert the date with format's options and locale's options. - * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), { - * weekday: 'long', - * year: 'numeric', - * month: 'long', - * day: 'numeric', - * }, { - * locale: 'de-DE', - * }) - * //=> Freitag, 4. Oktober 2019 - * - * @example - * // Represent 10 October 2019. - * // Convert the date with format's options. - * const result = intlFormat.default(new Date(2019, 9, 4, 12, 30, 13, 456), { - * year: 'numeric', - * month: 'numeric', - * day: 'numeric', - * hour: 'numeric', - * }) - * //=> 10/4/2019, 12 PM - * - * @example - * // Represent 10 October 2019 in Korean. - * // Convert the date with locale's options. - * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), { - * locale: 'ko-KR', - * }) - * //=> 2019. 10. 4. - * - * @example - * // Represent 10 October 2019 in middle-endian format: - * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456)) - * //=> 10/4/2019 - */ -function intlFormat(date, formatOrLocale, localeOptions) { - var _localeOptions; - - (0, _index.default)(1, arguments); - var formatOptions; - - if (isFormatOptions(formatOrLocale)) { - formatOptions = formatOrLocale; - } else { - localeOptions = formatOrLocale; - } - - return new Intl.DateTimeFormat((_localeOptions = localeOptions) === null || _localeOptions === void 0 ? void 0 : _localeOptions.locale, formatOptions).format(date); -} - -function isFormatOptions(opts) { - return opts !== undefined && !('locale' in opts); -} - -module.exports = exports.default; - -/***/ }), - -/***/ 3858: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = intlFormatDistance; - -var _index = __nccwpck_require__(5756); - -var _index2 = _interopRequireDefault(__nccwpck_require__(3086)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(5536)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(2342)); - -var _index5 = _interopRequireDefault(__nccwpck_require__(1633)); - -var _index6 = _interopRequireDefault(__nccwpck_require__(5237)); - -var _index7 = _interopRequireDefault(__nccwpck_require__(8740)); - -var _index8 = _interopRequireDefault(__nccwpck_require__(3842)); - -var _index9 = _interopRequireDefault(__nccwpck_require__(9448)); - -var _index10 = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index11 = _interopRequireDefault(__nccwpck_require__(2063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @name intlFormatDistance - * @category Common Helpers - * @summary Formats distance between two dates in a human-readable format - * @description - * The function calculates the difference between two dates and formats it as a human-readable string. - * - * The function will pick the most appropriate unit depending on the distance between dates. For example, if the distance is a few hours, it might return `x hours`. If the distance is a few months, it might return `x months`. + * The function will pick the most appropriate unit depending on the distance between dates. For example, if the distance is a few hours, it might return `x hours`. If the distance is a few months, it might return `x months`. * * You can also specify a unit to force using it regardless of the distance to get a result like `123456 hours`. * @@ -16265,6 +16157,114 @@ module.exports = exports.default; /***/ }), +/***/ 1982: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = intlFormat; + +var _index = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name intlFormat + * @category Common Helpers + * @summary Format the date with Intl.DateTimeFormat (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat). + * + * @description + * Return the formatted date string in the given format. + * The method uses [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) inside. + * formatOptions are the same as [`Intl.DateTimeFormat` options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#using_options) + * + * > ⚠️ Please note that before Node version 13.0.0, only the locale data for en-US is available by default. + * + * @param {Date|Number} argument - the original date. + * @param {Object} [formatOptions] - an object with options. + * @param {'lookup'|'best fit'} [formatOptions.localeMatcher='best fit'] - locale selection algorithm. + * @param {'narrow'|'short'|'long'} [formatOptions.weekday] - representation the days of the week. + * @param {'narrow'|'short'|'long'} [formatOptions.era] - representation of eras. + * @param {'numeric'|'2-digit'} [formatOptions.year] - representation of years. + * @param {'numeric'|'2-digit'|'narrow'|'short'|'long'} [formatOptions.month='numeric'] - representation of month. + * @param {'numeric'|'2-digit'} [formatOptions.day='numeric'] - representation of day. + * @param {'numeric'|'2-digit'} [formatOptions.hour='numeric'] - representation of hours. + * @param {'numeric'|'2-digit'} [formatOptions.minute] - representation of minutes. + * @param {'numeric'|'2-digit'} [formatOptions.second] - representation of seconds. + * @param {'short'|'long'} [formatOptions.timeZoneName] - representation of names of time zones. + * @param {'basic'|'best fit'} [formatOptions.formatMatcher='best fit'] - format selection algorithm. + * @param {Boolean} [formatOptions.hour12] - determines whether to use 12-hour time format. + * @param {String} [formatOptions.timeZone] - the time zone to use. + * @param {Object} [localeOptions] - an object with locale. + * @param {String|String[]} [localeOptions.locale] - the locale code + * @returns {String} the formatted date string. + * @throws {TypeError} 1 argument required. + * @throws {RangeError} `date` must not be Invalid Date + * + * @example + * // Represent 10 October 2019 in German. + * // Convert the date with format's options and locale's options. + * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), { + * weekday: 'long', + * year: 'numeric', + * month: 'long', + * day: 'numeric', + * }, { + * locale: 'de-DE', + * }) + * //=> Freitag, 4. Oktober 2019 + * + * @example + * // Represent 10 October 2019. + * // Convert the date with format's options. + * const result = intlFormat.default(new Date(2019, 9, 4, 12, 30, 13, 456), { + * year: 'numeric', + * month: 'numeric', + * day: 'numeric', + * hour: 'numeric', + * }) + * //=> 10/4/2019, 12 PM + * + * @example + * // Represent 10 October 2019 in Korean. + * // Convert the date with locale's options. + * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), { + * locale: 'ko-KR', + * }) + * //=> 2019. 10. 4. + * + * @example + * // Represent 10 October 2019 in middle-endian format: + * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456)) + * //=> 10/4/2019 + */ +function intlFormat(date, formatOrLocale, localeOptions) { + var _localeOptions; + + (0, _index.default)(1, arguments); + var formatOptions; + + if (isFormatOptions(formatOrLocale)) { + formatOptions = formatOrLocale; + } else { + localeOptions = formatOrLocale; + } + + return new Intl.DateTimeFormat((_localeOptions = localeOptions) === null || _localeOptions === void 0 ? void 0 : _localeOptions.locale, formatOptions).format(date); +} + +function isFormatOptions(opts) { + return opts !== undefined && !('locale' in opts); +} + +module.exports = exports.default; + +/***/ }), + /***/ 2755: /***/ ((module, exports, __nccwpck_require__) => { @@ -17255,7 +17255,7 @@ module.exports = exports.default; /***/ }), -/***/ 9852: +/***/ 3944: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -17264,51 +17264,46 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSameISOWeek; +exports["default"] = isSameISOWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(7013)); +var _index = _interopRequireDefault(__nccwpck_require__(776)); var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isSameISOWeek - * @category ISO Week Helpers - * @summary Are the given dates in the same ISO week (and year)? + * @name isSameISOWeekYear + * @category ISO Week-Numbering Year Helpers + * @summary Are the given dates in the same ISO week-numbering year? * * @description - * Are the given dates in the same ISO week (and year)? + * Are the given dates in the same ISO week-numbering year? * * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * * @param {Date|Number} dateLeft - the first date to check * @param {Date|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week (and year) + * @returns {Boolean} the dates are in the same ISO week-numbering year * @throws {TypeError} 2 arguments required * * @example - * // Are 1 September 2014 and 7 September 2014 in the same ISO week? - * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2014, 8, 7)) + * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year? + * const result = isSameISOWeekYear(new Date(2003, 11, 29), new Date(2005, 0, 2)) * //=> true - * - * @example - * // Are 1 September 2014 and 1 September 2015 in the same ISO week? - * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2015, 8, 1)) - * //=> false */ -function isSameISOWeek(dirtyDateLeft, dirtyDateRight) { +function isSameISOWeekYear(dirtyDateLeft, dirtyDateRight) { (0, _index2.default)(2, arguments); - return (0, _index.default)(dirtyDateLeft, dirtyDateRight, { - weekStartsOn: 1 - }); + var dateLeftStartOfYear = (0, _index.default)(dirtyDateLeft); + var dateRightStartOfYear = (0, _index.default)(dirtyDateRight); + return dateLeftStartOfYear.getTime() === dateRightStartOfYear.getTime(); } module.exports = exports.default; /***/ }), -/***/ 3944: +/***/ 9852: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -17317,39 +17312,44 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isSameISOWeekYear; +exports["default"] = isSameISOWeek; -var _index = _interopRequireDefault(__nccwpck_require__(776)); +var _index = _interopRequireDefault(__nccwpck_require__(7013)); var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name isSameISOWeekYear - * @category ISO Week-Numbering Year Helpers - * @summary Are the given dates in the same ISO week-numbering year? + * @name isSameISOWeek + * @category ISO Week Helpers + * @summary Are the given dates in the same ISO week (and year)? * * @description - * Are the given dates in the same ISO week-numbering year? + * Are the given dates in the same ISO week (and year)? * * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * * @param {Date|Number} dateLeft - the first date to check * @param {Date|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week-numbering year + * @returns {Boolean} the dates are in the same ISO week (and year) * @throws {TypeError} 2 arguments required * * @example - * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year? - * const result = isSameISOWeekYear(new Date(2003, 11, 29), new Date(2005, 0, 2)) + * // Are 1 September 2014 and 7 September 2014 in the same ISO week? + * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2014, 8, 7)) * //=> true + * + * @example + * // Are 1 September 2014 and 1 September 2015 in the same ISO week? + * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2015, 8, 1)) + * //=> false */ -function isSameISOWeekYear(dirtyDateLeft, dirtyDateRight) { +function isSameISOWeek(dirtyDateLeft, dirtyDateRight) { (0, _index2.default)(2, arguments); - var dateLeftStartOfYear = (0, _index.default)(dirtyDateLeft); - var dateRightStartOfYear = (0, _index.default)(dirtyDateRight); - return dateLeftStartOfYear.getTime() === dateRightStartOfYear.getTime(); + return (0, _index.default)(dirtyDateLeft, dirtyDateRight, { + weekStartsOn: 1 + }); } module.exports = exports.default; @@ -18671,7 +18671,7 @@ module.exports = exports.default; /***/ }), -/***/ 7692: +/***/ 217: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -18680,46 +18680,53 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = lastDayOfISOWeek; +exports["default"] = lastDayOfISOWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(666)); +var _index = _interopRequireDefault(__nccwpck_require__(6991)); -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(6307)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name lastDayOfISOWeek - * @category ISO Week Helpers - * @summary Return the last day of an ISO week for the given date. + * @name lastDayOfISOWeekYear + * @category ISO Week-Numbering Year Helpers + * @summary Return the last day of an ISO week-numbering year for the given date. * * @description - * Return the last day of an ISO week for the given date. + * Return the last day of an ISO week-numbering year, + * which always starts 3 days before the year's first Thursday. * The result will be in the local timezone. * * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * * @param {Date|Number} date - the original date - * @returns {Date} the last day of an ISO week + * @returns {Date} the end of an ISO week-numbering year * @throws {TypeError} 1 argument required * * @example - * // The last day of an ISO week for 2 September 2014 11:55:00: - * const result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 00:00:00 + * // The last day of an ISO week-numbering year for 2 July 2005: + * const result = lastDayOfISOWeekYear(new Date(2005, 6, 2)) + * //=> Sun Jan 01 2006 00:00:00 */ -function lastDayOfISOWeek(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate, { - weekStartsOn: 1 - }); +function lastDayOfISOWeekYear(dirtyDate) { + (0, _index3.default)(1, arguments); + var year = (0, _index.default)(dirtyDate); + var fourthOfJanuary = new Date(0); + fourthOfJanuary.setFullYear(year + 1, 0, 4); + fourthOfJanuary.setHours(0, 0, 0, 0); + var date = (0, _index2.default)(fourthOfJanuary); + date.setDate(date.getDate() - 1); + return date; } module.exports = exports.default; /***/ }), -/***/ 217: +/***/ 7692: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -18728,46 +18735,39 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = lastDayOfISOWeekYear; - -var _index = _interopRequireDefault(__nccwpck_require__(6991)); +exports["default"] = lastDayOfISOWeek; -var _index2 = _interopRequireDefault(__nccwpck_require__(6307)); +var _index = _interopRequireDefault(__nccwpck_require__(666)); -var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name lastDayOfISOWeekYear - * @category ISO Week-Numbering Year Helpers - * @summary Return the last day of an ISO week-numbering year for the given date. + * @name lastDayOfISOWeek + * @category ISO Week Helpers + * @summary Return the last day of an ISO week for the given date. * * @description - * Return the last day of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. + * Return the last day of an ISO week for the given date. * The result will be in the local timezone. * * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * * @param {Date|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year + * @returns {Date} the last day of an ISO week * @throws {TypeError} 1 argument required * * @example - * // The last day of an ISO week-numbering year for 2 July 2005: - * const result = lastDayOfISOWeekYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 00:00:00 + * // The last day of an ISO week for 2 September 2014 11:55:00: + * const result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Sun Sep 07 2014 00:00:00 */ -function lastDayOfISOWeekYear(dirtyDate) { - (0, _index3.default)(1, arguments); - var year = (0, _index.default)(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year + 1, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = (0, _index2.default)(fourthOfJanuary); - date.setDate(date.getDate() - 1); - return date; +function lastDayOfISOWeek(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate, { + weekStartsOn: 1 + }); } module.exports = exports.default; @@ -19893,79 +19893,6 @@ module.exports = exports.default; /***/ }), -/***/ 6133: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = milliseconds; - -var _index = _interopRequireDefault(__nccwpck_require__(2063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// Leap year occures every 4 years, except for years that are divisable by 100 and not divisable by 400. -// 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days -var daysInYear = 365.2425; -/** - * @name milliseconds - * @category Millisecond Helpers - * @summary - * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds. - * - * @description - * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds. - * - * One years equals 365.2425 days according to the formula: - * - * > Leap year occures every 4 years, except for years that are divisable by 100 and not divisable by 400. - * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days - * - * One month is a year divided by 12. - * - * @param {Duration} duration - the object with years, months, weeks, days, hours, minutes and seconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {number} the milliseconds - * @throws {TypeError} 1 argument required - * - * @example - * // 1 year in milliseconds - * milliseconds({ years: 1 }) - * //=> 31556952000 - * - * // 3 months in milliseconds - * milliseconds({ months: 3 }) - * //=> 7889238000 - */ - -function milliseconds(_ref) { - var years = _ref.years, - months = _ref.months, - weeks = _ref.weeks, - days = _ref.days, - hours = _ref.hours, - minutes = _ref.minutes, - seconds = _ref.seconds; - (0, _index.default)(1, arguments); - var totalDays = 0; - if (years) totalDays += years * daysInYear; - if (months) totalDays += months * (daysInYear / 12); - if (weeks) totalDays += weeks * 7; - if (days) totalDays += days; - var totalSeconds = totalDays * 24 * 60 * 60; - if (hours) totalSeconds += hours * 60 * 60; - if (minutes) totalSeconds += minutes * 60; - if (seconds) totalSeconds += seconds; - return Math.round(totalSeconds * 1000); -} - -module.exports = exports.default; - -/***/ }), - /***/ 9571: /***/ ((module, exports, __nccwpck_require__) => { @@ -20116,7 +20043,7 @@ module.exports = exports.default; /***/ }), -/***/ 5310: +/***/ 6133: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -20125,61 +20052,134 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = min; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); +exports["default"] = milliseconds; -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - +// Leap year occures every 4 years, except for years that are divisable by 100 and not divisable by 400. +// 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days +var daysInYear = 365.2425; /** - * @name min - * @category Common Helpers - * @summary Returns the earliest of the given dates. + * @name milliseconds + * @category Millisecond Helpers + * @summary + * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds. * * @description - * Returns the earliest of the given dates. + * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds. * - * @param {Date[]|Number[]} datesArray - the dates to compare - * @returns {Date} - the earliest of the dates + * One years equals 365.2425 days according to the formula: + * + * > Leap year occures every 4 years, except for years that are divisable by 100 and not divisable by 400. + * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days + * + * One month is a year divided by 12. + * + * @param {Duration} duration - the object with years, months, weeks, days, hours, minutes and seconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {number} the milliseconds * @throws {TypeError} 1 argument required * * @example - * // Which of these dates is the earliest? - * const result = min([ - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ]) - * //=> Wed Feb 11 1987 00:00:00 + * // 1 year in milliseconds + * milliseconds({ years: 1 }) + * //=> 31556952000 + * + * // 3 months in milliseconds + * milliseconds({ months: 3 }) + * //=> 7889238000 */ -function min(dirtyDatesArray) { - (0, _index2.default)(1, arguments); - var datesArray; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method - - if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') { - datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. - } else if (_typeof(dirtyDatesArray) === 'object' && dirtyDatesArray !== null) { - datesArray = Array.prototype.slice.call(dirtyDatesArray); - } else { - // `dirtyDatesArray` is non-iterable, return Invalid Date - return new Date(NaN); - } - - var result; - datesArray.forEach(function (dirtyDate) { - var currentDate = (0, _index.default)(dirtyDate); - - if (result === undefined || result > currentDate || isNaN(currentDate.getDate())) { - result = currentDate; - } - }); - return result || new Date(NaN); -} + +function milliseconds(_ref) { + var years = _ref.years, + months = _ref.months, + weeks = _ref.weeks, + days = _ref.days, + hours = _ref.hours, + minutes = _ref.minutes, + seconds = _ref.seconds; + (0, _index.default)(1, arguments); + var totalDays = 0; + if (years) totalDays += years * daysInYear; + if (months) totalDays += months * (daysInYear / 12); + if (weeks) totalDays += weeks * 7; + if (days) totalDays += days; + var totalSeconds = totalDays * 24 * 60 * 60; + if (hours) totalSeconds += hours * 60 * 60; + if (minutes) totalSeconds += minutes * 60; + if (seconds) totalSeconds += seconds; + return Math.round(totalSeconds * 1000); +} + +module.exports = exports.default; + +/***/ }), + +/***/ 5310: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = min; + +var _index = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * @name min + * @category Common Helpers + * @summary Returns the earliest of the given dates. + * + * @description + * Returns the earliest of the given dates. + * + * @param {Date[]|Number[]} datesArray - the dates to compare + * @returns {Date} - the earliest of the dates + * @throws {TypeError} 1 argument required + * + * @example + * // Which of these dates is the earliest? + * const result = min([ + * new Date(1989, 6, 10), + * new Date(1987, 1, 11), + * new Date(1995, 6, 2), + * new Date(1990, 0, 1) + * ]) + * //=> Wed Feb 11 1987 00:00:00 + */ +function min(dirtyDatesArray) { + (0, _index2.default)(1, arguments); + var datesArray; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method + + if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') { + datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. + } else if (_typeof(dirtyDatesArray) === 'object' && dirtyDatesArray !== null) { + datesArray = Array.prototype.slice.call(dirtyDatesArray); + } else { + // `dirtyDatesArray` is non-iterable, return Invalid Date + return new Date(NaN); + } + + var result; + datesArray.forEach(function (dirtyDate) { + var currentDate = (0, _index.default)(dirtyDate); + + if (result === undefined || result > currentDate || isNaN(currentDate.getDate())) { + result = currentDate; + } + }); + return result || new Date(NaN); +} module.exports = exports.default; @@ -20776,8 +20776,8 @@ module.exports = exports.default; /***/ }), -/***/ 5619: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 3390: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -20785,364 +20785,410 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Parser = void 0; - -var _Setter = __nccwpck_require__(5665); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +exports["default"] = parseISO; -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } +var _index = __nccwpck_require__(5756); -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); -var Parser = /*#__PURE__*/function () { - function Parser() { - _classCallCheck(this, Parser); - } +var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); - _createClass(Parser, [{ - key: "run", - value: function run(dateString, token, match, options) { - var result = this.parse(dateString, token, match, options); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (!result) { - return null; - } +/** + * @name parseISO + * @category Common Helpers + * @summary Parse ISO string + * + * @description + * Parse the given string in ISO 8601 format and return an instance of Date. + * + * Function accepts complete ISO 8601 formats as well as partial implementations. + * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 + * + * If the argument isn't a string, the function cannot parse the string or + * the values are invalid, it returns Invalid Date. + * + * @param {String} argument - the value to convert + * @param {Object} [options] - an object with options. + * @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format + * @returns {Date} the parsed date in the local time zone + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2 + * + * @example + * // Convert string '2014-02-11T11:30:30' to date: + * const result = parseISO('2014-02-11T11:30:30') + * //=> Tue Feb 11 2014 11:30:30 + * + * @example + * // Convert string '+02014101' to date, + * // if the additional number of digits in the extended year format is 1: + * const result = parseISO('+02014101', { additionalDigits: 1 }) + * //=> Fri Apr 11 2014 00:00:00 + */ +function parseISO(argument, options) { + var _options$additionalDi; - return { - setter: new _Setter.ValueSetter(result.value, this.validate, this.set, this.priority, this.subPriority), - rest: result.rest - }; - } - }, { - key: "validate", - value: function validate(_utcDate, _value, _options) { - return true; - } - }]); + (0, _index2.default)(1, arguments); + var additionalDigits = (0, _index3.default)((_options$additionalDi = options === null || options === void 0 ? void 0 : options.additionalDigits) !== null && _options$additionalDi !== void 0 ? _options$additionalDi : 2); - return Parser; -}(); + if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) { + throw new RangeError('additionalDigits must be 0, 1 or 2'); + } -exports.Parser = Parser; + if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) { + return new Date(NaN); + } -/***/ }), + var dateStrings = splitDateString(argument); + var date; -/***/ 5665: -/***/ ((__unused_webpack_module, exports) => { + if (dateStrings.date) { + var parseYearResult = parseYear(dateStrings.date, additionalDigits); + date = parseDate(parseYearResult.restDateString, parseYearResult.year); + } -"use strict"; + if (!date || isNaN(date.getTime())) { + return new Date(NaN); + } + var timestamp = date.getTime(); + var time = 0; + var offset; -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + if (dateStrings.time) { + time = parseTime(dateStrings.time); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ValueSetter = exports.Setter = exports.DateToSystemTimezoneSetter = void 0; + if (isNaN(time)) { + return new Date(NaN); + } + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + if (dateStrings.timezone) { + offset = parseTimezone(dateStrings.timezone); -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + if (isNaN(offset)) { + return new Date(NaN); + } + } else { + var dirtyDate = new Date(timestamp + time); // js parsed string assuming it's in UTC timezone + // but we need it to be parsed in our timezone + // so we use utc values to build date in our timezone. + // Year values from 0 to 99 map to the years 1900 to 1999 + // so set year explicitly with setFullYear. -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + var result = new Date(0); + result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate()); + result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds()); + return result; + } -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + return new Date(timestamp + time + offset); +} -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +var patterns = { + dateTimeDelimiter: /[T ]/, + timeZoneDelimiter: /[Z ]/i, + timezone: /([Z+-].*)$/ +}; +var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/; +var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/; +var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/; -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function splitDateString(dateString) { + var dateStrings = {}; + var array = dateString.split(patterns.dateTimeDelimiter); + var timeString; // The regex match should only return at maximum two array elements. + // [date], [time], or [date, time]. -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + if (array.length > 2) { + return dateStrings; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + if (/:/.test(array[0])) { + timeString = array[0]; + } else { + dateStrings.date = array[0]; + timeString = array[1]; -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + if (patterns.timeZoneDelimiter.test(dateStrings.date)) { + dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0]; + timeString = dateString.substr(dateStrings.date.length, dateString.length); + } + } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + if (timeString) { + var token = patterns.timezone.exec(timeString); -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var TIMEZONE_UNIT_PRIORITY = 10; - -var Setter = /*#__PURE__*/function () { - function Setter() { - _classCallCheck(this, Setter); - - _defineProperty(this, "subPriority", 0); - } - - _createClass(Setter, [{ - key: "validate", - value: function validate(_utcDate, _options) { - return true; + if (token) { + dateStrings.time = timeString.replace(token[1], ''); + dateStrings.timezone = token[1]; + } else { + dateStrings.time = timeString; } - }]); - - return Setter; -}(); + } -exports.Setter = Setter; + return dateStrings; +} -var ValueSetter = /*#__PURE__*/function (_Setter) { - _inherits(ValueSetter, _Setter); +function parseYear(dateString, additionalDigits) { + var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)'); + var captures = dateString.match(regex); // Invalid ISO-formatted year - var _super = _createSuper(ValueSetter); + if (!captures) return { + year: NaN, + restDateString: '' + }; + var year = captures[1] ? parseInt(captures[1]) : null; + var century = captures[2] ? parseInt(captures[2]) : null; // either year or century is null, not both - function ValueSetter(value, validateValue, setValue, priority, subPriority) { - var _this; + return { + year: century === null ? year : century * 100, + restDateString: dateString.slice((captures[1] || captures[2]).length) + }; +} - _classCallCheck(this, ValueSetter); +function parseDate(dateString, year) { + // Invalid ISO-formatted year + if (year === null) return new Date(NaN); + var captures = dateString.match(dateRegex); // Invalid ISO-formatted string - _this = _super.call(this); - _this.value = value; - _this.validateValue = validateValue; - _this.setValue = setValue; - _this.priority = priority; + if (!captures) return new Date(NaN); + var isWeekDate = !!captures[4]; + var dayOfYear = parseDateUnit(captures[1]); + var month = parseDateUnit(captures[2]) - 1; + var day = parseDateUnit(captures[3]); + var week = parseDateUnit(captures[4]); + var dayOfWeek = parseDateUnit(captures[5]) - 1; - if (subPriority) { - _this.subPriority = subPriority; + if (isWeekDate) { + if (!validateWeekDate(year, week, dayOfWeek)) { + return new Date(NaN); } - return _this; - } + return dayOfISOWeekYear(year, week, dayOfWeek); + } else { + var date = new Date(0); - _createClass(ValueSetter, [{ - key: "validate", - value: function validate(utcDate, options) { - return this.validateValue(utcDate, this.value, options); - } - }, { - key: "set", - value: function set(utcDate, flags, options) { - return this.setValue(utcDate, flags, this.value, options); + if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) { + return new Date(NaN); } - }]); - return ValueSetter; -}(Setter); + date.setUTCFullYear(year, month, Math.max(dayOfYear, day)); + return date; + } +} -exports.ValueSetter = ValueSetter; +function parseDateUnit(value) { + return value ? parseInt(value) : 1; +} -var DateToSystemTimezoneSetter = /*#__PURE__*/function (_Setter2) { - _inherits(DateToSystemTimezoneSetter, _Setter2); +function parseTime(timeString) { + var captures = timeString.match(timeRegex); + if (!captures) return NaN; // Invalid ISO-formatted time - var _super2 = _createSuper(DateToSystemTimezoneSetter); + var hours = parseTimeUnit(captures[1]); + var minutes = parseTimeUnit(captures[2]); + var seconds = parseTimeUnit(captures[3]); - function DateToSystemTimezoneSetter() { - var _this2; + if (!validateTime(hours, minutes, seconds)) { + return NaN; + } - _classCallCheck(this, DateToSystemTimezoneSetter); + return hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute + seconds * 1000; +} - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } +function parseTimeUnit(value) { + return value && parseFloat(value.replace(',', '.')) || 0; +} - _this2 = _super2.call.apply(_super2, [this].concat(args)); +function parseTimezone(timezoneString) { + if (timezoneString === 'Z') return 0; + var captures = timezoneString.match(timezoneRegex); + if (!captures) return 0; + var sign = captures[1] === '+' ? -1 : 1; + var hours = parseInt(captures[2]); + var minutes = captures[3] && parseInt(captures[3]) || 0; - _defineProperty(_assertThisInitialized(_this2), "priority", TIMEZONE_UNIT_PRIORITY); + if (!validateTimezone(hours, minutes)) { + return NaN; + } - _defineProperty(_assertThisInitialized(_this2), "subPriority", -1); + return sign * (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute); +} - return _this2; - } +function dayOfISOWeekYear(isoWeekYear, week, day) { + var date = new Date(0); + date.setUTCFullYear(isoWeekYear, 0, 4); + var fourthOfJanuaryDay = date.getUTCDay() || 7; + var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay; + date.setUTCDate(date.getUTCDate() + diff); + return date; +} // Validation functions +// February is null to handle the leap year (using ||) - _createClass(DateToSystemTimezoneSetter, [{ - key: "set", - value: function set(date, flags) { - if (flags.timestampIsSet) { - return date; - } - var convertedDate = new Date(0); - convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); - convertedDate.setHours(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()); - return convertedDate; - } - }]); +var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - return DateToSystemTimezoneSetter; -}(Setter); +function isLeapYearIndex(year) { + return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; +} -exports.DateToSystemTimezoneSetter = DateToSystemTimezoneSetter; +function validateDate(year, month, date) { + return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28)); +} -/***/ }), +function validateDayOfYearDate(year, dayOfYear) { + return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365); +} -/***/ 463: -/***/ ((__unused_webpack_module, exports) => { +function validateWeekDate(_year, week, day) { + return week >= 1 && week <= 53 && day >= 0 && day <= 6; +} -"use strict"; +function validateTime(hours, minutes, seconds) { + if (hours === 24) { + return minutes === 0 && seconds === 0; + } + return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25; +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.timezonePatterns = exports.numericPatterns = void 0; -var numericPatterns = { - month: /^(1[0-2]|0?\d)/, - // 0 to 12 - date: /^(3[0-1]|[0-2]?\d)/, - // 0 to 31 - dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/, - // 0 to 366 - week: /^(5[0-3]|[0-4]?\d)/, - // 0 to 53 - hour23h: /^(2[0-3]|[0-1]?\d)/, - // 0 to 23 - hour24h: /^(2[0-4]|[0-1]?\d)/, - // 0 to 24 - hour11h: /^(1[0-1]|0?\d)/, - // 0 to 11 - hour12h: /^(1[0-2]|0?\d)/, - // 0 to 12 - minute: /^[0-5]?\d/, - // 0 to 59 - second: /^[0-5]?\d/, - // 0 to 59 - singleDigit: /^\d/, - // 0 to 9 - twoDigits: /^\d{1,2}/, - // 0 to 99 - threeDigits: /^\d{1,3}/, - // 0 to 999 - fourDigits: /^\d{1,4}/, - // 0 to 9999 - anyDigitsSigned: /^-?\d+/, - singleDigitSigned: /^-?\d/, - // 0 to 9, -0 to -9 - twoDigitsSigned: /^-?\d{1,2}/, - // 0 to 99, -0 to -99 - threeDigitsSigned: /^-?\d{1,3}/, - // 0 to 999, -0 to -999 - fourDigitsSigned: /^-?\d{1,4}/ // 0 to 9999, -0 to -9999 +function validateTimezone(_hours, minutes) { + return minutes >= 0 && minutes <= 59; +} -}; -exports.numericPatterns = numericPatterns; -var timezonePatterns = { - basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/, - basic: /^([+-])(\d{2})(\d{2})|Z/, - basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/, - extended: /^([+-])(\d{2}):(\d{2})|Z/, - extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/ -}; -exports.timezonePatterns = timezonePatterns; +module.exports = exports.default; /***/ }), -/***/ 9187: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 8159: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AMPMMidnightParser = void 0; - -var _Parser2 = __nccwpck_require__(5619); - -var _utils = __nccwpck_require__(9042); +exports["default"] = parseJSON; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +var _index = _interopRequireDefault(__nccwpck_require__(6477)); -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +/** + * @name parseJSON + * @category Common Helpers + * @summary Parse a JSON date string + * + * @description + * Converts a complete ISO date string in UTC time, the typical format for transmitting + * a date in JSON, to a JavaScript `Date` instance. + * + * This is a minimal implementation for converting dates retrieved from a JSON API to + * a `Date` instance which can be used with other functions in the `date-fns` library. + * The following formats are supported: + * + * - `2000-03-15T05:20:10.123Z`: The output of `.toISOString()` and `JSON.stringify(new Date())` + * - `2000-03-15T05:20:10Z`: Without milliseconds + * - `2000-03-15T05:20:10+00:00`: With a zero offset, the default JSON encoded format in some other languages + * - `2000-03-15T05:20:10+05:45`: With a positive or negative offset, the default JSON encoded format in some other languages + * - `2000-03-15T05:20:10+0000`: With a zero offset without a colon + * - `2000-03-15T05:20:10`: Without a trailing 'Z' symbol + * - `2000-03-15T05:20:10.1234567`: Up to 7 digits in milliseconds field. Only first 3 are taken into account since JS does not allow fractional milliseconds + * - `2000-03-15 05:20:10`: With a space instead of a 'T' separator for APIs returning a SQL date without reformatting + * + * For convenience and ease of use these other input types are also supported + * via [toDate]{@link https://date-fns.org/docs/toDate}: + * + * - A `Date` instance will be cloned + * - A `number` will be treated as a timestamp + * + * Any other input type or invalid date strings will return an `Invalid Date`. + * + * @param {String|Number|Date} argument A fully formed ISO8601 date string to convert + * @returns {Date} the parsed date in the local time zone + * @throws {TypeError} 1 argument required + */ +function parseJSON(argument) { + (0, _index2.default)(1, arguments); -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + if (typeof argument === 'string') { + var parts = argument.match(/(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:Z|(.)(\d{2}):?(\d{2})?)?/); -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + if (parts) { + // Group 8 matches the sign + return new Date(Date.UTC(+parts[1], +parts[2] - 1, +parts[3], +parts[4] - (+parts[9] || 0) * (parts[8] == '-' ? -1 : 1), +parts[5] - (+parts[10] || 0) * (parts[8] == '-' ? -1 : 1), +parts[6], +((parts[7] || '0') + '00').substring(0, 3))); + } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + return new Date(NaN); + } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + return (0, _index.default)(argument); +} -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +module.exports = exports.default; -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +/***/ }), -var AMPMMidnightParser = /*#__PURE__*/function (_Parser) { - _inherits(AMPMMidnightParser, _Parser); +/***/ 5619: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var _super = _createSuper(AMPMMidnightParser); +"use strict"; - function AMPMMidnightParser() { - var _this; - _classCallCheck(this, AMPMMidnightParser); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Parser = void 0; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } +var _Setter = __nccwpck_require__(5665); - _this = _super.call.apply(_super, [this].concat(args)); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - _defineProperty(_assertThisInitialized(_this), "priority", 80); +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['a', 'B', 'H', 'k', 't', 'T']); +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - return _this; +var Parser = /*#__PURE__*/function () { + function Parser() { + _classCallCheck(this, Parser); } - _createClass(AMPMMidnightParser, [{ - key: "parse", - value: function parse(dateString, token, match) { - switch (token) { - case 'b': - case 'bb': - case 'bbb': - return match.dayPeriod(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.dayPeriod(dateString, { - width: 'narrow', - context: 'formatting' - }); - - case 'bbbbb': - return match.dayPeriod(dateString, { - width: 'narrow', - context: 'formatting' - }); + _createClass(Parser, [{ + key: "run", + value: function run(dateString, token, match, options) { + var result = this.parse(dateString, token, match, options); - case 'bbbb': - default: - return match.dayPeriod(dateString, { - width: 'wide', - context: 'formatting' - }) || match.dayPeriod(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.dayPeriod(dateString, { - width: 'narrow', - context: 'formatting' - }); + if (!result) { + return null; } + + return { + setter: new _Setter.ValueSetter(result.value, this.validate, this.set, this.priority, this.subPriority), + rest: result.rest + }; } }, { - key: "set", - value: function set(date, _flags, value) { - date.setUTCHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0); - return date; + key: "validate", + value: function validate(_utcDate, _value, _options) { + return true; } }]); - return AMPMMidnightParser; -}(_Parser2.Parser); + return Parser; +}(); -exports.AMPMMidnightParser = AMPMMidnightParser; +exports.Parser = Parser; /***/ }), -/***/ 8678: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5665: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -21152,17 +21198,7 @@ function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "functi Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AMPMParser = void 0; - -var _Parser2 = __nccwpck_require__(5619); - -var _utils = __nccwpck_require__(9042); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } +exports.ValueSetter = exports.Setter = exports.DateToSystemTimezoneSetter = void 0; function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } @@ -21178,82 +21214,181 @@ function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Re function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var AMPMParser = /*#__PURE__*/function (_Parser) { - _inherits(AMPMParser, _Parser); +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - var _super = _createSuper(AMPMParser); +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - function AMPMParser() { - var _this; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - _classCallCheck(this, AMPMParser); +var TIMEZONE_UNIT_PRIORITY = 10; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; +var Setter = /*#__PURE__*/function () { + function Setter() { + _classCallCheck(this, Setter); + + _defineProperty(this, "subPriority", 0); + } + + _createClass(Setter, [{ + key: "validate", + value: function validate(_utcDate, _options) { + return true; } + }]); - _this = _super.call.apply(_super, [this].concat(args)); + return Setter; +}(); - _defineProperty(_assertThisInitialized(_this), "priority", 80); +exports.Setter = Setter; - _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['b', 'B', 'H', 'k', 't', 'T']); +var ValueSetter = /*#__PURE__*/function (_Setter) { + _inherits(ValueSetter, _Setter); - return _this; - } + var _super = _createSuper(ValueSetter); - _createClass(AMPMParser, [{ - key: "parse", - value: function parse(dateString, token, match) { - switch (token) { - case 'a': - case 'aa': - case 'aaa': - return match.dayPeriod(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.dayPeriod(dateString, { - width: 'narrow', - context: 'formatting' - }); + function ValueSetter(value, validateValue, setValue, priority, subPriority) { + var _this; - case 'aaaaa': - return match.dayPeriod(dateString, { - width: 'narrow', - context: 'formatting' - }); + _classCallCheck(this, ValueSetter); - case 'aaaa': - default: - return match.dayPeriod(dateString, { - width: 'wide', - context: 'formatting' - }) || match.dayPeriod(dateString, { - width: 'abbreviated', - context: 'formatting' - }) || match.dayPeriod(dateString, { - width: 'narrow', - context: 'formatting' - }); - } + _this = _super.call(this); + _this.value = value; + _this.validateValue = validateValue; + _this.setValue = setValue; + _this.priority = priority; + + if (subPriority) { + _this.subPriority = subPriority; + } + + return _this; + } + + _createClass(ValueSetter, [{ + key: "validate", + value: function validate(utcDate, options) { + return this.validateValue(utcDate, this.value, options); } }, { key: "set", - value: function set(date, _flags, value) { - date.setUTCHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0); - return date; + value: function set(utcDate, flags, options) { + return this.setValue(utcDate, flags, this.value, options); } }]); - return AMPMParser; -}(_Parser2.Parser); + return ValueSetter; +}(Setter); -exports.AMPMParser = AMPMParser; +exports.ValueSetter = ValueSetter; + +var DateToSystemTimezoneSetter = /*#__PURE__*/function (_Setter2) { + _inherits(DateToSystemTimezoneSetter, _Setter2); + + var _super2 = _createSuper(DateToSystemTimezoneSetter); + + function DateToSystemTimezoneSetter() { + var _this2; + + _classCallCheck(this, DateToSystemTimezoneSetter); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _this2 = _super2.call.apply(_super2, [this].concat(args)); + + _defineProperty(_assertThisInitialized(_this2), "priority", TIMEZONE_UNIT_PRIORITY); + + _defineProperty(_assertThisInitialized(_this2), "subPriority", -1); + + return _this2; + } + + _createClass(DateToSystemTimezoneSetter, [{ + key: "set", + value: function set(date, flags) { + if (flags.timestampIsSet) { + return date; + } + + var convertedDate = new Date(0); + convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); + convertedDate.setHours(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()); + return convertedDate; + } + }]); + + return DateToSystemTimezoneSetter; +}(Setter); + +exports.DateToSystemTimezoneSetter = DateToSystemTimezoneSetter; /***/ }), -/***/ 4757: +/***/ 463: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.timezonePatterns = exports.numericPatterns = void 0; +var numericPatterns = { + month: /^(1[0-2]|0?\d)/, + // 0 to 12 + date: /^(3[0-1]|[0-2]?\d)/, + // 0 to 31 + dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/, + // 0 to 366 + week: /^(5[0-3]|[0-4]?\d)/, + // 0 to 53 + hour23h: /^(2[0-3]|[0-1]?\d)/, + // 0 to 23 + hour24h: /^(2[0-4]|[0-1]?\d)/, + // 0 to 24 + hour11h: /^(1[0-1]|0?\d)/, + // 0 to 11 + hour12h: /^(1[0-2]|0?\d)/, + // 0 to 12 + minute: /^[0-5]?\d/, + // 0 to 59 + second: /^[0-5]?\d/, + // 0 to 59 + singleDigit: /^\d/, + // 0 to 9 + twoDigits: /^\d{1,2}/, + // 0 to 99 + threeDigits: /^\d{1,3}/, + // 0 to 999 + fourDigits: /^\d{1,4}/, + // 0 to 9999 + anyDigitsSigned: /^-?\d+/, + singleDigitSigned: /^-?\d/, + // 0 to 9, -0 to -9 + twoDigitsSigned: /^-?\d{1,2}/, + // 0 to 99, -0 to -99 + threeDigitsSigned: /^-?\d{1,3}/, + // 0 to 999, -0 to -999 + fourDigitsSigned: /^-?\d{1,4}/ // 0 to 9999, -0 to -9999 + +}; +exports.numericPatterns = numericPatterns; +var timezonePatterns = { + basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/, + basic: /^([+-])(\d{2})(\d{2})|Z/, + basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/, + extended: /^([+-])(\d{2}):(\d{2})|Z/, + extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/ +}; +exports.timezonePatterns = timezonePatterns; + +/***/ }), + +/***/ 9187: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -21264,13 +21399,11 @@ function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "functi Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DateParser = void 0; - -var _utils = __nccwpck_require__(9042); +exports.AMPMMidnightParser = void 0; var _Parser2 = __nccwpck_require__(5619); -var _constants = __nccwpck_require__(463); +var _utils = __nccwpck_require__(9042); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } @@ -21294,18 +21427,15 @@ function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.g function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // Day of the month - -var DateParser = /*#__PURE__*/function (_Parser) { - _inherits(DateParser, _Parser); +var AMPMMidnightParser = /*#__PURE__*/function (_Parser) { + _inherits(AMPMMidnightParser, _Parser); - var _super = _createSuper(DateParser); + var _super = _createSuper(AMPMMidnightParser); - function DateParser() { + function AMPMMidnightParser() { var _this; - _classCallCheck(this, DateParser); + _classCallCheck(this, AMPMMidnightParser); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; @@ -21313,61 +21443,64 @@ var DateParser = /*#__PURE__*/function (_Parser) { _this = _super.call.apply(_super, [this].concat(args)); - _defineProperty(_assertThisInitialized(_this), "priority", 90); - - _defineProperty(_assertThisInitialized(_this), "subPriority", 1); + _defineProperty(_assertThisInitialized(_this), "priority", 80); - _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); + _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['a', 'B', 'H', 'k', 't', 'T']); return _this; } - _createClass(DateParser, [{ + _createClass(AMPMMidnightParser, [{ key: "parse", value: function parse(dateString, token, match) { switch (token) { - case 'd': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.date, dateString); + case 'b': + case 'bb': + case 'bbb': + return match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); - case 'do': - return match.ordinalNumber(dateString, { - unit: 'date' + case 'bbbbb': + return match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' }); + case 'bbbb': default: - return (0, _utils.parseNDigits)(token.length, dateString); - } - } - }, { - key: "validate", - value: function validate(date, value) { - var year = date.getUTCFullYear(); - var isLeapYear = (0, _utils.isLeapYearIndex)(year); - var month = date.getUTCMonth(); - - if (isLeapYear) { - return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month]; - } else { - return value >= 1 && value <= DAYS_IN_MONTH[month]; + return match.dayPeriod(dateString, { + width: 'wide', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); } } }, { key: "set", value: function set(date, _flags, value) { - date.setUTCDate(value); - date.setUTCHours(0, 0, 0, 0); + date.setUTCHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0); return date; } }]); - return DateParser; + return AMPMMidnightParser; }(_Parser2.Parser); -exports.DateParser = DateParser; +exports.AMPMMidnightParser = AMPMMidnightParser; /***/ }), -/***/ 7001: +/***/ 8678: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -21378,12 +21511,10 @@ function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "functi Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DayOfYearParser = void 0; +exports.AMPMParser = void 0; var _Parser2 = __nccwpck_require__(5619); -var _constants = __nccwpck_require__(463); - var _utils = __nccwpck_require__(9042); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } @@ -21408,15 +21539,15 @@ function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.g function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -var DayOfYearParser = /*#__PURE__*/function (_Parser) { - _inherits(DayOfYearParser, _Parser); +var AMPMParser = /*#__PURE__*/function (_Parser) { + _inherits(AMPMParser, _Parser); - var _super = _createSuper(DayOfYearParser); + var _super = _createSuper(AMPMParser); - function DayOfYearParser() { + function AMPMParser() { var _this; - _classCallCheck(this, DayOfYearParser); + _classCallCheck(this, AMPMParser); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; @@ -21424,54 +21555,282 @@ var DayOfYearParser = /*#__PURE__*/function (_Parser) { _this = _super.call.apply(_super, [this].concat(args)); - _defineProperty(_assertThisInitialized(_this), "priority", 90); - - _defineProperty(_assertThisInitialized(_this), "subpriority", 1); + _defineProperty(_assertThisInitialized(_this), "priority", 80); - _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'M', 'L', 'w', 'I', 'd', 'E', 'i', 'e', 'c', 't', 'T']); + _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['b', 'B', 'H', 'k', 't', 'T']); return _this; } - _createClass(DayOfYearParser, [{ + _createClass(AMPMParser, [{ key: "parse", value: function parse(dateString, token, match) { switch (token) { - case 'D': - case 'DD': - return (0, _utils.parseNumericPattern)(_constants.numericPatterns.dayOfYear, dateString); + case 'a': + case 'aa': + case 'aaa': + return match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); - case 'Do': - return match.ordinalNumber(dateString, { - unit: 'date' + case 'aaaaa': + return match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' }); + case 'aaaa': default: - return (0, _utils.parseNDigits)(token.length, dateString); - } - } - }, { - key: "validate", - value: function validate(date, value) { - var year = date.getUTCFullYear(); - var isLeapYear = (0, _utils.isLeapYearIndex)(year); - - if (isLeapYear) { - return value >= 1 && value <= 366; - } else { - return value >= 1 && value <= 365; + return match.dayPeriod(dateString, { + width: 'wide', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); } } }, { key: "set", value: function set(date, _flags, value) { - date.setUTCMonth(0, value); - date.setUTCHours(0, 0, 0, 0); + date.setUTCHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0); return date; } }]); - return DayOfYearParser; + return AMPMParser; +}(_Parser2.Parser); + +exports.AMPMParser = AMPMParser; + +/***/ }), + +/***/ 4757: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.DateParser = void 0; + +var _utils = __nccwpck_require__(9042); + +var _Parser2 = __nccwpck_require__(5619); + +var _constants = __nccwpck_require__(463); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // Day of the month + +var DateParser = /*#__PURE__*/function (_Parser) { + _inherits(DateParser, _Parser); + + var _super = _createSuper(DateParser); + + function DateParser() { + var _this; + + _classCallCheck(this, DateParser); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _this = _super.call.apply(_super, [this].concat(args)); + + _defineProperty(_assertThisInitialized(_this), "priority", 90); + + _defineProperty(_assertThisInitialized(_this), "subPriority", 1); + + _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); + + return _this; + } + + _createClass(DateParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'd': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.date, dateString); + + case 'do': + return match.ordinalNumber(dateString, { + unit: 'date' + }); + + default: + return (0, _utils.parseNDigits)(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(date, value) { + var year = date.getUTCFullYear(); + var isLeapYear = (0, _utils.isLeapYearIndex)(year); + var month = date.getUTCMonth(); + + if (isLeapYear) { + return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month]; + } else { + return value >= 1 && value <= DAYS_IN_MONTH[month]; + } + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCDate(value); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + + return DateParser; +}(_Parser2.Parser); + +exports.DateParser = DateParser; + +/***/ }), + +/***/ 7001: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.DayOfYearParser = void 0; + +var _Parser2 = __nccwpck_require__(5619); + +var _constants = __nccwpck_require__(463); + +var _utils = __nccwpck_require__(9042); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var DayOfYearParser = /*#__PURE__*/function (_Parser) { + _inherits(DayOfYearParser, _Parser); + + var _super = _createSuper(DayOfYearParser); + + function DayOfYearParser() { + var _this; + + _classCallCheck(this, DayOfYearParser); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _this = _super.call.apply(_super, [this].concat(args)); + + _defineProperty(_assertThisInitialized(_this), "priority", 90); + + _defineProperty(_assertThisInitialized(_this), "subpriority", 1); + + _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'M', 'L', 'w', 'I', 'd', 'E', 'i', 'e', 'c', 't', 'T']); + + return _this; + } + + _createClass(DayOfYearParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'D': + case 'DD': + return (0, _utils.parseNumericPattern)(_constants.numericPatterns.dayOfYear, dateString); + + case 'Do': + return match.ordinalNumber(dateString, { + unit: 'date' + }); + + default: + return (0, _utils.parseNDigits)(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(date, value) { + var year = date.getUTCFullYear(); + var isLeapYear = (0, _utils.isLeapYearIndex)(year); + + if (isLeapYear) { + return value >= 1 && value <= 366; + } else { + return value >= 1 && value <= 365; + } + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCMonth(0, value); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + + return DayOfYearParser; }(_Parser2.Parser); exports.DayOfYearParser = DayOfYearParser; @@ -24603,855 +24962,289 @@ var _LocalWeekParser = __nccwpck_require__(6125); var _ISOWeekParser = __nccwpck_require__(2127); -var _DateParser = __nccwpck_require__(4757); - -var _DayOfYearParser = __nccwpck_require__(7001); - -var _DayParser = __nccwpck_require__(2280); - -var _LocalDayParser = __nccwpck_require__(1190); - -var _StandAloneLocalDayParser = __nccwpck_require__(1556); - -var _ISODayParser = __nccwpck_require__(6376); - -var _AMPMParser = __nccwpck_require__(8678); - -var _AMPMMidnightParser = __nccwpck_require__(9187); - -var _DayPeriodParser = __nccwpck_require__(9273); - -var _Hour1to12Parser = __nccwpck_require__(7929); - -var _Hour0to23Parser = __nccwpck_require__(2610); - -var _Hour0To11Parser = __nccwpck_require__(323); - -var _Hour1To24Parser = __nccwpck_require__(5980); - -var _MinuteParser = __nccwpck_require__(4254); - -var _SecondParser = __nccwpck_require__(3478); - -var _FractionOfSecondParser = __nccwpck_require__(5194); - -var _ISOTimezoneWithZParser = __nccwpck_require__(9822); - -var _ISOTimezoneParser = __nccwpck_require__(9874); - -var _TimestampSecondsParser = __nccwpck_require__(771); - -var _TimestampMillisecondsParser = __nccwpck_require__(3726); - -/* - * | | Unit | | Unit | - * |-----|--------------------------------|-----|--------------------------------| - * | a | AM, PM | A* | Milliseconds in day | - * | b | AM, PM, noon, midnight | B | Flexible day period | - * | c | Stand-alone local day of week | C* | Localized hour w/ day period | - * | d | Day of month | D | Day of year | - * | e | Local day of week | E | Day of week | - * | f | | F* | Day of week in month | - * | g* | Modified Julian day | G | Era | - * | h | Hour [1-12] | H | Hour [0-23] | - * | i! | ISO day of week | I! | ISO week of year | - * | j* | Localized hour w/ day period | J* | Localized hour w/o day period | - * | k | Hour [1-24] | K | Hour [0-11] | - * | l* | (deprecated) | L | Stand-alone month | - * | m | Minute | M | Month | - * | n | | N | | - * | o! | Ordinal number modifier | O* | Timezone (GMT) | - * | p | | P | | - * | q | Stand-alone quarter | Q | Quarter | - * | r* | Related Gregorian year | R! | ISO week-numbering year | - * | s | Second | S | Fraction of second | - * | t! | Seconds timestamp | T! | Milliseconds timestamp | - * | u | Extended year | U* | Cyclic year | - * | v* | Timezone (generic non-locat.) | V* | Timezone (location) | - * | w | Local week of year | W* | Week of month | - * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) | - * | y | Year (abs) | Y | Local week-numbering year | - * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) | - * - * Letters marked by * are not implemented but reserved by Unicode standard. - * - * Letters marked by ! are non-standard, but implemented by date-fns: - * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs) - * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days, - * i.e. 7 for Sunday, 1 for Monday, etc. - * - `I` is ISO week of year, as opposed to `w` which is local week of year. - * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year. - * `R` is supposed to be used in conjunction with `I` and `i` - * for universal ISO week-numbering date, whereas - * `Y` is supposed to be used in conjunction with `w` and `e` - * for week-numbering date specific to the locale. - */ -var parsers = { - G: new _EraParser.EraParser(), - y: new _YearParser.YearParser(), - Y: new _LocalWeekYearParser.LocalWeekYearParser(), - R: new _ISOWeekYearParser.ISOWeekYearParser(), - u: new _ExtendedYearParser.ExtendedYearParser(), - Q: new _QuarterParser.QuarterParser(), - q: new _StandAloneQuarterParser.StandAloneQuarterParser(), - M: new _MonthParser.MonthParser(), - L: new _StandAloneMonthParser.StandAloneMonthParser(), - w: new _LocalWeekParser.LocalWeekParser(), - I: new _ISOWeekParser.ISOWeekParser(), - d: new _DateParser.DateParser(), - D: new _DayOfYearParser.DayOfYearParser(), - E: new _DayParser.DayParser(), - e: new _LocalDayParser.LocalDayParser(), - c: new _StandAloneLocalDayParser.StandAloneLocalDayParser(), - i: new _ISODayParser.ISODayParser(), - a: new _AMPMParser.AMPMParser(), - b: new _AMPMMidnightParser.AMPMMidnightParser(), - B: new _DayPeriodParser.DayPeriodParser(), - h: new _Hour1to12Parser.Hour1to12Parser(), - H: new _Hour0to23Parser.Hour0to23Parser(), - K: new _Hour0To11Parser.Hour0To11Parser(), - k: new _Hour1To24Parser.Hour1To24Parser(), - m: new _MinuteParser.MinuteParser(), - s: new _SecondParser.SecondParser(), - S: new _FractionOfSecondParser.FractionOfSecondParser(), - X: new _ISOTimezoneWithZParser.ISOTimezoneWithZParser(), - x: new _ISOTimezoneParser.ISOTimezoneParser(), - t: new _TimestampSecondsParser.TimestampSecondsParser(), - T: new _TimestampMillisecondsParser.TimestampMillisecondsParser() -}; -exports.parsers = parsers; - -/***/ }), - -/***/ 9042: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.dayPeriodEnumToHours = dayPeriodEnumToHours; -exports.isLeapYearIndex = isLeapYearIndex; -exports.mapValue = mapValue; -exports.normalizeTwoDigitYear = normalizeTwoDigitYear; -exports.parseAnyDigitsSigned = parseAnyDigitsSigned; -exports.parseNDigits = parseNDigits; -exports.parseNDigitsSigned = parseNDigitsSigned; -exports.parseNumericPattern = parseNumericPattern; -exports.parseTimezonePattern = parseTimezonePattern; - -var _index = __nccwpck_require__(5756); - -var _constants = __nccwpck_require__(463); - -function mapValue(parseFnResult, mapFn) { - if (!parseFnResult) { - return parseFnResult; - } - - return { - value: mapFn(parseFnResult.value), - rest: parseFnResult.rest - }; -} - -function parseNumericPattern(pattern, dateString) { - var matchResult = dateString.match(pattern); - - if (!matchResult) { - return null; - } - - return { - value: parseInt(matchResult[0], 10), - rest: dateString.slice(matchResult[0].length) - }; -} - -function parseTimezonePattern(pattern, dateString) { - var matchResult = dateString.match(pattern); - - if (!matchResult) { - return null; - } // Input is 'Z' - - - if (matchResult[0] === 'Z') { - return { - value: 0, - rest: dateString.slice(1) - }; - } - - var sign = matchResult[1] === '+' ? 1 : -1; - var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0; - var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0; - var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0; - return { - value: sign * (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute + seconds * _index.millisecondsInSecond), - rest: dateString.slice(matchResult[0].length) - }; -} - -function parseAnyDigitsSigned(dateString) { - return parseNumericPattern(_constants.numericPatterns.anyDigitsSigned, dateString); -} - -function parseNDigits(n, dateString) { - switch (n) { - case 1: - return parseNumericPattern(_constants.numericPatterns.singleDigit, dateString); - - case 2: - return parseNumericPattern(_constants.numericPatterns.twoDigits, dateString); - - case 3: - return parseNumericPattern(_constants.numericPatterns.threeDigits, dateString); - - case 4: - return parseNumericPattern(_constants.numericPatterns.fourDigits, dateString); - - default: - return parseNumericPattern(new RegExp('^\\d{1,' + n + '}'), dateString); - } -} - -function parseNDigitsSigned(n, dateString) { - switch (n) { - case 1: - return parseNumericPattern(_constants.numericPatterns.singleDigitSigned, dateString); - - case 2: - return parseNumericPattern(_constants.numericPatterns.twoDigitsSigned, dateString); - - case 3: - return parseNumericPattern(_constants.numericPatterns.threeDigitsSigned, dateString); - - case 4: - return parseNumericPattern(_constants.numericPatterns.fourDigitsSigned, dateString); - - default: - return parseNumericPattern(new RegExp('^-?\\d{1,' + n + '}'), dateString); - } -} - -function dayPeriodEnumToHours(dayPeriod) { - switch (dayPeriod) { - case 'morning': - return 4; - - case 'evening': - return 17; - - case 'pm': - case 'noon': - case 'afternoon': - return 12; - - case 'am': - case 'midnight': - case 'night': - default: - return 0; - } -} - -function normalizeTwoDigitYear(twoDigitYear, currentYear) { - var isCommonEra = currentYear > 0; // Absolute number of the current year: - // 1 -> 1 AC - // 0 -> 1 BC - // -1 -> 2 BC - - var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear; - var result; - - if (absCurrentYear <= 50) { - result = twoDigitYear || 100; - } else { - var rangeEnd = absCurrentYear + 50; - var rangeEndCentury = Math.floor(rangeEnd / 100) * 100; - var isPreviousCentury = twoDigitYear >= rangeEnd % 100; - result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0); - } - - return isCommonEra ? result : 1 - result; -} - -function isLeapYearIndex(year) { - return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; -} - -/***/ }), - -/***/ 1287: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = parse; - -var _index = _interopRequireDefault(__nccwpck_require__(618)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(7923)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(2631)); - -var _index5 = _interopRequireDefault(__nccwpck_require__(8387)); - -var _index6 = _interopRequireDefault(__nccwpck_require__(7032)); - -var _index7 = __nccwpck_require__(2509); - -var _index8 = _interopRequireDefault(__nccwpck_require__(1985)); - -var _index9 = _interopRequireDefault(__nccwpck_require__(2063)); - -var _Setter = __nccwpck_require__(5665); - -var _index10 = __nccwpck_require__(5193); - -var _index11 = __nccwpck_require__(9307); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -// This RegExp consists of three parts separated by `|`: -// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token -// (one of the certain letters followed by `o`) -// - (\w)\1* matches any sequences of the same letter -// - '' matches two quote characters in a row -// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), -// except a single quote symbol, which ends the sequence. -// Two quote characters do not end the sequence. -// If there is no matching single quote -// then the sequence will continue until the end of the string. -// - . matches any single character unmatched by previous parts of the RegExps -var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also -// sequences of symbols P, p, and the combinations like `PPPPPPPppppp` - -var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; -var escapedStringRegExp = /^'([^]*?)'?$/; -var doubleQuoteRegExp = /''/g; -var notWhitespaceRegExp = /\S/; -var unescapedLatinCharacterRegExp = /[a-zA-Z]/; -/** - * @name parse - * @category Common Helpers - * @summary Parse the date. - * - * @description - * Return the date parsed from string using the given format string. - * - * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. - * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * - * The characters in the format string wrapped between two single quotes characters (') are escaped. - * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. - * - * Format of the format string is based on Unicode Technical Standard #35: - * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table - * with a few additions (see note 5 below the table). - * - * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited - * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception: - * - * ```javascript - * parse('23 AM', 'HH a', new Date()) - * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time - * ``` - * - * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true - * - * Accepted format string patterns: - * | Unit |Prior| Pattern | Result examples | Notes | - * |---------------------------------|-----|---------|-----------------------------------|-------| - * | Era | 140 | G..GGG | AD, BC | | - * | | | GGGG | Anno Domini, Before Christ | 2 | - * | | | GGGGG | A, B | | - * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 | - * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 | - * | | | yy | 44, 01, 00, 17 | 4 | - * | | | yyy | 044, 001, 123, 999 | 4 | - * | | | yyyy | 0044, 0001, 1900, 2017 | 4 | - * | | | yyyyy | ... | 2,4 | - * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 | - * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 | - * | | | YY | 44, 01, 00, 17 | 4,6 | - * | | | YYY | 044, 001, 123, 999 | 4 | - * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 | - * | | | YYYYY | ... | 2,4 | - * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 | - * | | | RR | -43, 01, 00, 17 | 4,5 | - * | | | RRR | -043, 001, 123, 999, -999 | 4,5 | - * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 | - * | | | RRRRR | ... | 2,4,5 | - * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 | - * | | | uu | -43, 01, 99, -99 | 4 | - * | | | uuu | -043, 001, 123, 999, -999 | 4 | - * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 | - * | | | uuuuu | ... | 2,4 | - * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | | - * | | | Qo | 1st, 2nd, 3rd, 4th | 5 | - * | | | QQ | 01, 02, 03, 04 | | - * | | | QQQ | Q1, Q2, Q3, Q4 | | - * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | - * | | | QQQQQ | 1, 2, 3, 4 | 4 | - * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | | - * | | | qo | 1st, 2nd, 3rd, 4th | 5 | - * | | | qq | 01, 02, 03, 04 | | - * | | | qqq | Q1, Q2, Q3, Q4 | | - * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 | - * | | | qqqqq | 1, 2, 3, 4 | 3 | - * | Month (formatting) | 110 | M | 1, 2, ..., 12 | | - * | | | Mo | 1st, 2nd, ..., 12th | 5 | - * | | | MM | 01, 02, ..., 12 | | - * | | | MMM | Jan, Feb, ..., Dec | | - * | | | MMMM | January, February, ..., December | 2 | - * | | | MMMMM | J, F, ..., D | | - * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | | - * | | | Lo | 1st, 2nd, ..., 12th | 5 | - * | | | LL | 01, 02, ..., 12 | | - * | | | LLL | Jan, Feb, ..., Dec | | - * | | | LLLL | January, February, ..., December | 2 | - * | | | LLLLL | J, F, ..., D | | - * | Local week of year | 100 | w | 1, 2, ..., 53 | | - * | | | wo | 1st, 2nd, ..., 53th | 5 | - * | | | ww | 01, 02, ..., 53 | | - * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 | - * | | | Io | 1st, 2nd, ..., 53th | 5 | - * | | | II | 01, 02, ..., 53 | 5 | - * | Day of month | 90 | d | 1, 2, ..., 31 | | - * | | | do | 1st, 2nd, ..., 31st | 5 | - * | | | dd | 01, 02, ..., 31 | | - * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 | - * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 | - * | | | DD | 01, 02, ..., 365, 366 | 7 | - * | | | DDD | 001, 002, ..., 365, 366 | | - * | | | DDDD | ... | 2 | - * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | | - * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 | - * | | | EEEEE | M, T, W, T, F, S, S | | - * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | - * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 | - * | | | io | 1st, 2nd, ..., 7th | 5 | - * | | | ii | 01, 02, ..., 07 | 5 | - * | | | iii | Mon, Tue, Wed, ..., Sun | 5 | - * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 | - * | | | iiiii | M, T, W, T, F, S, S | 5 | - * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 | - * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | | - * | | | eo | 2nd, 3rd, ..., 1st | 5 | - * | | | ee | 02, 03, ..., 01 | | - * | | | eee | Mon, Tue, Wed, ..., Sun | | - * | | | eeee | Monday, Tuesday, ..., Sunday | 2 | - * | | | eeeee | M, T, W, T, F, S, S | | - * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | - * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | | - * | | | co | 2nd, 3rd, ..., 1st | 5 | - * | | | cc | 02, 03, ..., 01 | | - * | | | ccc | Mon, Tue, Wed, ..., Sun | | - * | | | cccc | Monday, Tuesday, ..., Sunday | 2 | - * | | | ccccc | M, T, W, T, F, S, S | | - * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | - * | AM, PM | 80 | a..aaa | AM, PM | | - * | | | aaaa | a.m., p.m. | 2 | - * | | | aaaaa | a, p | | - * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | | - * | | | bbbb | a.m., p.m., noon, midnight | 2 | - * | | | bbbbb | a, p, n, mi | | - * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | | - * | | | BBBB | at night, in the morning, ... | 2 | - * | | | BBBBB | at night, in the morning, ... | | - * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | | - * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 | - * | | | hh | 01, 02, ..., 11, 12 | | - * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | | - * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 | - * | | | HH | 00, 01, 02, ..., 23 | | - * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | | - * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 | - * | | | KK | 01, 02, ..., 11, 00 | | - * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | | - * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 | - * | | | kk | 24, 01, 02, ..., 23 | | - * | Minute | 60 | m | 0, 1, ..., 59 | | - * | | | mo | 0th, 1st, ..., 59th | 5 | - * | | | mm | 00, 01, ..., 59 | | - * | Second | 50 | s | 0, 1, ..., 59 | | - * | | | so | 0th, 1st, ..., 59th | 5 | - * | | | ss | 00, 01, ..., 59 | | - * | Seconds timestamp | 40 | t | 512969520 | | - * | | | tt | ... | 2 | - * | Fraction of second | 30 | S | 0, 1, ..., 9 | | - * | | | SS | 00, 01, ..., 99 | | - * | | | SSS | 000, 001, ..., 999 | | - * | | | SSSS | ... | 2 | - * | Milliseconds timestamp | 20 | T | 512969520900 | | - * | | | TT | ... | 2 | - * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | | - * | | | XX | -0800, +0530, Z | | - * | | | XXX | -08:00, +05:30, Z | | - * | | | XXXX | -0800, +0530, Z, +123456 | 2 | - * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | - * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | | - * | | | xx | -0800, +0530, +0000 | | - * | | | xxx | -08:00, +05:30, +00:00 | 2 | - * | | | xxxx | -0800, +0530, +0000, +123456 | | - * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | - * | Long localized date | NA | P | 05/29/1453 | 5,8 | - * | | | PP | May 29, 1453 | | - * | | | PPP | May 29th, 1453 | | - * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 | - * | Long localized time | NA | p | 12:00 AM | 5,8 | - * | | | pp | 12:00:00 AM | | - * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | | - * | | | PPpp | May 29, 1453, 12:00:00 AM | | - * | | | PPPpp | May 29th, 1453 at ... | | - * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 | - * Notes: - * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale - * are the same as "stand-alone" units, but are different in some languages. - * "Formatting" units are declined according to the rules of the language - * in the context of a date. "Stand-alone" units are always nominative singular. - * In `format` function, they will produce different result: - * - * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` - * - * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` - * - * `parse` will try to match both formatting and stand-alone units interchangably. - * - * 2. Any sequence of the identical letters is a pattern, unless it is escaped by - * the single quote characters (see below). - * If the sequence is longer than listed in table: - * - for numerical units (`yyyyyyyy`) `parse` will try to match a number - * as wide as the sequence - * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit. - * These variations are marked with "2" in the last column of the table. - * - * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. - * These tokens represent the shortest form of the quarter. - * - * 4. The main difference between `y` and `u` patterns are B.C. years: - * - * | Year | `y` | `u` | - * |------|-----|-----| - * | AC 1 | 1 | 1 | - * | BC 1 | 1 | 0 | - * | BC 2 | 2 | -1 | - * - * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`: - * - * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00` - * - * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00` - * - * while `uu` will just assign the year as is: - * - * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00` - * - * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00` - * - * The same difference is true for local and ISO week-numbering years (`Y` and `R`), - * except local week-numbering years are dependent on `options.weekStartsOn` - * and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear} - * and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}). - * - * 5. These patterns are not in the Unicode Technical Standard #35: - * - `i`: ISO day of week - * - `I`: ISO week of year - * - `R`: ISO week-numbering year - * - `o`: ordinal number modifier - * - `P`: long localized date - * - `p`: long localized time - * - * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. - * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * - * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. - * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * - * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based - * on the given locale. - * - * using `en-US` locale: `P` => `MM/dd/yyyy` - * using `en-US` locale: `p` => `hh:mm a` - * using `pt-BR` locale: `P` => `dd/MM/yyyy` - * using `pt-BR` locale: `p` => `HH:mm` - * - * Values will be assigned to the date in the descending order of its unit's priority. - * Units of an equal priority overwrite each other in the order of appearance. - * - * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year), - * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing. - * - * `referenceDate` must be passed for correct work of the function. - * If you're not sure which `referenceDate` to supply, create a new instance of Date: - * `parse('02/11/2014', 'MM/dd/yyyy', new Date())` - * In this case parsing will be done in the context of the current date. - * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`, - * then `Invalid Date` will be returned. - * - * The result may vary by locale. - * - * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned. - * - * If parsing failed, `Invalid Date` will be returned. - * Invalid Date is a Date, whose time value is NaN. - * Time value of Date: http://es5.github.io/#x15.9.1.1 - * - * @param {String} dateString - the string to parse - * @param {String} formatString - the string of tokens - * @param {Date|Number} referenceDate - defines values missing from the parsed dateString - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year - * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; - * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; - * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @returns {Date} the parsed date - * @throws {TypeError} 3 arguments required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 - * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 - * @throws {RangeError} `options.locale` must contain `match` property - * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md - * @throws {RangeError} format string contains an unescaped latin alphabet character - * - * @example - * // Parse 11 February 2014 from middle-endian format: - * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date()) - * //=> Tue Feb 11 2014 00:00:00 - * - * @example - * // Parse 28th of February in Esperanto locale in the context of 2010 year: - * import eo from 'date-fns/locale/eo' - * var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), { - * locale: eo - * }) - * //=> Sun Feb 28 2010 00:00:00 - */ - -function parse(dirtyDateString, dirtyFormatString, dirtyReferenceDate, options) { - var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; +var _DateParser = __nccwpck_require__(4757); - (0, _index9.default)(3, arguments); - var dateString = String(dirtyDateString); - var formatString = String(dirtyFormatString); - var defaultOptions = (0, _index11.getDefaultOptions)(); - var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : _index.default; +var _DayOfYearParser = __nccwpck_require__(7001); - if (!locale.match) { - throw new RangeError('locale must contain match property'); - } +var _DayParser = __nccwpck_require__(2280); - var firstWeekContainsDate = (0, _index8.default)((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN +var _LocalDayParser = __nccwpck_require__(1190); - if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { - throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); - } +var _StandAloneLocalDayParser = __nccwpck_require__(1556); - var weekStartsOn = (0, _index8.default)((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN +var _ISODayParser = __nccwpck_require__(6376); - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); - } +var _AMPMParser = __nccwpck_require__(8678); - if (formatString === '') { - if (dateString === '') { - return (0, _index3.default)(dirtyReferenceDate); - } else { - return new Date(NaN); - } - } +var _AMPMMidnightParser = __nccwpck_require__(9187); - var subFnOptions = { - firstWeekContainsDate: firstWeekContainsDate, - weekStartsOn: weekStartsOn, - locale: locale - }; // If timezone isn't specified, it will be set to the system timezone +var _DayPeriodParser = __nccwpck_require__(9273); - var setters = [new _Setter.DateToSystemTimezoneSetter()]; - var tokens = formatString.match(longFormattingTokensRegExp).map(function (substring) { - var firstCharacter = substring[0]; +var _Hour1to12Parser = __nccwpck_require__(7929); - if (firstCharacter in _index5.default) { - var longFormatter = _index5.default[firstCharacter]; - return longFormatter(substring, locale.formatLong); - } +var _Hour0to23Parser = __nccwpck_require__(2610); - return substring; - }).join('').match(formattingTokensRegExp); - var usedTokens = []; +var _Hour0To11Parser = __nccwpck_require__(323); - var _iterator = _createForOfIteratorHelper(tokens), - _step; +var _Hour1To24Parser = __nccwpck_require__(5980); - try { - var _loop = function _loop() { - var token = _step.value; +var _MinuteParser = __nccwpck_require__(4254); - if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && (0, _index7.isProtectedWeekYearToken)(token)) { - (0, _index7.throwProtectedError)(token, formatString, dirtyDateString); - } +var _SecondParser = __nccwpck_require__(3478); - if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && (0, _index7.isProtectedDayOfYearToken)(token)) { - (0, _index7.throwProtectedError)(token, formatString, dirtyDateString); - } +var _FractionOfSecondParser = __nccwpck_require__(5194); - var firstCharacter = token[0]; - var parser = _index10.parsers[firstCharacter]; +var _ISOTimezoneWithZParser = __nccwpck_require__(9822); - if (parser) { - var incompatibleTokens = parser.incompatibleTokens; +var _ISOTimezoneParser = __nccwpck_require__(9874); - if (Array.isArray(incompatibleTokens)) { - var incompatibleToken = usedTokens.find(function (usedToken) { - return incompatibleTokens.includes(usedToken.token) || usedToken.token === firstCharacter; - }); +var _TimestampSecondsParser = __nccwpck_require__(771); - if (incompatibleToken) { - throw new RangeError("The format string mustn't contain `".concat(incompatibleToken.fullToken, "` and `").concat(token, "` at the same time")); - } - } else if (parser.incompatibleTokens === '*' && usedTokens.length > 0) { - throw new RangeError("The format string mustn't contain `".concat(token, "` and any other token at the same time")); - } +var _TimestampMillisecondsParser = __nccwpck_require__(3726); - usedTokens.push({ - token: firstCharacter, - fullToken: token - }); - var parseResult = parser.run(dateString, token, locale.match, subFnOptions); +/* + * | | Unit | | Unit | + * |-----|--------------------------------|-----|--------------------------------| + * | a | AM, PM | A* | Milliseconds in day | + * | b | AM, PM, noon, midnight | B | Flexible day period | + * | c | Stand-alone local day of week | C* | Localized hour w/ day period | + * | d | Day of month | D | Day of year | + * | e | Local day of week | E | Day of week | + * | f | | F* | Day of week in month | + * | g* | Modified Julian day | G | Era | + * | h | Hour [1-12] | H | Hour [0-23] | + * | i! | ISO day of week | I! | ISO week of year | + * | j* | Localized hour w/ day period | J* | Localized hour w/o day period | + * | k | Hour [1-24] | K | Hour [0-11] | + * | l* | (deprecated) | L | Stand-alone month | + * | m | Minute | M | Month | + * | n | | N | | + * | o! | Ordinal number modifier | O* | Timezone (GMT) | + * | p | | P | | + * | q | Stand-alone quarter | Q | Quarter | + * | r* | Related Gregorian year | R! | ISO week-numbering year | + * | s | Second | S | Fraction of second | + * | t! | Seconds timestamp | T! | Milliseconds timestamp | + * | u | Extended year | U* | Cyclic year | + * | v* | Timezone (generic non-locat.) | V* | Timezone (location) | + * | w | Local week of year | W* | Week of month | + * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) | + * | y | Year (abs) | Y | Local week-numbering year | + * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) | + * + * Letters marked by * are not implemented but reserved by Unicode standard. + * + * Letters marked by ! are non-standard, but implemented by date-fns: + * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs) + * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days, + * i.e. 7 for Sunday, 1 for Monday, etc. + * - `I` is ISO week of year, as opposed to `w` which is local week of year. + * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year. + * `R` is supposed to be used in conjunction with `I` and `i` + * for universal ISO week-numbering date, whereas + * `Y` is supposed to be used in conjunction with `w` and `e` + * for week-numbering date specific to the locale. + */ +var parsers = { + G: new _EraParser.EraParser(), + y: new _YearParser.YearParser(), + Y: new _LocalWeekYearParser.LocalWeekYearParser(), + R: new _ISOWeekYearParser.ISOWeekYearParser(), + u: new _ExtendedYearParser.ExtendedYearParser(), + Q: new _QuarterParser.QuarterParser(), + q: new _StandAloneQuarterParser.StandAloneQuarterParser(), + M: new _MonthParser.MonthParser(), + L: new _StandAloneMonthParser.StandAloneMonthParser(), + w: new _LocalWeekParser.LocalWeekParser(), + I: new _ISOWeekParser.ISOWeekParser(), + d: new _DateParser.DateParser(), + D: new _DayOfYearParser.DayOfYearParser(), + E: new _DayParser.DayParser(), + e: new _LocalDayParser.LocalDayParser(), + c: new _StandAloneLocalDayParser.StandAloneLocalDayParser(), + i: new _ISODayParser.ISODayParser(), + a: new _AMPMParser.AMPMParser(), + b: new _AMPMMidnightParser.AMPMMidnightParser(), + B: new _DayPeriodParser.DayPeriodParser(), + h: new _Hour1to12Parser.Hour1to12Parser(), + H: new _Hour0to23Parser.Hour0to23Parser(), + K: new _Hour0To11Parser.Hour0To11Parser(), + k: new _Hour1To24Parser.Hour1To24Parser(), + m: new _MinuteParser.MinuteParser(), + s: new _SecondParser.SecondParser(), + S: new _FractionOfSecondParser.FractionOfSecondParser(), + X: new _ISOTimezoneWithZParser.ISOTimezoneWithZParser(), + x: new _ISOTimezoneParser.ISOTimezoneParser(), + t: new _TimestampSecondsParser.TimestampSecondsParser(), + T: new _TimestampMillisecondsParser.TimestampMillisecondsParser() +}; +exports.parsers = parsers; - if (!parseResult) { - return { - v: new Date(NaN) - }; - } +/***/ }), - setters.push(parseResult.setter); - dateString = parseResult.rest; - } else { - if (firstCharacter.match(unescapedLatinCharacterRegExp)) { - throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); - } // Replace two single quote characters with one single quote character +/***/ 9042: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; - if (token === "''") { - token = "'"; - } else if (firstCharacter === "'") { - token = cleanEscapedString(token); - } // Cut token from string, or, if string doesn't match the token, return Invalid Date +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.dayPeriodEnumToHours = dayPeriodEnumToHours; +exports.isLeapYearIndex = isLeapYearIndex; +exports.mapValue = mapValue; +exports.normalizeTwoDigitYear = normalizeTwoDigitYear; +exports.parseAnyDigitsSigned = parseAnyDigitsSigned; +exports.parseNDigits = parseNDigits; +exports.parseNDigitsSigned = parseNDigitsSigned; +exports.parseNumericPattern = parseNumericPattern; +exports.parseTimezonePattern = parseTimezonePattern; + +var _index = __nccwpck_require__(5756); + +var _constants = __nccwpck_require__(463); + +function mapValue(parseFnResult, mapFn) { + if (!parseFnResult) { + return parseFnResult; + } + + return { + value: mapFn(parseFnResult.value), + rest: parseFnResult.rest + }; +} + +function parseNumericPattern(pattern, dateString) { + var matchResult = dateString.match(pattern); + + if (!matchResult) { + return null; + } + + return { + value: parseInt(matchResult[0], 10), + rest: dateString.slice(matchResult[0].length) + }; +} + +function parseTimezonePattern(pattern, dateString) { + var matchResult = dateString.match(pattern); + + if (!matchResult) { + return null; + } // Input is 'Z' + + + if (matchResult[0] === 'Z') { + return { + value: 0, + rest: dateString.slice(1) + }; + } + + var sign = matchResult[1] === '+' ? 1 : -1; + var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0; + var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0; + var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0; + return { + value: sign * (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute + seconds * _index.millisecondsInSecond), + rest: dateString.slice(matchResult[0].length) + }; +} + +function parseAnyDigitsSigned(dateString) { + return parseNumericPattern(_constants.numericPatterns.anyDigitsSigned, dateString); +} + +function parseNDigits(n, dateString) { + switch (n) { + case 1: + return parseNumericPattern(_constants.numericPatterns.singleDigit, dateString); - if (dateString.indexOf(token) === 0) { - dateString = dateString.slice(token.length); - } else { - return { - v: new Date(NaN) - }; - } - } - }; + case 2: + return parseNumericPattern(_constants.numericPatterns.twoDigits, dateString); - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _ret = _loop(); + case 3: + return parseNumericPattern(_constants.numericPatterns.threeDigits, dateString); - if (_typeof(_ret) === "object") return _ret.v; - } // Check if the remaining input contains something other than whitespace + case 4: + return parseNumericPattern(_constants.numericPatterns.fourDigits, dateString); - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); + default: + return parseNumericPattern(new RegExp('^\\d{1,' + n + '}'), dateString); } +} - if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) { - return new Date(NaN); - } +function parseNDigitsSigned(n, dateString) { + switch (n) { + case 1: + return parseNumericPattern(_constants.numericPatterns.singleDigitSigned, dateString); - var uniquePrioritySetters = setters.map(function (setter) { - return setter.priority; - }).sort(function (a, b) { - return b - a; - }).filter(function (priority, index, array) { - return array.indexOf(priority) === index; - }).map(function (priority) { - return setters.filter(function (setter) { - return setter.priority === priority; - }).sort(function (a, b) { - return b.subPriority - a.subPriority; - }); - }).map(function (setterArray) { - return setterArray[0]; - }); - var date = (0, _index3.default)(dirtyReferenceDate); + case 2: + return parseNumericPattern(_constants.numericPatterns.twoDigitsSigned, dateString); - if (isNaN(date.getTime())) { - return new Date(NaN); - } // Convert the date in system timezone to the same date in UTC+00:00 timezone. + case 3: + return parseNumericPattern(_constants.numericPatterns.threeDigitsSigned, dateString); + case 4: + return parseNumericPattern(_constants.numericPatterns.fourDigitsSigned, dateString); - var utcDate = (0, _index2.default)(date, (0, _index6.default)(date)); - var flags = {}; + default: + return parseNumericPattern(new RegExp('^-?\\d{1,' + n + '}'), dateString); + } +} - var _iterator2 = _createForOfIteratorHelper(uniquePrioritySetters), - _step2; +function dayPeriodEnumToHours(dayPeriod) { + switch (dayPeriod) { + case 'morning': + return 4; - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var setter = _step2.value; + case 'evening': + return 17; - if (!setter.validate(utcDate, subFnOptions)) { - return new Date(NaN); - } + case 'pm': + case 'noon': + case 'afternoon': + return 12; - var result = setter.set(utcDate, flags, subFnOptions); // Result is tuple (date, flags) + case 'am': + case 'midnight': + case 'night': + default: + return 0; + } +} - if (Array.isArray(result)) { - utcDate = result[0]; - (0, _index4.default)(flags, result[1]); // Result is date - } else { - utcDate = result; - } - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); +function normalizeTwoDigitYear(twoDigitYear, currentYear) { + var isCommonEra = currentYear > 0; // Absolute number of the current year: + // 1 -> 1 AC + // 0 -> 1 BC + // -1 -> 2 BC + + var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear; + var result; + + if (absCurrentYear <= 50) { + result = twoDigitYear || 100; + } else { + var rangeEnd = absCurrentYear + 50; + var rangeEndCentury = Math.floor(rangeEnd / 100) * 100; + var isPreviousCentury = twoDigitYear >= rangeEnd % 100; + result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0); } - return utcDate; + return isCommonEra ? result : 1 - result; } -function cleanEscapedString(input) { - return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'"); +function isLeapYearIndex(year) { + return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; } -module.exports = exports.default; - /***/ }), -/***/ 3390: +/***/ 1287: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -25460,350 +25253,557 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = parseISO; +exports["default"] = parse; -var _index = __nccwpck_require__(5756); +var _index = _interopRequireDefault(__nccwpck_require__(618)); -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(7923)); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index3 = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(2631)); + +var _index5 = _interopRequireDefault(__nccwpck_require__(8387)); + +var _index6 = _interopRequireDefault(__nccwpck_require__(7032)); + +var _index7 = __nccwpck_require__(2509); + +var _index8 = _interopRequireDefault(__nccwpck_require__(1985)); + +var _index9 = _interopRequireDefault(__nccwpck_require__(2063)); + +var _Setter = __nccwpck_require__(5665); + +var _index10 = __nccwpck_require__(5193); + +var _index11 = __nccwpck_require__(9307); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +// This RegExp consists of three parts separated by `|`: +// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token +// (one of the certain letters followed by `o`) +// - (\w)\1* matches any sequences of the same letter +// - '' matches two quote characters in a row +// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), +// except a single quote symbol, which ends the sequence. +// Two quote characters do not end the sequence. +// If there is no matching single quote +// then the sequence will continue until the end of the string. +// - . matches any single character unmatched by previous parts of the RegExps +var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also +// sequences of symbols P, p, and the combinations like `PPPPPPPppppp` + +var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; +var escapedStringRegExp = /^'([^]*?)'?$/; +var doubleQuoteRegExp = /''/g; +var notWhitespaceRegExp = /\S/; +var unescapedLatinCharacterRegExp = /[a-zA-Z]/; /** - * @name parseISO + * @name parse * @category Common Helpers - * @summary Parse ISO string + * @summary Parse the date. + * + * @description + * Return the date parsed from string using the given format string. + * + * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. + * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * The characters in the format string wrapped between two single quotes characters (') are escaped. + * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. + * + * Format of the format string is based on Unicode Technical Standard #35: + * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table + * with a few additions (see note 5 below the table). + * + * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited + * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception: + * + * ```javascript + * parse('23 AM', 'HH a', new Date()) + * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time + * ``` + * + * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true + * + * Accepted format string patterns: + * | Unit |Prior| Pattern | Result examples | Notes | + * |---------------------------------|-----|---------|-----------------------------------|-------| + * | Era | 140 | G..GGG | AD, BC | | + * | | | GGGG | Anno Domini, Before Christ | 2 | + * | | | GGGGG | A, B | | + * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 | + * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | yy | 44, 01, 00, 17 | 4 | + * | | | yyy | 044, 001, 123, 999 | 4 | + * | | | yyyy | 0044, 0001, 1900, 2017 | 4 | + * | | | yyyyy | ... | 2,4 | + * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 | + * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | YY | 44, 01, 00, 17 | 4,6 | + * | | | YYY | 044, 001, 123, 999 | 4 | + * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 | + * | | | YYYYY | ... | 2,4 | + * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 | + * | | | RR | -43, 01, 00, 17 | 4,5 | + * | | | RRR | -043, 001, 123, 999, -999 | 4,5 | + * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 | + * | | | RRRRR | ... | 2,4,5 | + * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 | + * | | | uu | -43, 01, 99, -99 | 4 | + * | | | uuu | -043, 001, 123, 999, -999 | 4 | + * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 | + * | | | uuuuu | ... | 2,4 | + * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | | + * | | | Qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | QQ | 01, 02, 03, 04 | | + * | | | QQQ | Q1, Q2, Q3, Q4 | | + * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | + * | | | QQQQQ | 1, 2, 3, 4 | 4 | + * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | | + * | | | qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | qq | 01, 02, 03, 04 | | + * | | | qqq | Q1, Q2, Q3, Q4 | | + * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 | + * | | | qqqqq | 1, 2, 3, 4 | 3 | + * | Month (formatting) | 110 | M | 1, 2, ..., 12 | | + * | | | Mo | 1st, 2nd, ..., 12th | 5 | + * | | | MM | 01, 02, ..., 12 | | + * | | | MMM | Jan, Feb, ..., Dec | | + * | | | MMMM | January, February, ..., December | 2 | + * | | | MMMMM | J, F, ..., D | | + * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | | + * | | | Lo | 1st, 2nd, ..., 12th | 5 | + * | | | LL | 01, 02, ..., 12 | | + * | | | LLL | Jan, Feb, ..., Dec | | + * | | | LLLL | January, February, ..., December | 2 | + * | | | LLLLL | J, F, ..., D | | + * | Local week of year | 100 | w | 1, 2, ..., 53 | | + * | | | wo | 1st, 2nd, ..., 53th | 5 | + * | | | ww | 01, 02, ..., 53 | | + * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 | + * | | | Io | 1st, 2nd, ..., 53th | 5 | + * | | | II | 01, 02, ..., 53 | 5 | + * | Day of month | 90 | d | 1, 2, ..., 31 | | + * | | | do | 1st, 2nd, ..., 31st | 5 | + * | | | dd | 01, 02, ..., 31 | | + * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 | + * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 | + * | | | DD | 01, 02, ..., 365, 366 | 7 | + * | | | DDD | 001, 002, ..., 365, 366 | | + * | | | DDDD | ... | 2 | + * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | | + * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 | + * | | | EEEEE | M, T, W, T, F, S, S | | + * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | + * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 | + * | | | io | 1st, 2nd, ..., 7th | 5 | + * | | | ii | 01, 02, ..., 07 | 5 | + * | | | iii | Mon, Tue, Wed, ..., Sun | 5 | + * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 | + * | | | iiiii | M, T, W, T, F, S, S | 5 | + * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 | + * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | | + * | | | eo | 2nd, 3rd, ..., 1st | 5 | + * | | | ee | 02, 03, ..., 01 | | + * | | | eee | Mon, Tue, Wed, ..., Sun | | + * | | | eeee | Monday, Tuesday, ..., Sunday | 2 | + * | | | eeeee | M, T, W, T, F, S, S | | + * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | + * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | | + * | | | co | 2nd, 3rd, ..., 1st | 5 | + * | | | cc | 02, 03, ..., 01 | | + * | | | ccc | Mon, Tue, Wed, ..., Sun | | + * | | | cccc | Monday, Tuesday, ..., Sunday | 2 | + * | | | ccccc | M, T, W, T, F, S, S | | + * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | + * | AM, PM | 80 | a..aaa | AM, PM | | + * | | | aaaa | a.m., p.m. | 2 | + * | | | aaaaa | a, p | | + * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | | + * | | | bbbb | a.m., p.m., noon, midnight | 2 | + * | | | bbbbb | a, p, n, mi | | + * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | | + * | | | BBBB | at night, in the morning, ... | 2 | + * | | | BBBBB | at night, in the morning, ... | | + * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | | + * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 | + * | | | hh | 01, 02, ..., 11, 12 | | + * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | | + * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 | + * | | | HH | 00, 01, 02, ..., 23 | | + * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | | + * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 | + * | | | KK | 01, 02, ..., 11, 00 | | + * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | | + * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 | + * | | | kk | 24, 01, 02, ..., 23 | | + * | Minute | 60 | m | 0, 1, ..., 59 | | + * | | | mo | 0th, 1st, ..., 59th | 5 | + * | | | mm | 00, 01, ..., 59 | | + * | Second | 50 | s | 0, 1, ..., 59 | | + * | | | so | 0th, 1st, ..., 59th | 5 | + * | | | ss | 00, 01, ..., 59 | | + * | Seconds timestamp | 40 | t | 512969520 | | + * | | | tt | ... | 2 | + * | Fraction of second | 30 | S | 0, 1, ..., 9 | | + * | | | SS | 00, 01, ..., 99 | | + * | | | SSS | 000, 001, ..., 999 | | + * | | | SSSS | ... | 2 | + * | Milliseconds timestamp | 20 | T | 512969520900 | | + * | | | TT | ... | 2 | + * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | | + * | | | XX | -0800, +0530, Z | | + * | | | XXX | -08:00, +05:30, Z | | + * | | | XXXX | -0800, +0530, Z, +123456 | 2 | + * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | + * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | | + * | | | xx | -0800, +0530, +0000 | | + * | | | xxx | -08:00, +05:30, +00:00 | 2 | + * | | | xxxx | -0800, +0530, +0000, +123456 | | + * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | + * | Long localized date | NA | P | 05/29/1453 | 5,8 | + * | | | PP | May 29, 1453 | | + * | | | PPP | May 29th, 1453 | | + * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 | + * | Long localized time | NA | p | 12:00 AM | 5,8 | + * | | | pp | 12:00:00 AM | | + * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | | + * | | | PPpp | May 29, 1453, 12:00:00 AM | | + * | | | PPPpp | May 29th, 1453 at ... | | + * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 | + * Notes: + * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale + * are the same as "stand-alone" units, but are different in some languages. + * "Formatting" units are declined according to the rules of the language + * in the context of a date. "Stand-alone" units are always nominative singular. + * In `format` function, they will produce different result: * - * @description - * Parse the given string in ISO 8601 format and return an instance of Date. + * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` * - * Function accepts complete ISO 8601 formats as well as partial implementations. - * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 + * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` * - * If the argument isn't a string, the function cannot parse the string or - * the values are invalid, it returns Invalid Date. + * `parse` will try to match both formatting and stand-alone units interchangably. * - * @param {String} argument - the value to convert - * @param {Object} [options] - an object with options. - * @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format - * @returns {Date} the parsed date in the local time zone - * @throws {TypeError} 1 argument required - * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2 + * 2. Any sequence of the identical letters is a pattern, unless it is escaped by + * the single quote characters (see below). + * If the sequence is longer than listed in table: + * - for numerical units (`yyyyyyyy`) `parse` will try to match a number + * as wide as the sequence + * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit. + * These variations are marked with "2" in the last column of the table. * - * @example - * // Convert string '2014-02-11T11:30:30' to date: - * const result = parseISO('2014-02-11T11:30:30') - * //=> Tue Feb 11 2014 11:30:30 + * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. + * These tokens represent the shortest form of the quarter. * - * @example - * // Convert string '+02014101' to date, - * // if the additional number of digits in the extended year format is 1: - * const result = parseISO('+02014101', { additionalDigits: 1 }) - * //=> Fri Apr 11 2014 00:00:00 - */ -function parseISO(argument, options) { - var _options$additionalDi; - - (0, _index2.default)(1, arguments); - var additionalDigits = (0, _index3.default)((_options$additionalDi = options === null || options === void 0 ? void 0 : options.additionalDigits) !== null && _options$additionalDi !== void 0 ? _options$additionalDi : 2); - - if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) { - throw new RangeError('additionalDigits must be 0, 1 or 2'); - } - - if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) { - return new Date(NaN); - } - - var dateStrings = splitDateString(argument); - var date; - - if (dateStrings.date) { - var parseYearResult = parseYear(dateStrings.date, additionalDigits); - date = parseDate(parseYearResult.restDateString, parseYearResult.year); - } - - if (!date || isNaN(date.getTime())) { - return new Date(NaN); - } - - var timestamp = date.getTime(); - var time = 0; - var offset; - - if (dateStrings.time) { - time = parseTime(dateStrings.time); - - if (isNaN(time)) { - return new Date(NaN); - } - } + * 4. The main difference between `y` and `u` patterns are B.C. years: + * + * | Year | `y` | `u` | + * |------|-----|-----| + * | AC 1 | 1 | 1 | + * | BC 1 | 1 | 0 | + * | BC 2 | 2 | -1 | + * + * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`: + * + * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00` + * + * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00` + * + * while `uu` will just assign the year as is: + * + * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00` + * + * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00` + * + * The same difference is true for local and ISO week-numbering years (`Y` and `R`), + * except local week-numbering years are dependent on `options.weekStartsOn` + * and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear} + * and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}). + * + * 5. These patterns are not in the Unicode Technical Standard #35: + * - `i`: ISO day of week + * - `I`: ISO week of year + * - `R`: ISO week-numbering year + * - `o`: ordinal number modifier + * - `P`: long localized date + * - `p`: long localized time + * + * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. + * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. + * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based + * on the given locale. + * + * using `en-US` locale: `P` => `MM/dd/yyyy` + * using `en-US` locale: `p` => `hh:mm a` + * using `pt-BR` locale: `P` => `dd/MM/yyyy` + * using `pt-BR` locale: `p` => `HH:mm` + * + * Values will be assigned to the date in the descending order of its unit's priority. + * Units of an equal priority overwrite each other in the order of appearance. + * + * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year), + * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing. + * + * `referenceDate` must be passed for correct work of the function. + * If you're not sure which `referenceDate` to supply, create a new instance of Date: + * `parse('02/11/2014', 'MM/dd/yyyy', new Date())` + * In this case parsing will be done in the context of the current date. + * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`, + * then `Invalid Date` will be returned. + * + * The result may vary by locale. + * + * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned. + * + * If parsing failed, `Invalid Date` will be returned. + * Invalid Date is a Date, whose time value is NaN. + * Time value of Date: http://es5.github.io/#x15.9.1.1 + * + * @param {String} dateString - the string to parse + * @param {String} formatString - the string of tokens + * @param {Date|Number} referenceDate - defines values missing from the parsed dateString + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year + * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @returns {Date} the parsed date + * @throws {TypeError} 3 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * @throws {RangeError} `options.locale` must contain `match` property + * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} format string contains an unescaped latin alphabet character + * + * @example + * // Parse 11 February 2014 from middle-endian format: + * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date()) + * //=> Tue Feb 11 2014 00:00:00 + * + * @example + * // Parse 28th of February in Esperanto locale in the context of 2010 year: + * import eo from 'date-fns/locale/eo' + * var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), { + * locale: eo + * }) + * //=> Sun Feb 28 2010 00:00:00 + */ - if (dateStrings.timezone) { - offset = parseTimezone(dateStrings.timezone); +function parse(dirtyDateString, dirtyFormatString, dirtyReferenceDate, options) { + var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; - if (isNaN(offset)) { - return new Date(NaN); - } - } else { - var dirtyDate = new Date(timestamp + time); // js parsed string assuming it's in UTC timezone - // but we need it to be parsed in our timezone - // so we use utc values to build date in our timezone. - // Year values from 0 to 99 map to the years 1900 to 1999 - // so set year explicitly with setFullYear. + (0, _index9.default)(3, arguments); + var dateString = String(dirtyDateString); + var formatString = String(dirtyFormatString); + var defaultOptions = (0, _index11.getDefaultOptions)(); + var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : _index.default; - var result = new Date(0); - result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate()); - result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds()); - return result; + if (!locale.match) { + throw new RangeError('locale must contain match property'); } - return new Date(timestamp + time + offset); -} - -var patterns = { - dateTimeDelimiter: /[T ]/, - timeZoneDelimiter: /[Z ]/i, - timezone: /([Z+-].*)$/ -}; -var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/; -var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/; -var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/; - -function splitDateString(dateString) { - var dateStrings = {}; - var array = dateString.split(patterns.dateTimeDelimiter); - var timeString; // The regex match should only return at maximum two array elements. - // [date], [time], or [date, time]. + var firstWeekContainsDate = (0, _index8.default)((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN - if (array.length > 2) { - return dateStrings; + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); } - if (/:/.test(array[0])) { - timeString = array[0]; - } else { - dateStrings.date = array[0]; - timeString = array[1]; + var weekStartsOn = (0, _index8.default)((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN - if (patterns.timeZoneDelimiter.test(dateStrings.date)) { - dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0]; - timeString = dateString.substr(dateStrings.date.length, dateString.length); - } + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); } - if (timeString) { - var token = patterns.timezone.exec(timeString); - - if (token) { - dateStrings.time = timeString.replace(token[1], ''); - dateStrings.timezone = token[1]; + if (formatString === '') { + if (dateString === '') { + return (0, _index3.default)(dirtyReferenceDate); } else { - dateStrings.time = timeString; + return new Date(NaN); } } - return dateStrings; -} - -function parseYear(dateString, additionalDigits) { - var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)'); - var captures = dateString.match(regex); // Invalid ISO-formatted year - - if (!captures) return { - year: NaN, - restDateString: '' - }; - var year = captures[1] ? parseInt(captures[1]) : null; - var century = captures[2] ? parseInt(captures[2]) : null; // either year or century is null, not both - - return { - year: century === null ? year : century * 100, - restDateString: dateString.slice((captures[1] || captures[2]).length) - }; -} - -function parseDate(dateString, year) { - // Invalid ISO-formatted year - if (year === null) return new Date(NaN); - var captures = dateString.match(dateRegex); // Invalid ISO-formatted string - - if (!captures) return new Date(NaN); - var isWeekDate = !!captures[4]; - var dayOfYear = parseDateUnit(captures[1]); - var month = parseDateUnit(captures[2]) - 1; - var day = parseDateUnit(captures[3]); - var week = parseDateUnit(captures[4]); - var dayOfWeek = parseDateUnit(captures[5]) - 1; - - if (isWeekDate) { - if (!validateWeekDate(year, week, dayOfWeek)) { - return new Date(NaN); - } + var subFnOptions = { + firstWeekContainsDate: firstWeekContainsDate, + weekStartsOn: weekStartsOn, + locale: locale + }; // If timezone isn't specified, it will be set to the system timezone - return dayOfISOWeekYear(year, week, dayOfWeek); - } else { - var date = new Date(0); + var setters = [new _Setter.DateToSystemTimezoneSetter()]; + var tokens = formatString.match(longFormattingTokensRegExp).map(function (substring) { + var firstCharacter = substring[0]; - if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) { - return new Date(NaN); + if (firstCharacter in _index5.default) { + var longFormatter = _index5.default[firstCharacter]; + return longFormatter(substring, locale.formatLong); } - date.setUTCFullYear(year, month, Math.max(dayOfYear, day)); - return date; - } -} - -function parseDateUnit(value) { - return value ? parseInt(value) : 1; -} - -function parseTime(timeString) { - var captures = timeString.match(timeRegex); - if (!captures) return NaN; // Invalid ISO-formatted time - - var hours = parseTimeUnit(captures[1]); - var minutes = parseTimeUnit(captures[2]); - var seconds = parseTimeUnit(captures[3]); + return substring; + }).join('').match(formattingTokensRegExp); + var usedTokens = []; - if (!validateTime(hours, minutes, seconds)) { - return NaN; - } + var _iterator = _createForOfIteratorHelper(tokens), + _step; - return hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute + seconds * 1000; -} + try { + var _loop = function _loop() { + var token = _step.value; -function parseTimeUnit(value) { - return value && parseFloat(value.replace(',', '.')) || 0; -} + if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && (0, _index7.isProtectedWeekYearToken)(token)) { + (0, _index7.throwProtectedError)(token, formatString, dirtyDateString); + } -function parseTimezone(timezoneString) { - if (timezoneString === 'Z') return 0; - var captures = timezoneString.match(timezoneRegex); - if (!captures) return 0; - var sign = captures[1] === '+' ? -1 : 1; - var hours = parseInt(captures[2]); - var minutes = captures[3] && parseInt(captures[3]) || 0; + if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && (0, _index7.isProtectedDayOfYearToken)(token)) { + (0, _index7.throwProtectedError)(token, formatString, dirtyDateString); + } - if (!validateTimezone(hours, minutes)) { - return NaN; - } + var firstCharacter = token[0]; + var parser = _index10.parsers[firstCharacter]; - return sign * (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute); -} + if (parser) { + var incompatibleTokens = parser.incompatibleTokens; -function dayOfISOWeekYear(isoWeekYear, week, day) { - var date = new Date(0); - date.setUTCFullYear(isoWeekYear, 0, 4); - var fourthOfJanuaryDay = date.getUTCDay() || 7; - var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay; - date.setUTCDate(date.getUTCDate() + diff); - return date; -} // Validation functions -// February is null to handle the leap year (using ||) + if (Array.isArray(incompatibleTokens)) { + var incompatibleToken = usedTokens.find(function (usedToken) { + return incompatibleTokens.includes(usedToken.token) || usedToken.token === firstCharacter; + }); + if (incompatibleToken) { + throw new RangeError("The format string mustn't contain `".concat(incompatibleToken.fullToken, "` and `").concat(token, "` at the same time")); + } + } else if (parser.incompatibleTokens === '*' && usedTokens.length > 0) { + throw new RangeError("The format string mustn't contain `".concat(token, "` and any other token at the same time")); + } -var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + usedTokens.push({ + token: firstCharacter, + fullToken: token + }); + var parseResult = parser.run(dateString, token, locale.match, subFnOptions); -function isLeapYearIndex(year) { - return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; -} + if (!parseResult) { + return { + v: new Date(NaN) + }; + } -function validateDate(year, month, date) { - return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28)); -} + setters.push(parseResult.setter); + dateString = parseResult.rest; + } else { + if (firstCharacter.match(unescapedLatinCharacterRegExp)) { + throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); + } // Replace two single quote characters with one single quote character -function validateDayOfYearDate(year, dayOfYear) { - return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365); -} -function validateWeekDate(_year, week, day) { - return week >= 1 && week <= 53 && day >= 0 && day <= 6; -} + if (token === "''") { + token = "'"; + } else if (firstCharacter === "'") { + token = cleanEscapedString(token); + } // Cut token from string, or, if string doesn't match the token, return Invalid Date -function validateTime(hours, minutes, seconds) { - if (hours === 24) { - return minutes === 0 && seconds === 0; - } - return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25; -} + if (dateString.indexOf(token) === 0) { + dateString = dateString.slice(token.length); + } else { + return { + v: new Date(NaN) + }; + } + } + }; -function validateTimezone(_hours, minutes) { - return minutes >= 0 && minutes <= 59; -} + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _ret = _loop(); -module.exports = exports.default; + if (_typeof(_ret) === "object") return _ret.v; + } // Check if the remaining input contains something other than whitespace -/***/ }), + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } -/***/ 8159: -/***/ ((module, exports, __nccwpck_require__) => { + if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) { + return new Date(NaN); + } -"use strict"; + var uniquePrioritySetters = setters.map(function (setter) { + return setter.priority; + }).sort(function (a, b) { + return b - a; + }).filter(function (priority, index, array) { + return array.indexOf(priority) === index; + }).map(function (priority) { + return setters.filter(function (setter) { + return setter.priority === priority; + }).sort(function (a, b) { + return b.subPriority - a.subPriority; + }); + }).map(function (setterArray) { + return setterArray[0]; + }); + var date = (0, _index3.default)(dirtyReferenceDate); + if (isNaN(date.getTime())) { + return new Date(NaN); + } // Convert the date in system timezone to the same date in UTC+00:00 timezone. -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = parseJSON; -var _index = _interopRequireDefault(__nccwpck_require__(6477)); + var utcDate = (0, _index2.default)(date, (0, _index6.default)(date)); + var flags = {}; -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); + var _iterator2 = _createForOfIteratorHelper(uniquePrioritySetters), + _step2; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var setter = _step2.value; -/** - * @name parseJSON - * @category Common Helpers - * @summary Parse a JSON date string - * - * @description - * Converts a complete ISO date string in UTC time, the typical format for transmitting - * a date in JSON, to a JavaScript `Date` instance. - * - * This is a minimal implementation for converting dates retrieved from a JSON API to - * a `Date` instance which can be used with other functions in the `date-fns` library. - * The following formats are supported: - * - * - `2000-03-15T05:20:10.123Z`: The output of `.toISOString()` and `JSON.stringify(new Date())` - * - `2000-03-15T05:20:10Z`: Without milliseconds - * - `2000-03-15T05:20:10+00:00`: With a zero offset, the default JSON encoded format in some other languages - * - `2000-03-15T05:20:10+05:45`: With a positive or negative offset, the default JSON encoded format in some other languages - * - `2000-03-15T05:20:10+0000`: With a zero offset without a colon - * - `2000-03-15T05:20:10`: Without a trailing 'Z' symbol - * - `2000-03-15T05:20:10.1234567`: Up to 7 digits in milliseconds field. Only first 3 are taken into account since JS does not allow fractional milliseconds - * - `2000-03-15 05:20:10`: With a space instead of a 'T' separator for APIs returning a SQL date without reformatting - * - * For convenience and ease of use these other input types are also supported - * via [toDate]{@link https://date-fns.org/docs/toDate}: - * - * - A `Date` instance will be cloned - * - A `number` will be treated as a timestamp - * - * Any other input type or invalid date strings will return an `Invalid Date`. - * - * @param {String|Number|Date} argument A fully formed ISO8601 date string to convert - * @returns {Date} the parsed date in the local time zone - * @throws {TypeError} 1 argument required - */ -function parseJSON(argument) { - (0, _index2.default)(1, arguments); + if (!setter.validate(utcDate, subFnOptions)) { + return new Date(NaN); + } - if (typeof argument === 'string') { - var parts = argument.match(/(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:Z|(.)(\d{2}):?(\d{2})?)?/); + var result = setter.set(utcDate, flags, subFnOptions); // Result is tuple (date, flags) - if (parts) { - // Group 8 matches the sign - return new Date(Date.UTC(+parts[1], +parts[2] - 1, +parts[3], +parts[4] - (+parts[9] || 0) * (parts[8] == '-' ? -1 : 1), +parts[5] - (+parts[10] || 0) * (parts[8] == '-' ? -1 : 1), +parts[6], +((parts[7] || '0') + '00').substring(0, 3))); + if (Array.isArray(result)) { + utcDate = result[0]; + (0, _index4.default)(flags, result[1]); // Result is date + } else { + utcDate = result; + } } - - return new Date(NaN); + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); } - return (0, _index.default)(argument); + return utcDate; +} + +function cleanEscapedString(input) { + return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'"); } module.exports = exports.default; @@ -26477,7 +26477,7 @@ module.exports = exports.default; /***/ }), -/***/ 2031: +/***/ 8760: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -26486,99 +26486,39 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = set; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); +exports["default"] = setDate; -var _index2 = _interopRequireDefault(__nccwpck_require__(847)); +var _index = _interopRequireDefault(__nccwpck_require__(1985)); -var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index2 = _interopRequireDefault(__nccwpck_require__(6477)); -var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - /** - * @name set - * @category Common Helpers - * @summary Set date values to a given date. + * @name setDate + * @category Day Helpers + * @summary Set the day of the month to the given date. * * @description - * Set date values to a given date. - * - * Sets time values to date from object `values`. - * A value is not set if it is undefined or null or doesn't exist in `values`. - * - * Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts - * to use native `Date#setX` methods. If you use this function, you may not want to include the - * other `setX` functions that date-fns provides if you are concerned about the bundle size. + * Set the day of the month to the given date. * * @param {Date|Number} date - the date to be changed - * @param {Object} values - an object with options - * @param {Number} [values.year] - the number of years to be set - * @param {Number} [values.month] - the number of months to be set - * @param {Number} [values.date] - the number of days to be set - * @param {Number} [values.hours] - the number of hours to be set - * @param {Number} [values.minutes] - the number of minutes to be set - * @param {Number} [values.seconds] - the number of seconds to be set - * @param {Number} [values.milliseconds] - the number of milliseconds to be set - * @returns {Date} the new date with options set + * @param {Number} dayOfMonth - the day of the month of the new date + * @returns {Date} the new date with the day of the month set * @throws {TypeError} 2 arguments required - * @throws {RangeError} `values` must be an object - * - * @example - * // Transform 1 September 2014 into 20 October 2015 in a single line: - * const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 }) - * //=> Tue Oct 20 2015 00:00:00 * * @example - * // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00: - * const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 }) - * //=> Mon Sep 01 2014 12:23:45 + * // Set the 30th day of the month to 1 September 2014: + * const result = setDate(new Date(2014, 8, 1), 30) + * //=> Tue Sep 30 2014 00:00:00 */ -function set(dirtyDate, values) { - (0, _index4.default)(2, arguments); - - if (_typeof(values) !== 'object' || values === null) { - throw new RangeError('values parameter must be an object'); - } - - var date = (0, _index.default)(dirtyDate); // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date - - if (isNaN(date.getTime())) { - return new Date(NaN); - } - - if (values.year != null) { - date.setFullYear(values.year); - } - - if (values.month != null) { - date = (0, _index2.default)(date, values.month); - } - - if (values.date != null) { - date.setDate((0, _index3.default)(values.date)); - } - - if (values.hours != null) { - date.setHours((0, _index3.default)(values.hours)); - } - - if (values.minutes != null) { - date.setMinutes((0, _index3.default)(values.minutes)); - } - - if (values.seconds != null) { - date.setSeconds((0, _index3.default)(values.seconds)); - } - - if (values.milliseconds != null) { - date.setMilliseconds((0, _index3.default)(values.milliseconds)); - } - +function setDate(dirtyDate, dirtyDayOfMonth) { + (0, _index3.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var dayOfMonth = (0, _index.default)(dirtyDayOfMonth); + date.setDate(dayOfMonth); return date; } @@ -26586,7 +26526,7 @@ module.exports = exports.default; /***/ }), -/***/ 8760: +/***/ 4002: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -26595,7 +26535,7 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = setDate; +exports["default"] = setDayOfYear; var _index = _interopRequireDefault(__nccwpck_require__(1985)); @@ -26606,28 +26546,29 @@ var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name setDate + * @name setDayOfYear * @category Day Helpers - * @summary Set the day of the month to the given date. + * @summary Set the day of the year to the given date. * * @description - * Set the day of the month to the given date. + * Set the day of the year to the given date. * * @param {Date|Number} date - the date to be changed - * @param {Number} dayOfMonth - the day of the month of the new date - * @returns {Date} the new date with the day of the month set + * @param {Number} dayOfYear - the day of the year of the new date + * @returns {Date} the new date with the day of the year set * @throws {TypeError} 2 arguments required * * @example - * // Set the 30th day of the month to 1 September 2014: - * const result = setDate(new Date(2014, 8, 1), 30) - * //=> Tue Sep 30 2014 00:00:00 + * // Set the 2nd day of the year to 2 July 2014: + * const result = setDayOfYear(new Date(2014, 6, 2), 2) + * //=> Thu Jan 02 2014 00:00:00 */ -function setDate(dirtyDate, dirtyDayOfMonth) { +function setDayOfYear(dirtyDate, dirtyDayOfYear) { (0, _index3.default)(2, arguments); var date = (0, _index2.default)(dirtyDate); - var dayOfMonth = (0, _index.default)(dirtyDayOfMonth); - date.setDate(dayOfMonth); + var dayOfYear = (0, _index.default)(dirtyDayOfYear); + date.setMonth(0); + date.setDate(dayOfYear); return date; } @@ -26710,56 +26651,6 @@ module.exports = exports.default; /***/ }), -/***/ 4002: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = setDayOfYear; - -var _index = _interopRequireDefault(__nccwpck_require__(1985)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @name setDayOfYear - * @category Day Helpers - * @summary Set the day of the year to the given date. - * - * @description - * Set the day of the year to the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Number} dayOfYear - the day of the year of the new date - * @returns {Date} the new date with the day of the year set - * @throws {TypeError} 2 arguments required - * - * @example - * // Set the 2nd day of the year to 2 July 2014: - * const result = setDayOfYear(new Date(2014, 6, 2), 2) - * //=> Thu Jan 02 2014 00:00:00 - */ -function setDayOfYear(dirtyDate, dirtyDayOfYear) { - (0, _index3.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var dayOfYear = (0, _index.default)(dirtyDayOfYear); - date.setMonth(0); - date.setDate(dayOfYear); - return date; -} - -module.exports = exports.default; - -/***/ }), - /***/ 54: /***/ ((module, exports, __nccwpck_require__) => { @@ -26961,7 +26852,7 @@ module.exports = exports.default; /***/ }), -/***/ 3035: +/***/ 822: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -26970,44 +26861,51 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = setISOWeek; +exports["default"] = setISOWeekYear; var _index = _interopRequireDefault(__nccwpck_require__(1985)); var _index2 = _interopRequireDefault(__nccwpck_require__(6477)); -var _index3 = _interopRequireDefault(__nccwpck_require__(9894)); +var _index3 = _interopRequireDefault(__nccwpck_require__(776)); -var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(3086)); + +var _index5 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name setISOWeek - * @category ISO Week Helpers - * @summary Set the ISO week to the given date. + * @name setISOWeekYear + * @category ISO Week-Numbering Year Helpers + * @summary Set the ISO week-numbering year to the given date. * * @description - * Set the ISO week to the given date, saving the weekday number. + * Set the ISO week-numbering year to the given date, + * saving the week number and the weekday number. * * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * * @param {Date|Number} date - the date to be changed - * @param {Number} isoWeek - the ISO week of the new date - * @returns {Date} the new date with the ISO week set + * @param {Number} isoWeekYear - the ISO week-numbering year of the new date + * @returns {Date} the new date with the ISO week-numbering year set * @throws {TypeError} 2 arguments required * * @example - * // Set the 53rd ISO week to 7 August 2004: - * const result = setISOWeek(new Date(2004, 7, 7), 53) - * //=> Sat Jan 01 2005 00:00:00 + * // Set ISO week-numbering year 2007 to 29 December 2008: + * const result = setISOWeekYear(new Date(2008, 11, 29), 2007) + * //=> Mon Jan 01 2007 00:00:00 */ -function setISOWeek(dirtyDate, dirtyISOWeek) { - (0, _index4.default)(2, arguments); +function setISOWeekYear(dirtyDate, dirtyISOWeekYear) { + (0, _index5.default)(2, arguments); var date = (0, _index2.default)(dirtyDate); - var isoWeek = (0, _index.default)(dirtyISOWeek); - var diff = (0, _index3.default)(date) - isoWeek; - date.setDate(date.getDate() - diff * 7); + var isoWeekYear = (0, _index.default)(dirtyISOWeekYear); + var diff = (0, _index4.default)(date, (0, _index3.default)(date)); + var fourthOfJanuary = new Date(0); + fourthOfJanuary.setFullYear(isoWeekYear, 0, 4); + fourthOfJanuary.setHours(0, 0, 0, 0); + date = (0, _index3.default)(fourthOfJanuary); + date.setDate(date.getDate() + diff); return date; } @@ -27015,7 +26913,7 @@ module.exports = exports.default; /***/ }), -/***/ 822: +/***/ 3035: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -27024,51 +26922,44 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = setISOWeekYear; +exports["default"] = setISOWeek; var _index = _interopRequireDefault(__nccwpck_require__(1985)); var _index2 = _interopRequireDefault(__nccwpck_require__(6477)); -var _index3 = _interopRequireDefault(__nccwpck_require__(776)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(3086)); +var _index3 = _interopRequireDefault(__nccwpck_require__(9894)); -var _index5 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name setISOWeekYear - * @category ISO Week-Numbering Year Helpers - * @summary Set the ISO week-numbering year to the given date. + * @name setISOWeek + * @category ISO Week Helpers + * @summary Set the ISO week to the given date. * * @description - * Set the ISO week-numbering year to the given date, - * saving the week number and the weekday number. + * Set the ISO week to the given date, saving the weekday number. * * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * * @param {Date|Number} date - the date to be changed - * @param {Number} isoWeekYear - the ISO week-numbering year of the new date - * @returns {Date} the new date with the ISO week-numbering year set + * @param {Number} isoWeek - the ISO week of the new date + * @returns {Date} the new date with the ISO week set * @throws {TypeError} 2 arguments required * * @example - * // Set ISO week-numbering year 2007 to 29 December 2008: - * const result = setISOWeekYear(new Date(2008, 11, 29), 2007) - * //=> Mon Jan 01 2007 00:00:00 + * // Set the 53rd ISO week to 7 August 2004: + * const result = setISOWeek(new Date(2004, 7, 7), 53) + * //=> Sat Jan 01 2005 00:00:00 */ -function setISOWeekYear(dirtyDate, dirtyISOWeekYear) { - (0, _index5.default)(2, arguments); +function setISOWeek(dirtyDate, dirtyISOWeek) { + (0, _index4.default)(2, arguments); var date = (0, _index2.default)(dirtyDate); - var isoWeekYear = (0, _index.default)(dirtyISOWeekYear); - var diff = (0, _index4.default)(date, (0, _index3.default)(date)); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(isoWeekYear, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - date = (0, _index3.default)(fourthOfJanuary); - date.setDate(date.getDate() + diff); + var isoWeek = (0, _index.default)(dirtyISOWeek); + var diff = (0, _index3.default)(date) - isoWeek; + date.setDate(date.getDate() - diff * 7); return date; } @@ -27334,7 +27225,7 @@ module.exports = exports.default; /***/ }), -/***/ 2664: +/***/ 3438: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -27343,25 +27234,30 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = setWeek; +exports["default"] = setWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(81)); +var _index = _interopRequireDefault(__nccwpck_require__(3086)); -var _index2 = _interopRequireDefault(__nccwpck_require__(6477)); +var _index2 = _interopRequireDefault(__nccwpck_require__(8014)); -var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index3 = _interopRequireDefault(__nccwpck_require__(6477)); var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); +var _index5 = _interopRequireDefault(__nccwpck_require__(2063)); + +var _index6 = __nccwpck_require__(9307); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name setWeek - * @category Week Helpers - * @summary Set the local week to the given date. + * @name setWeekYear + * @category Week-Numbering Year Helpers + * @summary Set the local week-numbering year to the given date. * * @description - * Set the local week to the given date, saving the weekday number. + * Set the local week-numbering year to the given date, + * saving the week number and the weekday number. * The exact calculation depends on the values of * `options.weekStartsOn` (which is the index of the first day of the week) * and `options.firstWeekContainsDate` (which is the day of January, which is always in @@ -27370,37 +27266,45 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering * * @param {Date|Number} date - the date to be changed - * @param {Number} week - the week of the new date + * @param {Number} weekYear - the local week-numbering year of the new date * @param {Object} [options] - an object with options. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year - * @returns {Date} the new date with the local week set + * @returns {Date} the new date with the local week-numbering year set * @throws {TypeError} 2 arguments required * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 * * @example - * // Set the 1st week to 2 January 2005 with default options: - * const result = setWeek(new Date(2005, 0, 2), 1) - * //=> Sun Dec 26 2004 00:00:00 + * // Set the local week-numbering year 2004 to 2 January 2010 with default options: + * const result = setWeekYear(new Date(2010, 0, 2), 2004) + * //=> Sat Jan 03 2004 00:00:00 * * @example - * // Set the 1st week to 2 January 2005, - * // if Monday is the first day of the week, - * // and the first week of the year always contains 4 January: - * const result = setWeek(new Date(2005, 0, 2), 1, { + * // Set the local week-numbering year 2004 to 2 January 2010, + * // if Monday is the first day of week + * // and 4 January is always in the first week of the year: + * const result = setWeekYear(new Date(2010, 0, 2), 2004, { * weekStartsOn: 1, * firstWeekContainsDate: 4 * }) - * //=> Sun Jan 4 2004 00:00:00 + * //=> Sat Jan 01 2005 00:00:00 */ -function setWeek(dirtyDate, dirtyWeek, options) { - (0, _index3.default)(2, arguments); - var date = (0, _index2.default)(dirtyDate); - var week = (0, _index4.default)(dirtyWeek); - var diff = (0, _index.default)(date, options) - week; - date.setDate(date.getDate() - diff * 7); +function setWeekYear(dirtyDate, dirtyWeekYear, options) { + var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + + (0, _index5.default)(2, arguments); + var defaultOptions = (0, _index6.getDefaultOptions)(); + var firstWeekContainsDate = (0, _index4.default)((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); + var date = (0, _index3.default)(dirtyDate); + var weekYear = (0, _index4.default)(dirtyWeekYear); + var diff = (0, _index.default)(date, (0, _index2.default)(date, options)); + var firstWeek = new Date(0); + firstWeek.setFullYear(weekYear, 0, firstWeekContainsDate); + firstWeek.setHours(0, 0, 0, 0); + date = (0, _index2.default)(firstWeek, options); + date.setDate(date.getDate() + diff); return date; } @@ -27408,7 +27312,7 @@ module.exports = exports.default; /***/ }), -/***/ 3438: +/***/ 2664: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -27417,30 +27321,25 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = setWeekYear; +exports["default"] = setWeek; -var _index = _interopRequireDefault(__nccwpck_require__(3086)); +var _index = _interopRequireDefault(__nccwpck_require__(81)); -var _index2 = _interopRequireDefault(__nccwpck_require__(8014)); +var _index2 = _interopRequireDefault(__nccwpck_require__(6477)); -var _index3 = _interopRequireDefault(__nccwpck_require__(6477)); +var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); -var _index5 = _interopRequireDefault(__nccwpck_require__(2063)); - -var _index6 = __nccwpck_require__(9307); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name setWeekYear - * @category Week-Numbering Year Helpers - * @summary Set the local week-numbering year to the given date. + * @name setWeek + * @category Week Helpers + * @summary Set the local week to the given date. * * @description - * Set the local week-numbering year to the given date, - * saving the week number and the weekday number. + * Set the local week to the given date, saving the weekday number. * The exact calculation depends on the values of * `options.weekStartsOn` (which is the index of the first day of the week) * and `options.firstWeekContainsDate` (which is the day of January, which is always in @@ -27449,45 +27348,37 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering * * @param {Date|Number} date - the date to be changed - * @param {Number} weekYear - the local week-numbering year of the new date + * @param {Number} week - the week of the new date * @param {Object} [options] - an object with options. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year - * @returns {Date} the new date with the local week-numbering year set + * @returns {Date} the new date with the local week set * @throws {TypeError} 2 arguments required * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 * * @example - * // Set the local week-numbering year 2004 to 2 January 2010 with default options: - * const result = setWeekYear(new Date(2010, 0, 2), 2004) - * //=> Sat Jan 03 2004 00:00:00 + * // Set the 1st week to 2 January 2005 with default options: + * const result = setWeek(new Date(2005, 0, 2), 1) + * //=> Sun Dec 26 2004 00:00:00 * * @example - * // Set the local week-numbering year 2004 to 2 January 2010, - * // if Monday is the first day of week - * // and 4 January is always in the first week of the year: - * const result = setWeekYear(new Date(2010, 0, 2), 2004, { + * // Set the 1st week to 2 January 2005, + * // if Monday is the first day of the week, + * // and the first week of the year always contains 4 January: + * const result = setWeek(new Date(2005, 0, 2), 1, { * weekStartsOn: 1, * firstWeekContainsDate: 4 * }) - * //=> Sat Jan 01 2005 00:00:00 + * //=> Sun Jan 4 2004 00:00:00 */ -function setWeekYear(dirtyDate, dirtyWeekYear, options) { - var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - - (0, _index5.default)(2, arguments); - var defaultOptions = (0, _index6.getDefaultOptions)(); - var firstWeekContainsDate = (0, _index4.default)((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); - var date = (0, _index3.default)(dirtyDate); - var weekYear = (0, _index4.default)(dirtyWeekYear); - var diff = (0, _index.default)(date, (0, _index2.default)(date, options)); - var firstWeek = new Date(0); - firstWeek.setFullYear(weekYear, 0, firstWeekContainsDate); - firstWeek.setHours(0, 0, 0, 0); - date = (0, _index2.default)(firstWeek, options); - date.setDate(date.getDate() + diff); +function setWeek(dirtyDate, dirtyWeek, options) { + (0, _index3.default)(2, arguments); + var date = (0, _index2.default)(dirtyDate); + var week = (0, _index4.default)(dirtyWeek); + var diff = (0, _index.default)(date, options) - week; + date.setDate(date.getDate() - diff * 7); return date; } @@ -27549,6 +27440,115 @@ module.exports = exports.default; /***/ }), +/***/ 2031: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = set; + +var _index = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(847)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(1985)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(2063)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * @name set + * @category Common Helpers + * @summary Set date values to a given date. + * + * @description + * Set date values to a given date. + * + * Sets time values to date from object `values`. + * A value is not set if it is undefined or null or doesn't exist in `values`. + * + * Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts + * to use native `Date#setX` methods. If you use this function, you may not want to include the + * other `setX` functions that date-fns provides if you are concerned about the bundle size. + * + * @param {Date|Number} date - the date to be changed + * @param {Object} values - an object with options + * @param {Number} [values.year] - the number of years to be set + * @param {Number} [values.month] - the number of months to be set + * @param {Number} [values.date] - the number of days to be set + * @param {Number} [values.hours] - the number of hours to be set + * @param {Number} [values.minutes] - the number of minutes to be set + * @param {Number} [values.seconds] - the number of seconds to be set + * @param {Number} [values.milliseconds] - the number of milliseconds to be set + * @returns {Date} the new date with options set + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `values` must be an object + * + * @example + * // Transform 1 September 2014 into 20 October 2015 in a single line: + * const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 }) + * //=> Tue Oct 20 2015 00:00:00 + * + * @example + * // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00: + * const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 }) + * //=> Mon Sep 01 2014 12:23:45 + */ +function set(dirtyDate, values) { + (0, _index4.default)(2, arguments); + + if (_typeof(values) !== 'object' || values === null) { + throw new RangeError('values parameter must be an object'); + } + + var date = (0, _index.default)(dirtyDate); // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date + + if (isNaN(date.getTime())) { + return new Date(NaN); + } + + if (values.year != null) { + date.setFullYear(values.year); + } + + if (values.month != null) { + date = (0, _index2.default)(date, values.month); + } + + if (values.date != null) { + date.setDate((0, _index3.default)(values.date)); + } + + if (values.hours != null) { + date.setHours((0, _index3.default)(values.hours)); + } + + if (values.minutes != null) { + date.setMinutes((0, _index3.default)(values.minutes)); + } + + if (values.seconds != null) { + date.setSeconds((0, _index3.default)(values.seconds)); + } + + if (values.milliseconds != null) { + date.setMilliseconds((0, _index3.default)(values.milliseconds)); + } + + return date; +} + +module.exports = exports.default; + +/***/ }), + /***/ 1868: /***/ ((module, exports, __nccwpck_require__) => { @@ -27689,7 +27689,7 @@ module.exports = exports.default; /***/ }), -/***/ 6307: +/***/ 776: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -27698,46 +27698,52 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = startOfISOWeek; +exports["default"] = startOfISOWeekYear; -var _index = _interopRequireDefault(__nccwpck_require__(9813)); +var _index = _interopRequireDefault(__nccwpck_require__(6991)); -var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(6307)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name startOfISOWeek - * @category ISO Week Helpers - * @summary Return the start of an ISO week for the given date. + * @name startOfISOWeekYear + * @category ISO Week-Numbering Year Helpers + * @summary Return the start of an ISO week-numbering year for the given date. * * @description - * Return the start of an ISO week for the given date. + * Return the start of an ISO week-numbering year, + * which always starts 3 days before the year's first Thursday. * The result will be in the local timezone. * * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * * @param {Date|Number} date - the original date - * @returns {Date} the start of an ISO week + * @returns {Date} the start of an ISO week-numbering year * @throws {TypeError} 1 argument required * * @example - * // The start of an ISO week for 2 September 2014 11:55:00: - * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 + * // The start of an ISO week-numbering year for 2 July 2005: + * const result = startOfISOWeekYear(new Date(2005, 6, 2)) + * //=> Mon Jan 03 2005 00:00:00 */ -function startOfISOWeek(dirtyDate) { - (0, _index2.default)(1, arguments); - return (0, _index.default)(dirtyDate, { - weekStartsOn: 1 - }); +function startOfISOWeekYear(dirtyDate) { + (0, _index3.default)(1, arguments); + var year = (0, _index.default)(dirtyDate); + var fourthOfJanuary = new Date(0); + fourthOfJanuary.setFullYear(year, 0, 4); + fourthOfJanuary.setHours(0, 0, 0, 0); + var date = (0, _index2.default)(fourthOfJanuary); + return date; } module.exports = exports.default; /***/ }), -/***/ 776: +/***/ 6307: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; @@ -27746,45 +27752,39 @@ module.exports = exports.default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = startOfISOWeekYear; - -var _index = _interopRequireDefault(__nccwpck_require__(6991)); +exports["default"] = startOfISOWeek; -var _index2 = _interopRequireDefault(__nccwpck_require__(6307)); +var _index = _interopRequireDefault(__nccwpck_require__(9813)); -var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); +var _index2 = _interopRequireDefault(__nccwpck_require__(2063)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @name startOfISOWeekYear - * @category ISO Week-Numbering Year Helpers - * @summary Return the start of an ISO week-numbering year for the given date. + * @name startOfISOWeek + * @category ISO Week Helpers + * @summary Return the start of an ISO week for the given date. * * @description - * Return the start of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. + * Return the start of an ISO week for the given date. * The result will be in the local timezone. * * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * * @param {Date|Number} date - the original date - * @returns {Date} the start of an ISO week-numbering year + * @returns {Date} the start of an ISO week * @throws {TypeError} 1 argument required * * @example - * // The start of an ISO week-numbering year for 2 July 2005: - * const result = startOfISOWeekYear(new Date(2005, 6, 2)) - * //=> Mon Jan 03 2005 00:00:00 + * // The start of an ISO week for 2 September 2014 11:55:00: + * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Mon Sep 01 2014 00:00:00 */ -function startOfISOWeekYear(dirtyDate) { - (0, _index3.default)(1, arguments); - var year = (0, _index.default)(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = (0, _index2.default)(fourthOfJanuary); - return date; +function startOfISOWeek(dirtyDate) { + (0, _index2.default)(1, arguments); + return (0, _index.default)(dirtyDate, { + weekStartsOn: 1 + }); } module.exports = exports.default; @@ -28042,93 +28042,22 @@ exports["default"] = startOfTomorrow; * Return the start of tomorrow. * * > ⚠️ Please note that this function is not present in the FP submodule as - * > it uses `new Date()` internally hence impure and can't be safely curried. - * - * @returns {Date} the start of tomorrow - * - * @example - * // If today is 6 October 2014: - * const result = startOfTomorrow() - * //=> Tue Oct 7 2014 00:00:00 - */ -function startOfTomorrow() { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(0, 0, 0, 0); - return date; -} - -module.exports = exports.default; - -/***/ }), - -/***/ 9813: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = startOfWeek; - -var _index = _interopRequireDefault(__nccwpck_require__(6477)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(1985)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); - -var _index4 = __nccwpck_require__(9307); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @name startOfWeek - * @category Week Helpers - * @summary Return the start of a week for the given date. - * - * @description - * Return the start of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|Number} date - the original date - * @param {Object} [options] - an object with options. - * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} - * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the start of a week - * @throws {TypeError} 1 argument required - * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * > it uses `new Date()` internally hence impure and can't be safely curried. * - * @example - * // The start of a week for 2 September 2014 11:55:00: - * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Aug 31 2014 00:00:00 + * @returns {Date} the start of tomorrow * * @example - * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: - * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) - * //=> Mon Sep 01 2014 00:00:00 + * // If today is 6 October 2014: + * const result = startOfTomorrow() + * //=> Tue Oct 7 2014 00:00:00 */ -function startOfWeek(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - - (0, _index3.default)(1, arguments); - var defaultOptions = (0, _index4.getDefaultOptions)(); - var weekStartsOn = (0, _index2.default)((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN - - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); - } - - var date = (0, _index.default)(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - date.setDate(date.getDate() - diff); +function startOfTomorrow() { + var now = new Date(); + var year = now.getFullYear(); + var month = now.getMonth(); + var day = now.getDate(); + var date = new Date(0); + date.setFullYear(year, month, day + 1); date.setHours(0, 0, 0, 0); return date; } @@ -28217,6 +28146,77 @@ module.exports = exports.default; /***/ }), +/***/ 9813: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = startOfWeek; + +var _index = _interopRequireDefault(__nccwpck_require__(6477)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(1985)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); + +var _index4 = __nccwpck_require__(9307); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @name startOfWeek + * @category Week Helpers + * @summary Return the start of a week for the given date. + * + * @description + * Return the start of a week for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @returns {Date} the start of a week + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * + * @example + * // The start of a week for 2 September 2014 11:55:00: + * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Sun Aug 31 2014 00:00:00 + * + * @example + * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: + * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) + * //=> Mon Sep 01 2014 00:00:00 + */ +function startOfWeek(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + + (0, _index3.default)(1, arguments); + var defaultOptions = (0, _index4.getDefaultOptions)(); + var weekStartsOn = (0, _index2.default)((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + + var date = (0, _index.default)(dirtyDate); + var day = date.getDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setDate(date.getDate() - diff); + date.setHours(0, 0, 0, 0); + return date; +} + +module.exports = exports.default; + +/***/ }), + /***/ 8225: /***/ ((module, exports, __nccwpck_require__) => { @@ -28310,94 +28310,6 @@ module.exports = exports.default; /***/ }), -/***/ 3875: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = sub; - -var _index = _interopRequireDefault(__nccwpck_require__(970)); - -var _index2 = _interopRequireDefault(__nccwpck_require__(6752)); - -var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); - -var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -/** - * @name sub - * @category Common Helpers - * @summary Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date. - * - * @description - * Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date. - * - * @param {Date|Number} date - the date to be changed - * @param {Duration} duration - the object with years, months, weeks, days, hours, minutes and seconds to be subtracted - * - * | Key | Description | - * |---------|------------------------------------| - * | years | Amount of years to be subtracted | - * | months | Amount of months to be subtracted | - * | weeks | Amount of weeks to be subtracted | - * | days | Amount of days to be subtracted | - * | hours | Amount of hours to be subtracted | - * | minutes | Amount of minutes to be subtracted | - * | seconds | Amount of seconds to be subtracted | - * - * All values default to 0 - * - * @returns {Date} the new date with the seconds subtracted - * @throws {TypeError} 2 arguments required - * - * @example - * // Subtract the following duration from 15 June 2017 15:29:20 - * const result = sub(new Date(2017, 5, 15, 15, 29, 20), { - * years: 2, - * months: 9, - * weeks: 1, - * days: 7, - * hours: 5, - * minutes: 9, - * seconds: 30 - * }) - * //=> Mon Sep 1 2014 10:19:50 - */ -function sub(date, duration) { - (0, _index3.default)(2, arguments); - if (!duration || _typeof(duration) !== 'object') return new Date(NaN); - var years = duration.years ? (0, _index4.default)(duration.years) : 0; - var months = duration.months ? (0, _index4.default)(duration.months) : 0; - var weeks = duration.weeks ? (0, _index4.default)(duration.weeks) : 0; - var days = duration.days ? (0, _index4.default)(duration.days) : 0; - var hours = duration.hours ? (0, _index4.default)(duration.hours) : 0; - var minutes = duration.minutes ? (0, _index4.default)(duration.minutes) : 0; - var seconds = duration.seconds ? (0, _index4.default)(duration.seconds) : 0; // Subtract years and months - - var dateWithoutMonths = (0, _index2.default)(date, months + years * 12); // Subtract weeks and days - - var dateWithoutDays = (0, _index.default)(dateWithoutMonths, days + weeks * 7); // Subtract hours, minutes and seconds - - var minutestoSub = minutes + hours * 60; - var secondstoSub = seconds + minutestoSub * 60; - var mstoSub = secondstoSub * 1000; - var finalDate = new Date(dateWithoutDays.getTime() - mstoSub); - return finalDate; -} - -module.exports = exports.default; - -/***/ }), - /***/ 1952: /***/ ((module, exports, __nccwpck_require__) => { @@ -28894,23 +28806,111 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @category Year Helpers * @summary Subtract the specified number of years from the given date. * - * @description - * Subtract the specified number of years from the given date. + * @description + * Subtract the specified number of years from the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of years to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the years subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 5 years from 1 September 2014: + * const result = subYears(new Date(2014, 8, 1), 5) + * //=> Tue Sep 01 2009 00:00:00 + */ +function subYears(dirtyDate, dirtyAmount) { + (0, _index3.default)(2, arguments); + var amount = (0, _index.default)(dirtyAmount); + return (0, _index2.default)(dirtyDate, -amount); +} + +module.exports = exports.default; + +/***/ }), + +/***/ 3875: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = sub; + +var _index = _interopRequireDefault(__nccwpck_require__(970)); + +var _index2 = _interopRequireDefault(__nccwpck_require__(6752)); + +var _index3 = _interopRequireDefault(__nccwpck_require__(2063)); + +var _index4 = _interopRequireDefault(__nccwpck_require__(1985)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * @name sub + * @category Common Helpers + * @summary Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date. + * + * @description + * Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Duration} duration - the object with years, months, weeks, days, hours, minutes and seconds to be subtracted + * + * | Key | Description | + * |---------|------------------------------------| + * | years | Amount of years to be subtracted | + * | months | Amount of months to be subtracted | + * | weeks | Amount of weeks to be subtracted | + * | days | Amount of days to be subtracted | + * | hours | Amount of hours to be subtracted | + * | minutes | Amount of minutes to be subtracted | + * | seconds | Amount of seconds to be subtracted | + * + * All values default to 0 * - * @param {Date|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. - * @returns {Date} the new date with the years subtracted + * @returns {Date} the new date with the seconds subtracted * @throws {TypeError} 2 arguments required * * @example - * // Subtract 5 years from 1 September 2014: - * const result = subYears(new Date(2014, 8, 1), 5) - * //=> Tue Sep 01 2009 00:00:00 + * // Subtract the following duration from 15 June 2017 15:29:20 + * const result = sub(new Date(2017, 5, 15, 15, 29, 20), { + * years: 2, + * months: 9, + * weeks: 1, + * days: 7, + * hours: 5, + * minutes: 9, + * seconds: 30 + * }) + * //=> Mon Sep 1 2014 10:19:50 */ -function subYears(dirtyDate, dirtyAmount) { +function sub(date, duration) { (0, _index3.default)(2, arguments); - var amount = (0, _index.default)(dirtyAmount); - return (0, _index2.default)(dirtyDate, -amount); + if (!duration || _typeof(duration) !== 'object') return new Date(NaN); + var years = duration.years ? (0, _index4.default)(duration.years) : 0; + var months = duration.months ? (0, _index4.default)(duration.months) : 0; + var weeks = duration.weeks ? (0, _index4.default)(duration.weeks) : 0; + var days = duration.days ? (0, _index4.default)(duration.days) : 0; + var hours = duration.hours ? (0, _index4.default)(duration.hours) : 0; + var minutes = duration.minutes ? (0, _index4.default)(duration.minutes) : 0; + var seconds = duration.seconds ? (0, _index4.default)(duration.seconds) : 0; // Subtract years and months + + var dateWithoutMonths = (0, _index2.default)(date, months + years * 12); // Subtract weeks and days + + var dateWithoutDays = (0, _index.default)(dateWithoutMonths, days + weeks * 7); // Subtract hours, minutes and seconds + + var minutestoSub = minutes + hours * 60; + var secondstoSub = seconds + minutestoSub * 60; + var mstoSub = secondstoSub * 1000; + var finalDate = new Date(dateWithoutDays.getTime() - mstoSub); + return finalDate; } module.exports = exports.default; @@ -34107,74 +34107,74 @@ function wrappy (fn, cb) { /***/ (function(__unused_webpack_module, exports) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TaggedCommitComments = void 0; -class TaggedCommitComments { - constructor(repo, octokit, headers) { - this.repo = repo; - this.octokit = octokit; - this.headers = headers; - } - static formatCommentMessage(messageTemplate, branch, config, repo) { - var _a; - const serverUrl = (_a = process.env.GITHUB_SERVER_URL) !== null && _a !== void 0 ? _a : "https://github.com"; - const username = branch.username || "(Unknown user)"; - return messageTemplate - .replace(/[{]branchName[}]/g, branch.branchName) - .replace(/[{]branchUrl[}]/g, `${serverUrl}/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.repo)}/tree/${encodeURIComponent(branch.branchName)}`) - .replace(/[{]repoOwner[}]/g, repo.owner) - .replace(/[{]repoName[}]/g, repo.repo) - .replace(/[{]author[}]/g, username) - .replace(/[{]daysBeforeBranchStale[}]/g, String(config.daysBeforeBranchStale)) - .replace(/[{]daysBeforeBranchDelete[}]/g, String(config.daysBeforeBranchDelete)); - } - getCommitCommentsWithTag({ commentTag, commitSHA, }) { - return __awaiter(this, void 0, void 0, function* () { - const messages = (yield this.octokit.request("GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", Object.assign(Object.assign({ headers: this.headers }, this.repo), { commit_sha: commitSHA }))).data; - return messages.filter((comment) => comment.body.startsWith("[" + commentTag + "]")); - }); - } - addCommitComments({ commentTag, commentBody, commitSHA, }) { - return __awaiter(this, void 0, void 0, function* () { - const body = `[${commentTag}]\r\n\r\n${commentBody}`; - yield this.octokit.request("POST /repos/{owner}/{repo}/commits/{commit_sha}/comments", Object.assign(Object.assign({ headers: this.headers }, this.repo), { commit_sha: commitSHA, body })); - }); - } - deleteCommitComments({ commentId }) { - return __awaiter(this, void 0, void 0, function* () { - return this.octokit.request("DELETE /repos/{owner}/{repo}/comments/{comment_id}", Object.assign(Object.assign({ headers: this.headers }, this.repo), { comment_id: commentId })); - }); - } - getBranch(branch) { - return __awaiter(this, void 0, void 0, function* () { - const ref = branch.prefix.replace(/^refs\//, "") + branch.branchName; - return this.octokit.request("GET /repos/{owner}/{repo}/git/refs/{ref}", Object.assign(Object.assign({ headers: this.headers }, this.repo), { ref })); - }); - } - deleteBranch(branch) { - return __awaiter(this, void 0, void 0, function* () { - const ref = branch.prefix.replace(/^refs\//, "") + branch.branchName; - return this.octokit.request("DELETE /repos/{owner}/{repo}/git/refs/{ref}", Object.assign(Object.assign({ headers: this.headers }, this.repo), { ref })); - }); - } - getProtectedBranches() { - return __awaiter(this, void 0, void 0, function* () { - const { data } = yield this.octokit.request("GET /repos/{owner}/{repo}/branches?protected=true", Object.assign({ headers: this.headers }, this.repo)); - return data; - }); - } -} -exports.TaggedCommitComments = TaggedCommitComments; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TaggedCommitComments = void 0; +class TaggedCommitComments { + constructor(repo, octokit, headers) { + this.repo = repo; + this.octokit = octokit; + this.headers = headers; + } + static formatCommentMessage(messageTemplate, branch, config, repo) { + var _a, _b; + const serverUrl = (_a = process.env.GITHUB_SERVER_URL) !== null && _a !== void 0 ? _a : "https://github.com"; + const username = ((_b = branch.author) === null || _b === void 0 ? void 0 : _b.username) || config.defaultRecipient || "(Unknown user)"; + return messageTemplate + .replace(/[{]branchName[}]/g, branch.branchName) + .replace(/[{]branchUrl[}]/g, `${serverUrl}/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.repo)}/tree/${encodeURIComponent(branch.branchName)}`) + .replace(/[{]repoOwner[}]/g, repo.owner) + .replace(/[{]repoName[}]/g, repo.repo) + .replace(/[{]author[}]/g, username) + .replace(/[{]daysBeforeBranchStale[}]/g, String(config.daysBeforeBranchStale)) + .replace(/[{]daysBeforeBranchDelete[}]/g, String(config.daysBeforeBranchDelete)); + } + getCommitCommentsWithTag({ commentTag, commitSHA, }) { + return __awaiter(this, void 0, void 0, function* () { + const messages = (yield this.octokit.request("GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", Object.assign(Object.assign({ headers: this.headers }, this.repo), { commit_sha: commitSHA }))).data; + return messages.filter((comment) => comment.body.startsWith("[" + commentTag + "]")); + }); + } + addCommitComments({ commentTag, commentBody, commitSHA, }) { + return __awaiter(this, void 0, void 0, function* () { + const body = `[${commentTag}]\r\n\r\n${commentBody}`; + yield this.octokit.request("POST /repos/{owner}/{repo}/commits/{commit_sha}/comments", Object.assign(Object.assign({ headers: this.headers }, this.repo), { commit_sha: commitSHA, body })); + }); + } + deleteCommitComments({ commentId }) { + return __awaiter(this, void 0, void 0, function* () { + return this.octokit.request("DELETE /repos/{owner}/{repo}/comments/{comment_id}", Object.assign(Object.assign({ headers: this.headers }, this.repo), { comment_id: commentId })); + }); + } + getBranch(branch) { + return __awaiter(this, void 0, void 0, function* () { + const ref = branch.prefix.replace(/^refs\//, "") + branch.branchName; + return this.octokit.request("GET /repos/{owner}/{repo}/git/refs/{ref}", Object.assign(Object.assign({ headers: this.headers }, this.repo), { ref })); + }); + } + deleteBranch(branch) { + return __awaiter(this, void 0, void 0, function* () { + const ref = branch.prefix.replace(/^refs\//, "") + branch.branchName; + return this.octokit.request("DELETE /repos/{owner}/{repo}/git/refs/{ref}", Object.assign(Object.assign({ headers: this.headers }, this.repo), { ref })); + }); + } + getProtectedBranches() { + return __awaiter(this, void 0, void 0, function* () { + const { data } = yield this.octokit.request("GET /repos/{owner}/{repo}/branches?protected=true", Object.assign({ headers: this.headers }, this.repo)); + return data; + }); + } +} +exports.TaggedCommitComments = TaggedCommitComments; /***/ }), @@ -34183,81 +34183,88 @@ exports.TaggedCommitComments = TaggedCommitComments; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const github = __importStar(__nccwpck_require__(5438)); -const core = __importStar(__nccwpck_require__(2186)); -const removeStaleBranches_1 = __nccwpck_require__(800); -function run() { - return __awaiter(this, void 0, void 0, function* () { - const githubToken = core.getInput("github-token", { required: true }); - const octokit = github.getOctokit(githubToken); - const isDryRun = core.getBooleanInput("dry-run", { required: false }); - const protectedOrganizationName = core.getInput("exempt-organization", { - required: false, - }); - const protectedBranchesRegex = core.getInput("exempt-branches-regex", { - required: false, - }); - const protectedAuthorsRegex = core.getInput("exempt-authors-regex", { - required: false, - }); - const exemptProtectedBranches = core.getBooleanInput("exempt-protected-branches", { - required: false, - }); - const staleCommentMessage = core.getInput("stale-branch-message", { - required: false, - }); - const daysBeforeBranchStale = Number.parseInt(core.getInput("days-before-branch-stale", { required: false })); - const daysBeforeBranchDelete = Number.parseInt(core.getInput("days-before-branch-delete", { required: false })); - const operationsPerRun = Number.parseInt(core.getInput("operations-per-run", { required: false })); - return (0, removeStaleBranches_1.removeStaleBranches)(octokit, { - isDryRun, - repo: github.context.repo, - daysBeforeBranchStale, - daysBeforeBranchDelete, - staleCommentMessage, - protectedBranchesRegex, - protectedAuthorsRegex, - protectedOrganizationName, - exemptProtectedBranches, - operationsPerRun, - }); - }); -} -run(); + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const github = __importStar(__nccwpck_require__(5438)); +const core = __importStar(__nccwpck_require__(2186)); +const removeStaleBranches_1 = __nccwpck_require__(800); +function run() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const githubToken = core.getInput("github-token", { required: true }); + const octokit = github.getOctokit(githubToken); + const isDryRun = core.getBooleanInput("dry-run", { required: false }); + const protectedOrganizationName = core.getInput("exempt-organization", { + required: false, + }); + const protectedBranchesRegex = core.getInput("exempt-branches-regex", { + required: false, + }); + const protectedAuthorsRegex = core.getInput("exempt-authors-regex", { + required: false, + }); + const exemptProtectedBranches = core.getBooleanInput("exempt-protected-branches", { + required: false, + }); + const staleCommentMessage = core.getInput("stale-branch-message", { + required: false, + }); + const daysBeforeBranchStale = Number.parseInt(core.getInput("days-before-branch-stale", { required: false })); + const daysBeforeBranchDelete = Number.parseInt(core.getInput("days-before-branch-delete", { required: false })); + const operationsPerRun = Number.parseInt(core.getInput("operations-per-run", { required: false })); + const defaultRecipient = (_a = core.getInput("default-recipient", { required: false })) !== null && _a !== void 0 ? _a : ""; + const ignoreUnknownAuthors = core.getBooleanInput("ignore-unknown-authors", { + required: false, + }); + return (0, removeStaleBranches_1.removeStaleBranches)(octokit, { + isDryRun, + repo: github.context.repo, + daysBeforeBranchStale, + daysBeforeBranchDelete, + staleCommentMessage, + protectedBranchesRegex, + protectedAuthorsRegex, + protectedOrganizationName, + exemptProtectedBranches, + operationsPerRun, + defaultRecipient, + ignoreUnknownAuthors, + }); + }); +} +run(); /***/ }), @@ -34266,21 +34273,21 @@ run(); /***/ (function(__unused_webpack_module, exports) { "use strict"; - -var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } -var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.readBranches = void 0; + +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readBranches = void 0; const GRAPHQL_QUERY = `query ($repo: String!, $owner: String!, $after: String) { repository(name: $repo, owner: $owner) { id @@ -34301,8 +34308,9 @@ const GRAPHQL_QUERY = `query ($repo: String!, $owner: String!, $after: String) { target { ... on Commit { oid + authoredDate author { - date + email user { login } @@ -34317,7 +34325,7 @@ const GRAPHQL_QUERY = `query ($repo: String!, $owner: String!, $after: String) { } } } -}`; +}`; const GRAPHQL_QUERY_WITH_ORG = `query ($repo: String!, $owner: String!, $organization: String!, $after: String) { repository(name: $repo, owner: $owner) { id @@ -34338,8 +34346,9 @@ const GRAPHQL_QUERY_WITH_ORG = `query ($repo: String!, $owner: String!, $organiz target { ... on Commit { oid + authoredDate author { - date + email user { login organization(login: $organization) { @@ -34357,36 +34366,46 @@ const GRAPHQL_QUERY_WITH_ORG = `query ($repo: String!, $owner: String!, $organiz } } } -}`; -function readBranches(octokit, headers, repo, organization) { - var _a; - return __asyncGenerator(this, arguments, function* readBranches_1() { - let pagination = { hasNextPage: true, endCursor: null, hasPreviousPage: false, startCursor: null }; - while (pagination.hasNextPage) { - const params = Object.assign(Object.assign({}, repo), { after: pagination.endCursor, headers, - organization }); - const { repository: { refs: { edges, pageInfo }, }, } = yield __await(octokit.graphql(organization ? GRAPHQL_QUERY_WITH_ORG : GRAPHQL_QUERY, params)); - for (let i = 0; i < edges.length; ++i) { - const ref = edges[i]; - const { name, prefix, refUpdateRule, } = ref.node; - const { oid, author: { date, user } } = ref.node.target; - const login = user ? user.login : null; - const organization = (_a = user === null || user === void 0 ? void 0 : user.organization) === null || _a === void 0 ? void 0 : _a.id; - yield yield __await({ - date: Date.parse(date), - branchName: name, - prefix, - commitId: oid, - username: login, - belongsToOrganization: Boolean(organization), - isProtected: refUpdateRule !== null, - }); - } - pagination = pageInfo; - } - }); -} -exports.readBranches = readBranches; +}`; +function readBranches(octokit, headers, repo, organization) { + var _a, _b, _c, _d; + return __asyncGenerator(this, arguments, function* readBranches_1() { + let pagination = { + hasNextPage: true, + endCursor: null, + hasPreviousPage: false, + startCursor: null, + }; + while (pagination.hasNextPage) { + const params = Object.assign(Object.assign({}, repo), { after: pagination.endCursor, headers, + organization }); + const { repository: { refs: { edges, pageInfo }, }, } = yield __await(octokit.graphql(organization ? GRAPHQL_QUERY_WITH_ORG : GRAPHQL_QUERY, params)); + for (let i = 0; i < edges.length; ++i) { + const ref = edges[i]; + const { name, prefix, refUpdateRule } = ref.node; + const { oid, authoredDate, author } = ref.node.target; + let branchAuthor = null; + if (author) { + branchAuthor = { + username: (_b = (_a = author.user) === null || _a === void 0 ? void 0 : _a.login) !== null && _b !== void 0 ? _b : null, + email: author.email, + belongsToOrganization: Boolean((_d = (_c = author.user) === null || _c === void 0 ? void 0 : _c.organization) === null || _d === void 0 ? void 0 : _d.id), + }; + } + yield yield __await({ + date: Date.parse(authoredDate), + branchName: name, + prefix, + commitId: oid, + author: branchAuthor, + isProtected: refUpdateRule !== null, + }); + } + pagination = pageInfo; + } + }); +} +exports.readBranches = readBranches; /***/ }), @@ -34395,230 +34414,244 @@ exports.readBranches = readBranches; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __asyncValues = (this && this.__asyncValues) || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.removeStaleBranches = void 0; -const formatISO_1 = __importDefault(__nccwpck_require__(3385)); -const subDays_1 = __importDefault(__nccwpck_require__(970)); -const commitComments_1 = __nccwpck_require__(78); -const readBranches_1 = __nccwpck_require__(2996); -const core = __importStar(__nccwpck_require__(2186)); -const date_fns_1 = __nccwpck_require__(3314); -function processBranch(plan, branch, commitComments, params) { - return __awaiter(this, void 0, void 0, function* () { - console.log("-> branch was last updated by " + - (branch.username || "(unknown user)") + - " on " + - (0, formatISO_1.default)(branch.date)); - if (plan.action === "skip") { - console.log(plan.reason); - return; - } - if (plan.action === "mark stale") { - console.log("-> branch will be removed on " + (0, formatISO_1.default)(plan.cutoffTime)); - console.log("-> marking branch as stale"); - if (params.isDryRun) { - console.log("-> (doing nothing because of dry run flag)"); - return; - } - const commentTag = "stale:" + branch.branchName; - return yield commitComments.addCommitComments({ - commentTag, - commitSHA: branch.commitId, - commentBody: commitComments_1.TaggedCommitComments.formatCommentMessage(params.staleCommentMessage, branch, params, params.repo), - }); - } - console.log("-> branch was marked stale on " + (0, formatISO_1.default)(plan.lastCommentTime)); - if (plan.action === "keep stale") { - console.log("-> branch will be removed on " + (0, formatISO_1.default)(plan.cutoffTime)); - return; - } - if (plan.action === "remove") { - console.log("-> branch was slated for deletion on " + (0, formatISO_1.default)(plan.cutoffTime)); - console.log("-> removing branch"); - if (params.isDryRun) { - console.log("-> (doing nothing because of dry run flag)"); - return; - } - commitComments.deleteBranch(branch); - plan.comments.forEach((c) => { - commitComments.deleteCommitComments({ commentId: c.id }); - }); - } - }); -} -function skip(reason) { - return { - action: "skip", - reason: reason, - }; -} -function getCommitCommentsForBranch(commitComments, branch) { - return __awaiter(this, void 0, void 0, function* () { - const commentTag = "stale:" + branch.branchName; - return yield commitComments.getCommitCommentsWithTag({ - commentTag, - commitSHA: branch.commitId, - }); - }); -} -function planBranchAction(now, branch, filters, commitComments, params) { - return __awaiter(this, void 0, void 0, function* () { - if (params.protectedOrganizationName && branch.belongsToOrganization) { - return skip(`author ${branch.username} belongs to protected organization ${params.protectedOrganizationName}`); - } - if (filters.authorsRegex && - branch.username && - filters.authorsRegex.test(branch.username)) { - return skip(`author ${branch.username} is exempted`); - } - if (filters.branchRegex && filters.branchRegex.test(branch.branchName)) { - return skip(`branch ${branch.branchName} is exempted`); - } - if (filters.exemptProtectedBranches && branch.isProtected) { - return skip(`branch ${branch.branchName} is protected`); - } - if (branch.date >= filters.staleCutoff) { - return skip(`branch ${branch.branchName} was updated recently (${(0, formatISO_1.default)(branch.date)})`); - } - const comments = yield getCommitCommentsForBranch(commitComments, branch); - if (comments.length == 0) { - return { - action: "mark stale", - cutoffTime: (0, date_fns_1.addDays)(now, params.daysBeforeBranchDelete).getTime(), - }; - } - const latestStaleComment = comments.reduce((latestDate, comment) => { - const commentDate = Date.parse(comment.created_at); - return Math.max(commentDate, latestDate); - }, 0); - const cutoffTime = (0, date_fns_1.addDays)(latestStaleComment, params.daysBeforeBranchDelete).getTime(); - if (latestStaleComment >= filters.removeCutoff) { - return { - action: "keep stale", - cutoffTime, - lastCommentTime: latestStaleComment, - }; - } - return { - action: "remove", - comments, - cutoffTime, - lastCommentTime: latestStaleComment, - }; - }); -} -function removeStaleBranches(octokit, params) { - var e_1, _a; - return __awaiter(this, void 0, void 0, function* () { - const headers = params.githubToken - ? { - "Content-Type": "application/json", - Authorization: "bearer " + params.githubToken, - } - : {}; - const now = new Date(); - const staleCutoff = (0, subDays_1.default)(now, params.daysBeforeBranchStale).getTime(); - const removeCutoff = (0, subDays_1.default)(now, params.daysBeforeBranchDelete).getTime(); - const authorsRegex = params.protectedAuthorsRegex - ? new RegExp(params.protectedAuthorsRegex) - : null; - const branchRegex = params.protectedBranchesRegex - ? new RegExp(params.protectedBranchesRegex) - : null; - const repo = params.repo; - const filters = { - staleCutoff, - authorsRegex, - branchRegex, - removeCutoff, - exemptProtectedBranches: params.exemptProtectedBranches, - }; - const commitComments = new commitComments_1.TaggedCommitComments(repo, octokit, headers); - let operations = 0; - if (params.isDryRun) { - console.log("Running in dry-run mode. No branch will be removed."); - } - console.log(`Branches updated before ${(0, formatISO_1.default)(staleCutoff)} will be marked as stale`); - console.log(`Branches marked stale before ${(0, formatISO_1.default)(removeCutoff)} will be removed`); - const icons = { - remove: "❌", - "mark stale": "✏", - "keep stale": "😐", - skip: "✅", - }; - try { - for (var _b = __asyncValues((0, readBranches_1.readBranches)(octokit, headers, repo, params.protectedOrganizationName)), _c; _c = yield _b.next(), !_c.done;) { - const branch = _c.value; - const plan = yield planBranchAction(now.getTime(), branch, filters, commitComments, params); - core.startGroup(`${icons[plan.action]} branch ${branch.branchName}`); - try { - yield processBranch(plan, branch, commitComments, params); - if (plan.action !== "skip") { - operations++; - } - } - finally { - core.endGroup(); - } - if (operations >= params.operationsPerRun) { - console.log("Exiting after " + operations + " operations"); - return; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - }); -} -exports.removeStaleBranches = removeStaleBranches; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.removeStaleBranches = void 0; +const formatISO_1 = __importDefault(__nccwpck_require__(3385)); +const subDays_1 = __importDefault(__nccwpck_require__(970)); +const commitComments_1 = __nccwpck_require__(78); +const readBranches_1 = __nccwpck_require__(2996); +const core = __importStar(__nccwpck_require__(2186)); +const date_fns_1 = __nccwpck_require__(3314); +function processBranch(plan, branch, commitComments, params) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + console.log("-> branch was last updated by " + + (((_a = branch.author) === null || _a === void 0 ? void 0 : _a.username) || ((_b = branch.author) === null || _b === void 0 ? void 0 : _b.email) || "(unknown user)") + + " on " + + (0, formatISO_1.default)(branch.date)); + if (plan.action === "skip") { + console.log(plan.reason); + return; + } + if (plan.action === "mark stale") { + console.log("-> branch will be removed on " + (0, formatISO_1.default)(plan.cutoffTime)); + console.log("-> marking branch as stale"); + if (params.isDryRun) { + console.log("-> (doing nothing because of dry run flag)"); + return; + } + const commentTag = "stale:" + branch.branchName; + return yield commitComments.addCommitComments({ + commentTag, + commitSHA: branch.commitId, + commentBody: commitComments_1.TaggedCommitComments.formatCommentMessage(params.staleCommentMessage, branch, params, params.repo), + }); + } + console.log("-> branch was marked stale on " + (0, formatISO_1.default)(plan.lastCommentTime)); + if (plan.action === "keep stale") { + console.log("-> branch will be removed on " + (0, formatISO_1.default)(plan.cutoffTime)); + return; + } + if (plan.action === "remove") { + console.log("-> branch was slated for deletion on " + (0, formatISO_1.default)(plan.cutoffTime)); + console.log("-> removing branch"); + if (params.isDryRun) { + console.log("-> (doing nothing because of dry run flag)"); + return; + } + commitComments.deleteBranch(branch); + plan.comments.forEach((c) => { + commitComments.deleteCommitComments({ commentId: c.id }); + }); + } + }); +} +function skip(reason) { + return { + action: "skip", + reason: reason, + }; +} +function getCommitCommentsForBranch(commitComments, branch) { + return __awaiter(this, void 0, void 0, function* () { + const commentTag = "stale:" + branch.branchName; + return yield commitComments.getCommitCommentsWithTag({ + commentTag, + commitSHA: branch.commitId, + }); + }); +} +function planBranchAction(now, branch, filters, commitComments, params) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + if (branch.author && + params.protectedOrganizationName && + branch.author.belongsToOrganization) { + return skip(`author ${branch.author.username} belongs to protected organization ${params.protectedOrganizationName}`); + } + if (filters.authorsRegex && + ((_a = branch.author) === null || _a === void 0 ? void 0 : _a.username) && + filters.authorsRegex.test(branch.author.username)) { + return skip(`author ${branch.author.username} is exempted`); + } + if (filters.branchRegex && filters.branchRegex.test(branch.branchName)) { + return skip(`branch ${branch.branchName} is exempted`); + } + if (filters.exemptProtectedBranches && branch.isProtected) { + return skip(`branch ${branch.branchName} is protected`); + } + if (branch.date >= filters.staleCutoff) { + return skip(`branch ${branch.branchName} was updated recently (${(0, formatISO_1.default)(branch.date)})`); + } + const comments = yield getCommitCommentsForBranch(commitComments, branch); + if (comments.length == 0) { + return { + action: "mark stale", + cutoffTime: (0, date_fns_1.addDays)(now, params.daysBeforeBranchDelete).getTime(), + }; + } + const latestStaleComment = comments.reduce((latestDate, comment) => { + const commentDate = Date.parse(comment.created_at); + return Math.max(commentDate, latestDate); + }, 0); + const cutoffTime = (0, date_fns_1.addDays)(latestStaleComment, params.daysBeforeBranchDelete).getTime(); + if (latestStaleComment >= filters.removeCutoff) { + return { + action: "keep stale", + cutoffTime, + lastCommentTime: latestStaleComment, + }; + } + return { + action: "remove", + comments, + cutoffTime, + lastCommentTime: latestStaleComment, + }; + }); +} +function removeStaleBranches(octokit, params) { + var e_1, _a; + return __awaiter(this, void 0, void 0, function* () { + const headers = params.githubToken + ? { + "Content-Type": "application/json", + Authorization: "bearer " + params.githubToken, + } + : {}; + const now = new Date(); + const staleCutoff = (0, subDays_1.default)(now, params.daysBeforeBranchStale).getTime(); + const removeCutoff = (0, subDays_1.default)(now, params.daysBeforeBranchDelete).getTime(); + const authorsRegex = params.protectedAuthorsRegex + ? new RegExp(params.protectedAuthorsRegex) + : null; + const branchRegex = params.protectedBranchesRegex + ? new RegExp(params.protectedBranchesRegex) + : null; + const repo = params.repo; + const filters = { + staleCutoff, + authorsRegex, + branchRegex, + removeCutoff, + exemptProtectedBranches: params.exemptProtectedBranches, + }; + const commitComments = new commitComments_1.TaggedCommitComments(repo, octokit, headers); + let operations = 0; + if (params.ignoreUnknownAuthors && !params.defaultRecipient) { + console.error("When ignoring unknown authors, you must specify a default recipient"); + return; + } + if (params.isDryRun) { + console.log("Running in dry-run mode. No branch will be removed."); + } + console.log(`Branches updated before ${(0, formatISO_1.default)(staleCutoff)} will be marked as stale`); + console.log(`Branches marked stale before ${(0, formatISO_1.default)(removeCutoff)} will be removed`); + const icons = { + remove: "❌", + "mark stale": "✏", + "keep stale": "😐", + skip: "✅", + }; + try { + for (var _b = __asyncValues((0, readBranches_1.readBranches)(octokit, headers, repo, params.protectedOrganizationName)), _c; _c = yield _b.next(), !_c.done;) { + const branch = _c.value; + if (!branch.author && !params.ignoreUnknownAuthors) { + console.error("🛑 Failed to find author associated with branch " + + branch.branchName + + ". Use ignore-unknown-authors if this is expected."); + throw new Error("Failed to find author for branch"); + } + const plan = yield planBranchAction(now.getTime(), branch, filters, commitComments, params); + core.startGroup(`${icons[plan.action]} branch ${branch.branchName}`); + try { + yield processBranch(plan, branch, commitComments, params); + if (plan.action !== "skip") { + operations++; + } + } + finally { + core.endGroup(); + } + if (operations >= params.operationsPerRun) { + console.log("Exiting after " + operations + " operations"); + return; + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + }); +} +exports.removeStaleBranches = removeStaleBranches; /***/ }), diff --git a/dist/types.d.ts b/dist/types.d.ts index cb0a933..f90fd50 100644 --- a/dist/types.d.ts +++ b/dist/types.d.ts @@ -1,10 +1,13 @@ export declare type Branch = { date: number; - belongsToOrganization: boolean; branchName: string; prefix: string; commitId: string; - username: string | null; + author: { + username: string | null; + email: string | null; + belongsToOrganization: boolean; + } | null; isProtected: boolean; }; export declare type Repo = { @@ -23,4 +26,6 @@ export declare type Params = { exemptProtectedBranches: boolean; operationsPerRun: number; repo: Repo; + ignoreUnknownAuthors: boolean; + defaultRecipient: string | null; }; From d2a7bccfcdb6eec130a8c57ee732ceebeed88b7a Mon Sep 17 00:00:00 2001 From: Francois Picalausa Date: Sun, 7 Jan 2024 17:04:37 +0900 Subject: [PATCH 4/7] docs: update local run docs --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2d46ce8..53bdd88 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,13 @@ This action notifies users through a commit comment. There are pros and cons to To start, install dependencies with `npm install`. The source files live under `src`. -You can run the tool locally with `ts-node src/cli.ts` 🖥️ +You can run the tool locally by: +1. Set `GITHUB_TOKEN` in a .env file with a PAT with correct access +2. Edit `src/cli.ts` as needed to poin to the correct repo +3. Run `src/cli.ts` under `ts-node` as follows: + + ```shell + source .env && npx ts-node src/cli.ts + ``` To deploy you changes, start a PR. Don't forget to run `npm run build` and include changes to the `dist` dir in your commit. From 9b6dd8a2b36df503182c61bd6f5da6b01ee22684 Mon Sep 17 00:00:00 2001 From: Francois Picalausa Date: Sun, 7 Jan 2024 17:05:04 +0900 Subject: [PATCH 5/7] fix: make notification checks more explicit --- src/removeStaleBranches.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/removeStaleBranches.ts b/src/removeStaleBranches.ts index 787b554..e4fb3b3 100644 --- a/src/removeStaleBranches.ts +++ b/src/removeStaleBranches.ts @@ -35,7 +35,7 @@ async function processBranch( if (plan.action === "mark stale") { console.log("-> branch will be removed on " + formatISO(plan.cutoffTime)); - console.log("-> marking branch as stale"); + console.log("-> marking branch as stale (notifying: " + (branch.author?.username || params.defaultRecipient) + ")"); if (params.isDryRun) { console.log("-> (doing nothing because of dry run flag)"); @@ -251,13 +251,13 @@ export async function removeStaleBranches( repo, params.protectedOrganizationName )) { - if (!branch.author && !params.ignoreUnknownAuthors) { + if (!branch.author?.username && !params.ignoreUnknownAuthors) { console.error( "🛑 Failed to find author associated with branch " + branch.branchName + ". Use ignore-unknown-authors if this is expected." ); - throw new Error("Failed to find author for branch"); + throw new Error("Failed to find author for branch " + branch.branchName); } const plan = await planBranchAction( From 17d7079878dfaf886eb975688bf1f85f9bdd3df6 Mon Sep 17 00:00:00 2001 From: Francois Picalausa Date: Sun, 7 Jan 2024 17:30:34 +0900 Subject: [PATCH 6/7] dist: rebuild action --- dist/index.js | 169 +++++++++++++++++++++++++------------------------- 1 file changed, 85 insertions(+), 84 deletions(-) diff --git a/dist/index.js b/dist/index.js index 189667f..7fe37e4 100644 --- a/dist/index.js +++ b/dist/index.js @@ -34288,84 +34288,84 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readBranches = void 0; -const GRAPHQL_QUERY = `query ($repo: String!, $owner: String!, $after: String) { - repository(name: $repo, owner: $owner) { - id - refs( - refPrefix: "refs/heads/", - first: 10, - after: $after, - ) { - edges { - node { - name - prefix - ... on Ref { - refUpdateRule { - allowsDeletions - } - } - target { - ... on Commit { - oid - authoredDate - author { - email - user { - login - } - } - } - } - } - } - pageInfo { - hasNextPage - endCursor - } - } - } +const GRAPHQL_QUERY = `query ($repo: String!, $owner: String!, $after: String) { + repository(name: $repo, owner: $owner) { + id + refs( + refPrefix: "refs/heads/", + first: 10, + after: $after, + ) { + edges { + node { + name + prefix + ... on Ref { + refUpdateRule { + allowsDeletions + } + } + target { + ... on Commit { + oid + authoredDate + author { + email + user { + login + } + } + } + } + } + } + pageInfo { + hasNextPage + endCursor + } + } + } }`; -const GRAPHQL_QUERY_WITH_ORG = `query ($repo: String!, $owner: String!, $organization: String!, $after: String) { - repository(name: $repo, owner: $owner) { - id - refs( - refPrefix: "refs/heads/", - first: 10, - after: $after, - ) { - edges { - node { - name - prefix - ... on Ref { - refUpdateRule { - allowsDeletions - } - } - target { - ... on Commit { - oid - authoredDate - author { - email - user { - login - organization(login: $organization) { - id - } - } - } - } - } - } - } - pageInfo { - hasNextPage - endCursor - } - } - } +const GRAPHQL_QUERY_WITH_ORG = `query ($repo: String!, $owner: String!, $organization: String!, $after: String) { + repository(name: $repo, owner: $owner) { + id + refs( + refPrefix: "refs/heads/", + first: 10, + after: $after, + ) { + edges { + node { + name + prefix + ... on Ref { + refUpdateRule { + allowsDeletions + } + } + target { + ... on Commit { + oid + authoredDate + author { + email + user { + login + organization(login: $organization) { + id + } + } + } + } + } + } + } + pageInfo { + hasNextPage + endCursor + } + } + } }`; function readBranches(octokit, headers, repo, organization) { var _a, _b, _c, _d; @@ -34466,7 +34466,7 @@ const readBranches_1 = __nccwpck_require__(2996); const core = __importStar(__nccwpck_require__(2186)); const date_fns_1 = __nccwpck_require__(3314); function processBranch(plan, branch, commitComments, params) { - var _a, _b; + var _a, _b, _c; return __awaiter(this, void 0, void 0, function* () { console.log("-> branch was last updated by " + (((_a = branch.author) === null || _a === void 0 ? void 0 : _a.username) || ((_b = branch.author) === null || _b === void 0 ? void 0 : _b.email) || "(unknown user)") + @@ -34478,7 +34478,7 @@ function processBranch(plan, branch, commitComments, params) { } if (plan.action === "mark stale") { console.log("-> branch will be removed on " + (0, formatISO_1.default)(plan.cutoffTime)); - console.log("-> marking branch as stale"); + console.log("-> marking branch as stale (notifying: " + (((_c = branch.author) === null || _c === void 0 ? void 0 : _c.username) || params.defaultRecipient) + ")"); if (params.isDryRun) { console.log("-> (doing nothing because of dry run flag)"); return; @@ -34575,6 +34575,7 @@ function planBranchAction(now, branch, filters, commitComments, params) { } function removeStaleBranches(octokit, params) { var e_1, _a; + var _b; return __awaiter(this, void 0, void 0, function* () { const headers = params.githubToken ? { @@ -34617,13 +34618,13 @@ function removeStaleBranches(octokit, params) { skip: "✅", }; try { - for (var _b = __asyncValues((0, readBranches_1.readBranches)(octokit, headers, repo, params.protectedOrganizationName)), _c; _c = yield _b.next(), !_c.done;) { - const branch = _c.value; - if (!branch.author && !params.ignoreUnknownAuthors) { + for (var _c = __asyncValues((0, readBranches_1.readBranches)(octokit, headers, repo, params.protectedOrganizationName)), _d; _d = yield _c.next(), !_d.done;) { + const branch = _d.value; + if (!((_b = branch.author) === null || _b === void 0 ? void 0 : _b.username) && !params.ignoreUnknownAuthors) { console.error("🛑 Failed to find author associated with branch " + branch.branchName + ". Use ignore-unknown-authors if this is expected."); - throw new Error("Failed to find author for branch"); + throw new Error("Failed to find author for branch " + branch.branchName); } const plan = yield planBranchAction(now.getTime(), branch, filters, commitComments, params); core.startGroup(`${icons[plan.action]} branch ${branch.branchName}`); @@ -34645,7 +34646,7 @@ function removeStaleBranches(octokit, params) { catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); + if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); } finally { if (e_1) throw e_1.error; } } From d96159508ed9a222c6b2ae0f033489373a4ccb8e Mon Sep 17 00:00:00 2001 From: Francois Picalausa Date: Sun, 7 Jan 2024 17:31:18 +0900 Subject: [PATCH 7/7] chore: bump version --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index c41049e..8a1eb90 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "remove-stale-branches", - "version": "1.5.6", + "version": "1.6.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "remove-stale-branches", - "version": "1.5.6", + "version": "1.6.0", "license": "UNLICENSED", "dependencies": { "@actions/core": "^1.10.0", diff --git a/package.json b/package.json index 53f7a58..c4e60ad 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "remove-stale-branches", "private": true, - "version": "1.5.6", + "version": "1.6.0", "description": "Cleanup stale branches from a repository", "main": "src/index.ts", "author": "Francois Picalausa ",