@typeonce/oxlint-plugin-ritmo 0.14.0 → 0.15.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # @typeonce/oxlint-plugin-ritmo
2
2
 
3
+ ## 0.15.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3a195b7: **Cooldowns and timers are deadlines: the step they end on, exact through saves and rollback.** A timer counted down by `dt` drifts by a rounded float every tick, and the float it saves means nothing once the fixed step changes. `Clock.Deadline<Hz>` is the absolute step a duration ends on, a plain number branded with the clock's rate:
8
+
9
+ ```ts
10
+ // ready: Clock.Deadline<60> | null, its schema narrowing with Clock.isDeadline(step)
11
+ const Weapon = Descriptor.ConstructedComponent(
12
+ z.object({ ready: z.unknown().refine(Clock.isDeadline(step)).nullable() })
13
+ )("Game/Weapon");
14
+
15
+ const time = resources.time.get();
16
+ const { ready } = data.weapon.get();
17
+ if (ready === null || Clock.reached(time, ready)) {
18
+ fire();
19
+ data.weapon.set({ ready: Clock.deadline(time, Clock.duration(step, 0.5)) });
20
+ }
21
+ ```
22
+
23
+ - `Clock.deadline(time, duration)`, `Clock.reached(time, deadline)`, and `Clock.remaining(time, deadline)` (whole steps left, for a readout). A deadline of a 60 Hz clock does not compile against a 30 Hz `Time`, and a raw number is not a deadline.
24
+ - `Clock.isDeadline(step)` is the guard for a game's schema, like `Entity.isHandle`: any whole number of steps, 0 or more.
25
+ - New lint rule `ritmo/no-float-timers` for simulation files: reports `timer -= dt`, `cooldown - time.dt`, and the like, and names `Clock.deadline` / `Clock.reached`. `position.x += velocity.x * dt` is integration and is not reported. Turn it on in the simulation override of `.oxlintrc.json`: `"ritmo/no-float-timers": "error"`.
26
+
27
+ - c75daff: **`oxlint --fix` does the whole job for `ritmo/use-ops-for-math`.** The rule points at `Ops` from `@typeonce/ritmo` (it moved from `@typeonce/ritmo-math`), and its fix now adds `import { Ops } from "@typeonce/ritmo"` when the file has none, once per file, after the last import (a `const { Ops } = require("@typeonce/ritmo")` in CommonJS, for vendored code). `x **= y` is fixed to `x = Ops.pow(x, y)` when `x` is a variable. `ritmo/use-random-for-randomness` names `Random` from `@typeonce/ritmo` the same way.
28
+
29
+ **Aliasing `Math` is reported.** `const { sin } = Math`, `const M = Math`, passing `Math` to a function, `globalThis.Math.sin`, and `Math[name]` with a computed key hid a non-exact call from the rule; each is now reported (without a fix). Exact members (`Math.PI`, `Math.abs`, `const { floor } = Math`) stay valid.
30
+
31
+ **New rule `ritmo/no-brand-cast`.** A cast to a branded type (`raw as ItemId` where `ItemId` comes from `.brand()`, `Schema.brand`, `Brand.Branded`, or a Ritmo brand such as `Random.State` or `Clock.Deadline`) skips the check the brand stands for. The rule reports it in simulation code and names the fix: decode through the schema, or the Ritmo constructor (`Random.seed`, `Clock.deadline`, `Game.Entity.handle`). Turn it on in the simulation override:
32
+
33
+ ```json
34
+ {
35
+ "files": ["src/simulation/**"],
36
+ "rules": { "ritmo/no-brand-cast": "error" }
37
+ }
38
+ ```
39
+
3
40
  ## 0.14.0
4
41
 
5
42
  ### Minor Changes
package/README.md CHANGED
@@ -5,7 +5,9 @@
5
5
  Ritmo's types reject wrong calls, and its devtools lints reject wrong runs. These rules catch the source patterns neither can see:
6
6
 
7
7
  - simulation code that reads the wall clock, `Math.random`, engine-dependent math, or the page;
8
+ - timers counted in floats;
8
9
  - data that cannot be saved;
10
+ - casts that claim a brand's check without running it;
9
11
  - state values that keep a previous state's fields;
10
12
  - runtime results that are dropped.
11
13
 
@@ -39,14 +41,16 @@ Register the plugin and turn the rules on in `.oxlintrc.json`. The simulation ru
39
41
  "ritmo/use-random-for-randomness": "error",
40
42
  "ritmo/use-ops-for-math": "error",
41
43
  "ritmo/keep-simulation-headless": "error",
42
- "ritmo/no-infinity-in-simulation-data": "error"
44
+ "ritmo/no-infinity-in-simulation-data": "error",
45
+ "ritmo/no-float-timers": "error",
46
+ "ritmo/no-brand-cast": "error"
43
47
  }
44
48
  }
45
49
  ]
46
50
  }
