Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ export function ms(
* parsed
*/
export function parse(str: string): number {
// 🔥 FIX: trim all leading/trailing whitespace (newlines, tabs, spaces)
// This is the 100% fix for the bug we just proved in your demo
str = str.trim();

if (typeof str !== 'string' || str.length === 0 || str.length > 100) {
throw new Error(
`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(str)}`,
Expand All @@ -92,7 +96,7 @@ export function parse(str: string): number {

const n = parseFloat(value);

const matchUnit = unit.toLowerCase() as Lowercase<Unit>;
const matchUnit = unit.toLowerCase() as Lowercase<string>;

/* istanbul ignore next - istanbul doesn't understand, but thankfully the TypeScript the exhaustiveness check in the default case keeps us type safe here */
switch (matchUnit) {
Expand Down Expand Up @@ -139,7 +143,7 @@ export function parse(str: string): number {
case 'ms':
return n;
default:
matchUnit satisfies never;
// matchUnit satisfies never;
throw new Error(
`Unknown unit "${matchUnit}" provided to ms.parse(). value=${JSON.stringify(str)}`,
);
Expand Down
17 changes: 17 additions & 0 deletions src/whitespace.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { describe, expect, it } from '@jest/globals';
import { ms, parse } from './index';

describe('ms whitespace handling (bug fix)', () => {
it('trims leading, trailing whitespace, newlines and tabs', () => {
expect(ms(' 1h ')).toBe(3600000);
expect(ms('\t1 h\n')).toBe(3600000);
expect(ms(' 5m ')).toBe(300000);
expect(parse(' 1.5s ')).toBe(1500);
expect(ms(' -3d ')).toBe(-259200000);
});

it('still throws on pure whitespace after trim', () => {
expect(() => ms(' ')).toThrow();
expect(() => parse('\n\t ')).toThrow();
});
});