@murky-web/typebuddy 2.1.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +184 -72
  2. package/dist/collections.js +1 -2
  3. package/dist/empty.js +34 -13
  4. package/dist/guards.js +33 -9
  5. package/dist/ids.js +6 -6
  6. package/dist/oxlint.js +7 -7
  7. package/dist/parse.js +39 -15
  8. package/dist/result.js +6 -6
  9. package/dist/rules/async_rule.js +39 -25
  10. package/dist/rules/deliberate_throw.js +5 -6
  11. package/dist/rules/maybe_promise_rule.js +99 -40
  12. package/dist/rules/maybe_rule.js +7 -5
  13. package/dist/rules/nullable_rule.js +7 -5
  14. package/dist/rules/optional_rule.js +8 -4
  15. package/dist/rules/own_subtree.js +1 -2
  16. package/dist/rules/test_file.js +63 -0
  17. package/dist/rules/typebuddy_import.js +242 -35
  18. package/dist/rules/use_server.js +1 -2
  19. package/globals.d.ts +49 -44
  20. package/jsr.json +24 -23
  21. package/oxlint/index.ts +9 -7
  22. package/package.json +92 -91
  23. package/rules/async_rule.ts +91 -75
  24. package/rules/deliberate_throw.ts +11 -11
  25. package/rules/maybe_promise_rule.ts +238 -111
  26. package/rules/maybe_rule.ts +76 -49
  27. package/rules/nullable_rule.ts +77 -52
  28. package/rules/optional_rule.ts +79 -53
  29. package/rules/own_subtree.ts +33 -33
  30. package/rules/test_file.ts +114 -0
  31. package/rules/typebuddy_import.ts +479 -87
  32. package/rules/use_server.ts +5 -4
  33. package/src/collections.ts +1 -1
  34. package/src/empty.ts +58 -20
  35. package/src/guards.ts +100 -34
  36. package/src/ids.ts +10 -4
  37. package/src/index.ts +1 -18
  38. package/src/parse.ts +108 -29
  39. package/src/public_api.ts +22 -0
  40. package/src/result.ts +8 -7
  41. package/src/types/globals.ts +11 -11
  42. package/src/types/index.ts +21 -21
  43. package/src/types/json.ts +48 -11
  44. package/src/types/maybe_promise.ts +17 -12
  45. package/src/types/nullable.ts +2 -2
  46. package/src/types/optional.ts +6 -6
package/src/empty.ts CHANGED
@@ -12,40 +12,78 @@ import {
12
12
  isNull,
13
13
  isObject,
14
14
  isString,
15
- isUndefined,
15
+ isUndefined
16
16
  } from "./guards.js";
17
17
 
18
+ type Container = {
19
+ readonly node: object;
20
+ readonly entries: readonly unknown[];
21
+ };
22
+
23
+ // The arrays and plain objects `isEmptyLike` looks into, with what to look at.
24
+ // Class instances, dates, maps and the like are not containers: they are
25
+ // content.
26
+ function toContainer(value: unknown): Container | undefined {
27
+ if (isArray(value)) {
28
+ return { entries: value, node: value };
29
+ }
30
+ if (isObject(value) && Object.getPrototypeOf(value) === Object.prototype) {
31
+ return { entries: Object.values(value), node: value };
32
+ }
33
+
34
+ return undefined;
35
+ }
36
+
18
37
  /**
19
38
  * Returns true for values that behave like "empty" application input.
20
39
  *
40
+ * A reference back to an array or object that is still being walked adds no
41
+ * content of its own, so it counts as empty and the walk ends there: a cyclic
42
+ * structure is empty-like when everything else in it is. A value that merely
43
+ * appears twice is not a cycle and is walked both times.
44
+ *
21
45
  * @param {unknown} value - The value to check.
22
46
  * @returns {boolean} True if the value is nullish, empty string, empty array,
23
47
  * false, or a plain object whose values are all empty-like.
24
48
  */