47
51
  ```
48
52
 
49
- Rules are named `ritmo/<rule>`. `ritmo/use-ops-for-math` and `ritmo/use-cell-value` fix themselves with `oxlint --fix` (`use-ops-for-math` once `Ops` is imported in the file).
53
+ Rules are named `ritmo/<rule>`. `ritmo/use-ops-for-math` and `ritmo/use-cell-value` fix themselves with `oxlint --fix`.
50
54
 
51
55
  A deliberate exception, such as a host-time module inside a simulation folder, takes a disable comment with the reason:
52
56
 
@@ -59,9 +63,11 @@ const started = performance.now()
59
63
  |---|---|---|---|
60
64
  | [`use-clock-for-time`](#ritmouse-clock-for-time) | simulation | `Date.now()`, `performance.now()`, `new Date()`, timers | `Clock` |
61
65
  | [`use-random-for-randomness`](#ritmouse-random-for-randomness) | simulation | `Math.random()`, `crypto` randomness | `Random.draw(resources.rng)` |
62
- | [`use-ops-for-math`](#ritmouse-ops-for-math) | simulation | `Math.sin`, `Math.hypot`, `a ** b`, ... | `Ops` |
66
+ | [`use-ops-for-math`](#ritmouse-ops-for-math) | simulation | `Math.sin`, `Math.hypot`, `a ** b`, `const { sin } = Math`, ... | `Ops` |
63
67
  | [`keep-simulation-headless`](#ritmokeep-simulation-headless) | simulation | page globals, host I/O, renderer imports | input and data from the host, drawing in a render schedule |
64
68
  | [`no-infinity-in-simulation-data`](#ritmono-infinity-in-simulation-data) | simulation | `Infinity` / `NaN` in object literals | `null` |
69
+ | [`no-float-timers`](#ritmono-float-timers) | simulation | `timer -= dt`, `cooldown - time.dt` | `Clock.deadline` / `Clock.reached` |
70
+ | [`no-brand-cast`](#ritmono-brand-cast) | simulation | `raw as UserId`, `1 as Random.State` | the schema or constructor that brands it |
65
71
  | [`handle-tick-result`](#ritmohandle-tick-result) | everywhere | a dropped `runtime.tick(...)` / `restore(...)` / `rewind(...)` result | check `.ok` |
66
72
  | [`prefix-descriptor-and-system-names`](#ritmoprefix-descriptor-and-system-names) | everywhere | `"Position"`, `Game.System("Move", ...)` | `"Game/Position"` |
67
73
  | [`use-cell-value`](#ritmouse-cell-value) | everywhere | `cell.present ? cell.get() : undefined` | `cell.value()` |
@@ -80,7 +86,7 @@ setTimeout(() => spawnWave(), 500) // reported
80
86
  // instead
81
87
  const time = resources.time.get()
82
88
  if (Clock.elapsed(time) > 3) open() // seconds since the start
83
- const due = time.step + Clock.steps(Clock.duration(step, 0.5)) // store it, compare each tick
89
+ const due = Clock.deadline(time, Clock.duration(step, 0.5)) // store it, Clock.reached(time, due) each tick
84
90
  if (Clock.every(time, waveEvery)) spawnWave() // repeats
85
91
  ```
86
92
 
@@ -103,19 +109,23 @@ Catches `Math.random()`, `crypto.getRandomValues()`, and `crypto.randomUUID()`.
103
109
 
104
110
  ### `ritmo/use-ops-for-math`
105
111
 
