@sister.software/oxlint-config 9.2.0 → 10.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.
package/src/index.ts CHANGED
@@ -12,6 +12,76 @@ export * from "./restrictions.js"
12
12
  /** An oxlint configuration object, as consumed by `oxlint.config.ts` / `.oxlintrc.json`. */
13
13
  export type OxlintConfig = Record<string, unknown>
14
14
 
15
+ /** Numeric ceilings for the legibility-guardrail rules. Each is a hard ceiling, not a target. */
16
+ export interface OxlintConfigLimits {
17
+ /** Maximum block nesting depth. */
18
+ maxDepth: number
19
+ /** Maximum parameters on a single function. */
20
+ maxParams: number
21
+ /** Maximum statements in a single function body. */
22
+ maxStatements: number
23
+ /** Maximum lines in a single function body, blank lines and comments excluded. */
24
+ maxLinesPerFunction: number
25
+ /** Maximum lines in a single file, blank lines and comments excluded. */
26
+ maxLines: number
27
+ /** Maximum nested callback depth. */
28
+ maxNestedCallbacks: number
29
+ /** Maximum nested call-expression depth, e.g. `a(b(c(d())))`. */
30
+ maxNestedCalls: number
31
+ /** Maximum cyclomatic complexity of a single function. */
32
+ complexity: number
33
+ }
34
+
35
+ /**
36
+ * Calibrated against the mailwoman corpus (1,048 non-test source files). Each value sits just past the knee in that
37
+ * repo's distribution, so considered human code stays silent and runaway generation does not. See the design spec for
38
+ * the full sweep.
39
+ *
40
+ * The four SIZE ceilings are deliberately looser than the knee. Adopting v10 surfaced 172 pre-existing violations, and
41
+ * splitting that many functions across a parser — with no accuracy gate available to verify the result — is a larger
42
+ * risk than the legibility it buys. They are set at the p90 of the measured overage instead, so the worst decile had to
43
+ * be fixed at adoption while the body was grandfathered:
44
+ *
45
+ * max-statements n=88 median= 73 p90= 115 max= 272
46
+ * complexity n=32 median= 49 p90= 84 max= 173
47
+ * max-lines-per-function n=26 median=283 p90= 829 max=1329
48
+ * max-params n=15 median= 7 p90= 8 max= 10
49
+ *
50
+ * RATCHET THESE DOWN as the grandfathered functions are split. They exist to stop new code drifting, and every step
51
+ * toward the knee makes them do more of that job.
52
+ */
53
+ export const DefaultLimits: OxlintConfigLimits = {
54
+ maxDepth: 5,
55
+ maxParams: 8,
56
+ maxStatements: 115,
57
+ maxLinesPerFunction: 830,
58
+ maxLines: 750,
59
+ maxNestedCallbacks: 4,
60
+ maxNestedCalls: 4,
61
+ complexity: 85,
62
+ }
63
+
64
+ /** Globs treated as test files, where the size and named-constant rules are switched off. */
65
+ export const DefaultTestFilePatterns = [
66
+ "**/*.test.ts",
67
+ "**/*.test.tsx",
68
+ "**/test/**",
69
+ "**/fixtures/**",
70
+ "**/*.bench.ts",
71
+ // Storybook stories are fixtures in the same sense: each export is a rendered case, and its NAME is
72
+ // the label shown in the sidebar. A JSDoc block on `export const Default: Story = {}` says nothing
73
+ // the name does not.
74
+ "**/*.stories.ts",
75
+ "**/*.stories.tsx",
76
+ ]
77
+
78
+ /**
79
+ * Globs whose contents are emitted by a generator, not written by hand. The size ceilings are meaningless there — the
80
+ * file is as long as its input is wide, and no reviewer reads it top to bottom — but every correctness rule still
81
+ * applies, because generated code ships.
82
+ */
83
+ export const DefaultGeneratedFilePatterns = ["**/*.gen.ts", "**/*.gen.tsx", "**/*.generated.ts", "**/generated/**"]
84
+
15
85
  /** Options for {@link createOxlintConfig}. */