25
49
  function isEmptyLike(value: unknown): boolean {
26
- if (isNull(value) || isUndefined(value)) {
27
- return true;
28
- }
29
- if (isString(value)) {
30
- return isEmptyString(value);
31
- }
32
- if (isArray(value)) {
33
- return value.every((entry) => {
34
- return isEmptyLike(entry);
35
- });
36
- }
37
- if (isBoolean(value)) {
38
- return !value;
39
- }
40
- if (isObject(value)) {
41
- if (Object.getPrototypeOf(value) !== Object.prototype) {
50
+ // The arrays and objects on the path from the root to the value being
51
+ // looked at. An entry is removed again when its walk is done, so a value
52
+ // that appears twice side by side is not taken for a cycle.
53
+ const walking = new WeakSet<object>();
54
+
55
+ /**
56
+ * @param {unknown} candidate - The value being looked at.
57
+ * @returns {boolean} True if the candidate is empty-like.
58
+ */
59
+ function walk(candidate: unknown): boolean {
60
+ if (isNull(candidate) || isUndefined(candidate)) {
61
+ return true;
62
+ }
63
+ if (isString(candidate)) {
64
+ return isEmptyString(candidate);
65
+ }
66
+ if (isBoolean(candidate)) {
67
+ return !candidate;
68
+ }
69
+
70
+ const container = toContainer(candidate);
71
+ if (container === undefined) {
42
72
  return false;
43
73
  }
44
- return Object.values(value).every((entry) => {
45
- return isEmptyLike(entry);
74
+ if (walking.has(container.node)) {
75
+ return true;
76
+ }
77
+
78
+ walking.add(container.node);
79
+ const result = container.entries.every((entry) => {
80
+ return walk(entry);
46
81
  });
82
+ walking.delete(container.node);
83
+ return result;
47
84
  }
48
- return false;
85
+
86
+ return walk(value);
49
87
  }
50
88
 
51
89
  /**
package/src/guards.ts CHANGED
@@ -9,6 +9,40 @@ import type { Optional } from "./types/optional.js";
9
9
 
10
10
  type UnknownFunction = (...args: readonly never[]) => unknown;
11
11
 
12
+ declare const finiteNumberBrand: unique symbol;
13
+
14
+ /**
15
+ * A `number` that `isNumber` accepted: neither `NaN` nor `±Infinity`.
16
+ *
17
+ * It is a brand rather than plain `number` on purpose. A guard typed `value is
18
+ * number` also narrows the false branch, so `number | null` would become `null`
19
+ * after `if (!isNumber(value))`, although `NaN` and `Infinity` are `number`s
20
+ * that land there too. A branded type is not what a bare `number` is assignable
21
+ * to, so the false branch keeps them.
22
+ */
23
+ type FiniteNumber<T extends number = number> = T & {
24
+ readonly [finiteNumberBrand]: true;
25
+ };
26
+
27
+ declare const integerBrand: unique symbol;
28
+ declare const floatBrand: unique symbol;
29
+
30
+ /**
31
+ * A `number` that `isInteger` accepted. A brand for the same reason as
32
+ * `FiniteNumber`: a plain `value is number` would leave `null` alone in the
33
+ * false branch of a `number | null`, although `1.5` and `NaN` land there too.
34
+ */
35
+ type IntegerNumber = FiniteNumber & { readonly [integerBrand]: true };
36
+
37
+ /** A `number` that `isFloat` accepted. See `IntegerNumber` for the brand. */
38
+ type FloatNumber = FiniteNumber & { readonly [floatBrand]: true };
39
+
40
+ /**
41
+ * What `isEmptyObject` narrows to: an object with no own keys at all. The index
42
+ * signature of `never` is the type of "nothing can be read from it".
43
+ */
44
+ type EmptyObject = Record<string, never>;
45
+
12
46
  const EMPTY_LENGTH = 0;
13
47
 
14
48
  /**
@@ -111,7 +145,10 @@ function isEmptyArray(value: unknown): value is readonly unknown[] {
111
145
  }
112
146
 
113
147
  /**
114
- * More performant implementation of isArray for large arrays
148
+ * Kept for compatibility: the same check as `isArray`. It used to compare
149
+ * `Object.prototype.toString` with `"[object Array]"`, which any object can
150
+ * fake through `Symbol.toStringTag`; `Array.isArray` cannot be faked and is the
151
+ * fast path engines optimise anyway.
115
152
  *
116
153
  * @param {unknown} value - The value to check.
117
154
  * @returns {boolean} True if the value is an array.
@@ -119,18 +156,23 @@ function isEmptyArray(value: unknown): value is readonly unknown[] {
119
156
  function fastIsArray<T>(value: Nullable<readonly T[]>): value is readonly T[];
120
157
  function fastIsArray(value: unknown): value is readonly unknown[];
121
158
  function fastIsArray(value: unknown): value is readonly unknown[] {
122
- return Object.prototype.toString.call(value) === "[object Array]";
159
+ return Array.isArray(value);
123
160
  }
124
161
 
125
162
  /**
126
- * Check if a value is a number.
163
+ * Check if a value is a finite number: not `NaN`, not `±Infinity`.
164
+ *
165
+ * The narrowed type is `FiniteNumber`, a brand over `number`, so the false
166
+ * branch still contains the `number`s this guard rejects.
127
167
  *
128
168
  * @param {unknown} value - The value to check.
129
- * @returns {boolean} True if the value is a number.
169
+ * @returns {boolean} True if the value is a finite number.
130
170
  */
131
- function isNumber<T extends number>(value: Nullable<T>): value is T;
132
- function isNumber(value: unknown): value is number;
133
- function isNumber(value: unknown): value is number {
171
+ function isNumber<T extends number>(
172
+ value: Nullable<T>
173
+ ): value is FiniteNumber<T>;
174
+ function isNumber(value: unknown): value is FiniteNumber;
175
+ function isNumber(value: unknown): value is FiniteNumber {
134
176
  if (typeof value === "string" && value.trim() === "") {
135
177
  return false;
136
178
  }
@@ -148,7 +190,7 @@ function isNumber(value: unknown): value is number {
148
190
  * @returns {boolean} True if the value is an object.
149
191
  */
150
192
  function isObject<T extends Record<string, unknown>>(
151
- value: Nullable<T>,
193
+ value: Nullable<T>
152
194
  ): value is T;
153
195
  function isObject(value: unknown): value is Record<string, unknown>;
154
196
  function isObject(value: unknown): value is Record<string, unknown> {
@@ -190,21 +232,32 @@ function isFunction(value: unknown): value is UnknownFunction {
190
232
  }
191
233
 
192
234
  /**
193
- * Returns true if the value is a promise.
235
+ * Returns true if the value is a promise, or any other thenable: an object or a
236
+ * function with a callable `then`.
237
+ *
238
+ * A `then` getter that throws, or a revoked Proxy, means the value cannot be
239
+ * awaited safely; that is a `false`, not an exception from the guard.
194
240
  *
195
241
  * @param {unknown} value - The value to check.
196
242
  * @returns {boolean} True if the value is a promise.
197
243
  */
198
244
  function isPromise<T>(
199
- value: Nullable<Readonly<PromiseLike<T>>>,
245
+ value: Nullable<Readonly<PromiseLike<T>>>
200
246
  ): value is PromiseLike<T>;
201
247
  function isPromise(value: unknown): value is PromiseLike<unknown>;
202
248
  function isPromise(value: unknown): value is PromiseLike<unknown> {
203
- if (typeof value !== "object" || value === null) {
249
+ if (
250
+ (typeof value !== "object" && typeof value !== "function") ||
251
+ value === null
252
+ ) {
204
253
  return false;
205
254
  }
206
255
 
207
- return typeof Reflect.get(value, "then") === "function";
256
+ try {
257
+ return typeof Reflect.get(value, "then") === "function";
258
+ } catch {
259
+ return false;
260
+ }
208
261
  }
209
262
 
210
263
  /**
@@ -256,24 +309,31 @@ function isSymbol(value: unknown): value is symbol {
256
309
  }
257
310
 
258
311
  /**
259
- * Check if a value is a plain object.
312
+ * Check if a value is an empty plain object: its prototype is
313
+ * `Object.prototype` and it has no own keys at all. A symbol key or a
314
+ * non-enumerable key counts as a key, so `{ [Symbol()]: 1 }` is not empty.
315
+ *
316
+ * The guard narrows to `EmptyObject`, never to the caller's own object type: an
317
+ * object type with required keys can not be empty, and narrowing to it would
318
+ * hide the very values the guard rejects from the false branch.
260
319
  *
261
320
  * @param {unknown} value - The value to check.
262
- * @returns {boolean} True if the value is a plain object.
321
+ * @returns {boolean} True if the value is an empty plain object.
263
322
  */
264
- function isEmptyObject<T extends Record<string, unknown>>(
265
- value: Nullable<T>,
266
- ): value is T;
267
- function isEmptyObject(value: unknown): value is Record<string, unknown>;
268
- function isEmptyObject(value: unknown): value is Record<string, unknown> {
269
- return (
270
- typeof value === "object" &&
271
- !isNull(value) &&
272
- !isUndefined(value) &&
273
- !isEmptyArray(value) &&
274
- Object.getPrototypeOf(value) === Object.prototype &&
275
- Object.keys(value).length === EMPTY_LENGTH
276
- );
323
+ function isEmptyObject(value: unknown): value is EmptyObject {
324
+ if (typeof value !== "object" || value === null) {
325
+ return false;
326
+ }
327
+
328
+ // A revoked Proxy is an `object` whose every trap throws.
329
+ try {
330
+ return (
331
+ Object.getPrototypeOf(value) === Object.prototype &&
332
+ Reflect.ownKeys(value).length === EMPTY_LENGTH
333
+ );
334
+ } catch {
335
+ return false;
336
+ }
277
337
  }
278
338
 
279
339
  /**
@@ -285,35 +345,41 @@ function isEmptyObject(value: unknown): value is Record<string, unknown> {
285
345
  */
286
346
  function isInstanceOf<T>(
287
347
  value: unknown,
288
- constructor: new (...args: unknown[]) => T,
348
+ constructor: new (...args: unknown[]) => T
289
349
  ): value is T {
290
350
  return value instanceof constructor;
291
351
  }
292
352
 
293
353
  /**
294
- * Check if a value is an integer.
354
+ * Check if a value is an integer. The narrowed type is `IntegerNumber`, a brand
355
+ * over `number`, so the false branch still contains the `number`s this guard
356
+ * rejects.
295
357
  *
296
358
  * @param {unknown} value - The value to check.
297
359
  * @returns {boolean} True if the value is an integer.
298
360
  */
299
- function isInteger(value: unknown): value is number {
361
+ function isInteger(value: unknown): value is IntegerNumber {
300
362
  return typeof value === "number" && Number.isInteger(value);
301
363
  }
302
364
 
303
365
  /**
304
- * Check if a value is a float.
366
+ * Check if a value is a float: a finite number with a fractional part. `NaN`
367
+ * and `±Infinity` are not floats, consistent with `isNumber`. The narrowed type
368
+ * is `FloatNumber`, a brand over `number`, like `isInteger`'s.
305
369
  *
306
370
  * @param {unknown} value - The value to check.
307
371
  * @returns {boolean} True if the value is a float.
308
372
  */
309
- function isFloat(value: unknown): value is number {
373
+ function isFloat(value: unknown): value is FloatNumber {
310
374
  return (
311
375
  typeof value === "number" &&
312
- !Number.isNaN(value) &&
376
+ Number.isFinite(value) &&
313
377
  !Number.isInteger(value)
314
378
  );
315
379
  }
316
380
 
381
+ export type { EmptyObject, FiniteNumber, FloatNumber, IntegerNumber };
382
+
317
383
  export {
318
384
  fastIsArray,
319
385
  isArray,
@@ -337,5 +403,5 @@ export {
337
403
  isRegExp,
338
404
  isString,
339
405
  isSymbol,
340
- isUndefined,
406
+ isUndefined
341
407
  };
package/src/ids.ts CHANGED
@@ -6,13 +6,19 @@
6
6
 
7
7
  import { isString } from "./guards.js";
8
8
 
9
+ // RFC 9562: versions 1 to 8 with the `10xx` variant, plus the two special
10
+ // values, nil (all zero) and max (all one). Case-insensitive.
9
11
  const uuidRegex =
10
- /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;
12
+ /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|0{8}-0{4}-0{4}-0{4}-0{12}|f{8}-f{4}-f{4}-f{4}-f{12})$/i;
11
13
 
12
- const ulidRegex = /^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$/;
14
+ // Crockford base32 (no I, L, O, U), case-insensitive. The first character
15
+ // carries the top 3 bits of the 48-bit timestamp, so it stops at `7`: anything
16
+ // above overflows 128 bits and is not a ULID.
17
+ const ulidRegex = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i;
13
18
 
14
19
  /**
15
- * Returns true if the input is a UUID string.
20
+ * Returns true if the input is a UUID string: versions 1 to 8, or the nil or
21
+ * max UUID, in either case.
16
22
  *
17
23
  * @param {string} input - The input to check.
18
24
  * @returns {boolean} True if the input is a UUID string.
@@ -22,7 +28,7 @@ function isUuidString(input: unknown): input is string {
22
28
  }
23
29
 
24
30
  /**
25
- * Returns true if the input is a ULID string.
31
+ * Returns true if the input is a ULID string, in either case.
26
32
  *
27
33
  * @param {string} input - The input to check.
28
34
  * @returns {boolean} True if the input is a ULID string.
package/src/index.ts CHANGED
@@ -7,21 +7,4 @@
7
7
  // oxlint-disable-next-line no-empty-named-blocks, no-relative-parent-imports, require-module-specifiers
8
8
  import type {} from "../globals.js";
9
9
 
10
- export * from "./type_helper.js";
11
-
12
- export type {
13
- AsyncResult,
14
- Failed,
15
- JsonifiedObject,
16
- JsonifiedValue,
17
- Maybe,
18
- MaybePromise,
19
- Nullable,
20
- Optional,
21
- ResolveMaybe,
22
- ResolveNullable,
23
- ResolveOptional,
24
- Result,
25
- Stringified,
26
- Success,
27
- } from "./types/index.js";
10
+ export * from "./public_api.js";
package/src/parse.ts CHANGED
@@ -6,18 +6,54 @@
6
6
 
7
7
  import {
8
8
  isArray,
9
- isEmptyObject,
10
9
  isNull,
11
10
  isNumber,
11
+ isObject,
12
12
  isString,
13
- isUndefined,
13
+ isUndefined
14
14
  } from "./guards.js";
15
15
  import type { Optional } from "./types/optional.js";
16
16
 
17
17
  const EMPTY_LENGTH = 0;
18
+ const ZERO = 0;
19
+
20
+ // Whole-string shapes. Anchored on both ends: a string is a number or it is
21
+ // not, never "a number followed by something".
22
+ const INTEGER_TEXT = /^[+-]?\d+(?:\.0+)?$/;
23
+ const DECIMAL_TEXT = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
24
+ // A comma that is the only separator: `1,5`, `0,25`, `,5`.
25
+ const COMMA_DECIMAL_TEXT = /^[+-]?\d*,\d+$/;
26
+ // `1,000`, `12,345`: exactly three digits after the comma behind a short
27
+ // integer part read as a thousands group in English and as a decimal in German.
28
+ // Guessing wrong silently is worse than refusing, so these are refused. An
29
+ // integer part of a lone `0` is no thousands group (nobody writes `0,500` for
30
+ // five hundred), so `0,500` and `0,125` stay decimals.
31
+ const GROUPED_TEXT = /^[+-]?[1-9]\d{0,2},\d{3}$/;
32
+
33
+ // Turns a trimmed string into dot-decimal notation, or `undefined` when the
34
+ // comma in it cannot be told from a thousands separator.
35
+ function toDotDecimal(text: string): string | undefined {
36
+ if (!COMMA_DECIMAL_TEXT.test(text)) {
37
+ return text;
38
+ }
39
+ if (GROUPED_TEXT.test(text)) {
40
+ return undefined;
41
+ }
42
+
43
+ return text.replace(",", ".");
44
+ }
45
+
46
+ // `-0` is the integer zero; callers comparing with `Object.is` never see it.
47
+ function withoutNegativeZero(value: number): number {
48
+ if (value === ZERO) {
49
+ return ZERO;
50
+ }
51
+
52
+ return value;
53
+ }
18
54
 
19
55
  function cloneDefaultArray(
20
- defaultValue?: readonly unknown[],
56
+ defaultValue?: readonly unknown[]
21
57
  ): unknown[] | undefined {
22
58
  if (!defaultValue) {
23
59
  return defaultValue;
@@ -27,8 +63,13 @@ function cloneDefaultArray(
27
63
  }
28
64
 
29
65
  /**
30
- * Parses the input value as an integer. Returns NaN if the value cannot be
31
- * parsed.
66
+ * Parses the input value as an integer. A number is truncated toward zero
67
+ * (`-1.5` is `-1`). A string has to be an integer written out in full: digits
68
+ * with an optional sign, surrounding whitespace and a zero-only fraction
69
+ * (`"42.0"`). Empty or blank strings, `"12abc"`, `"0x10"`, `"1e3"`, `"1,000"`
70
+ * and digits beyond the safe integer range (`"9007199254740993"`, also as a
71
+ * number: `1e21`) are not integers. Returns the default (or `undefined`) when
72
+ * the value cannot be parsed.
32
73
  *
33
74
  * @param {unknown} value - The value to check.
34
75
  * @param {Optional<number>} defaultValue - Value gets returned if integer could
@@ -39,20 +80,38 @@ function parseInteger(value: unknown): Optional<number>;
39
80
  function parseInteger(value: unknown, defaultValue: number): number;
40
81
  function parseInteger(value: unknown, defaultValue?: number): Optional<number> {
41
82
  if (isNumber(value)) {
42
- return Math.floor(value);
83
+ // The same limit as for strings: past 2^53 a double stands for a range
84
+ // of integers, not for one, so there is no integer to answer with.
85
+ const truncated = Math.trunc(value);
86
+ if (Number.isSafeInteger(truncated)) {
87
+ return withoutNegativeZero(truncated);
88
+ }
89
+ return defaultValue;
43
90
  }
44
91
 
45
92
  if (isString(value)) {
46
- const parsed = Number(value.trim());
47
- if (Number.isInteger(parsed)) {
48
- return parsed;
93
+ const trimmed = value.trim();
94
+ if (INTEGER_TEXT.test(trimmed)) {
95
+ const parsed = Number(trimmed);
96
+ // Past 2^53 the digits no longer fit a double: `"9007199254740993"`
97
+ // would come back as `...992`, a different number than the one
98
+ // written. Refusing it is better than answering with that.
99
+ if (Number.isSafeInteger(parsed)) {
100
+ return withoutNegativeZero(parsed);
101
+ }
49
102
  }
50
103
  }
51
104
  return defaultValue;
52
105
  }
53
106
 
54
107
  /**
55
- * Parses the input value as a float. Returns NaN if the value cannot be parsed.
108
+ * Parses the input value as a float. A string has to be a decimal number in
109
+ * full: `"1.5"`, `".5"`, `"-2"`, `"1.5e2"`. A comma is accepted as the one and
110
+ * only decimal separator (`"1,5"`); mixed forms (`"1,234.56"`, `"1.234,56"`),
111
+ * several commas and grouped forms (`"1,000"`) are refused, because the comma
112
+ * could be a thousands separator. Empty or blank strings, `"12abc"`, `"0x10"`
113
+ * and `"Infinity"` are refused too. Returns the default (or `undefined`) when
114
+ * the value cannot be parsed.
56
115
  *
57
116
  * @param {unknown} value - The value to check.
58
117
  * @param {Optional<number>} defaultValue - Value gets returned if float could
@@ -63,21 +122,27 @@ function parseFloat(value: unknown): Optional<number>;
63
122
  function parseFloat(value: unknown, defaultValue: number): number;
64
123
  function parseFloat(value: unknown, defaultValue?: number): Optional<number> {
65
124
  if (isNumber(value)) {
66
- return value;
125
+ return withoutNegativeZero(value);
67
126
  }
68
127
  if (isString(value)) {
69
- const normalizedValue = value.trim().replace(",", ".");
70
- const parsed = Number.parseFloat(normalizedValue);
71
- if (!Number.isNaN(parsed)) {
72
- return parsed;
128
+ const dotted = toDotDecimal(value.trim());
129
+ if (dotted !== undefined && DECIMAL_TEXT.test(dotted)) {
130
+ const parsed = Number(dotted);
131
+ if (Number.isFinite(parsed)) {
132
+ return withoutNegativeZero(parsed);
133
+ }
73
134
  }
74
135
  }
75
136
  return defaultValue;
76
137
  }
77
138
 
78
139
  /**
79
- * Parses the input value as a number. Returns NaN if the value cannot be
80
- * parsed.
140
+ * Parses the input value as a number. The most permissive of the three: a
141
+ * string may be anything `Number()` accepts for the whole string, so also
142
+ * `"1e3"`, `"0xff"` and `"0b10"`. The comma rule is the one of `parseFloat`
143
+ * (`"1,5"` is `1.5`, `"1,000"` and `"1,234.56"` are refused). Empty or blank
144
+ * strings, `"12abc"` and `"Infinity"` are refused. Returns the default (or
145
+ * `undefined`) when the value cannot be parsed.
81
146
  *
82
147
  * @param {unknown} value - The value to check.
83
148
  * @param {Optional<number>} defaultValue - Value gets returned if number could
@@ -88,13 +153,15 @@ function parseNumber(value: unknown): Optional<number>;
88
153
  function parseNumber(value: unknown, defaultValue: number): number;
89
154
  function parseNumber(value: unknown, defaultValue?: number): Optional<number> {
90
155
  if (isNumber(value)) {
91
- return value;
156
+ return withoutNegativeZero(value);
92
157
  }
93
158
  if (isString(value)) {
94
- const normalizedValue = value.trim().replace(",", ".");
95
- const parsed = Number(normalizedValue);
96
- if (Number.isFinite(parsed)) {
97
- return parsed;
159
+ const dotted = toDotDecimal(value.trim());
160
+ if (dotted !== undefined && dotted !== "") {
161
+ const parsed = Number(dotted);
162
+ if (Number.isFinite(parsed)) {
163
+ return withoutNegativeZero(parsed);
164
+ }
98
165
  }
99
166
  }
100
167
  return defaultValue;
@@ -123,8 +190,12 @@ function parseString(value: unknown, defaultValue = ""): string {
123
190
  }
124
191
 
125
192
  /**
126
- * Parses the input value as an array. Returns an empty array if the value
127
- * cannot be parsed as an array.
193
+ * Parses the input value as an array. An array is copied, a string is split on
194
+ * commas, pipes, semicolons and whitespace, a finite number or a plain object
195
+ * becomes a one-element array. Anything else (`null`, `NaN`, `Infinity`, a
196
+ * class instance, a symbol) gives the default, or `undefined` without one: a
197
+ * single-argument call with a number is therefore typed `number[] | undefined`,
198
+ * since `NaN` has no array.
128
199
  *
129
200
  * @param {unknown} value - The value to check.
130
201
  * @param {Optional<T[]>} defaultValue - Value gets returned if array could not
@@ -134,13 +205,13 @@ function parseString(value: unknown, defaultValue = ""): string {
134
205
 
135
206
  function parseArray<T>(value: readonly T[]): T[];
136
207
  function parseArray(value: string): string[];
137
- function parseArray(value: number): number[];
208
+ function parseArray(value: number): number[] | undefined;
138
209
  function parseArray<T extends Record<string, unknown>>(value: T): T[];
139
210
  function parseArray<T>(value: unknown, defaultValue: readonly T[]): T[];
140
211
  function parseArray(value: unknown): unknown[] | undefined;
141
212
  function parseArray(
142
213
  value: unknown,
143
- defaultValue?: readonly unknown[],
214
+ defaultValue?: readonly unknown[]
144
215
  ): unknown[] | undefined {
145
216
  if (isArray(value)) {
146
217
  return [...value];
@@ -159,7 +230,7 @@ function parseArray(
159
230
  if (isNumber(value)) {
160
231
  return [value];
161
232
  }
162
- if (isEmptyObject(value)) {
233
+ if (isObject(value)) {
163
234
  return [value];
164
235
  }
165
236
 
@@ -170,7 +241,15 @@ function parseArray(
170
241
  }
171
242
 
172
243
  /**
173
- * Parses the domain name from a URL.
244
+ * Parses the first label of the hostname of a URL, without a leading `www.` or
245
+ * `www2.`: `"https://www.example.com/x"` gives `"example"`.
246
+ *
247
+ * This is a display helper, not a registrable-domain check. It returns the
248
+ * LEFTMOST label, so `"example.attacker.net"` gives `"example"` as well, and
249
+ * `"subdomain.example.dev"` gives `"subdomain"`. It knows nothing about the
250
+ * public-suffix list. Never use it to decide whether a host belongs to a site,
251
+ * for an allowlist, a redirect check or a CORS origin: compare the whole
252
+ * hostname (`new URL(url).hostname`) against the exact hosts you trust.
174
253
  *
175
254
  * @param {string} url - The URL to parse.
176
255
  * @param {Optional<T>} defaultValue - The fallback when parsing fails.
@@ -211,5 +290,5 @@ export {
211
290
  parseFloat,
212
291
  parseInteger,
213
292
  parseNumber,
214
- parseString,
293
+ parseString
215
294
  };
@@ -0,0 +1,22 @@
1
+ // Everything the root entry exports, without the global type augmentation.
2
+ // `index.ts` adds the augmentation on top of this file for npm; JSR publishes
3
+ // this file as its root export, because JSR rejects `declare global`.
4
+
5
+ export * from "./type_helper.js";
6
+
7
+ export type {
8
+ AsyncResult,
9
+ Failed,
10
+ JsonifiedObject,
11
+ JsonifiedValue,
12
+ Maybe,
13
+ MaybePromise,
14
+ Nullable,
15
+ Optional,
16
+ ResolveMaybe,
17
+ ResolveNullable,
18
+ ResolveOptional,
19
+ Result,
20
+ Stringified,
21
+ Success
22
+ } from "./types/index.js";