@murky-web/typebuddy 2.0.0 → 3.0.0

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 (45) 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 +9 -8
  9. package/dist/rules/async_rule.js +45 -28
  10. package/dist/rules/deliberate_throw.js +5 -6
  11. package/dist/rules/maybe_promise_rule.js +109 -47
  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 +63 -0
  19. package/globals.d.ts +49 -44
  20. package/jsr.json +3 -2
  21. package/oxlint/index.ts +7 -5
  22. package/package.json +92 -91
  23. package/rules/async_rule.ts +87 -67
  24. package/rules/deliberate_throw.ts +11 -11
  25. package/rules/maybe_promise_rule.ts +229 -98
  26. package/rules/maybe_rule.ts +74 -47
  27. package/rules/nullable_rule.ts +78 -50
  28. package/rules/optional_rule.ts +80 -51
  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 +117 -0
  33. package/src/empty.ts +57 -19
  34. package/src/guards.ts +96 -30
  35. package/src/ids.ts +10 -4
  36. package/src/index.ts +1 -18
  37. package/src/parse.ts +104 -25
  38. package/src/public_api.ts +22 -0
  39. package/src/result.ts +11 -9
  40. package/src/types/globals.ts +11 -11
  41. package/src/types/index.ts +21 -21
  42. package/src/types/json.ts +48 -11
  43. package/src/types/maybe_promise.ts +17 -12
  44. package/src/types/nullable.ts +2 -2
  45. package/src/types/optional.ts +6 -6
@@ -0,0 +1,117 @@
1
+ type UseServerNode = {
2
+ type: string;
3
+ parent?: unknown;
4
+ body?: unknown;
5
+ };
6
+
7
+ const USE_SERVER = "use server";
8
+
9
+ const FUNCTION_TYPES = new Set([
10
+ "ArrowFunctionExpression",
11
+ "FunctionDeclaration",
12
+ "FunctionExpression",
13
+ ]);
14
+
15
+ function isUseServerNode(value: unknown): value is UseServerNode {
16
+ return (
17
+ typeof value === "object" &&
18
+ value !== null &&
19
+ "type" in value &&
20
+ typeof value.type === "string"
21
+ );
22
+ }
23
+
24
+ /**
25
+ * Whether a statement is the `"use server"` directive.
26
+ *
27
+ * Parsers disagree on the shape: ESTree-style ASTs set `directive` on the
28
+ * expression statement, others only give the string literal.
29
+ */
30
+ function isUseServerDirective(statement: unknown): boolean {
31
+ if (
32
+ !isUseServerNode(statement) ||
33
+ statement.type !== "ExpressionStatement"
34
+ ) {
35
+ return false;
36
+ }
37
+
38
+ if ("directive" in statement && statement.directive === USE_SERVER) {
39
+ return true;
40
+ }
41
+
42
+ return (
43
+ "expression" in statement &&
44
+ isUseServerNode(statement.expression) &&
45
+ statement.expression.type === "Literal" &&
46
+ "value" in statement.expression &&
47
+ statement.expression.value === USE_SERVER
48
+ );
49
+ }
50
+
51
+ function startsWithUseServer(statements: unknown): boolean {
52
+ return (
53
+ Array.isArray(statements) &&
54
+ statements.length > 0 &&
55
+ isUseServerDirective(statements[0])
56
+ );
57
+ }
58
+
59
+ function isUseServerFunction(node: UseServerNode): boolean {
60
+ if (!FUNCTION_TYPES.has(node.type) || !isUseServerNode(node.body)) {
61
+ return false;
62
+ }
63
+
64
+ return (
65
+ node.body.type === "BlockStatement" &&
66
+ startsWithUseServer(node.body.body)
67
+ );
68
+ }
69
+
70
+ function isInsideUseServerFunction(node: UseServerNode): boolean {
71
+ let current: unknown = node;
72
+
73
+ while (isUseServerNode(current)) {
74
+ if (isUseServerFunction(current)) {
75
+ return true;
76
+ }
77
+
78
+ current = current.parent;
79
+ }
80
+
81
+ return false;
82
+ }
83
+
84
+ /**
85
+ * Exempt server code from a rule.
86
+ *
87
+ * Functions in `"use server"` modules log and throw on failure; the page
88
+ * catches the throw with `<Errored>`. A returned failure would resolve the
89
+ * caller's promise as a success, so the result-returning rules must not touch
90
+ * them. The exemption covers a module whose first statement is the directive
91
+ * and a function whose body starts with it, nested code included.
92
+ *
93
+ * `Program` has to be registered as a visitor next to the guarded ones: it runs
94
+ * first and records whether the whole file is server code.
95
+ */
96
+ function createUseServerGuard() {
97
+ let serverModule = false;
98
+
99
+ return {
100
+ Program(node: UseServerNode): void {
101
+ serverModule = startsWithUseServer(node.body);
102
+ },
103
+ guard<Node extends UseServerNode>(
104
+ visitor: (node: Node) => void,
105
+ ): (node: Node) => void {
106
+ return (node) => {
107
+ if (serverModule || isInsideUseServerFunction(node)) {
108
+ return;
109
+ }
110
+
111
+ visitor(node);
112
+ };
113
+ },
114
+ };
115
+ }
116
+
117
+ export { createUseServerGuard };
package/src/empty.ts CHANGED
@@ -15,37 +15,75 @@ import {
15
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
  }
@@ -190,7 +232,11 @@ 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.
@@ -200,11 +246,18 @@ function isPromise<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
  /**
@@ -291,29 +351,35 @@ function isInstanceOf<T>(
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,
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";