16
86
  export interface OxlintConfigOptions {
17
87
  /** The package namespace whose runtime boundaries are enforced, e.g. `@sister.software`. */
@@ -30,13 +100,36 @@ export interface OxlintConfigOptions {
30
100
  padding?: boolean
31
101
  /** Require braces around single-statement work bodies (bare `return` exempt; on by default). */
32
102
  braces?: boolean
103
+ /**
104
+ * Forbid direct `process.env` / `process.argv` access (off by default). Turn on once the project funnels those reads
105
+ * through blessed helpers, which disable `sister-software/no-process-globals`.
106
+ */
107
+ restrictProcessGlobals?: boolean
108
+ /**
109
+ * Flag numeric literals used as comparison thresholds (off by default). Pass an object to change the ignore list or
110
+ * to stop exempting radix-prefixed literals.
111
+ */
112
+ unnamedThresholds?: boolean | { ignore?: number[]; allowHex?: boolean }
113
+ /**
114
+ * Require a JSDoc block on module-level constants (off by default). `scope` selects which ones: `"exported"`,
115
+ * `"screaming"`, or the default `"exported-or-screaming"`.
116
+ */
117
+ constantDocs?: boolean | { scope?: "exported" | "screaming" | "exported-or-screaming" }
118
+ /** Rewrite explicit length comparisons to truthiness in boolean positions (on by default). */
119
+ lengthTruthiness?: boolean
120
+ /** Override individual legibility ceilings. Unspecified keys keep their calibrated default. */
121
+ limits?: Partial<OxlintConfigLimits>
122
+ /** Replace the globs treated as test files. */
123
+ testFilePatterns?: string[]
124
+ /** Replace the globs treated as generated files, where only the size ceilings are switched off. */
125
+ generatedFilePatterns?: string[]
33
126
  /** Override the default ignore patterns. */
34
127
  ignorePatterns?: string[]
35
128
  /** Extra config deep-merged last; an escape hatch for per-repo tweaks. */
36
129
  overrides?: OxlintConfig
37
130
  }
38
131
 
39
- /** Default ignore patterns for generated/build output. */
132
+ /** Default ignore patterns for generated/build output and vendored tooling. */
40
133
  export const DefaultIgnorePatterns = [
41
134
  "**/out",
42
135
  "**/dist",
@@ -44,6 +137,9 @@ export const DefaultIgnorePatterns = [
44
137
  "**/node_modules",
45
138
  "**/coverage",
46
139
  "**/storybook-static",
140
+ // Yarn 4 vendors its own release bundle and plugin code here. It is third-party, minified, and
141
+ // not ours to lint — Tier 2's `no-abusive-eslint-disable` fires on it otherwise.
142
+ "**/.yarn/**",
47
143
  ]
48
144
 
49
145
  /**
@@ -70,18 +166,26 @@ export function createOxlintConfig(options: OxlintConfigOptions = {}): OxlintCon
70
166
  headers = true,
71
167
  padding = true,
72
168
  braces = true,
169
+ restrictProcessGlobals = false,
170
+ unnamedThresholds = false,
171
+ constantDocs = false,
172
+ lengthTruthiness = true,
173
+ limits: limitOverrides = {},
174
+ testFilePatterns = DefaultTestFilePatterns,
175
+ generatedFilePatterns = DefaultGeneratedFilePatterns,
73
176
  ignorePatterns = DefaultIgnorePatterns,
74
177
  overrides = {},
75
178
  } = options
76
179
 
77
- const plugins = ["typescript", "unicorn", "oxc", ...(react ? ["react"] : [])]
180
+ const limits: OxlintConfigLimits = { ...DefaultLimits, ...limitOverrides }
181
+
182
+ const plugins = ["typescript", "unicorn", "oxc", "import", "promise", "vitest", ...(react ? ["react"] : [])]
78
183
 
79
184
  const rules: Record<string, unknown> = {
80
185
  // JavaScript
81
186
  eqeqeq: ["error", "always", { null: "ignore" }],
82
187
  "prefer-const": "warn",
83
188
  "object-shorthand": ["warn", "always"],
84
- "no-shadow": "off",
85
189
  "no-undef": "off",
86
190
  "no-unused-vars": [
87
191
  "warn",
@@ -107,6 +211,191 @@ export function createOxlintConfig(options: OxlintConfigOptions = {}): OxlintCon
107
211
  "typescript/no-non-null-assertion": "off",
108
212
  "typescript/no-var-requires": "off",
109
213
  "typescript/no-require-imports": "off",
214
+
215
+ // Tier 1 — legibility guardrails. Thresholds are ceilings past the knee of the calibration
216
+ // corpus's distribution: they stay silent on considered code and fire on runaway generation.
217
+ "max-depth": ["error", { max: limits.maxDepth }],
218
+ "max-params": ["error", { max: limits.maxParams }],
219
+ "max-statements": ["error", { max: limits.maxStatements }],
220
+ "max-lines-per-function": ["error", { max: limits.maxLinesPerFunction, skipBlankLines: true, skipComments: true }],
221
+ "max-lines": ["error", { max: limits.maxLines, skipBlankLines: true, skipComments: true }],
222
+ "max-nested-callbacks": ["error", { max: limits.maxNestedCallbacks }],
223
+ "unicorn/max-nested-calls": ["error", { max: limits.maxNestedCalls }],
224
+ complexity: ["error", limits.complexity],
225
+ "unicorn/no-array-reduce": "error",
226
+ "unicorn/no-unreadable-array-destructuring": "error",
227
+
228
+ // Tier 2 — defect classes that `correctness` does not cover. Every rule here corresponds to a
229
+ // way working-looking code is wrong at runtime.
230
+ "no-shadow": "error",
231
+ "no-promise-executor-return": "error",
232
+ "no-useless-assignment": "error",
233
+ "no-unreachable-loop": "error",
234
+ "no-unmodified-loop-condition": "error",
235
+ "no-loop-func": "error",
236
+ // `.sort()` and `.reverse()` mutate in place; on a shared or cached array that is a bug at a
237
+ // distance. The fixes are `toSorted()` / `toReversed()`.
238
+ "unicorn/no-array-sort": "error",
239
+ "unicorn/no-array-reverse": "error",
240
+ "unicorn/no-immediate-mutation": "error",
241
+ "unicorn/no-array-method-this-argument": "error",
242
+ "unicorn/no-typeof-undefined": "error",
243
+ "unicorn/no-useless-promise-resolve-reject": "error",
244
+ "unicorn/prefer-type-error": "error",
245
+ // Global `isNaN` coerces its argument; `Number.isNaN` does not.
246
+ "unicorn/prefer-number-properties": "error",
247
+ "unicorn/no-abusive-eslint-disable": "error",
248
+ // Off despite the name: it fires on `.map(x => ({ ...x, field }))`, which is O(n·k) overall and the
249
+ // ordinary way to add a field. The quadratic accumulation worth catching is `acc = { ...acc, x }`
250
+ // inside a reduce, which this does not distinguish. 14 sites, 14 false positives.
251
+ "oxc/no-map-spread": "off",
252
+ "oxc/bad-bitwise-operator": "error",
253
+ "oxc/branches-sharing-code": "error",
254
+ "typescript/no-dynamic-delete": "error",
255
+ "typescript/prefer-ts-expect-error": "error",
256
+ // A cycle here is not a style issue: it leaves bindings unevaluated at import time, which
257
+ // surfaces as a base class that is `undefined` at class-definition time.
258
+ "import/no-cycle": "error",
259
+ // `ignoreLastCallback` keeps the rule pointed at CHAINS, where a missing return silently feeds
260
+ // undefined to the next link. A terminal `.then(…)` doing side effects has nothing downstream
261
+ // to starve, and rewriting those adds a return whose value no one reads.
262
+ "promise/always-return": ["error", { ignoreLastCallback: true }],
263
+ // Off: it cannot see that a ternary settles exactly once. `cb((err) => (err ? reject(err) : resolve()))`
264
+ // is the standard way to bridge a node-style callback to a promise, and the rule flagged every
265
+ // instance of it on the calibration corpus — 6 sites, 6 false positives, no real double-settle.
266
+ "promise/no-multiple-resolved": "off",
267
+
268
+ // Tier 3 — test discipline. `expect-expect` is the one that matters most: it catches a test
269
+ // that runs, passes, and asserts nothing.
270
+ "vitest/expect-expect": "error",
271
+ // vitest's `expect(value, message)` takes an optional assertion message as a second argument —
272
+ // the rule's default of one would flag the API's own signature.
273
+ "vitest/valid-expect": ["error", { maxArgs: 2 }],
274
+ "vitest/valid-title": "error",
275
+ "vitest/valid-describe-callback": "error",
276
+ // Off: the dominant shape it flags is a parameterized assertion helper, where the conditional IS
277
+ // the contract — `expectProposal(out, { kind, body, minConfidence? })` asserts only what the
278
+ // caller specified. 33 sites on the calibration corpus, none a hidden never-running assertion.
279
+ "vitest/no-conditional-expect": "off",
280
+ "vitest/no-conditional-tests": "error",
281
+ "vitest/no-disabled-tests": "error",
282
+ "vitest/no-commented-out-tests": "error",
283
+ "vitest/no-alias-methods": "error",
284
+ "vitest/prefer-to-be": "error",
285
+ "vitest/prefer-to-have-length": "error",
286
+ "vitest/prefer-to-contain": "error",
287
+ "vitest/require-to-throw-message": "error",
288
+ // Playwright names its e2e specs `*.spec.ts`; vitest unit tests are `*.test.ts`. A repo running
289
+ // both has two legitimate conventions, so the rule is scoped to the vitest ones.
290
+ "vitest/consistent-test-filename": ["error", { allTestPattern: String.raw`.*\.test\.[tj]sx?$` }],
291
+ // Enabling a plugin also activates its `correctness`-category rules, so a rule this tier turned
292
+ // down must be switched off explicitly rather than merely left out of the list above.
293
+ "vitest/require-mock-type-parameters": "off",
294
+ "vitest/no-conditional-in-test": "off",
295
+
296
+ // Tier 4 — mechanical hygiene. All autofixable, none requiring judgment.
297
+ // Literal form.
298
+ "unicorn/numeric-separators-style": "error",
299
+ "unicorn/no-zero-fractions": "error",
300
+ "unicorn/text-encoding-identifier-case": "error",
301
+ "unicorn/escape-case": "error",
302
+ "unicorn/no-hex-escape": "error",
303
+ // Import discipline.
304
+ // `disallowTypeAnnotations: false` keeps the valuable half — a type-only import must be written
305
+ // `import type` — while allowing `typeof import("…")` in an annotation. That form is how a
306
+ // guarded dynamic import is typed: the module is optional and loaded at runtime, and the inline
307
+ // annotation is what says so. `import type` would erase to nothing and read as a hard dep.
308
+ "typescript/consistent-type-imports": ["error", { disallowTypeAnnotations: false }],
309
+ "typescript/no-import-type-side-effects": "error",
310
+ "unicorn/prefer-export-from": "error",
311
+ "import/no-duplicates": "error",
312
+ "import/first": "error",
313
+ "import/newline-after-import": "error",
314
+ // Modern API preference.
315
+ "unicorn/prefer-string-replace-all": "error",
316
+ // `caught` is permitted alongside `error`: when a catch sits inside a scope that already binds
317
+ // `error` (a React component's error state, say), no-shadow requires a different name and this
318
+ // rule would otherwise demand the shadowing one. The two rules are in direct conflict without it.
319
+ "unicorn/catch-error-name": ["error", { ignore: ["caught"] }],
320
+ "unicorn/prefer-at": "error",
321
+ "unicorn/prefer-global-this": "error",
322
+ "unicorn/consistent-existence-index-check": "error",
323
+ "unicorn/new-for-builtins": "error",
324
+ "unicorn/prefer-array-find": "error",
325
+ "unicorn/prefer-structured-clone": "error",
326
+ "unicorn/prefer-negative-index": "error",
327
+ "unicorn/prefer-math-min-max": "error",
328
+ "unicorn/no-useless-collection-argument": "error",
329
+ "unicorn/throw-new-error": "error",
330
+ // Two rules that look mechanical but are not type-safe, so they stay off:
331
+ //
332
+ // `unicorn/prefer-code-point` rewrites `charCodeAt` to `codePointAt`, which returns
333
+ // `number | undefined`. It exists for surrogate-pair correctness, but on the ASCII arithmetic
334
+ // where it usually fires it buys nothing and forces an undefined branch at every site.
335
+ //
336
+ // `unicorn/no-useless-undefined` drops an explicitly-passed `undefined` argument. oxlint has no
337
+ // type information, so it cannot tell an optional parameter from a required one and will
338
+ // silently turn `f(a, undefined)` into a call that no longer type-checks.
339
+ //
340
+ // `unicorn/prefer-string-raw` rewrites a string literal to a String.raw template. That is
341
+ // runtime-identical but not type-identical: the literal type is lost, so any template-literal
342
+ // type built from the value collapses. It widens types silently, which is worse than the
343
+ // escaped backslashes it removes.
344
+ "unicorn/prefer-code-point": "off",
345
+ "unicorn/no-useless-undefined": "off",
346
+ "unicorn/prefer-string-raw": "off",
347
+ //
348
+ // `unicorn/prefer-math-trunc` is the one that is not merely type-unsafe but semantically wrong.
349
+ // `x | 0` and `x >>> 0` are int32/uint32 coercion, and the wrapping is the point — every site on
350
+ // the calibration corpus was a hash function, a PRNG, or a seeded evaluation harness.
351
+ // `Math.trunc` does not wrap, so taking its suggestion silently changes what those produce.
352
+ "unicorn/prefer-math-trunc": "off",
353
+ //
354
+ // `unicorn/prefer-number-coercion` rewrites `Number.parseInt(x, 10)` to
355
+ // `Math.trunc(Number(x))`. parseInt parses a numeric PREFIX; Number is strict, so
356
+ // `parseInt("12px", 10)` is 12 where `Number("12px")` is NaN. On the calibration corpus the
357
+ // inputs included CLI options and an HTTP status of uncertain type — exactly where the
358
+ // difference bites. It also reintroduces Math.trunc, disabled just above.
359
+ "unicorn/prefer-number-coercion": "off",
360
+ //
361
+ // These two are not unsafe — they are unsatisfiable. oxfmt reverts both fixes on its next run:
362
+ // it lowercases hex digits, and it strips the parentheses unicorn/no-nested-ternary adds. Lint
363
+ // and format are both CI gates, so a rule the formatter undoes can never go green. Neither
364
+ // behaviour is configurable in oxfmt today.
365
+ "unicorn/number-literal-case": "off",
366
+ "unicorn/no-nested-ternary": "off",
367
+ //
368
+ // `unicorn/explicit-length-check` enforces `x.length > 0`, the opposite of the house
369
+ // convention. `sister-software/prefer-length-truthiness` enforces ours.
370
+ "unicorn/explicit-length-check": "off",
371
+ //
372
+ // Core `no-duplicate-imports` is not TypeScript-aware: it counts a value import and an
373
+ // `import type` from the same module as a duplicate, which is the split
374
+ // `typescript/consistent-type-imports` exists to create. On the calibration corpus it reported
375
+ // 71 sites where the TS-aware `import/no-duplicates` reported 1, and that 1 was real.
376
+ "no-duplicate-imports": "off",
377
+
378
+ // TS style.
379
+ "typescript/consistent-type-definitions": "error",
380
+ "typescript/consistent-indexed-object-style": "error",
381
+ "typescript/prefer-for-of": "error",
382
+ "typescript/no-inferrable-types": "error",
383
+ // Small structural.
384
+ "unicorn/prefer-ternary": "error",
385
+ "unicorn/prefer-logical-operator-over-ternary": "error",
386
+ "unicorn/no-lonely-if": "error",
387
+ "unicorn/no-console-spaces": "error",
388
+ "unicorn/no-static-only-class": "error",
389
+ "no-useless-return": "error",
390
+ }
391
+
392
+ if (react) {
393
+ rules["react-hooks/rules-of-hooks"] = "error"
394
+ rules["react/no-unstable-nested-components"] = "error"
395
+ rules["react/no-object-type-as-default-prop"] = "error"
396
+ rules["react/jsx-no-constructed-context-values"] = "error"
397
+ // The automatic JSX runtime made this obsolete; the rule predates it.
398
+ rules["react/react-in-jsx-scope"] = "off"
110
399
  }
111
400
 
112
401
  if (headers) {
@@ -125,13 +414,73 @@ export function createOxlintConfig(options: OxlintConfigOptions = {}): OxlintCon
125
414
  rules["sister-software/require-braces"] = "warn"
126
415
  }
127
416
 
417
+ if (restrictProcessGlobals) {
418
+ // Error severity: a governance gate — direct env/argv access should fail the lint.
419
+ rules["sister-software/no-process-globals"] = "error"
420
+ }
421
+
422
+ if (unnamedThresholds) {
423
+ // Error severity: an unnamed threshold is a legibility defect, not a style preference.
424
+ rules["sister-software/no-unnamed-threshold"] = [
425
+ "error",
426
+ typeof unnamedThresholds === "object" ? unnamedThresholds : {},
427
+ ]
428
+ }
429
+
430
+ if (constantDocs) {
431
+ // Error severity: an undocumented public constant or tuning knob is a legibility defect.
432
+ rules["sister-software/require-constant-doc"] = ["error", typeof constantDocs === "object" ? constantDocs : {}]
433
+ }
434
+
435
+ if (lengthTruthiness) {
436
+ rules["sister-software/prefer-length-truthiness"] = "error"
437
+ }
438
+
439
+ // Rules switched off inside test files. Table-driven test bodies are legitimately long, and
440
+ // expected values are legitimately unnamed numbers. oxlint validates override entries against the
441
+ // registered rule set, so an entry may only name a rule this config actually turned on.
442
+ const testFileRules: Record<string, unknown> = {
443
+ "max-lines-per-function": "off",
444
+ "max-statements": "off",
445
+ "max-lines": "off",
446
+ }
447
+
448
+ if (react) {
449
+ // A Storybook `render` IS a component — React calls it as one — but it is not NAMED like one, so
450
+ // the hook rules read it as a plain function. Test files that render hooks go through a
451
+ // testing-library wrapper for the same reason.
452
+ testFileRules["react-hooks/rules-of-hooks"] = "off"
453
+ }
454
+
455
+ if (unnamedThresholds) {
456
+ testFileRules["sister-software/no-unnamed-threshold"] = "off"
457
+ }
458
+
459
+ if (constantDocs) {
460
+ testFileRules["sister-software/require-constant-doc"] = "off"
461
+ }
462
+
463
+ /** Generated files: size ceilings only. Everything else still applies — generated code ships. */
464
+ const generatedFileRules: Record<string, unknown> = {
465
+ "max-lines": "off",
466
+ "max-lines-per-function": "off",
467
+ "max-statements": "off",
468
+ complexity: "off",
469
+ }
470
+
128
471
  return {
129
472
  plugins,
130
- ...(headers || padding || braces ? { jsPlugins: ["@sister.software/oxlint-config/plugin"] } : {}),
473
+ ...(headers || padding || braces || restrictProcessGlobals || unnamedThresholds || constantDocs || lengthTruthiness
474
+ ? { jsPlugins: ["@sister.software/oxlint-config/plugin"] }
475
+ : {}),
131
476
  categories: { correctness: "error" },
132
477
  ignorePatterns,
133
478
  rules,
134
- overrides: createRuntimeOverrides(packageNamespace),
479
+ overrides: [
480
+ ...createRuntimeOverrides(packageNamespace),
481
+ { files: testFilePatterns, rules: testFileRules },
482
+ { files: generatedFilePatterns, rules: generatedFileRules },
483
+ ],
135
484
  ...overrides,
136
485
  }
137
486
  }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file A prefer-length-truthiness rule, authored as an oxlint JS plugin (ESLint v9-compatible API).
6
+ * It is the house counterpart to `unicorn/explicit-length-check`, which enforces the opposite
7
+ * convention and is therefore off: `if (items.length)` reads better here than
8
+ * `if (items.length > 0)`.
9
+ *
10
+ * The rule only fires where the value is ALREADY coerced to a boolean — a condition, a ternary
11
+ * test, or the operand of `!` — including through `&&`/`||` nested inside one. Outside those
12
+ * positions the comparison is the value itself, and rewriting `const hasItems = items.length > 0`
13
+ * would silently change its type from boolean to number.
14
+ */
15
+
16
+ import type { AstNode, Fixer, Rule, RuleContext } from "./plugin-types.js"
17
+
18
+ /** Comparisons meaning "non-empty", which become the bare length. */
19
+ const TRUTHY_FORMS = new Set(["> 0", "!== 0", "!= 0", ">= 1"])
20
+
21
+ /** Comparisons meaning "empty", which become a negated length. */
22
+ const FALSY_FORMS = new Set(["=== 0", "== 0", "< 1"])
23
+
24
+ /** Members whose length-ness the rule understands. */
25
+ const LENGTH_PROPERTIES = new Set(["length", "size"])
26
+
27
+ /** The comparison rendered as `<operator> <literal>`, or null when it is not a length comparison. */
28
+ function classify(node: AstNode): { member: AstNode; negate: boolean } | null {
29
+ if (node.type !== "BinaryExpression" || !node.operator || !node.left || !node.right) return null
30
+
31
+ // Accept both `x.length > 0` and the flipped `0 < x.length`.
32
+ const flipped: Record<string, string> = { "<": ">", ">": "<", "<=": ">=", ">=": "<=" }
33
+ let { left, right, operator } = { left: node.left, right: node.right, operator: node.operator }
34
+
35
+ if (left.type === "Literal" || left.type === "NumericLiteral") {
36
+ ;[left, right] = [right, left]
37
+ operator = flipped[operator] ?? operator
38
+ }
39
+
40
+ if (left.type !== "MemberExpression" && left.type !== "StaticMemberExpression") return null
41
+
42
+ const property = (left as AstNode & { property?: AstNode }).property
43
+
44
+ if (!property || property.type !== "Identifier" || !LENGTH_PROPERTIES.has(property.name ?? "")) return null
45
+
46
+ if (right.type !== "Literal" && right.type !== "NumericLiteral") return null
47
+
48
+ if (typeof right.value !== "number") return null
49
+
50
+ const form = `${operator} ${right.value}`
51
+
52
+ if (TRUTHY_FORMS.has(form)) return { member: left, negate: false }
53
+
54
+ if (FALSY_FORMS.has(form)) return { member: left, negate: true }
55
+
56
+ return null
57
+ }
58
+
59
+ export const preferLengthTruthinessRule: Rule = {
60
+ meta: {
61
+ name: "prefer-length-truthiness",
62
+ type: "suggestion",
63
+ fixable: "code",
64
+ schema: [{ type: "object", additionalProperties: true }],
65
+ },
66
+ create(context: RuleContext) {
67
+ const sourceCode = context.sourceCode ?? context.getSourceCode!()
68
+ const text = sourceCode.getText()
69
+
70
+ function report(node: AstNode) {
71
+ const hit = classify(node)
72
+
73
+ if (!hit) return
74
+
75
+ const member = text.slice(hit.member.range[0], hit.member.range[1])
76
+ const replacement = hit.negate ? `!${member}` : member
77
+
78
+ context.report({
79
+ node,
80
+ message: `Prefer \`${replacement}\` over an explicit length comparison — the house convention is truthiness.`,
81
+ fix(fixer: Fixer) {
82
+ return fixer.replaceTextRange(node.range, replacement)
83
+ },
84
+ })
85
+ }
86
+
87
+ /** Walk into a boolean context: logical operands and `!` arguments stay boolean. */
88
+ function visitCondition(node: AstNode | null | undefined) {
89
+ if (!node) return
90
+
91
+ if (node.type === "LogicalExpression") {
92
+ visitCondition(node.left)
93
+ visitCondition(node.right)
94
+
95
+ return
96
+ }
97
+
98
+ if (node.type === "UnaryExpression" && node.operator === "!") {
99
+ visitCondition(node.argument)
100
+
101
+ return
102
+ }
103
+
104
+ report(node)
105
+ }
106
+
107
+ return {
108
+ IfStatement(node) {
109
+ visitCondition(node.test)
110
+ },
111
+ WhileStatement(node) {
112
+ visitCondition(node.test)
113
+ },
114
+ DoWhileStatement(node) {
115
+ visitCondition(node.test)
116
+ },
117
+ ForStatement(node) {
118
+ visitCondition(node.test)
119
+ },
120
+ ConditionalExpression(node) {
121
+ visitCondition(node.test)
122
+ },
123
+ UnaryExpression(node) {
124
+ if (node.operator === "!") {
125
+ visitCondition(node.argument)
126
+ }
127
+ },
128
+ }
129
+ },
130
+ }
131
+
132
+ export default preferLengthTruthinessRule
@@ -22,6 +22,29 @@ export interface AstNode {
22
22
  /** `if`/`else` branches, for the require-braces rule. */
23
23
  consequent?: AstNode
24
24
  alternate?: AstNode | null
25
+ /** Binary/unary operator text, for the threshold rule. */
26
+ operator?: string
27
+ /** Binary-expression operands. */
28
+ left?: AstNode
29
+ right?: AstNode
30
+ /** Unary-expression operand. */
31
+ argument?: AstNode
32
+ /** A literal's value, and its verbatim source text (`raw` preserves a `0x` prefix). */
33
+ value?: unknown
34
+ raw?: string
35
+ /** `const` / `let` / `var`, for the constant-doc rule. */
36
+ kind?: string
37
+ /** Declarators of a variable declaration. */
38
+ declarations?: AstNode[]
39
+ /** A declarator's binding identifier and initializer. */
40
+ id?: AstNode
41
+ init?: AstNode | null
42
+ /** An identifier's name. */
43
+ name?: string
44
+ /** The condition of an `if`/`while`/`for`/ternary, for the length-truthiness rule. */
45
+ test?: AstNode | null
46
+ /** A member expression's accessed property. */
47
+ property?: AstNode
25
48
  }
26
49
 
27
50
  export interface SourceCode {
package/src/plugin.ts CHANGED
@@ -7,9 +7,13 @@
7
7
  */
8
8
 
9
9
  import { bracesRule } from "./braces-plugin.js"
10
+ import { requireConstantDocRule } from "./constant-doc-plugin.js"
10
11
  import { headerRule } from "./headers-plugin.js"
12
+ import { preferLengthTruthinessRule } from "./length-truthiness-plugin.js"
11
13
  import { paddingRule } from "./padding-plugin.js"
12
14
  import type { Plugin } from "./plugin-types.js"
15
+ import { noProcessGlobalsRule } from "./process-globals-plugin.js"
16
+ import { noUnnamedThresholdRule } from "./threshold-plugin.js"
13
17
 
14
18
  const sisterSoftwarePlugin: Plugin = {
15
19
  meta: { name: "sister-software" },
@@ -17,6 +21,10 @@ const sisterSoftwarePlugin: Plugin = {
17
21
  "require-file-header": headerRule,
18
22
  "padding-lines": paddingRule,
19
23
  "require-braces": bracesRule,
24
+ "no-process-globals": noProcessGlobalsRule,
25
+ "no-unnamed-threshold": noUnnamedThresholdRule,
26
+ "require-constant-doc": requireConstantDocRule,
27
+ "prefer-length-truthiness": preferLengthTruthinessRule,
20
28
  },
21
29
  }
22
30
 
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file A no-process-globals rule, authored as an oxlint JS plugin (ESLint v9-compatible API). It
6
+ * forbids direct `process.env` / `process.argv` access so those reads can be funneled through a
7
+ * few blessed helpers; the helper files disable the rule (`sister-software/no-process-globals`).
8
+ * oxlint has no `no-restricted-syntax`, so this is a small dedicated rule instead.
9
+ */
10
+
11
+ import type { AstNode, Rule } from "./plugin-types.js"
12
+
13
+ /** `process` members that must be reached through a blessed helper, not accessed directly. */
14
+ const RESTRICTED_MEMBERS = new Set(["env", "argv"])
15
+
16
+ interface Identifierish extends AstNode {
17
+ name?: string
18
+ value?: unknown
19
+ }
20
+
21
+ interface MemberNode extends AstNode {
22
+ object?: Identifierish
23
+ property?: Identifierish
24
+ computed?: boolean
25
+ }
26
+
27
+ /** The accessed member name for `process.env` (identifier) or `process["env"]` (string literal). */
28
+ function accessedMember(node: MemberNode): string | null {
29
+ const property = node.property
30
+
31
+ if (!property) return null
32
+
33
+ if (!node.computed && property.type === "Identifier") return property.name ?? null
34
+
35
+ if (node.computed && (property.type === "Literal" || property.type === "StringLiteral")) {
36
+ return typeof property.value === "string" ? property.value : null
37
+ }
38
+
39
+ return null
40
+ }
41
+
42
+ export const noProcessGlobalsRule: Rule = {
43
+ meta: {
44
+ name: "no-process-globals",
45
+ type: "problem",
46
+ schema: [{ type: "object", additionalProperties: true }],
47
+ },
48
+ create(context) {
49
+ return {
50
+ MemberExpression(node) {
51
+ const member = node as MemberNode
52
+
53
+ if (member.object?.type !== "Identifier" || member.object.name !== "process") return
54
+
55
+ const name = accessedMember(member)
56
+
57
+ if (!name || !RESTRICTED_MEMBERS.has(name)) return
58
+
59
+ context.report({
60
+ node,
61
+ message: `Direct \`process.${name}\` access is restricted — read it through the project's blessed helper (disable \`sister-software/no-process-globals\` there).`,
62
+ })
63
+ },
64
+ }
65
+ },
66
+ }
67
+
68
+ export default noProcessGlobalsRule