106
- The spec lets engines approximate `Math.sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `exp`, `expm1`, `log`, `log2`, `log10`, `log1p`, `cbrt`, `pow`, `hypot`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`, and `a ** b`, and they do: Chrome, Safari, macOS, and Linux disagree in the last bit, and a simulation grows that bit into a different run. [`Ops`](https://github.com/typeonce-dev/ritmo/blob/main/packages/math/README.md#determinism-across-devices) from `@typeonce/ritmo-math` has each of them as a port that returns the same bits everywhere.
112
+ The spec lets engines approximate `Math.sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `exp`, `expm1`, `log`, `log2`, `log10`, `log1p`, `cbrt`, `pow`, `hypot`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`, and `a ** b`, and they do: Chrome, Safari, macOS, and Linux disagree in the last bit, and a simulation grows that bit into a different run. [`Ops`](https://github.com/typeonce-dev/ritmo/blob/main/packages/core/README.md) from `@typeonce/ritmo` has each of them as a port that returns the same bits everywhere.
107
113
 
108
114
  ```ts
109
115
  const turn = Math.atan2(Math.sin(b - a), Math.cos(b - a)) // reported
110
116
  const beauty = base * repeat ** n // reported
111
117
 
112
118
  // instead
113
- import { Ops } from "@typeonce/ritmo-math"
119
+ import { Ops } from "@typeonce/ritmo"
114
120
  const turn = Ops.atan2(Ops.sin(b - a), Ops.cos(b - a))
115
121
  const beauty = base * Ops.pow(repeat, n)
116
122
  ```
117
123
 
118
- `Math.sqrt`, `abs`, `min`, `max`, `floor`, `ceil`, `round`, `trunc`, `sign`, `+ - * /`, and `x ** 2` are exact everywhere and are not reported. With `Ops` imported in the file, `oxlint --fix` rewrites the calls.
124
+ `Math.sqrt`, `abs`, `min`, `max`, `floor`, `ceil`, `round`, `trunc`, `sign`, `+ - * /`, and `x ** 2` are exact everywhere and are not reported (`Math.PI`, `Math["floor"]`, and `const { abs, PI } = Math` neither).
125
+
126
+ `oxlint --fix` does the whole change in one run: it rewrites `Math.sin(x)` to `Ops.sin(x)`, `a ** b` to `Ops.pow(a, b)`, and `x **= y` to `x = Ops.pow(x, y)`, and adds `import { Ops } from "@typeonce/ritmo"` once, after the last import (`const { Ops } = require("@typeonce/ritmo")` in a CommonJS file). It uses `Ops` where the file already imports it, under any name (`import { Ops as M }`, `import * as Ops from "@typeonce/ritmo/Ops"`). It leaves the report unfixed where a rewrite could change the code: `body.speed **= y` (the rewrite would evaluate `body` twice), and a file or function where the name `Ops` already means something else (a type-only import included).
127
+
128
+ The global Math handed on as a value hides the calls made through it from the rule, so it is reported too (without a fix): an alias (`const M = Math`), a destructured function or rest element (`const { sin } = Math`), an argument (`apply(Math, "sin", x)`), a computed key (`Math[name]`), and `globalThis.Math` used the same ways. Call `Ops.sin` directly, and read exact members by name. A local named `Math` is not the global and is not reported.
119
129
 
120
130
  ### `ritmo/keep-simulation-headless`
121
131
 
@@ -147,6 +157,50 @@ dash: { remaining: 0, since: null } // since: numbe
147
157
 
148
158
  Catches `Infinity`, `-Infinity`, `NaN`, and `Number.POSITIVE_INFINITY` / `NEGATIVE_INFINITY` / `NaN` as a property value in any object literal in simulation files, including values built in helpers before they are spawned. Search seeds in locals (`let best = Infinity`) are not reported.
149
159
 
160
+ ### `ritmo/no-float-timers`
161
+
162
+ A timer counted down by `dt` adds a rounded float every tick, so it ends a step early or late, and the float it saves means nothing once the fixed step changes. A deadline is the step the timer ends on: written once, exact, and valid after a restore or a rollback, since the clock it is measured against is saved and rewound with it.
163
+
164
+ ```ts
165
+ cooldown.remaining -= dt // reported
166
+ data.buff.set({ ...buff, left: buff.left - time.dt }) // reported
167
+
168
+ // instead: ready: Clock.Deadline<60> | null, its schema narrowing with Clock.isDeadline(step)
169
+ const cooldown = Clock.duration(step, 0.5)
170
+ const time = resources.time.get()
171
+ const { ready } = data.weapon.get()
172
+ if (ready === null || Clock.reached(time, ready)) {
173
+ fire()
174
+ data.weapon.set({ ready: Clock.deadline(time, cooldown) })
175
+ }
176
+ const bar = ready === null ? 0 : Clock.remaining(time, ready) / Clock.steps(cooldown) // a readout
177
+ ```
178
+
179
+ Catches a stored value (a local or a field) plus or minus a tick's seconds on their own: `dt`, `deltaTime`, or `deltaSeconds`, as a local, a field (`time.dt`), or a resource read (`resources.deltaTime.get()`), in `x -= dt`, `x += dt`, and `x - dt` / `x + dt` anywhere (`Math.max(0, x - dt)`, an object literal). A rate scaled by `dt` (`position.x += velocity.x * dt`) is integration and is not reported, nor is a count of whole steps (`cooldown - 1`), nor a `delta` that is not time (a pointer's).
180
+
181
+ ### `ritmo/no-brand-cast`
182
+
183
+ A branded type (`UserId`, `Random.State`, `Clock.Deadline<60>`) stands for a check the value passed. A cast claims the brand without running the check, so an invalid value travels as a valid one: a save holding it fails to load, or the simulation computes with it.
184
+
185
+ ```ts
186
+ const UserId = z.string().uuid().brand("UserId")
187
+ type UserId = z.infer<typeof UserId>
188
+ const id = raw as UserId // reported
189
+ const rng = Random.resource("Game/Rng", 1 as Random.State) // reported
190
+
191
+ // instead
192
+ const id = UserId.parse(raw) // Effect: Schema.decodeUnknownSync(UserId)(raw)
193
+ const rng = Random.resource("Game/Rng", Random.seed(1))
194
+ ```
195
+
196
+ Oxlint has no type information, so the rule reads the brand from the code: a cast (`x as T` or `<T>x`) to
197
+ - a brand helper: `Brand.Branded<...>`, Effect's `Brand.Brand<...>`, Zod's `z.BRAND<...>` / `z.$brand<...>`, or a `Brand<...>` / `Branded<...>` of any library;
198
+ - an object type with a brand key: `T & { readonly __brand: "UserId" }` (also `_brand`, `__type`), or a key declared as `declare const brand: unique symbol`;
199
+ - a type alias or interface in the same file that is one of these, or the type of a schema in the same file built with `.brand(...)` / `Schema.brand(...)` (`z.infer<typeof UserId>`, `typeof Gold.Type`, `Schema.Schema.Type<typeof Gold>`);
200
+ - a branded Ritmo export imported from `@typeonce/ritmo` (or a subpath such as `@typeonce/ritmo/Clock`): `Clock.Deadline`, `Clock.Step`, `Clock.Duration`, `Clock.ClockResource`, `Entity.Handle`, `Entity.EntityId`, `Random.State`, `Checkpoint.Checkpoint`, `Checkpoint.Rewindable`.
201
+
202
+ Make the value through its check: decode at the boundary with the game's schema, or with Ritmo's constructor or guard (`Random.seed` / `Random.result`, `Clock.deadline` / `Clock.isDeadline`, `Game.Entity.handle` / `Entity.isHandle`). `as const`, `satisfies`, and casts to types without a brand are not reported, nor are brands imported from another file of the game (the rule cannot see them).
203
+
150
204
  ## Rules for every file
151
205
 
152
206
  ### `ritmo/handle-tick-result`
package/dist/index.js CHANGED
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * Types catch wrong calls and devtools catch wrong runs; these rules catch
5
5
  * the source patterns neither can see: simulation code that reads the wall
6
- * clock, `Math.random`, engine-dependent math, or the page, data that cannot
7
- * be saved, state values that keep a previous state's fields, and runtime
8
- * results that are dropped. Every report names the
9
- * Ritmo API to use instead.
6
+ * clock, `Math.random`, engine-dependent math, or the page, timers counted
7
+ * in floats, data that cannot be saved, casts that skip a brand's check,
8
+ * state values that keep a previous state's fields, and runtime results that
9
+ * are dropped. Every report names the Ritmo API to use instead.
10
10
  *
11
11
  * Register the plugin in `.oxlintrc.json` with `"jsPlugins":
12
12
  * ["@typeonce/oxlint-plugin-ritmo"]`. Its rules are named `ritmo/<rule>`.
@@ -16,7 +16,8 @@
16
16
  *
17
17
  * - Simulation files: `ritmo/use-clock-for-time`,
18
18
  * `ritmo/use-random-for-randomness`, `ritmo/use-ops-for-math`,
19
- * `ritmo/keep-simulation-headless`, `ritmo/no-infinity-in-simulation-data`.
19
+ * `ritmo/keep-simulation-headless`, `ritmo/no-infinity-in-simulation-data`,
20
+ * `ritmo/no-float-timers`, `ritmo/no-brand-cast`.
20
21
  * - Every file: `ritmo/handle-tick-result`,
21
22
  * `ritmo/prefix-descriptor-and-system-names`, `ritmo/use-cell-value`,
22
23
  * `ritmo/no-state-spread`.
@@ -26,6 +27,8 @@
26
27
  import { definePlugin } from "@oxlint/plugins";
27
28
  import handleTickResult from "./rules/handle-tick-result.js";
28
29
  import keepSimulationHeadless from "./rules/keep-simulation-headless.js";
30
+ import noBrandCast from "./rules/no-brand-cast.js";
31
+ import noFloatTimers from "./rules/no-float-timers.js";
29
32
  import noInfinityInSimulationData from "./rules/no-infinity-in-simulation-data.js";
30
33
  import noStateSpread from "./rules/no-state-spread.js";
31
34
  import prefixDescriptorAndSystemNames from "./rules/prefix-descriptor-and-system-names.js";
@@ -41,6 +44,8 @@ export default definePlugin({
41
44
  "use-ops-for-math": useOpsForMath,
42
45
  "keep-simulation-headless": keepSimulationHeadless,
43
46
  "no-infinity-in-simulation-data": noInfinityInSimulationData,
47
+ "no-float-timers": noFloatTimers,
48
+ "no-brand-cast": noBrandCast,
44
49
  "handle-tick-result": handleTickResult,
45
50
  "prefix-descriptor-and-system-names": prefixDescriptorAndSystemNames,
46
51
  "use-cell-value": useCellValue,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAE9C,OAAO,gBAAgB,MAAM,+BAA+B,CAAA;AAC5D,OAAO,sBAAsB,MAAM,q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B,MAAM,sCAAsC,CAAA;AAEzE,eAAe,YAAY,CAAC;IAC1B,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE;IACvB,KAAK,EAAE;QACL,oBAAoB,EAAE,eAAe;QACrC,2BAA2B,EAAE,sBAAsB;QACnD,kBAAkB,EAAE,aAAa;QACjC,0BAA0B,EAAE,sBAAsB;QAClD,gCAAgC,EAAE,0BAA0B;QAC5D,iBAAiB,EAAE,aAAa;QAChC,eAAe,EAAE,WAAW;QAC5B,oBAAoB,EAAE,gBAAgB;QACtC,oCAAoC,EAAE,8BAA8B;QACpE,gBAAgB,EAAE,YAAY;QAC9B,iBAAiB,EAAE,aAAa;KACjC;CACF,CAAC,CAAA"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Simulation code never casts a value to a branded type: a brand stands for a
3
+ * check, and the cast claims it without running it.
4
+ */
5
+ declare const _default: import("@oxlint/plugins").Rule;
6
+ export default _default;
7
+ //# sourceMappingURL=no-brand-cast.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"no-brand-cast.d.ts","sourceRoot":"","sources":["../../src/rules/no-brand-cast.ts"],"names":[],"mappings":"AAmDA;;;GAGG"}
@@ -0,0 +1,195 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+ import { docsUrl } from "../internal/ast.js";
3
+ /** The type names that are brands wherever they come from: `Brand.Branded<...>`, Effect's `Brand.Brand<...>`, Zod's `z.BRAND<...>` / `z.$brand<...>`. */
4
+ const brandNames = new Set(["Brand", "Branded", "BRAND", "$brand"]);
5
+ /** Property keys that only a brand declares (`T & { readonly __brand: "UserId" }`). */
6
+ const brandKey = /^(__?brand|__publicBrand|__type)$/;
7
+ /** Ritmo's branded exports, by module: `Clock.Deadline`, `Random.State`, `Entity.Handle`, ... */
8
+ const ritmoBrands = new Map([
9
+ ["Clock", new Set(["Deadline", "Step", "Duration", "ClockResource"])],
10
+ ["Entity", new Set(["Handle", "EntityId"])],
11
+ ["Random", new Set(["State"])],
12
+ ["Checkpoint", new Set(["Checkpoint", "Rewindable"])]
13
+ ]);
14
+ /** The type helpers that read the type out of a schema: `z.infer<typeof X>`, `Schema.Schema.Type<typeof X>`. */
15
+ const schemaTypeHelpers = new Set(["infer", "output", "TypeOf", "Infer", "Type"]);
16
+ /** A schema built with a brand: Zod's `.brand(...)` / `.brand<"X">()`, Effect's `Schema.brand(...)` / `.pipe(Schema.brand(...))`. */
17
+ const brandsSchema = /\bbrand\s*(<[^>]*>\s*)?\(/;
18
+ /** The dotted names of a type name or expression (`Clock.Deadline` gives `["Clock", "Deadline"]`). */
19
+ const segments = (node) => {
20
+ if (node.type === "Identifier")
21
+ return [node.name];
22
+ if (node.type === "TSQualifiedName") {
23
+ const left = segments(node.left);
24
+ return left === undefined ? undefined : [...left, node.right.name];
25
+ }
26
+ if (node.type === "MemberExpression" && !node.computed && node.property.type === "Identifier") {
27
+ const left = segments(node.object);
28
+ return left === undefined ? undefined : [...left, node.property.name];
29
+ }
30
+ return undefined;
31
+ };
32
+ /** Where a local name imported from Ritmo points: `[]` for the package, `["Clock"]` for a module, `["Clock", "Deadline"]` for a type. */
33
+ const ritmoImport = (declaration, specifier) => {
34
+ const match = /^@typeonce\/ritmo(\/([A-Za-z0-9]+))?$/.exec(declaration.source.value);
35
+ if (match === null)
36
+ return undefined;
37
+ const module = match[2];
38
+ const base = module === undefined ? [] : [module];
39
+ if (specifier.type === "ImportNamespaceSpecifier")
40
+ return base;
41
+ if (specifier.type !== "ImportSpecifier")
42
+ return undefined;
43
+ const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
44
+ return [...base, imported];
45
+ };
46
+ /**
47
+ * Simulation code never casts a value to a branded type: a brand stands for a
48
+ * check, and the cast claims it without running it.
49
+ */
50
+ export default defineRule({
51
+ meta: {
52
+ type: "problem",
53
+ docs: {
54
+ description: "Make a branded value through its schema or constructor, not with `as` / `<T>` casts.",
55
+ url: docsUrl("no-brand-cast")
56
+ },
57
+ messages: {
58
+ cast: "This casts to `{{type}}`, a branded type: a brand stands for a check the value passed, and the cast claims it without running the check, so an invalid value travels as a valid one (and a save holding it fails to load, or the simulation computes with it). Make the value through its check instead: decode it at the boundary with the schema that brands it (`UserId.parse(raw)` with Zod, `Schema.decodeUnknownSync(UserId)(raw)` with Effect), or with Ritmo's constructor or guard: `Random.seed(n)` / `Random.result(n)`, `Clock.deadline(time, duration)` / `Clock.isDeadline(step)`, `Game.Entity.handle(id)` / `Entity.isHandle(Root)`."
59
+ },
60
+ schema: []
61
+ },
62
+ create(context) {
63
+ const aliases = new Map();
64
+ const interfaces = new Map();
65
+ const values = new Map();
66
+ const uniqueSymbols = new Set();
67
+ const imports = new Map();
68
+ const casts = [];
69
+ /** Whether the value named `name` is a schema built with a brand in this file. */
70
+ const isBrandedSchema = (name) => {
71
+ const init = values.get(name);
72
+ return init !== undefined && brandsSchema.test(context.sourceCode.getText(init));
73
+ };
74
+ /** Whether a dotted name is a brand: a brand helper, Ritmo's branded export, or a local brand alias. */
75
+ const namesBrand = (names, hasArguments, seen) => {
76
+ const [root, ...rest] = names;
77
+ if (root === undefined)
78
+ return false;
79
+ const imported = imports.get(root);
80
+ if (imported !== undefined) {
81
+ const [module, type, ...more] = [...imported, ...rest];
82
+ if (module !== undefined && type !== undefined && more.length === 0 && ritmoBrands.get(module)?.has(type) === true)
83
+ return true;
84
+ }
85
+ const last = names[names.length - 1];
86
+ if (names.length === 1) {
87
+ const alias = aliases.get(root);
88
+ if (alias !== undefined)
89
+ return !seen.has(root) && isBrand(alias, new Set([...seen, root]));
90
+ const declared = interfaces.get(root);
91
+ if (declared !== undefined)
92
+ return !seen.has(root) && interfaceIsBrand(declared, new Set([...seen, root]));
93
+ return hasArguments && brandNames.has(root);
94
+ }
95
+ return brandNames.has(last);
96
+ };
97
+ const interfaceIsBrand = (node, seen) => node.body.body.some(memberIsBrand) ||
98
+ node.extends.some((heritage) => {
99
+ const names = segments(heritage.expression);
100
+ return names !== undefined && namesBrand(names, heritage.typeArguments !== null, seen);
101
+ });
102
+ const memberIsBrand = (member) => {
103
+ if (member.type !== "TSPropertySignature")
104
+ return false;
105
+ if (!member.computed)
106
+ return member.key.type === "Identifier" ? brandKey.test(member.key.name) : false;
107
+ if (member.key.type === "Identifier" && uniqueSymbols.has(member.key.name))
108
+ return true;
109
+ return /brand/i.test(context.sourceCode.getText(member.key));
110
+ };
111
+ /** Whether `node` reads the type of a branded schema: `typeof X.Type`, `(typeof X)["Type"]`. */
112
+ const readsBrandedSchema = (node) => {
113
+ if (node.type === "TSTypeQuery") {
114
+ const names = segments(node.exprName);
115
+ return names !== undefined && names.length === 2 && names[1] === "Type" && isBrandedSchema(names[0]);
116
+ }
117
+ if (node.type === "TSIndexedAccessType" && node.objectType.type === "TSTypeQuery") {
118
+ const names = segments(node.objectType.exprName);
119
+ const index = node.indexType;
120
+ return names !== undefined && names.length === 1 && isBrandedSchema(names[0]) &&
121
+ index.type === "TSLiteralType" && index.literal.type === "Literal" && index.literal.value === "Type";
122
+ }
123
+ return false;
124
+ };
125
+ const isBrand = (node, seen) => {
126
+ switch (node.type) {
127
+ case "TSIntersectionType":
128
+ case "TSUnionType":
129
+ return node.types.some((type) => isBrand(type, seen));
130
+ case "TSArrayType":
131
+ return isBrand(node.elementType, seen);
132
+ case "TSTypeOperator":
133
+ return node.operator === "readonly" && isBrand(node.typeAnnotation, seen);
134
+ case "TSParenthesizedType":
135
+ return isBrand(node.typeAnnotation, seen);
136
+ case "TSTypeLiteral":
137
+ return node.members.some(memberIsBrand);
138
+ case "TSTypeReference": {
139
+ const names = segments(node.typeName);
140
+ if (names === undefined)
141
+ return false;
142
+ const schema = node.typeArguments?.params[0];
143
+ if (names.length > 1 && schemaTypeHelpers.has(names[names.length - 1]) && schema?.type === "TSTypeQuery") {
144
+ const target = segments(schema.exprName);
145
+ if (target !== undefined && target.length === 1 && isBrandedSchema(target[0]))
146
+ return true;
147
+ }
148
+ return namesBrand(names, node.typeArguments !== null, seen);
149
+ }
150
+ default:
151
+ return readsBrandedSchema(node);
152
+ }
153
+ };
154
+ return {
155
+ ImportDeclaration(node) {
156
+ for (const specifier of node.specifiers) {
157
+ const target = ritmoImport(node, specifier);
158
+ if (target !== undefined)
159
+ imports.set(specifier.local.name, target);
160
+ }
161
+ },
162
+ TSTypeAliasDeclaration(node) {
163
+ aliases.set(node.id.name, node.typeAnnotation);
164
+ },
165
+ TSInterfaceDeclaration(node) {
166
+ interfaces.set(node.id.name, node);
167
+ },
168
+ VariableDeclarator(node) {
169
+ if (node.id.type !== "Identifier")
170
+ return;
171
+ const annotation = node.id.typeAnnotation?.typeAnnotation;
172
+ // `declare const brand: unique symbol` names a key no value has; a symbol made at runtime is a real key.
173
+ if (annotation?.type === "TSTypeOperator" && annotation.operator === "unique" && node.init === null)
174
+ uniqueSymbols.add(node.id.name);
175
+ if (node.init !== null)
176
+ values.set(node.id.name, node.init);
177
+ },
178
+ TSAsExpression(node) {
179
+ casts.push(node);
180
+ },
181
+ TSTypeAssertion(node) {
182
+ casts.push(node);
183
+ },
184
+ // Declarations may follow the casts that use them, so casts are checked once the file is read.
185
+ "Program:exit"() {
186
+ for (const cast of casts) {
187
+ if (!isBrand(cast.typeAnnotation, new Set()))
188
+ continue;
189
+ context.report({ node: cast, messageId: "cast", data: { type: context.sourceCode.getText(cast.typeAnnotation) } });
190
+ }
191
+ }
192
+ };
193
+ }
194
+ });
195
+ //# sourceMappingURL=no-brand-cast.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"no-brand-cast.js","sourceRoot":"","sources":["../../src/rules/no-brand-cast.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAG5C,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AAE5C,yJAAyJ;AACzJ,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAA;AAEnE,uFAAuF;AACvF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M;gBACzC,MAAM,UAAU,GAAG,IAAI,CAAC,EAAE,CAAC,cAAc,EAAE,cAAc,CAAA;gBACzD,yGAAyG;gBACzG,IAAI,UAAU,EAAE,IAAI,KAAK,gBAAgB,IAAI,UAAU,CAAC,QAAQ,KAAK,QAAQ,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI;oBAAE,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,CAAA;gBACpI,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI;oBAAE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAA;YAC7D,CAAC;YACD,cAAc,CAAC,IAAI;gBACjB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;YAClB,CAAC;YACD,eAAe,CAAC,IAAI;gBAClB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;YAClB,CAAC;YACD,+FAA+F;YAC/F,cAAc;gBACZ,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;oBACzB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,GAAG,EAAE,CAAC;wBAAE,SAAQ;oBACtD,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,EAAE,EAAE,CAAC,CAAA;gBACpH,CAAC;YACH,CAAC;SACF,CAAA;IACH,CAAC;CACF,CAAC,CAAA"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * A timer in simulation code is a deadline in steps, never a float counted
3
+ * down (or up) by `dt`: the float drifts, and the value it saves means
4
+ * nothing once the fixed step changes.
5
+ */
6
+ declare const _default: import("@oxlint/plugins").Rule;
7
+ export default _default;
8
+ //# sourceMappingURL=no-float-timers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"no-float-timers.d.ts","sourceRoot":"","sources":["../../src/rules/no-float-timers.ts"],"names":[],"mappings":"AA8BA;;;;GAIG"}
@@ -0,0 +1,60 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+ import { calledMethod, docsUrl, propertyName } from "../internal/ast.js";
3
+ // The names a tick's seconds go by: a local, a field (`time.dt`), or a resource read (`resources.deltaTime.get()`).
4
+ const deltaNames = ["dt", "deltaTime", "deltaSeconds"];
5
+ /** `node` without the type-only wrappers TypeScript adds (`dt as number`, `dt!`). */
6
+ const unwrap = (node) => node.type === "TSAsExpression" || node.type === "TSNonNullExpression" || node.type === "TSSatisfiesExpression" ? unwrap(node.expression) : node;
7
+ /** Whether `node` is a tick's seconds on their own: `dt`, `time.dt`, or `resources.deltaTime.get()`. */
8
+ const isDelta = (raw) => {
9
+ const node = unwrap(raw);
10
+ if (node.type === "Identifier")
11
+ return deltaNames.includes(node.name);
12
+ if (node.type === "MemberExpression")
13
+ return deltaNames.includes(propertyName(node) ?? "");
14
+ if (node.type === "CallExpression" && calledMethod(node) === "get" && node.callee.type === "MemberExpression") {
15
+ const receiver = unwrap(node.callee.object);
16
+ return receiver.type === "MemberExpression" && deltaNames.includes(propertyName(receiver) ?? "");
17
+ }
18
+ return false;
19
+ };
20
+ /** Whether `node` reads a stored value (a local or a field), the thing a timer counts. */
21
+ const isStored = (raw) => {
22
+ const node = unwrap(raw);
23
+ return (node.type === "Identifier" || node.type === "MemberExpression") && !isDelta(node);
24
+ };
25
+ /**
26
+ * A timer in simulation code is a deadline in steps, never a float counted
27
+ * down (or up) by `dt`: the float drifts, and the value it saves means
28
+ * nothing once the fixed step changes.
29
+ */
30
+ export default defineRule({
31
+ meta: {
32
+ type: "problem",
33
+ docs: {
34
+ description: "Keep timers and cooldowns as Clock deadlines in steps, not floats counted by dt.",
35
+ url: docsUrl("no-float-timers")
36
+ },
37
+ messages: {
38
+ floatTimer: "`{{text}}` counts a timer by `dt` in floating point: rounding error builds up each tick, so it ends a step early or late, and the float it saves means nothing once the fixed step changes. Store the step it ends on instead: `ready: Clock.deadline(time, Clock.duration(step, seconds))` in the component or resource (its schema narrows with `Clock.isDeadline(step)`), and check `Clock.reached(time, ready)` each tick (`Clock.remaining(time, ready)` for a readout, `Clock.every(time, duration)` for something that repeats, `Clock.elapsed(time)` for seconds since the start)."
39
+ },
40
+ schema: []
41
+ },
42
+ create(context) {
43
+ const report = (node) => context.report({ node, messageId: "floatTimer", data: { text: context.sourceCode.getText(node) } });
44
+ return {
45
+ AssignmentExpression(node) {
46
+ // `timer -= dt`, `elapsed += time.dt`
47
+ if ((node.operator === "-=" || node.operator === "+=") && isDelta(node.right))
48
+ report(node);
49
+ },
50
+ BinaryExpression(node) {
51
+ // `cooldown.remaining - dt`, `time.dt + since`; `x + vx * dt` scales dt, so it is integration.
52
+ if (node.operator !== "-" && node.operator !== "+")
53
+ return;
54
+ if ((isDelta(node.right) && isStored(node.left)) || (isDelta(node.left) && isStored(node.right)))
55
+ report(node);
56
+ }
57
+ };
58
+ }
59
+ });
60
+ //# sourceMappingURL=no-float-timers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"no-float-timers.js","sourceRoot":"","sources":["../../src/rules/no-float-timers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAG5C,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAExE,oHAAoH;AACpH,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,WAAW,EAAE,cAAc,CAAC,CAAA;AAEtD,qFAAqF;AACrF,MAAM,MAAM,GAAG,CAAC,IAAiB,EAAe,EAAE,CAChD,IAAI,CAAC,IAAI,KAAK,gBAAgB,IAAI,IAAI,CAAC,IAAI,KAAK,qBAAqB,IAAI,IAAI,CAAC,IAAI,KAAK,uBAAuB,CAAC,CAAC,CAAC,MAAM,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/F,GAAG,EAAE,OAAO,CAAC,iBAAiB,CAAC;SAChC;QACD,QAAQ,EAAE;YACR,UAAU,EACR,4jBAA4jB;SAC/jB;QACD,MAAM,EAAE,EAAE;KACX;IACD,MAAM,CAAC,OAAO;QACZ,MAAM,MAAM,GAAG,CAAC,IAAiB,EAAE,EAAE,CACnC,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,YAAY,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,CAAA;QACrG,OAAO;YACL,oBAAoB,CAAC,IAAI;gBACvB,sCAAsC;gBACtC,IAAI,CAAC,IAAI,CAAC,QAAQ,KAAK,IAAI,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC;oBAAE,MAAM,CAAC,IAAI,CAAC,CAAA;YAC7F,CAAC;YACD,gBAAgB,CAAC,IAAI;gBACnB,+FAA+F;gBAC/F,IAAI,IAAI,CAAC,QAAQ,KAAK,GAAG,IAAI,IAAI,CAAC,QAAQ,KAAK,GAAG;oBAAE,OAAM;gBAC1D,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;oBAAE,MAAM,CAAC,IAAI,CAAC,CAAA;YAChH,CAAC;SACF,CAAA;IACH,CAAC;CACF,CAAC,CAAA"}
@@ -14,7 +14,7 @@ export default defineRule({
14
14
  },
15
15
  messages: {
16
16
  wallClock: "{{call}} reads the wall clock, so the simulation plays differently on every run and replays diverge. For time since the start, read the Clock resource (`Clock.elapsed(time)` in seconds, `time.step` in steps). For today's date, read it in host code and pass it in with `runtime.send(...)` or a resource, so the replay records it.",
17
- timer: "{{call}}() runs its callback outside the tick, at a moment a replay cannot reproduce. Count steps instead: store the step it fires at (`time.step + Clock.steps(Clock.duration(step, seconds))`) in a component or resource and compare it each tick, or use `Clock.every(time, duration)` for something that repeats."
17
+ timer: "{{call}}() runs its callback outside the tick, at a moment a replay cannot reproduce. Count steps instead: store the step it fires at (`Clock.deadline(time, Clock.duration(step, seconds))`) in a component or resource and check it each tick with `Clock.reached(time, due)`, or use `Clock.every(time, duration)` for something that repeats."
18
18
  },
19
19
  schema: []
20
20
  },
@@ -1 +1 @@
1
- {"version":3,"file":"use-clock-for-time.js","sourceRoot":"","sources":["../../src/rules/use-clock-for-time.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAE5C,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AAEjG,MAAM,MAAM,GAAG,CAAC,YAAY,EAAE,aAAa,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,gBAAgB,CAAC,CAAA;AAE9G;;;GAGG;AACH,eAAe,UAAU,CAAC;IACxB,IAAI,EAAE;QACJ,IAAI,EAAE,SAAS;QACf,IAAI,EAAE;YACJ,WAAW,EAAE,0FAA0F;YACvG,GAAG,EAAE,OAAO,CAAC,oBAAoB,CAAC;SACnC;QACD,QAAQ,EAAE;YACR,SAAS,EACP,0UAA0U;YAC5U,KAAK,EACH,wTAAwT;SAC3T;QACD,MAAM,EAAE,EAAE;KACX;IACD,MAAM,CAAC,OAAO;QACZ,OAAO;YACL,gBAAgB,CAAC,IAAI;gBACnB,KAAK,MAAM,MAAM,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,EAAE,CAAC;oBAC7C,IAAI,YAAY,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,KAAK,KAAK,EAAE,CAAC;wBAClD,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,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,OAAO,EAAE,MAAM,CAAC;oBAAE,OAAM;gBAC/C,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,CAAA;YAC3E,CAAC;SACF,CAAA;IACH,CAAC;CACF,CAAC,CAAA"}
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Simulation code uses `Ops` from `@typeonce/ritmo-math` for the math
3
- * functions engines may approximate, so every device computes the same bits.
2
+ * Simulation code uses `Ops` from `@typeonce/ritmo` for the math functions
3
+ * engines may approximate, so every device computes the same bits.
4
4
  */
5
5
  declare const _default: import("@oxlint/plugins").Rule;
6
6
  export default _default;
@@ -1 +1 @@
1
- {"version":3,"file":"use-ops-for-math.d.ts","sourceRoot":"","sources":["../../src/rules/use-ops-for-math.ts"],"names":[],"mappings":"AA4BA;;;GAGG"}
1
+ {"version":3,"file":"use-ops-for-math.d.ts","sourceRoot":"","sources":["../../src/rules/use-ops-for-math.ts"],"names":[],"mappings":"AAsFA;;;GAGG"}