@typeonce/oxlint-plugin-ritmo 0.22.0 → 0.24.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 (55) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +88 -22
  3. package/dist/index.js +13 -6
  4. package/dist/index.js.map +1 -1
  5. package/dist/internal/ast.d.ts +43 -0
  6. package/dist/internal/ast.d.ts.map +1 -1
  7. package/dist/internal/ast.js +127 -0
  8. package/dist/internal/ast.js.map +1 -1
  9. package/dist/rules/handle-runtime-result.d.ts.map +1 -1
  10. package/dist/rules/handle-runtime-result.js +82 -10
  11. package/dist/rules/handle-runtime-result.js.map +1 -1
  12. package/dist/rules/keep-simulation-headless.d.ts +3 -3
  13. package/dist/rules/keep-simulation-headless.d.ts.map +1 -1
  14. package/dist/rules/keep-simulation-headless.js +30 -15
  15. package/dist/rules/keep-simulation-headless.js.map +1 -1
  16. package/dist/rules/no-float-timers.d.ts +2 -2
  17. package/dist/rules/no-float-timers.d.ts.map +1 -1
  18. package/dist/rules/no-float-timers.js +133 -20
  19. package/dist/rules/no-float-timers.js.map +1 -1
  20. package/dist/rules/no-infinity-in-simulation-data.d.ts.map +1 -1
  21. package/dist/rules/no-infinity-in-simulation-data.js +134 -10
  22. package/dist/rules/no-infinity-in-simulation-data.js.map +1 -1
  23. package/dist/rules/no-kept-query-values.d.ts +9 -0
  24. package/dist/rules/no-kept-query-values.d.ts.map +1 -0
  25. package/dist/rules/no-kept-query-values.js +375 -0
  26. package/dist/rules/no-kept-query-values.js.map +1 -0
  27. package/dist/rules/no-state-spread.d.ts.map +1 -1
  28. package/dist/rules/no-state-spread.js +137 -14
  29. package/dist/rules/no-state-spread.js.map +1 -1
  30. package/dist/rules/use-clock-for-time.d.ts.map +1 -1
  31. package/dist/rules/use-clock-for-time.js +31 -15
  32. package/dist/rules/use-clock-for-time.js.map +1 -1
  33. package/dist/rules/use-keyboard-for-game-keys.d.ts +9 -0
  34. package/dist/rules/use-keyboard-for-game-keys.d.ts.map +1 -0
  35. package/dist/rules/use-keyboard-for-game-keys.js +81 -0
  36. package/dist/rules/use-keyboard-for-game-keys.js.map +1 -0
  37. package/dist/rules/use-ops-for-math.d.ts.map +1 -1
  38. package/dist/rules/use-ops-for-math.js +11 -7
  39. package/dist/rules/use-ops-for-math.js.map +1 -1
  40. package/dist/rules/use-random-for-randomness.d.ts.map +1 -1
  41. package/dist/rules/use-random-for-randomness.js +11 -13
  42. package/dist/rules/use-random-for-randomness.js.map +1 -1
  43. package/package.json +1 -1
  44. package/src/index.ts +13 -6
  45. package/src/internal/ast.ts +125 -0
  46. package/src/rules/handle-runtime-result.ts +86 -8
  47. package/src/rules/keep-simulation-headless.ts +32 -12
  48. package/src/rules/no-float-timers.ts +124 -19
  49. package/src/rules/no-infinity-in-simulation-data.ts +133 -10
  50. package/src/rules/no-kept-query-values.ts +353 -0
  51. package/src/rules/no-state-spread.ts +140 -12
  52. package/src/rules/use-clock-for-time.ts +31 -14
  53. package/src/rules/use-keyboard-for-game-keys.ts +85 -0
  54. package/src/rules/use-ops-for-math.ts +10 -10
  55. package/src/rules/use-random-for-randomness.ts +9 -11
@@ -1,13 +1,40 @@
1
1
  import { defineRule } from "@oxlint/plugins"
2
2
  import type { ESTree } from "@oxlint/plugins"
3
3
 
4
- import { docsUrl, stringValue } from "../internal/ast.ts"
4
+ import { calledMethod, docsUrl, globalPath, propertyKey, propertyName, receiverName, stringValue } from "../internal/ast.ts"
5
5
 
