@open-tomato/eslint-plugin 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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,10 @@
1
+ @open-tomato/packages
2
+ Copyright 2026 Marcos Tomatti and the open-tomato contributors
3
+
4
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ The configs, rules and gates in this repository began in other
7
+ open-tomato repositories and are developed here since: the ESLint and
8
+ TypeScript configs and the two ESLint rules in rafa, the control-byte
9
+ gate in rafa, the privacy gate in components, and the pack and publish
10
+ scripts in service.
package/README.md CHANGED
@@ -1,3 +1,72 @@
1
- # Temporary Holding Version
1
+ # @open-tomato/eslint-plugin
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
+ The custom ESLint rules of the open-tomato projects. The plugin registers
4
+ under the `@open-tomato` key, so each rule reads `@open-tomato/<rule>` in a
5
+ config and in a disable comment.
6
+
7
+ ```bash
8
+ bun add -d @open-tomato/eslint-plugin eslint
9
+ ```
10
+
11
+ [`@open-tomato/eslint-config`](../eslint-config/README.md) already turns
12
+ the rules on, so a project that uses the config needs no setup of its own.
13
+ A project with its own config registers the plugin itself:
14
+
15
+ ```js
16
+ import openTomato from '@open-tomato/eslint-plugin';
17
+
18
+ export default [
19
+ {
20
+ plugins: { '@open-tomato': openTomato },
21
+ rules: { '@open-tomato/no-unsafe-unicode': 'error' },
22
+ },
23
+ ];
24
+ ```
25
+
26
+ ## Rules
27
+
28
+ ### `no-unsafe-unicode`
29
+
30
+ Refuses characters that are invisible or misleading in a source file,
31
+ written literally:
32
+
33
+ - C0 control characters except tab, line feed and carriage return, and DEL.
34
+ A NUL makes git treat the file as binary, and makes grep miss text that is
35
+ there.
36
+ - Bidirectional overrides and isolates, the Trojan Source set
37
+ (CVE-2021-42574), which make code display in a different order than it
38
+ runs.
39
+ - Zero-width and default-ignorable characters, invisible to a reviewer.
40
+ - The line and paragraph separators U+2028 and U+2029.
41
+
42
+ The fix is the escape: write the six-character backslash-u form instead of
43
+ the character. A zero-width joiner between two emoji is allowed, since that
44
+ is how emoji sequences are built. The rule runs on code, JSON and Markdown.
45
+
46
+ The control-byte gate of [`@open-tomato/gates`](../gates/README.md) checks
47
+ the same set at the byte level over every tracked file, and its tests assert
48
+ the two agree.
49
+
50
+ ### `cva-only-classname`
51
+
52
+ For component libraries whose classes live in `cva` calls. A JSX
53
+ `className` may hold only:
54
+
55
+ - a variants call, any function whose name ends in `Variants`:
56
+ `className={cardVariants({ tone })}`;
57
+ - a `cn()` call over variants calls and the passthrough `className`, alone
58
+ or behind `&&`, `||`, `??` or a ternary:
59
+ `className={cn(cardVariants({ tone }), className)}`;
60
+ - the passthrough `className` itself.
61
+
62
+ A string, a template literal or any other expression is refused. The `cva`
63
+ flavor of the config turns it on outside templates, pages, stories and
64
+ tests.
65
+
66
+ ## Exports
67
+
68
+ | Path | What it holds |
69
+ | --- | --- |
70
+ | `.` | the plugin, and `PLUGIN_KEY` |
71
+ | `./rules/no-unsafe-unicode` | the rule, and `findUnsafeUnicode(text)` |
72
+ | `./rules/cva-only-classname` | the rule |
package/index.d.mts ADDED
@@ -0,0 +1,9 @@
1
+ /** Types for `index.mjs`, the `@open-tomato/eslint-plugin` entry. */
2
+ import type { ESLint } from 'eslint';
3
+
4
+ /** The key a config registers the plugin under. */
5
+ export declare const PLUGIN_KEY: '@open-tomato';
6
+
7
+ /** The plugin, with the `cva-only-classname` and `no-unsafe-unicode` rules. */
8
+ declare const plugin: ESLint.Plugin;
9
+ export default plugin;
package/index.mjs ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * `@open-tomato/eslint-plugin`: the custom rules every open-tomato project
3
+ * can turn on. The plugin registers under the `@open-tomato` key, so each
4
+ * rule reads `@open-tomato/<rule>` in a config or a disable comment.
5
+ *
6
+ * - `no-unsafe-unicode` refuses control, BiDi-override and invisible
7
+ * characters written literally. `@open-tomato/eslint-config` turns it on
8
+ * for every linted language.
9
+ * - `cva-only-classname` holds a JSX `className` to a CVA variants call.
10
+ * The `cva` flavor of `@open-tomato/eslint-config` turns it on.
11
+ */
12
+ import { cvaOnlyClassName } from './rules/cva-only-classname.mjs';
13
+ import { noUnsafeUnicode } from './rules/no-unsafe-unicode.mjs';
14
+
15
+ /** The key a config registers the plugin under. */
16
+ export const PLUGIN_KEY = '@open-tomato';
17
+
18
+ export default {
19
+ meta: { name: '@open-tomato/eslint-plugin' },
20
+ rules: {
21
+ 'cva-only-classname': cvaOnlyClassName,
22
+ 'no-unsafe-unicode': noUnsafeUnicode,
23
+ },
24
+ };
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@open-tomato/eslint-plugin",
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": "The custom ESLint rules of the open-tomato projects: no-unsafe-unicode and cva-only-classname.",
5
+ "license": "Apache-2.0",
6
+ "author": "Marcos Tomatti",
7
+ "openTomato": {
8
+ "team": "@open-tomato/maintainers"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/open-tomato/packages.git",
13
+ "directory": "packages/eslint-plugin"
14
+ },
15
+ "homepage": "https://github.com/open-tomato/packages/tree/main/packages/eslint-plugin#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/open-tomato/packages/issues"
18
+ },
19
+ "keywords": [
20
+ "eslint",
21
+ "eslintplugin",
22
+ "eslint-plugin",
23
+ "unicode",
24
+ "trojan-source",
25
+ "cva"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "exports": {
30
+ ".": {
31
+ "types": "./index.d.mts",
32
+ "default": "./index.mjs"
33
+ },
34
+ "./rules/no-unsafe-unicode": {
35
+ "types": "./rules/no-unsafe-unicode.d.mts",
36
+ "default": "./rules/no-unsafe-unicode.mjs"
37
+ },
38
+ "./rules/cva-only-classname": {
39
+ "types": "./rules/cva-only-classname.d.mts",
40
+ "default": "./rules/cva-only-classname.mjs"
41
+ },
42
+ "./package.json": "./package.json"
43
+ },
44
+ "files": [
45
+ "index.mjs",
46
+ "index.d.mts",
47
+ "rules",
48
+ "LICENSE",
49
+ "NOTICE"
50
+ ],
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "registry": "https://registry.npmjs.org/"
54
+ },
55
+ "engines": {
56
+ "node": ">=20.19"
57
+ },
58
+ "scripts": {
59
+ "lint": "eslint .",
60
+ "check-types": "tsc --noEmit",
61
+ "test": "bun test"
62
+ },
63
+ "peerDependencies": {
64
+ "eslint": "^9.39.0"
65
+ },
66
+ "devDependencies": {
67
+ "@types/bun": "^1.3.0",
68
+ "@typescript-eslint/parser": "^8.72.0",
69
+ "eslint": "^9.39.5",
70
+ "typescript": "^5.9.3"
71
+ }
72
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Types for `cva-only-classname.mjs`, so its TypeScript test reads the
3
+ * export typed rather than as an implicit `any`.
4
+ */
5
+ import type { Rule } from 'eslint';
6
+
7
+ /** The rule itself. */
8
+ export declare const cvaOnlyClassName: Rule.RuleModule;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @open-tomato/cva-only-classname
3
+ *
4
+ * A component's classes live in its `{C}.variants.ts` file as `cva` calls,
5
+ * so a `className` JSX attribute may hold only one of three values:
6
+ *
7
+ * - a variants call: `className={cardVariants({ tone })}`, any callee
8
+ * whose name ends in `Variants`;
9
+ * - a `cn(...)` call whose arguments are themselves variants calls or
10
+ * the passthrough `className` identifier, alone or behind a `&&`,
11
+ * `||`, `??` or a ternary: `cn(cardVariants({ tone }), className)`;
12
+ * - the passthrough `className` identifier, handed on unchanged.
13
+ *
14
+ * A string literal, a template literal, or any other expression is an
15
+ * ad-hoc class and is refused. The `cva` flavor of
16
+ * `@open-tomato/eslint-config` registers the rule for TSX and JSX files and
17
+ * leaves out `templates/`, `pages/`, `*.stories.tsx` and `*.test.tsx`,
18
+ * where a layout class is the point.
19
+ */
20
+
21
+ /** The passthrough prop a component merges last. */
22
+ const PASSTHROUGH = 'className';
23
+
24
+ /** The class merger, `cn()`: `twMerge(clsx(...))` by convention. */
25
+ const MERGER = 'cn';
26
+
27
+ /** A variants function, as `cva` calls are named by convention. */
28
+ const VARIANTS_CALLEE = /Variants$/;
29
+
30
+ /** The callee's name, for a plain identifier callee; `undefined` otherwise. */
31
+ function calleeName(node) {
32
+ return node.type === 'CallExpression' && node.callee.type === 'Identifier'
33
+ ? node.callee.name
34
+ : undefined;
35
+ }
36
+
37
+ /** A variants call: `xVariants(...)`. */
38
+ function isVariantsCall(node) {
39
+ const name = calleeName(node);
40
+ return name !== undefined && VARIANTS_CALLEE.test(name);
41
+ }
42
+
43
+ /** The passthrough identifier: `className`. */
44
+ function isPassthrough(node) {
45
+ return node.type === 'Identifier' && node.name === PASSTHROUGH;
46
+ }
47
+
48
+ /** An argument `cn` may take: a variants call or the passthrough, alone or behind a condition. */
49
+ function isMergeable(node) {
50
+ if (isVariantsCall(node) || isPassthrough(node)) return true;
51
+ if (node.type === 'LogicalExpression') return isMergeable(node.right);
52
+ if (node.type === 'ConditionalExpression') return isMergeable(node.consequent) && isMergeable(node.alternate);
53
+ return false;
54
+ }
55
+
56
+ /** A `cn(...)` call whose every argument is mergeable. */
57
+ function isMergeCall(node) {
58
+ return calleeName(node) === MERGER && node.arguments.every(isMergeable);
59
+ }
60
+
61
+ /** Whether a `className` attribute's expression is one of the three allowed values. */
62
+ function isAllowedValue(expression) {
63
+ return isVariantsCall(expression) || isMergeCall(expression) || isPassthrough(expression);
64
+ }
65
+
66
+ export const cvaOnlyClassName = {
67
+ meta: {
68
+ type: 'problem',
69
+ docs: {
70
+ description:
71
+ 'Allow a className JSX attribute only as a CVA variants call, a cn() over variants and the passthrough className, or the passthrough itself.',
72
+ },
73
+ schema: [],
74
+ messages: {
75
+ adHoc:
76
+ 'className holds an ad-hoc value. Put the classes in the component\'s .variants.ts as a cva call and pass {{hint}} instead.',
77
+ },
78
+ },
79
+ create(context) {
80
+ return {
81
+ JSXAttribute(node) {
82
+ if (node.name.type !== 'JSXIdentifier' || node.name.name !== PASSTHROUGH) return;
83
+ const { value } = node;
84
+ const allowed = value !== null
85
+ && value.type === 'JSXExpressionContainer'
86
+ && value.expression.type !== 'JSXEmptyExpression'
87
+ && isAllowedValue(value.expression);
88
+ if (allowed) return;
89
+ context.report({
90
+ node,
91
+ messageId: 'adHoc',
92
+ data: { hint: 'xVariants(...), cn(xVariants(...), className) or className' },
93
+ });
94
+ },
95
+ };
96
+ },
97
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Types for `no-unsafe-unicode.mjs`, so a TypeScript file importing it
3
+ * (the control-byte gate's agreement test) reads its exports typed rather
4
+ * than as an implicit `any`.
5
+ */
6
+ import type { Rule } from 'eslint';
7
+
8
+ /** One unsafe character: its UTF-16 index, its code point and what kind it is. */
9
+ export interface UnsafeUnicodeFinding {
10
+ readonly index: number;
11
+ readonly code: number;
12
+ readonly kind: string;
13
+ }
14
+
15
+ /** Every unsafe character in `text`. */
16
+ export declare function findUnsafeUnicode(text: string): UnsafeUnicodeFinding[];
17
+
18
+ /** The rule itself. */
19
+ export declare const noUnsafeUnicode: Rule.RuleModule;
@@ -0,0 +1,189 @@
1
+ /**
2
+ * @open-tomato/no-unsafe-unicode
3
+ *
4
+ * Flags characters that are invisible or misleading in a source file, and
5
+ * that defeat the tools we rely on to review it:
6
+ *
7
+ * - C0 controls / DEL. A NUL makes git classify the blob as binary, so
8
+ * every later diff renders `Bin N -> M bytes`, and makes POSIX grep
9
+ * report NO MATCH for text that is present. Both are silent false
10
+ * negatives. ESC lets file content rewrite a terminal that prints it.
11
+ * - BiDi overrides (Trojan Source, CVE-2021-42574). These make source
12
+ * display in a different order than it compiles, so review and
13
+ * compiler disagree.
14
+ * - Zero-width and default-ignorable characters. Invisible to a
15
+ * reviewer, fully present in what a parser or a model consumes.
16
+ * - U+2028 / U+2029, which historically split JS and JSON parsers.
17
+ *
18
+ * None of this is caught by anything in `eslint:recommended`. In
19
+ * particular `no-irregular-whitespace` defaults to `skipStrings: true`,
20
+ * so it exempts string literals — exactly where these characters land.
21
+ *
22
+ * The fix is always the same: write the escape (the six-character backslash-u form),
23
+ * never the literal character. Runtime behaviour is identical; tool
24
+ * visibility is not.
25
+ *
26
+ * ZWJ/ZWNJ inside an emoji sequence are legitimate and are not reported —
27
+ * a rule with false positives is a rule someone turns off.
28
+ *
29
+ * The byte-level floor under this rule is the control-byte gate of
30
+ * `@open-tomato/gates`, which scans every tracked file (linted or not) on
31
+ * a bare checkout. Its test suite asserts the two implementations agree
32
+ * on what counts as unsafe.
33
+ */
34
+
35
+ /** C0 controls except TAB/LF/CR, plus DEL. */
36
+ const C0_AND_DEL = new Set([
37
+ ...Array.from({ length: 0x20 }, (_, c) => c).filter(
38
+ (c) => c !== 0x09 && c !== 0x0a && c !== 0x0d,
39
+ ),
40
+ 0x7f,
41
+ ]);
42
+
43
+ /** Bidirectional overrides and isolates — the Trojan Source set. */
44
+ const BIDI = new Set([
45
+ 0x202a, 0x202b, 0x202c, 0x202d, 0x202e,
46
+ 0x2066, 0x2067, 0x2068, 0x2069,
47
+ ]);
48
+
49
+ /** Invisible / default-ignorable characters with no business in source. */
50
+ const INVISIBLE = new Set([
51
+ 0x00ad, // SOFT HYPHEN
52
+ 0x200b, // ZERO WIDTH SPACE
53
+ 0x200e, // LEFT-TO-RIGHT MARK
54
+ 0x200f, // RIGHT-TO-LEFT MARK
55
+ 0x2060, // WORD JOINER
56
+ 0xfeff, // ZERO WIDTH NO-BREAK SPACE (BOM when leading)
57
+ ]);
58
+
59
+ /** Parser-splitting separators. */
60
+ const SEPARATORS = new Set([0x2028, 0x2029]);
61
+
62
+ /** Legitimate inside emoji sequences, suspicious anywhere else. */
63
+ const EMOJI_JOINERS = new Set([0x200c, 0x200d]);
64
+
65
+ // Deliberately not \p{Emoji_Component}: that property includes ASCII
66
+ // digits, `#` and `*`, which would let `1<ZWJ>2` pass as an "emoji
67
+ // sequence". Regional indicators and the keycap mark are left out too —
68
+ // flags and keycap sequences never use ZWJ, and both trip
69
+ // `no-misleading-character-class`.
70
+ const EMOJI_ADJACENT =
71
+ /[\p{Extended_Pictographic}\p{Emoji_Modifier}\u{FE0F}]/u;
72
+
73
+ /**
74
+ * Code point ending at `i`, walking back over a surrogate pair. Indexing
75
+ * with `text[i - 1]` returns a lone low surrogate for any astral emoji,
76
+ * which never matches a Unicode property escape — that read every real
77
+ * person-plus-laptop ZWJ sequence as a violation.
78
+ */
79
+ function codePointBefore(text, i) {
80
+ if (i <= 0) return -1;
81
+ const lo = text.charCodeAt(i - 1);
82
+ if (lo >= 0xdc00 && lo <= 0xdfff && i >= 2) {
83
+ const hi = text.charCodeAt(i - 2);
84
+ if (hi >= 0xd800 && hi <= 0xdbff) {
85
+ return (hi - 0xd800) * 0x400 + (lo - 0xdc00) + 0x10000;
86
+ }
87
+ }
88
+ return lo;
89
+ }
90
+
91
+ const isEmojiAdjacent = (code) => code >= 0 && EMOJI_ADJACENT.test(String.fromCodePoint(code));
92
+
93
+ const label = (code) => {
94
+ if (C0_AND_DEL.has(code)) return 'control character';
95
+ if (BIDI.has(code)) return 'bidirectional override (Trojan Source)';
96
+ if (SEPARATORS.has(code)) return 'line/paragraph separator';
97
+ if (EMOJI_JOINERS.has(code)) return 'zero-width joiner outside an emoji sequence';
98
+ return 'invisible character';
99
+ };
100
+
101
+ const hex = (code) => `U+${code.toString(16).toUpperCase()
102
+ .padStart(4, '0')}`;
103
+
104
+ /**
105
+ * Every unsafe character in `text`, as `{ index, code, kind }`.
106
+ * Exported so the control-byte gate of `@open-tomato/gates` can assert
107
+ * the two agree.
108
+ */
109
+ export function findUnsafeUnicode(text) {
110
+ const found = [];
111
+ for (let i = 0; i < text.length; i++) {
112
+ const code = text.codePointAt(i);
113
+
114
+ // A leading BOM is a file-encoding artifact, not a smuggled character.
115
+ if (code === 0xfeff && i === 0) continue;
116
+
117
+ // ZWJ/ZWNJ are how emoji sequences are built (e.g. a person + a
118
+ // laptop). Only report one that is not doing that job.
119
+ if (EMOJI_JOINERS.has(code)) {
120
+ const prev = codePointBefore(text, i);
121
+ const next = i + 1 < text.length
122
+ ? text.codePointAt(i + 1)
123
+ : -1;
124
+ if (isEmojiAdjacent(prev) && isEmojiAdjacent(next)) continue;
125
+ found.push({ index: i, code, kind: label(code) });
126
+ continue;
127
+ }
128
+
129
+ if (
130
+ C0_AND_DEL.has(code) ||
131
+ BIDI.has(code) ||
132
+ INVISIBLE.has(code) ||
133
+ SEPARATORS.has(code)
134
+ ) {
135
+ found.push({ index: i, code, kind: label(code) });
136
+ }
137
+ }
138
+ return found;
139
+ }
140
+
141
+ /** 1-based line, 0-based column (the shape ESLint's `loc` wants). */
142
+ function locAt(text, index) {
143
+ let line = 1;
144
+ let lineStart = 0;
145
+ for (let i = 0; i < index; i++) {
146
+ if (text[i] === '\n') {
147
+ line += 1;
148
+ lineStart = i + 1;
149
+ }
150
+ }
151
+ return { line, column: index - lineStart };
152
+ }
153
+
154
+ export const noUnsafeUnicode = {
155
+ meta: {
156
+ type: 'problem',
157
+ docs: {
158
+ description:
159
+ 'Disallow control, bidirectional-override and invisible characters in source; write them as escapes instead.',
160
+ },
161
+ schema: [],
162
+ messages: {
163
+ unsafe:
164
+ '{{kind}} {{hex}} written literally. Use the escape "\\u{{escape}}" instead — a literal one is invisible in review and can make git and grep report nothing.',
165
+ },
166
+ },
167
+ create(context) {
168
+ const check = () => {
169
+ const { text } = context.sourceCode;
170
+ for (const { index, code, kind } of findUnsafeUnicode(text)) {
171
+ const start = locAt(text, index);
172
+ context.report({
173
+ loc: { start, end: { line: start.line, column: start.column + 1 } },
174
+ messageId: 'unsafe',
175
+ data: {
176
+ kind: kind.charAt(0).toUpperCase() + kind.slice(1),
177
+ hex: hex(code),
178
+ escape: code.toString(16).toUpperCase()
179
+ .padStart(4, '0'),
180
+ },
181
+ });
182
+ }
183
+ };
184
+ // `Program` covers JS/TS and the jsonc parser; `root` covers mdast, so
185
+ // one rule serves the code, JSON and Markdown blocks of
186
+ // `@open-tomato/eslint-config`.
187
+ return { Program: check, root: check };
188
+ },
189
+ };