@uinaf/oxlint-plugin-no-comments 0.0.0-stage → 0.1.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +60 -2
  3. package/dist/index.js +562 -0
  4. package/package.json +54 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 uinaf
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # @uinaf/oxlint-plugin-no-comments
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An Oxlint rule that bans code comments. Names, types, and tests carry intent;
4
+ the commit message carries the why.
5
+
6
+ ```ts
7
+ // Parse the id before saving. ✗ uinaf/no-comments
8
+ const id = parse(raw);
9
+
10
+ // SAFETY: parse() checked the brand. ✓ anti-slop requires it
11
+ const user = id as UserId;
12
+
13
+ /** Load a user by id. */ ✓ exported API docs
14
+ export function load(id: UserId) {}
15
+ ```
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pnpm add -D @uinaf/oxlint-plugin-no-comments
21
+ ```
22
+
23
+ `.oxlintrc.json`:
24
+
25
+ ```json
26
+ {
27
+ "jsPlugins": ["@uinaf/oxlint-plugin-no-comments"],
28
+ "rules": { "uinaf/no-comments": "error" }
29
+ }
30
+ ```
31
+
32
+ Vite+ (`vite.config.ts`):
33
+
34
+ ```ts
35
+ lint: {
36
+ jsPlugins: [{ name: "uinaf", specifier: "@uinaf/oxlint-plugin-no-comments" }],
37
+ rules: { "uinaf/no-comments": "error" },
38
+ }
39
+ ```
40
+
41
+ ## What stays
42
+
43
+ | Kind | Allowed |
44
+ | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
45
+ | Tool directives | `eslint-disable*`, `eslint-enable*`, `oxlint-disable*`, `oxlint-enable*`, `@ts-expect-error`, `@ts-ignore`, `@ts-nocheck`, `@ts-check`, `/// <reference …>`, `prettier-ignore`, `istanbul`/`c8`/`v8 ignore`, `node:coverage`, `@__PURE__`, `@__NO_SIDE_EFFECTS__`, `@vite-ignore`, `@vitest-environment` |
46
+ | License headers | `/*! … */`, `@license`, or `SPDX-*` before the first statement |
47
+ | API docs | The last JSDoc block before an exported declaration, or before a public member of an exported class, interface, type, or enum |
48
+ | Lint-required | `SAFETY:` comments that anti-slop's `require-safety-comment-for-type-assertion` accepts for a non-`const` type assertion |
49
+
50
+ Everything else is reported, including `TODO`, JSX comments, JSDoc on
51
+ internal code, and `SAFETY:` comments with no assertion to justify.
52
+
53
+ ## Options
54
+
55
+ ```json
56
+ ["error", { "allow": ["^webpackChunkName:"], "safetyMarkers": ["SAFETY"] }]
57
+ ```
58
+
59
+ - `allow`: regular expressions for extra directives. Each one is tested
60
+ against the comment text with leading `*` and spaces removed.
61
+ - `safetyMarkers`: keep equal to anti-slop's `markers` option.
package/dist/index.js ADDED
@@ -0,0 +1,562 @@
1
+ // node_modules/.pnpm/@oxlint+plugins@1.90.0/node_modules/@oxlint/plugins/index.js
2
+ /**
3
+ * Define a rule.
4
+ *
5
+ * No-op function, just to provide type safety. Input is passed through unchanged.
6
+ *
7
+ * @param rule - Rule to define
8
+ * @returns Same rule as passed in
9
+ */
10
+ function defineRule(rule) {
11
+ return rule;
12
+ }
13
+ const EMPTY_VISITOR = {};
14
+ /**
15
+ * Convert a plugin which used Oxlint's `createOnce` API to also work with ESLint.
16
+ *
17
+ * If any of the plugin's rules use the Oxlint alternative `createOnce` API,
18
+ * add ESLint-compatible `create` methods to those rules, which delegate to `createOnce`.
19
+ * This makes the plugin compatible with ESLint.
20
+ *
21
+ * The `plugin` object passed in is mutated in-place.
22
+ *
23
+ * @param plugin - Plugin to convert
24
+ * @returns Plugin with all rules having `create` method
25
+ * @throws {Error} If `plugin` is not an object, or `plugin.rules` is not an object
26
+ */
27
+ function eslintCompatPlugin(plugin) {
28
+ if (typeof plugin != "object" || !plugin) throw Error("Plugin must be an object");
29
+ let { rules } = plugin;
30
+ if (typeof rules != "object" || !rules) throw Error("Plugin must have an object as `rules` property");
31
+ let afterHooksState = new AfterHooksState();
32
+ for (let ruleName in rules) Object.hasOwn(rules, ruleName) && convertRule(rules[ruleName], afterHooksState);
33
+ return plugin;
34
+ }
35
+ /**
36
+ * Class containing state for tracking if any `after` hooks for a plugin's rules need to be called.
37
+ *
38
+ * # Aims
39
+ *
40
+ * Aims are:
41
+ * 1. `after` hook of each rule runs after all other AST visit functions, and CFG event handlers.
42
+ * 2. `after` hooks for *all* a plugin's rules run after *all* that plugin's rules have completed visiting AST.
43
+ * 3. `after` hooks for *all* a plugin's rules run before *any* of plugin's rules begin linting another file.
44
+ * 4. In the case of an error during AST traversal, `after` hooks are always still run.
45
+ *
46
+ * The above exactly matches the behavior when running a `createOnce` rule in Oxlint.
47
+ *
48
+ * # Why this is important
49
+ *
50
+ * All the complication comes from ensuring `after` hooks run even after an error during AST traversal.
51
+ *
52
+ * In ESLint CLI, an error will crash the process, so it doesn't particularly matter if `after` hooks run or not,
53
+ * but language servers will typically swallow errors, and keep the process running.
54
+ *
55
+ * Rules using `before` and `after` hooks will often rely on both hooks running in a predictable order,
56
+ * to maintain some internal state. For example, they may use `before` and `after` hooks to maintain a per-file
57
+ * cache of data which is shared between rules. The cache use case is why rule (2) above is important.
58
+ *
59
+ * Below is an example of using `before` and `after` hooks to maintain a per-file cache, shared between rules.
60
+ * It relies on all `before` hooks running before any rule starts visiting the AST,
61
+ * and all `after` hooks running after all rules have finished visiting the AST.
62
+ *
63
+ * ```ts
64
+ * let cache: Data | null = null;
65
+ *
66
+ * let numRunningRules = 0;
67
+ *
68
+ * const setupCache = (context) => {
69
+ * if (cache === null) cache = new Data(context);
70
+ * numRunningRules++;
71
+ * };
72
+ *
73
+ * const teardownCache = () => {
74
+ * numRunningRules--;
75
+ * if (numRunningRules === 0) cache = null;
76
+ * };
77
+ *
78
+ * const rule1 = {
79
+ * createOnce(context) {
80
+ * return {
81
+ * before() {
82
+ * setupCache(context);
83
+ * },
84
+ * Identifier(node) {
85
+ * // Use `cache`
86
+ * },
87
+ * after: teardownCache,
88
+ * };
89
+ * },
90
+ * };
91
+ *
92
+ * const rule2 = {
93
+ * // Same as above
94
+ * };
95
+ *
96
+ * const rule3 = {
97
+ * // Same as above
98
+ * };
99
+ * ```
100
+ *
101
+ * If `after` hooks did not always run, the next lint run could get stale state, and malfunction.
102
+ * If `after` hooks ran in the wrong order (e.g. after some `before` hooks for next file),
103
+ * `numRunningRules` would never get to 0, and cache would never be cleared.
104
+ *
105
+ * Note that because all rules run together in a single AST traversal, if a rule from plugin X throws an error,
106
+ * it can disrupt rules from plugin Y. This would make it hard to debug.
107
+ *
108
+ * # Mechanism
109
+ *
110
+ * ## Initialization
111
+ *
112
+ * Rules with an `after` hook register themselves by:
113
+ *
114
+ * 1. Calling `registerResetFunction` to register a function to run `after` hook and clean up internal state.
115
+ * This call adds the reset fn to `resetFunctions`, and adds `AFTER_HOOK_INACTIVE` to `pendingStates`.
116
+ * 2. Adding an `onCodePathEnd` CFG event handler to the visitor which calls `ruleFinished` at end of AST traversal.
117
+ *
118
+ * ## Per-file setup
119
+ *
120
+ * Before linting a file, `create` will call `setupAfterHook` which is created by `createContextAndVisitor`.
121
+ * This registers that the `after` hook for the rule needs to run, by setting `pendingStates[ruleIndex]`
122
+ * to `AFTER_HOOK_PENDING`, and incrementing `pendingCount`.
123
+ *
124
+ * If a cleanup microtask has not been scheduled yet, one is scheduled now (see reason below).
125
+ *
126
+ * ## Normal operation
127
+ *
128
+ * AST traversal for each rule ends with `ruleFinished` hook being called from `onCodePathEnd` CFG event handler.
129
+ * It increments `lintFinishedCount`. If `lintFinishedCount` equals `pendingCount`, all rules have finished linting
130
+ * the file, and `reset` is called, which calls all the pending `after` hooks.
131
+ *
132
+ * ## Error handling
133
+ *
134
+ * If an error is thrown during AST traversal, we ensure that `after` hooks are still run by 2 mechanisms:
135
+ *
136
+ * ### 1. Next microtick
137
+ *
138
+ * Before any rules began linting files, a microtask was scheduled, which runs on next micro-tick.
139
+ * All language servers we're aware of run each lint task in a separate tick, so this microtask will run in next tick
140
+ * after a linting run, before the next lint task starts.
141
+ *
142
+ * If the linting run completed successfully, the microtask does nothing.
143
+ *
144
+ * But if an error was thrown during AST traversal, this will be visible from the state of `pendingCount`.
145
+ * The microtask will run any `after` hooks which need to be run, and reset state to reflect that there are
146
+ * no more pending `after` hooks.
147
+ *
148
+ * ### 2. Fallback: Next lint run
149
+ *
150
+ * Before linting any file, the state of `pendingCount` is checked.
151
+ * If any `after` hooks are still pending, they are run immediately.
152
+ * They're run before the `context` objects in `createOnce` closures are updated to the next file,
153
+ * so they run with access to the old `context` object from the last file.
154
+ *
155
+ * This fallback should not be required, but it's included as "belt and braces", to handle if any language server
156
+ * or other environment running ESLint programmatically, does not pause a tick between linting runs.
157
+ */
158
+ var AfterHooksState = class {
159
+ resetFunctions = [];
160
+ pendingStates = [];
161
+ pendingCount = 0;
162
+ lintFinishedCount = 0;
163
+ resetIsScheduled = !1;
164
+ sourceCode = null;
165
+ resetMicrotask = this.resetMicrotaskImpl.bind(this);
166
+ /**
167
+ * Register a function to run `after` hook for a rule, and reset state.
168
+ * @param reset - Function to run `after` hook and reset state
169
+ * @returns Index of rule
170
+ */
171
+ registerResetFunction(reset) {
172
+ let { pendingStates } = this, index = pendingStates.length;
173
+ return pendingStates.push(0), this.resetFunctions.push(reset), index;
174
+ }
175
+ /**
176
+ * Register that a rule with `after` hook has completed linting a file.
177
+ * Called by `onCodePathEnd` CFG event handler which is added to visitor for rules with `after` hooks.
178
+ *
179
+ * If all rules with an `after` hook which needs to be run have completed linting the file, run all `after` hooks.
180
+ */
181
+ ruleFinished() {
182
+ this.lintFinishedCount++, this.lintFinishedCount === this.pendingCount && this.reset(!1);
183
+ }
184
+ /**
185
+ * Call all reset functions where corresponding entry in `pendingStates` is `AFTER_HOOK_PENDING`.
186
+ * Should only be called when some `after` hooks are pending.
187
+ *
188
+ * @param ignoreErrors - `true` to catch and silently ignore any errors which occur in `after` hooks.
189
+ * `false` to throw them,
190
+ * @throws {unknown} If `ignoreErrors` is `false` and an error occurs in any `after` hooks.
191
+ */
192
+ reset(ignoreErrors) {
193
+ this.pendingCount;
194
+ let { resetFunctions, pendingStates } = this, hooksLen = pendingStates.length, hasError = !1, error;
195
+ for (let i = 0; i < hooksLen; i++) if (pendingStates[i] !== 0) {
196
+ pendingStates[i] = 0;
197
+ try {
198
+ resetFunctions[i]();
199
+ } catch (e) {
200
+ hasError === !1 && (hasError = !0, error = e);
201
+ }
202
+ }
203
+ if (this.pendingCount = 0, this.lintFinishedCount = 0, this.sourceCode = null, hasError === !0 && ignoreErrors === !1) throw error;
204
+ }
205
+ /**
206
+ * Schedule a microtask to run `reset` functions.
207
+ */
208
+ scheduleReset() {
209
+ queueMicrotask(this.resetMicrotask), this.resetIsScheduled = !0;
210
+ }
211
+ /**
212
+ * Function which is scheduled as the cleanup microtask.
213
+ * `scheduleReset` uses `resetMicrotask` which is this method bound to `this`.
214
+ */
215
+ resetMicrotaskImpl() {
216
+ this.resetIsScheduled = !1, this.pendingCount !== 0 && this.reset(!0);
217
+ }
218
+ };
219
+ /**
220
+ * Convert a rule.
221
+ *
222
+ * The `rule` object passed in is mutated in-place.
223
+ *
224
+ * @param rule - Rule to convert
225
+ * @param afterHooksState - State of `after` hooks
226
+ * @throws {Error} If `rule` is not an object
227
+ */
228
+ function convertRule(rule, afterHooksState) {
229
+ if (typeof rule != "object" || !rule) throw Error("Rule must be an object");
230
+ if ("create" in rule) return;
231
+ let context = null, visitor, beforeHook, setupAfterHook;
232
+ rule.create = (eslintContext) => {
233
+ context === null && ({context, visitor, beforeHook, setupAfterHook} = createContextAndVisitor(rule, afterHooksState));
234
+ let eslintFileContext = Object.getPrototypeOf(eslintContext);
235
+ if (setupAfterHook !== null) {
236
+ let { sourceCode } = eslintFileContext;
237
+ afterHooksState.sourceCode !== sourceCode && (afterHooksState.sourceCode = sourceCode, afterHooksState.pendingCount !== 0 && afterHooksState.reset(!0));
238
+ }
239
+ return Object.defineProperties(context, {
240
+ id: { value: eslintContext.id },
241
+ options: { value: eslintContext.options },
242
+ report: { value: eslintContext.report }
243
+ }), Object.setPrototypeOf(context, eslintFileContext), beforeHook !== null && beforeHook() === !1 ? EMPTY_VISITOR : (setupAfterHook !== null && (setupAfterHook(eslintFileContext.sourceCode.ast), afterHooksState.resetIsScheduled === !1 && afterHooksState.scheduleReset()), visitor);
244
+ };
245
+ }
246
+ const FILE_CONTEXT = Object.freeze({
247
+ get filename() {
248
+ throw Error("Cannot access `context.filename` in `createOnce`");
249
+ },
250
+ getFilename() {
251
+ throw Error("Cannot call `context.getFilename` in `createOnce`");
252
+ },
253
+ get physicalFilename() {
254
+ throw Error("Cannot access `context.physicalFilename` in `createOnce`");
255
+ },
256
+ getPhysicalFilename() {
257
+ throw Error("Cannot call `context.getPhysicalFilename` in `createOnce`");
258
+ },
259
+ get cwd() {
260
+ throw Error("Cannot access `context.cwd` in `createOnce`");
261
+ },
262
+ getCwd() {
263
+ throw Error("Cannot call `context.getCwd` in `createOnce`");
264
+ },
265
+ get sourceCode() {
266
+ throw Error("Cannot access `context.sourceCode` in `createOnce`");
267
+ },
268
+ getSourceCode() {
269
+ throw Error("Cannot call `context.getSourceCode` in `createOnce`");
270
+ },
271
+ get languageOptions() {
272
+ throw Error("Cannot access `context.languageOptions` in `createOnce`");
273
+ },
274
+ get settings() {
275
+ throw Error("Cannot access `context.settings` in `createOnce`");
276
+ },
277
+ extend(extension) {
278
+ return Object.freeze(Object.assign(Object.create(this), extension));
279
+ },
280
+ get parserOptions() {
281
+ throw Error("Cannot access `context.parserOptions` in `createOnce`");
282
+ },
283
+ get parserPath() {
284
+ throw Error("Cannot access `context.parserPath` in `createOnce`");
285
+ }
286
+ });
287
+ /**
288
+ * Call `createOnce` method of rule, and return `Context`, `Visitor`, and `beforeHook` (if any).
289
+ *
290
+ * @param rule - Rule with `createOnce` method
291
+ * @param afterHooksState - State of `after` hooks
292
+ * @returns Object with `context`, `visitor`, and `beforeHook` properties,
293
+ * and `setupAfterHook` function if visitor has an `after` hook
294
+ */
295
+ function createContextAndVisitor(rule, afterHooksState) {
296
+ let { createOnce } = rule;
297
+ if (createOnce == null) throw Error("Rules must define either a `create` or `createOnce` method");
298
+ if (typeof createOnce != "function") throw Error("Rule `createOnce` property must be a function");
299
+ let context = Object.create(FILE_CONTEXT, {
300
+ id: {
301
+ value: null,
302
+ enumerable: !0,
303
+ configurable: !0
304
+ },
305
+ options: {
306
+ value: null,
307
+ enumerable: !0,
308
+ configurable: !0
309
+ },
310
+ report: {
311
+ value() {
312
+ throw Error("Cannot report errors in `createOnce`");
313
+ },
314
+ enumerable: !0,
315
+ configurable: !0
316
+ }
317
+ }), { before: beforeHook, after: afterHook, ...visitor } = createOnce.call(rule, context);
318
+ if (beforeHook === void 0) beforeHook = null;
319
+ else if (beforeHook !== null && typeof beforeHook != "function") throw Error("`before` property of visitor must be a function if defined");
320
+ let setupAfterHook = null;
321
+ if (afterHook != null) {
322
+ if (typeof afterHook != "function") throw Error("`after` property of visitor must be a function if defined");
323
+ let program = null, ruleIndex = afterHooksState.registerResetFunction(() => {
324
+ program = null, afterHook();
325
+ });
326
+ setupAfterHook = (ast) => {
327
+ program = ast, afterHooksState.pendingStates[ruleIndex] = 1, afterHooksState.pendingCount++;
328
+ };
329
+ let onCodePathEnd = visitor.onCodePathEnd;
330
+ visitor.onCodePathEnd = onCodePathEnd == null ? function(_codePath, node) {
331
+ node === program && afterHooksState.ruleFinished();
332
+ } : function(codePath, node) {
333
+ onCodePathEnd.call(this, codePath, node), node === program && afterHooksState.ruleFinished();
334
+ };
335
+ }
336
+ return {
337
+ context,
338
+ visitor,
339
+ beforeHook,
340
+ setupAfterHook
341
+ };
342
+ }
343
+ // src/rules/no-comments.ts
344
+ const DEFAULT_SAFETY_MARKERS = ["SAFETY"];
345
+ const directivePatterns = [
346
+ /^(?:eslint|oxlint)-(?:disable|enable)(?:-next-line|-line)?(?:\s|$)/u,
347
+ /^@ts-(?:expect-error|ignore|nocheck|check)(?![\w-])/u,
348
+ /^\/\s*<(?:reference|amd-module|amd-dependency)\s/u,
349
+ /^prettier-ignore(?:\s|$)/u,
350
+ /^(?:istanbul|c8|v8)\s+ignore(?:\s|$)/u,
351
+ /^node:coverage\s+(?:ignore|disable|enable)(?:\s|$)/u,
352
+ /^[#@]__(?:PURE|NO_SIDE_EFFECTS)__$/u,
353
+ /^@vite-ignore$/u,
354
+ /^@vitest-environment\s/u
355
+ ];
356
+ const licensePattern = /@license(?![\w-])|SPDX-(?:License-Identifier|FileCopyrightText):/u;
357
+ const declarationKinds = /* @__PURE__ */ new Set([
358
+ "ClassDeclaration",
359
+ "FunctionDeclaration",
360
+ "TSDeclareFunction",
361
+ "TSEnumDeclaration",
362
+ "TSInterfaceDeclaration",
363
+ "TSModuleDeclaration",
364
+ "TSTypeAliasDeclaration",
365
+ "VariableDeclaration"
366
+ ]);
367
+ const commentOwnerKinds = /* @__PURE__ */ new Set([
368
+ "ExpressionStatement",
369
+ "PropertyDefinition",
370
+ "ReturnStatement",
371
+ "ThrowStatement",
372
+ "VariableDeclaration"
373
+ ]);
374
+ function stringList(configured) {
375
+ if (!Array.isArray(configured)) return [];
376
+ return configured.flatMap((item) => typeof item === "string" && item.trim().length > 0 ? [item.trim()] : []);
377
+ }
378
+ function safetyPattern(markers) {
379
+ const alternation = markers.map((marker) => marker.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`)).join("|");
380
+ return new RegExp(String.raw`(?:^|[^\p{L}\p{N}_])(?:${alternation})\s*:\s*\S`, "u");
381
+ }
382
+ function buildMatchers(option) {
383
+ const isObject = typeof option === "object" && option !== null;
384
+ const allow = isObject && "allow" in option ? stringList(option.allow) : [];
385
+ const markers = isObject && "safetyMarkers" in option ? stringList(option.safetyMarkers) : [];
386
+ return {
387
+ allow: allow.map((source) => new RegExp(source, "u")),
388
+ safety: safetyPattern(markers.length > 0 ? markers : DEFAULT_SAFETY_MARKERS)
389
+ };
390
+ }
391
+ function commentText(comment) {
392
+ return comment.type === "Block" ? comment.value.replace(/^\s*\**\s*/u, "").trimEnd() : comment.value.trim();
393
+ }
394
+ function isJSDoc(comment) {
395
+ return comment.type === "Block" && comment.value.startsWith("*");
396
+ }
397
+ function isLicenseHeader(comment, headerEnd) {
398
+ if (comment.end > headerEnd) return false;
399
+ return comment.type === "Block" && comment.value.startsWith("!") || licensePattern.test(comment.value);
400
+ }
401
+ function isConstAssertion(node) {
402
+ return node.typeAnnotation.type === "TSTypeReference" && node.typeAnnotation.typeName.type === "Identifier" && node.typeAnnotation.typeName.name === "const";
403
+ }
404
+ function isPrivateMember(node) {
405
+ if ("accessibility" in node && node.accessibility === "private") return true;
406
+ return "key" in node && node.key.type === "PrivateIdentifier";
407
+ }
408
+ function declaredNames(node) {
409
+ if (node.type === "VariableDeclaration") return node.declarations.flatMap((declarator) => declarator.id.type === "Identifier" ? [declarator.id.name] : []);
410
+ if ("id" in node && node.id !== null && node.id.type === "Identifier") return [node.id.name];
411
+ return [];
412
+ }
413
+ function lastJSDocBefore(sourceCode, node) {
414
+ return sourceCode.getCommentsBefore(node).findLast(isJSDoc);
415
+ }
416
+ function isInsideApi(member, api) {
417
+ let previous = member;
418
+ let current = member.parent;
419
+ while (current !== null) {
420
+ if (api.has(current)) return true;
421
+ if (current.type === "BlockStatement" || current.type === "StaticBlock") return false;
422
+ if (current.type === "ArrowFunctionExpression" && current.body === previous) return false;
423
+ previous = current;
424
+ current = current.parent;
425
+ }
426
+ return false;
427
+ }
428
+ function safetyCommentsFor(sourceCode, assertion, pattern) {
429
+ const found = [];
430
+ const collect = (owner) => {
431
+ for (const comment of sourceCode.getCommentsBefore(owner)) if (comment.end <= assertion.start && pattern.test(comment.value)) found.push(comment);
432
+ };
433
+ let current = assertion;
434
+ while (true) {
435
+ collect(current);
436
+ if (commentOwnerKinds.has(current.type)) {
437
+ const exportDeclaration = current.parent;
438
+ if (exportDeclaration?.type === "ExportNamedDeclaration" && exportDeclaration.declaration === current) collect(exportDeclaration);
439
+ return found;
440
+ }
441
+ if (current.parent === null || current.parent.type === "Program") return found;
442
+ current = current.parent;
443
+ }
444
+ }
445
+ // src/index.ts
446
+ /** Oxlint plugin that keeps intent in names, types, tests, and commit messages instead of comments. */
447
+ const plugin = eslintCompatPlugin({
448
+ meta: { name: "uinaf" },
449
+ rules: { "no-comments": defineRule({
450
+ meta: {
451
+ type: "suggestion",
452
+ docs: { description: "Disallow comments other than tool directives, license headers, JSDoc on exported API, and SAFETY justifications for type assertions." },
453
+ messages: { comment: "Remove this comment. Names, types, and tests carry intent; the commit message carries the why." },
454
+ schema: [{
455
+ type: "object",
456
+ properties: {
457
+ allow: {
458
+ type: "array",
459
+ items: {
460
+ type: "string",
461
+ minLength: 1
462
+ },
463
+ uniqueItems: true
464
+ },
465
+ safetyMarkers: {
466
+ type: "array",
467
+ items: {
468
+ type: "string",
469
+ minLength: 1
470
+ },
471
+ minItems: 1,
472
+ uniqueItems: true
473
+ }
474
+ },
475
+ additionalProperties: false
476
+ }],
477
+ defaultOptions: [{
478
+ allow: [],
479
+ safetyMarkers: ["SAFETY"]
480
+ }]
481
+ },
482
+ createOnce(context) {
483
+ const matchersByOption = /* @__PURE__ */ new Map();
484
+ const apiNodes = /* @__PURE__ */ new Set();
485
+ const members = [];
486
+ const assertions = [];
487
+ const localExports = /* @__PURE__ */ new Set();
488
+ const addMember = (node) => {
489
+ members.push(node);
490
+ };
491
+ const addAssertion = (node) => {
492
+ if (!isConstAssertion(node)) assertions.push(node);
493
+ };
494
+ return {
495
+ before() {
496
+ apiNodes.clear();
497
+ members.length = 0;
498
+ assertions.length = 0;
499
+ localExports.clear();
500
+ },
501
+ ExportNamedDeclaration(node) {
502
+ if (node.declaration !== null) apiNodes.add(node);
503
+ if (node.source !== null) return;
504
+ for (const specifier of node.specifiers) if (specifier.local.type === "Identifier") localExports.add(specifier.local.name);
505
+ },
506
+ ExportDefaultDeclaration(node) {
507
+ apiNodes.add(node);
508
+ if (node.declaration.type === "Identifier") localExports.add(node.declaration.name);
509
+ },
510
+ AccessorProperty: addMember,
511
+ MethodDefinition: addMember,
512
+ PropertyDefinition: addMember,
513
+ TSAbstractAccessorProperty: addMember,
514
+ TSAbstractMethodDefinition: addMember,
515
+ TSAbstractPropertyDefinition: addMember,
516
+ TSCallSignatureDeclaration: addMember,
517
+ TSConstructSignatureDeclaration: addMember,
518
+ TSEnumMember: addMember,
519
+ TSIndexSignature: addMember,
520
+ TSMethodSignature: addMember,
521
+ TSPropertySignature: addMember,
522
+ TSAsExpression: addAssertion,
523
+ TSTypeAssertion: addAssertion,
524
+ "Program:exit"(program) {
525
+ const { sourceCode } = context;
526
+ const option = context.options[0];
527
+ const optionKey = JSON.stringify(option ?? null);
528
+ const matchers = matchersByOption.get(optionKey) ?? buildMatchers(option);
529
+ matchersByOption.set(optionKey, matchers);
530
+ for (const statement of program.body) {
531
+ if (!declarationKinds.has(statement.type)) continue;
532
+ if (declaredNames(statement).some((name) => localExports.has(name))) apiNodes.add(statement);
533
+ }
534
+ const allowed = /* @__PURE__ */ new Set();
535
+ for (const node of apiNodes) {
536
+ const doc = lastJSDocBefore(sourceCode, node);
537
+ if (doc !== void 0) allowed.add(doc.start);
538
+ }
539
+ for (const member of members) {
540
+ if (isPrivateMember(member) || !isInsideApi(member, apiNodes)) continue;
541
+ const doc = lastJSDocBefore(sourceCode, member);
542
+ if (doc !== void 0) allowed.add(doc.start);
543
+ }
544
+ for (const assertion of assertions) for (const comment of safetyCommentsFor(sourceCode, assertion, matchers.safety)) allowed.add(comment.start);
545
+ const headerEnd = program.body[0]?.start ?? program.end;
546
+ for (const comment of sourceCode.getAllComments()) {
547
+ if (comment.type === "Shebang" || allowed.has(comment.start)) continue;
548
+ if (isLicenseHeader(comment, headerEnd)) continue;
549
+ const text = commentText(comment);
550
+ if (directivePatterns.some((pattern) => pattern.test(text))) continue;
551
+ if (matchers.allow.some((pattern) => pattern.test(text))) continue;
552
+ context.report({
553
+ node: comment,
554
+ messageId: "comment"
555
+ });
556
+ }
557
+ }
558
+ };
559
+ }
560
+ }) }
561
+ });
562
+ export { plugin as default };
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@uinaf/oxlint-plugin-no-comments",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Oxlint rule that bans code comments, except tool directives, license headers, API docs, and SAFETY justifications",
5
+ "keywords": [
6
+ "comments",
7
+ "eslint",
8
+ "eslintplugin",
9
+ "oxlint",
10
+ "oxlint-plugin"
11
+ ],
12
+ "homepage": "https://github.com/uinaf/oxlint-plugin-no-comments#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/uinaf/oxlint-plugin-no-comments/issues"
15
+ },
16
+ "license": "MIT",
17
+ "author": "undefined is not a function LLC",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/uinaf/oxlint-plugin-no-comments.git"
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "type": "module",
26
+ "exports": {
27
+ ".": "./dist/index.js"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "scripts": {
34
+ "verify": "vp run ready",
35
+ "verify:full": "vp run --no-cache ready",
36
+ "prepublishOnly": "pnpm run verify:full"
37
+ },
38
+ "devDependencies": {
39
+ "@oxlint/plugins": "1.90.0",
40
+ "@types/node": "^26.6.6",
41
+ "oxlint": "1.90.0",
42
+ "vite": "catalog:",
43
+ "vite-plus": "catalog:"
44
+ },
45
+ "devEngines": {
46
+ "runtime": {
47
+ "name": "node",
48
+ "version": "^24.11.0 || >=26.0.0",
49
+ "onFail": "error"
50
+ }
51
+ },
52
+ "engines": {
53
+ "node": ">=20.19.0"
54
+ },
55
+ "packageManager": "pnpm@12.16.0"
56
+ }