6
6
  /** The `_tag` property of an object literal, if it has one written out. */
7
7
  const isTag = (node: ESTree.Node): node is ESTree.ObjectProperty =>
8
8
  node.type === "Property" && node.kind === "init" &&
9
9
  ((!node.computed && node.key.type === "Identifier" && node.key.name === "_tag") || stringValue(node.key) === "_tag")
10
10
 
11
+ const unwrap = (node: ESTree.Node): ESTree.Node =>
12
+ node.type === "TSAsExpression" || node.type === "TSNonNullExpression" || node.type === "TSSatisfiesExpression" || node.type === "ParenthesizedExpression" || node.type === "ChainExpression"
13
+ ? unwrap(node.expression)
14
+ : node
15
+
16
+ /** One part of a value being built, in order: a field written out, or a value spread into it. */
17
+ type Part = { readonly tag: ESTree.ObjectProperty } | { readonly spread: ESTree.Node }
18
+
19
+ /** The parts of an object literal, with literals spread into it read as their own parts (`{ ...a, ...{ _tag } }`). */
20
+ const partsOf = (literal: ESTree.ObjectExpression): ReadonlyArray<Part> =>
21
+ literal.properties.flatMap((property): ReadonlyArray<Part> => {
22
+ if (property.type === "SpreadElement") {
23
+ const argument = unwrap(property.argument)
24
+ return argument.type === "ObjectExpression" ? partsOf(argument) : [{ spread: property.argument }]
25
+ }
26
+ return isTag(property) ? [{ tag: property }] : []
27
+ })
28
+
29
+ /** The function (or the program) `node` is in. */
30
+ const functionOf = (node: ESTree.Node): ESTree.Node | undefined => {
31
+ let current = node.parent
32
+ while (current !== null && current.type !== "ArrowFunctionExpression" && current.type !== "FunctionExpression" && current.type !== "FunctionDeclaration" && current.type !== "Program") {
33
+ current = current.parent
34
+ }
35
+ return current ?? undefined
36
+ }
37
+
11
38
  /**
12
39
  * A tagged value changes state by writing the new state's fields, never by
13
40
  * re-tagging a spread of the old one: the old state's fields would survive at
@@ -22,25 +49,126 @@ export default defineRule({
22
49
  },
23
50
  messages: {
24
51
  spread:
25
- "This sets `_tag` over a spread of `{{spread}}`: every field of the previous state survives at runtime, though the type of the new state hides it, so it comes back when the value is saved, compared, or spread again. Move an entity state with `data.state.transition(entity, { from, to, data })`, which takes the new state's fields; queue a state machine's move with the new state's fields, `nextMachines.mode.set({ _tag: \"Talking\", speaker, page: 0 })`; anywhere else, write the new state's fields out: `{ _tag: \"air\", vy, coyote }`. Spread the previous value only to change fields of the same state."
52
+ "This sets `_tag` over a spread of `{{spread}}`: every field of the previous state survives at runtime, though the type of the new state hides it, so it comes back when the value is saved, compared, or spread again. Move an entity state with `data.state.transition(entity, { from, to, data })`, which takes the new state's fields; queue a state machine's move with `nextMachines.mode.transition({ from, to, data })`, which takes them too; anywhere else, write the new state's fields out: `{ _tag: \"air\", vy, coyote }`. Spread the previous value only to change fields of the same state."
26
53
  },
27
54
  schema: []
28
55
  },
29
56
  create(context) {
30
57
  const text = (node: ESTree.Node): string => context.sourceCode.getText(node)
58
+ /** Values built by parts, checked at the end, once every `_tag` read and slot move of the file is known. */
59
+ const built: Array<ReadonlyArray<Part>> = []
60
+ /** `x._tag` reads, by the function they are in and the text of `x`. */
61
+ const tagReads = new Set<string>()
62
+ /** Slots moved as entity states (`data.contact.transition(...)`), by function and slot text. */
63
+ const movedSlots = new Set<string>()
64
+ const ids = new Map<ESTree.Node, number>()
65
+ const scoped = (at: ESTree.Node, key: string): string => {
66
+ const fn = functionOf(at)
67
+ if (fn !== undefined && !ids.has(fn)) ids.set(fn, ids.size)
68
+ return `${fn === undefined ? -1 : ids.get(fn)}:${key}`
69
+ }
70
+
71
+ const variableOf = (node: ESTree.Node) =>
72
+ context.sourceCode.getScope(node).references.find((reference) => reference.identifier === node)?.resolved ?? undefined
73
+
74
+ /** The declarator that binds `node` (a `let` or `const` in the file), and the binding in its pattern. */
75
+ const declaratorOf = (node: ESTree.Node) => {
76
+ const definition = node.type === "Identifier" ? variableOf(node)?.defs[0] : undefined
77
+ return definition?.type === "Variable" && definition.node.type === "VariableDeclarator" ? { declarator: definition.node, name: definition.name } : undefined
78
+ }
79
+
80
+ /** Whether `node` reads a state machine's value: `machines.x.get()`, `nextMachines.x.getPending()`. */
81
+ const isMachineRead = (node: ESTree.Node): boolean => {
82
+ if (node.type !== "CallExpression" || node.callee.type !== "MemberExpression" || node.arguments.length > 0) return false
83
+ const machine = unwrap(node.callee.object)
84
+ if (machine.type !== "MemberExpression") return false
85
+ const view = receiverName(unwrap(machine.object))
86
+ const method = calledMethod(node)
87
+ return (method === "get" && view === "machines") || (method === "getPending" && view === "nextMachines")
88
+ }
89
+
90
+ /** Whether `node` reads an entity state's slot that the same function moves: `data.contact.get(entity)` next to `data.contact.transition(...)`. */
91
+ const isStateSlotRead = (node: ESTree.Node): boolean =>
92
+ node.type === "CallExpression" && calledMethod(node) === "get" && node.callee.type === "MemberExpression" &&
93
+ movedSlots.has(scoped(node, text(unwrap(node.callee.object))))
94
+
95
+ /** Whether the destructuring that binds `name` takes `_tag` out: `rest` in `const { _tag, ...rest } = ground`. */
96
+ const isTaglessRest = (node: ESTree.Node): boolean => {
97
+ const found = declaratorOf(node)
98
+ const rest = found?.name.parent
99
+ return rest?.type === "RestElement" && rest.parent.type === "ObjectPattern" &&
100
+ rest.parent.properties.some((property) => property.type === "Property" && propertyKey(property) === "_tag")
101
+ }
102
+
103
+ /**
104
+ * Whether the file shows that `raw` is a state's value: read from a state
105
+ * machine or a moved entity state slot (directly or through the variable
106
+ * it was stored in), or a value whose `_tag` the same function reads
107
+ * (`if (body._tag === "ground")`, `switch (state._tag)`, `const { _tag } = previous`).
108
+ */
109
+ const isState = (raw: ESTree.Node, at: ESTree.Node): boolean => {
110
+ const node = unwrap(raw)
111
+ if (isMachineRead(node) || isStateSlotRead(node)) return true
112
+ if (tagReads.has(scoped(at, text(node)))) return true
113
+ if (node.type !== "Identifier") return false
114
+ const variable = variableOf(node)
115
+ if (variable?.references.some((reference) => {
116
+ const parent = reference.identifier.parent
117
+ // `x._tag`, wherever the variable is read
118
+ if (parent?.type === "MemberExpression" && parent.object === reference.identifier && propertyName(parent) === "_tag") return true
119
+ // `const { _tag } = x`
120
+ return parent?.type === "VariableDeclarator" && parent.init === reference.identifier && parent.id.type === "ObjectPattern" &&
121
+ parent.id.properties.some((property) => property.type === "Property" && propertyKey(property) === "_tag")
122
+ })) return true
123
+ const found = declaratorOf(node)
124
+ const init = found?.declarator.id === found?.name ? found?.declarator.init : undefined
125
+ return init !== undefined && init !== null && (isMachineRead(unwrap(init)) || isStateSlotRead(unwrap(init)))
126
+ }
127
+
128
+ const check = (parts: ReadonlyArray<Part>): void => {
129
+ const spreads = parts.flatMap((part, index) => ("spread" in part ? [{ node: part.spread, index }] : []))
130
+ for (const [index, part] of parts.entries()) {
131
+ if (!("tag" in part)) continue
132
+ // The state spread before this `_tag`. A `_tag` before a spread names the state the spread's fields are, unless they are a rest
133
+ // that took its tag out and the new tag names a state (`{ _tag: "air", ...rest }`; `{ _tag: tag, ...rest }` may put the same one back).
134
+ const state = spreads.filter((spread) => spread.index < index && isState(spread.node, part.tag)).at(-1) ??
135
+ (stringValue(unwrap(part.tag.value)) === undefined ? undefined : spreads.find((spread) => isTaglessRest(unwrap(spread.node))))
136
+ if (state === undefined) continue
137
+ // `{ ...value, _tag: value._tag }` keeps the state it spreads.
138
+ if (text(part.tag.value) === `${text(state.node)}._tag`) continue
139
+ context.report({ node: part.tag, messageId: "spread", data: { spread: text(state.node) } })
140
+ }
141
+ }
142
+
31
143
  return {
32
- ObjectExpression(node) {
33
- let spread: ESTree.SpreadElement | undefined
34
- for (const property of node.properties) {
35
- if (property.type === "SpreadElement") {
36
- spread = property
37
- continue
144
+ MemberExpression(node) {
145
+ if (propertyName(node) === "_tag") tagReads.add(scoped(node, text(unwrap(node.object))))
146
+ },
147
+ CallExpression(node) {
148
+ const method = calledMethod(node)
149
+ // `data.contact.transition(entity, { from, to })`, `data.contact.update(entity, { state, data })`: an entity state's slot.
150
+ if (node.callee.type === "MemberExpression" && node.arguments.length === 2 && (method === "transition" || method === "update")) {
151
+ const move = node.arguments[1]
152
+ if (method === "transition" || (move?.type === "ObjectExpression" && move.properties.some((property) => property.type === "Property" && propertyKey(property) === "state"))) {
153
+ movedSlots.add(scoped(node, text(unwrap(node.callee.object))))
38
154
  }
39
- if (spread === undefined || !isTag(property)) continue
40
- // `{ ...value, _tag: value._tag }` keeps the state it spreads.
41
- if (text(property.value) === `${text(spread.argument)}._tag`) continue
42
- context.report({ node: property, messageId: "spread", data: { spread: text(spread.argument) } })
43
155
  }
156
+ // `Object.assign({}, ground, { _tag: "air" })`
157
+ if (globalPath(context, node.callee) === "Object.assign") {
158
+ built.push(node.arguments.flatMap((argument): ReadonlyArray<Part> => {
159
+ if (argument.type === "SpreadElement") return []
160
+ const value = unwrap(argument)
161
+ return value.type === "ObjectExpression" ? partsOf(value) : [{ spread: argument }]
162
+ }))
163
+ }
164
+ },
165
+ ObjectExpression(node) {
166
+ // A literal spread into another is checked as part of it.
167
+ if (node.parent.type === "SpreadElement" && node.parent.parent.type === "ObjectExpression") return
168
+ built.push(partsOf(node))
169
+ },
170
+ "Program:exit"() {
171
+ for (const parts of built) check(parts)
44
172
  }
45
173
  }
46
174
  }
@@ -1,8 +1,19 @@
1
1
  import { defineRule } from "@oxlint/plugins"
2
+ import type { ESTree } from "@oxlint/plugins"
2
3
 
3
- import { docsUrl, globalMember, isGlobalIdentifier, isGlobalReference } from "../internal/ast.ts"
4
+ import { calledMethod, docsUrl, globalPath, globalRead } from "../internal/ast.ts"
4
5
 
5
- const timers = ["setTimeout", "setInterval", "requestAnimationFrame", "requestIdleCallback", "queueMicrotask"]
6
+ const timers = new Set(["setTimeout", "setInterval", "setImmediate", "requestAnimationFrame", "requestIdleCallback", "queueMicrotask"])
7
+
8
+ /** The globals that read the wall clock, by path, with the call named in the report. */
9
+ const wallClocks = new Map([
10
+ ["Date.now", "Date.now()"],
11
+ ["performance.now", "performance.now()"],
12
+ ["performance.timeOrigin", "performance.timeOrigin"],
13
+ ["performance.mark", "performance.mark()"],
14
+ ["process.hrtime", "process.hrtime()"],
15
+ ["Temporal.Now", "Temporal.Now"]
16
+ ])
6
17
 
7
18
  /**
8
19
  * Simulation code reads time from the world's Clock, never from the wall
@@ -24,24 +35,30 @@ export default defineRule({
24
35
  schema: []
25
36
  },
26
37
  create(context) {
38
+ /** Reports a read of a wall clock: a member (`globalThis.Date.now`) or a destructured property (`const { now } = Date`). */
39
+ const check = (node: ESTree.Node): void => {
40
+ const path = globalRead(context, node)?.path
41
+ const call = path === undefined ? undefined : wallClocks.get(path)
42
+ if (call !== undefined) context.report({ node, messageId: "wallClock", data: { call } })
43
+ }
27
44
  return {
28
- MemberExpression(node) {
29
- for (const object of ["Date", "performance"]) {
30
- if (globalMember(context, node, object) === "now") {
31
- context.report({ node, messageId: "wallClock", data: { call: `${object}.now()` } })
32
- }
33
- }
34
- },
45
+ MemberExpression: check,
46
+ Property: check,
35
47
  NewExpression(node) {
36
- if (node.arguments.length === 0 && isGlobalIdentifier(context, node.callee, "Date")) {
48
+ if (node.arguments.length === 0 && globalPath(context, node.callee) === "Date") {
37
49
  context.report({ node, messageId: "wallClock", data: { call: "new Date()" } })
38
50
  }
39
51
  },
40
52
  CallExpression(node) {
41
- const callee = node.callee
42
- if (callee.type !== "Identifier" || !timers.includes(callee.name)) return
43
- if (!isGlobalReference(context, callee)) return
44
- context.report({ node, messageId: "timer", data: { call: callee.name } })
53
+ // The host's time zone, which a replay on another device does not share.
54
+ if (calledMethod(node) === "getTimezoneOffset") {
55
+ context.report({ node, messageId: "wallClock", data: { call: "getTimezoneOffset()" } })
56
+ return
57
+ }
58
+ const callee = globalPath(context, node.callee)
59
+ // `Date()` without `new` returns the current time as a string, whatever its arguments.
60
+ if (callee === "Date") context.report({ node, messageId: "wallClock", data: { call: "Date()" } })
61
+ if (callee !== undefined && timers.has(callee)) context.report({ node, messageId: "timer", data: { call: callee } })
45
62
  }
46
63
  }
47
64
  }
@@ -0,0 +1,85 @@
1
+ import { defineRule } from "@oxlint/plugins"
2
+ import type { Context, ESTree } from "@oxlint/plugins"
3
+
4
+ import { constValue, docsUrl, globalPath, stringValue } from "../internal/ast.ts"
5
+
6
+ /** The listeners on the whole page, by the path `globalPath` gives (`window.addEventListener` is `addEventListener`). */
7
+ const pageListeners = new Set(["addEventListener", "document.addEventListener", "document.body.addEventListener", "document.documentElement.addEventListener"])
8
+
9
+ const keyEvents = new Set(["keydown", "keyup", "keypress"])
10
+
11
+ type FunctionNode = ESTree.ArrowFunctionExpression | ESTree.Function
12
+
13
+ const isFunction = (node: ESTree.Node | null | undefined): node is FunctionNode =>
14
+ node !== null && node !== undefined && (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration")
15
+
16
+ /** The function a listener argument is: written inline, or a `const` or function declaration of the file it names. */
17
+ const listenerFunction = (context: Context, node: ESTree.Node): FunctionNode | undefined => {
18
+ if (isFunction(node)) return node
19
+ if (node.type !== "Identifier") return undefined
20
+ const value = constValue(context, node)
21
+ if (isFunction(value)) return value
22
+ const variable = context.sourceCode.getScope(node).references.find((reference) => reference.identifier === node)?.resolved
23
+ const definition = variable?.defs.length === 1 ? variable.defs[0] : undefined
24
+ return definition?.type === "FunctionName" && isFunction(definition.node) ? definition.node : undefined
25
+ }
26
+
27
+ /** Whether a parameter list binds `name`, so the event of an outer listener is shadowed inside. */
28
+ const binds = (params: ReadonlyArray<ESTree.ParamPattern>, name: string): boolean =>
29
+ params.some((param) => param.type === "Identifier" && param.name === name)
30
+
31
+ /** Whether `node` calls `<name>.preventDefault()` anywhere inside, outside nested functions that rebind `name`. */
32
+ const preventsDefault = (node: ESTree.Node, name: string): boolean => {
33
+ if (node.type === "CallExpression") {
34
+ const callee = node.callee
35
+ if (
36
+ callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && callee.property.name === "preventDefault" &&
37
+ callee.object.type === "Identifier" && callee.object.name === name
38
+ ) return true
39
+ }
40
+ if (isFunction(node) && binds(node.params, name)) return false
41
+ for (const [key, value] of Object.entries(node)) {
42
+ if (key === "parent") continue
43
+ const children: ReadonlyArray<unknown> = Array.isArray(value) ? value : [value]
44
+ for (const child of children) {
45
+ if (typeof child === "object" && child !== null && typeof (child as { readonly type?: unknown }).type === "string" && preventsDefault(child as ESTree.Node, name)) return true
46
+ }
47
+ }
48
+ return false
49
+ }
50
+
51
+ /**
52
+ * Host code takes game keys through `Keyboard.actions` / `Keyboard.presses`,
53
+ * which leave keys the page is using (a focused control, an open dialog, a
54
+ * form field) to the page, not through a key listener on the whole page
55
+ * that prevents their default.
56
+ */
57
+ export default defineRule({
58
+ meta: {
59
+ type: "problem",
60
+ docs: {
61
+ description: "Take game keys with Keyboard.actions, not a key listener on window or document that calls preventDefault().",
62
+ url: docsUrl("use-keyboard-for-game-keys")
63
+ },
64
+ messages: {
65
+ pageListener:
66
+ "A `{{type}}` listener on the whole page that calls `preventDefault()` also takes Enter, Space, and the arrows from a focused button, link, or open dialog, so the page's controls stop working by keyboard (games hide this with `tabIndex = -1` or `blur()`). Bind the key with `Keyboard.actions(window, bindings)` from `@typeonce/ritmo-browser` and read its `pressed` edge each frame (one-shot keys like Escape or M too; `Keyboard.presses(window)` for any key): it leaves keys the page is using to the page. A key for one piece of UI (a dialog's Escape, a menu's arrows) listens on that element instead."
67
+ },
68
+ schema: []
69
+ },
70
+ create(context) {
71
+ return {
72
+ CallExpression(node) {
73
+ const path = globalPath(context, node.callee)
74
+ if (path === undefined || !pageListeners.has(path)) return
75
+ const type = stringValue(node.arguments[0])
76
+ const listener = node.arguments[1]
77
+ if (type === undefined || !keyEvents.has(type) || listener === undefined) return
78
+ const handler = listenerFunction(context, listener)
79
+ const event = handler?.params[0]
80
+ if (handler === undefined || handler.body === null || event === undefined || event.type !== "Identifier") return
81
+ if (preventsDefault(handler.body, event.name)) context.report({ node, messageId: "pageListener", data: { type } })
82
+ }
83
+ }
84
+ }
85
+ })
@@ -1,7 +1,7 @@
1
1
  import { defineRule } from "@oxlint/plugins"
2
2
  import type { Context, ESTree, Fixer, Fix } from "@oxlint/plugins"
3
3
 
4
- import { docsUrl, globalMember, isGlobalReference, propertyName, stringValue } from "../internal/ast.ts"
4
+ import { docsUrl, globalRead, isGlobalReference, propertyKey, propertyName, stringValue, typePositions } from "../internal/ast.ts"
5
5
 
6
6
  /** The Math functions engines may approximate; each has an `Ops` counterpart. */
7
7
  const approximated = new Set([
@@ -10,9 +10,6 @@ const approximated = new Set([
10
10
  "sinh", "cosh", "tanh", "asinh", "acosh", "atanh"
11
11
  ])
12
12
 
13
- /** Where the type checker reads `Math` as a type: these never run. */
14
- const typePositions = new Set(["TSTypeQuery", "TSQualifiedName", "TSTypeReference", "TSClassImplements", "TSInterfaceHeritage"])
15
-
16
13
  /** The value `require("<source>")` loads, if `node` is that call. */
17
14
  const requireOf = (node: ESTree.Node | null | undefined): string | undefined =>
18
15
  node?.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "require" && node.arguments.length === 1
@@ -48,10 +45,6 @@ const opsBinding = (program: ESTree.Program): ESTree.BindingIdentifier | undefin
48
45
  return undefined
49
46
  }
50
47
 
51
- /** The static name of an object pattern or literal property (`a`, `"a"`), if it has one. */
52
- const propertyKey = (node: ESTree.ObjectProperty | ESTree.AssignmentTargetProperty | ESTree.BindingProperty): string | undefined =>
53
- !node.computed && node.key.type === "Identifier" ? node.key.name : stringValue(node.key)
54
-
55
48
  /** The variable `name` resolves to from `scope`, if any declaration in the file binds it. */
56
49
  const resolve = (scope: ReturnType<Context["sourceCode"]["getScope"]>, name: string) => {
57
50
  for (let current: typeof scope | null = scope; current !== null; current = current.upper) {
@@ -109,11 +102,14 @@ export default defineRule({
109
102
  create(context) {
110
103
  const pending: Array<Pending> = []
111
104
 
112
- /** Whether `node` is the global Math: `Math` or `globalThis.Math` (not a local named Math). */
105
+ /**
106
+ * Whether `node` is the global Math: `Math`, or a member of a global
107
+ * object (`globalThis.Math`, `self.Math`), not a local named Math.
108
+ */
113
109
  const isMath = (node: ESTree.Node): boolean =>
114
110
  node.type === "Identifier"
115
111
  ? node.name === "Math" && isGlobalReference(context, node)
116
- : node.type === "MemberExpression" && globalMember(context, node, "globalThis") === "Math"
112
+ : node.type === "MemberExpression" && globalRead(context, node)?.path === "Math"
117
113
 
118
114
  /** Whether destructuring Math with `pattern` pulls only exact members by name. */
119
115
  const pullsOnlyExact = (pattern: ESTree.Node): boolean =>
@@ -150,6 +146,10 @@ export default defineRule({
150
146
  MemberExpression(node) {
151
147
  if (isMath(node)) checkMath(node)
152
148
  },
149
+ // `const { Math: M } = globalThis` is an alias too.
150
+ Property(node) {
151
+ if (globalRead(context, node)?.path === "Math" && !pullsOnlyExact(node.value)) pending.push({ node, messageId: "alias" })
152
+ },
153
153
  BinaryExpression(node) {
154
154
  if (node.operator !== "**") return
155
155
  if (node.right.type === "Literal" && node.right.value === 2) return
@@ -1,6 +1,7 @@
1
1
  import { defineRule } from "@oxlint/plugins"
2
+ import type { ESTree } from "@oxlint/plugins"
2
3
 
3
- import { docsUrl, globalMember } from "../internal/ast.ts"
4
+ import { docsUrl, globalRead } from "../internal/ast.ts"
4
5
 
5
6
  /**
6
7
  * Simulation code draws randomness from the world's Random resource, which is
@@ -22,16 +23,13 @@ export default defineRule({
22
23
  schema: []
23
24
  },
24
25
  create(context) {
25
- return {
26
- MemberExpression(node) {
27
- if (globalMember(context, node, "Math") === "random") {
28
- context.report({ node, messageId: "random", data: { call: "Math.random()" } })
29
- return
30
- }
31
- const crypto = globalMember(context, node, "crypto")
32
- if (crypto === "getRandomValues") context.report({ node, messageId: "random", data: { call: "crypto.getRandomValues()" } })
33
- if (crypto === "randomUUID") context.report({ node, messageId: "uuid" })
34
- }
26
+ /** Reports a read of a random source: a member (`globalThis.Math.random`) or a destructured property (`const { random } = Math`). */
27
+ const check = (node: ESTree.Node): void => {
28
+ const path = globalRead(context, node)?.path
29
+ if (path === "Math.random") context.report({ node, messageId: "random", data: { call: "Math.random()" } })
30
+ if (path === "crypto.getRandomValues") context.report({ node, messageId: "random", data: { call: "crypto.getRandomValues()" } })
31
+ if (path === "crypto.randomUUID") context.report({ node, messageId: "uuid" })
35
32
  }
33
+ return { MemberExpression: check, Property: check }
36
34
  }
37
35
  })