@kashi-ui/eslint-plugin 0.0.0-stage → 2.30.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.
@@ -0,0 +1,149 @@
1
+ // قانون‌های نگارش فارسی؛ همه روی lintPersianText از @kashi-ui/persian ساخته شده‌اند.
2
+ import { DOCS, metaMessages, reporter, visible } from "../util.js";
3
+ import { issuesOf, textVisitors } from "../text.js";
4
+ const IGNORE_ATTRIBUTES = { type: "array", items: { type: "string" }, description: "attributeهای اضافه‌ای که متن نیستند" };
5
+ function textRule(spec) {
6
+ return {
7
+ meta: {
8
+ type: "suggestion",
9
+ fixable: "code",
10
+ docs: { description: spec.description, descriptionFa: spec.descriptionFa, recommended: true, url: `${DOCS}#${spec.name}` },
11
+ schema: [{ type: "object", properties: { ignoreAttributes: IGNORE_ATTRIBUTES, ...spec.schema }, additionalProperties: false }],
12
+ messages: metaMessages(spec.messages),
13
+ },
14
+ create(context) {
15
+ const options = (context.options[0] ?? {});
16
+ const lintOptions = spec.lintOptions?.(options) ?? {};
17
+ const report = reporter(context, spec.messages);
18
+ return textVisitors(context, { ignoreAttributes: options.ignoreAttributes }, (segment) => {
19
+ // اشتباه‌های چسبیده به هم (مثل «يك») یک گزارش با یک اصلاح می‌شوند؛ ESLint اصلاح‌های هم‌مرز را در یک دور اعمال نمی‌کند
20
+ const groups = [];
21
+ for (const issue of issuesOf(segment, lintOptions)) {
22
+ if (!spec.types.includes(issue.type))
23
+ continue;
24
+ const last = groups[groups.length - 1];
25
+ const prev = last?.[last.length - 1];
26
+ if (prev && issue.start <= prev.end && spec.messageFor(issue) === spec.messageFor(prev))
27
+ last.push(issue);
28
+ else
29
+ groups.push([issue]);
30
+ }
31
+ for (const group of groups) {
32
+ const first = group[0];
33
+ const from = first.start;
34
+ const to = Math.max(...group.map((i) => i.end));
35
+ let replacement = "";
36
+ let pos = from;
37
+ for (const i of group) {
38
+ replacement += segment.text.slice(pos, Math.max(pos, i.start)) + (i.start >= pos ? i.replacement : "");
39
+ pos = Math.max(pos, i.end);
40
+ }
41
+ replacement += segment.text.slice(pos, to);
42
+ const found = segment.text.slice(from, to);
43
+ const start = segment.start + from;
44
+ const end = segment.start + to;
45
+ const loc = {
46
+ start: context.sourceCode.getLocFromIndex(start),
47
+ end: context.sourceCode.getLocFromIndex(Math.max(end, start + 1)),
48
+ };
49
+ report({
50
+ loc,
51
+ messageId: spec.messageFor(first),
52
+ data: { found: visible(found), replacement: visible(replacement), context: visible(segment.text.slice(Math.max(0, from - 8), to + 8).trim()) },
53
+ fix: (fixer) => fixer.replaceTextRange([start, end], replacement),
54
+ });
55
+ }
56
+ });
57
+ },
58
+ };
59
+ }
60
+ export const noArabicChars = textRule({
61
+ name: "no-arabic-chars",
62
+ description: "Disallow Arabic Yeh/Kaf (ي ى ك) and Arabic presentation forms in Persian text",
63
+ descriptionFa: "«ي»، «ى» و «ك» عربی و شکل‌های نمایشی عربی (کپی از PDF) در متن فارسی ممنوع است.",
64
+ types: ["arabic-char"],
65
+ messages: {
66
+ arabic: ["«{{found}}» عربی است؛ «{{replacement}}» فارسی بنویسید", "“{{found}}” is an Arabic letter; use the Persian “{{replacement}}”"],
67
+ },
68
+ messageFor: () => "arabic",
69
+ });
70
+ export const persianDigits = textRule({
71
+ name: "persian-digits",
72
+ description: "Use one script for digits in Persian text (Persian digits by default)",
73
+ descriptionFa: "ارقام عربی (٤٥٦) و ارقام لاتین کنار متن فارسی ← ارقام فارسی؛ یا با prefer: \"latin\" برعکس.", // eslint-disable-line kashi/persian-digits -- نمونهٔ غلط در توضیح قانون
74
+ types: ["digit"],
75
+ messages: {
76
+ toPersian: ["رقم «{{found}}» در متن فارسی؛ «{{replacement}}» بنویسید", "Digits “{{found}}” in Persian text; use “{{replacement}}”"],
77
+ toLatin: ["رقم «{{found}}»؛ این پروژه ارقام لاتین «{{replacement}}» می‌خواهد", "Digits “{{found}}”; this project uses Latin digits “{{replacement}}”"],
78
+ },
79
+ schema: { prefer: { enum: ["fa", "latin"], description: "خط ارقام" } },
80
+ lintOptions: (o) => ({ digits: o.prefer === "latin" ? "latin" : "fa" }),
81
+ messageFor: (i) => (/[0-9]/.test(i.replacement) ? "toLatin" : "toPersian"),
82
+ });
83
+ export const zwnj = textRule({
84
+ name: "zwnj",
85
+ description: "Require a zero-width non-joiner (half-space) in می/نمی prefixes and ها/تر/ترین suffixes",
86
+ descriptionFa: "نیم‌فاصلهٔ جاافتاده: «می شود»، «کتاب ها»، «بزرگ تر»، «خسته ام»؛ و فاصلهٔ صفرعرض (ZWSP) به‌جای نیم‌فاصله.", // eslint-disable-line kashi/zwnj -- نمونهٔ غلط در توضیح قانون
87
+ types: ["missing-zwnj", "zwsp"],
88
+ messages: {
89
+ missing: ["«{{context}}»: این‌جا نیم‌فاصله لازم است، نه فاصله", "“{{context}}”: use a half-space (ZWNJ) here, not a space"],
90
+ zwsp: ["«{{context}}»: فاصلهٔ صفرعرض (U+200B) به‌جای نیم‌فاصله (U+200C)", "“{{context}}”: zero-width space (U+200B) used instead of ZWNJ (U+200C)"],
91
+ },
92
+ messageFor: (i) => (i.type === "zwsp" ? "zwsp" : "missing"),
93
+ });
94
+ export const noInvalidZwnj = textRule({
95
+ name: "no-invalid-zwnj",
96
+ description: "Disallow repeated or misplaced zero-width non-joiners",
97
+ descriptionFa: "نیم‌فاصلهٔ تکراری، یا نیم‌فاصله کنار فاصله، علامت، رقم یا حرف لاتین.",
98
+ types: ["invalid-zwnj"],
99
+ messages: {
100
+ invalid: ["«{{context}}»: نیم‌فاصلهٔ بی‌جا یا تکراری", "“{{context}}”: misplaced or repeated ZWNJ"],
101
+ },
102
+ messageFor: () => "invalid",
103
+ });
104
+ export const punctuationSpacing = textRule({
105
+ name: "punctuation-spacing",
106
+ description: "Enforce Persian spacing around punctuation: no space before «،» «؛» «؟» «!», one space after",
107
+ descriptionFa: "فاصلهٔ اضافه پیش از «،» «؛» «؟» «!» «.» «:» و بستن پرانتز/گیومه، فاصلهٔ اضافه پس از باز کردنشان، و فاصلهٔ جاافتاده پس از «،» «؛» «؟» «!».",
108
+ types: ["space-before-punctuation", "missing-space-after-punctuation"],
109
+ messages: {
110
+ before: ["«{{context}}»: فاصلهٔ اضافه کنار علامت", "“{{context}}”: extra space next to punctuation"],
111
+ after: ["«{{context}}»: پس از علامت یک فاصله لازم است", "“{{context}}”: add a space after the punctuation mark"],
112
+ },
113
+ messageFor: (i) => (i.type === "missing-space-after-punctuation" ? "after" : "before"),
114
+ });
115
+ export const persianPunctuation = textRule({
116
+ name: "persian-punctuation",
117
+ description: "Use Persian comma, question mark and semicolon (، ؟ ؛) in Persian text",
118
+ descriptionFa: "«,» «?» «;» لاتین کنار متن فارسی ← «،» «؟» «؛».",
119
+ types: ["latin-punctuation"],
120
+ messages: {
121
+ latin: ["«{{found}}» لاتین در متن فارسی؛ «{{replacement}}» بنویسید", "Latin “{{found}}” in Persian text; use “{{replacement}}”"],
122
+ },
123
+ messageFor: () => "latin",
124
+ });
125
+ export const noKashida = textRule({
126
+ name: "no-kashida",
127
+ description: "Disallow kashida (tatweel, ـ) between letters",
128
+ descriptionFa: "کشیده (ـ) بین حروف؛ کشیدهٔ آغاز کلمه (مثل «ـها» برای نشان دادن پسوند) مجاز است.",
129
+ types: ["kashida"],
130
+ messages: {
131
+ kashida: ["«{{context}}»: کشیده (ـ) را حذف کنید", "“{{context}}”: remove the kashida (tatweel)"],
132
+ },
133
+ messageFor: () => "kashida",
134
+ });
135
+ export const noExtraDiacritics = textRule({
136
+ name: "no-extra-diacritics",
137
+ description: "Disallow repeated or orphan diacritics (and, with mode \"all\", optional harakat)",
138
+ descriptionFa: "اعراب تکراری یا بی‌پایه؛ با mode: \"all\" هر اعرابی جز «ً» «ّ» «ٔ» (یا allow).", // eslint-disable-line kashi/no-extra-diacritics -- نمونه‌های اعراب در توضیح قانون
139
+ types: ["diacritic"],
140
+ messages: {
141
+ diacritic: ["«{{context}}»: اعراب اضافه", "“{{context}}”: extra diacritic"],
142
+ },
143
+ schema: {
144
+ mode: { enum: ["invalid", "all"] },
145
+ allow: { type: "string", description: "اعراب مجاز با mode: all" },
146
+ },
147
+ lintOptions: (o) => ({ diacritics: o.mode === "all" ? "all" : "invalid", ...(typeof o.allow === "string" ? { allowedDiacritics: o.allow } : {}) }),
148
+ messageFor: () => "diacritic",
149
+ });
package/dist/text.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { Rule } from "eslint";
2
+ import { type LintPersianTextOptions, type PersianTextIssue } from "@kashi-ui/persian";
3
+ export type AnyNode = any;
4
+ export type SegmentKind = "string" | "template" | "jsx-text" | "jsx-attribute" | "vue-text" | "vue-attribute" | "svelte-text" | "svelte-attribute";
5
+ export interface Segment {
6
+ node: AnyNode;
7
+ kind: SegmentKind;
8
+ /** جای شروع متن خام در کد */
9
+ start: number;
10
+ text: string;
11
+ }
12
+ export declare function isTextAttribute(name: string, extraIgnored?: readonly string[]): boolean;
13
+ export interface CollectOptions {
14
+ /** attributeهای اضافه‌ای که متن نیستند */
15
+ ignoreAttributes?: readonly string[];
16
+ }
17
+ /** برای هر متن فارسی‌دار فایل onSegment را صدا می‌زند */
18
+ export declare function textVisitors(context: Rule.RuleContext, options: CollectOptions, onSegment: (s: Segment) => void): Rule.RuleListener;
19
+ export declare function issuesOf(segment: Segment, options: LintPersianTextOptions): PersianTextIssue[];
package/dist/text.js ADDED
@@ -0,0 +1,267 @@
1
+ // متن‌هایی که قانون‌های نگارشی بررسی می‌کنند: رشته‌ها، template literalها، متن JSX، attributeهای متنی JSX،
2
+ // و (با vue-eslint-parser و svelte-eslint-parser) متن و attributeهای قالب Vue و Svelte.
3
+ // هر متن به شکل «بازهٔ خام در کد» برگردانده می‌شود تا اصلاح‌ها دقیقاً همان نویسه‌ها را عوض کنند.
4
+ import { lintPersianText } from "@kashi-ui/persian";
5
+ /** attributeهایی که متن نیستند (نشانی، کلاس، شناسه، الگو…) */
6
+ const NON_TEXT_ATTRIBUTES = new Set([
7
+ "key", "ref", "id", "class", "classname", "class:list", "style", "href", "src", "srcset", "to", "as", "type", "name", "rel", "target",
8
+ "role", "htmlfor", "for", "method", "action", "pattern", "accept", "autocomplete", "inputmode", "lang", "dir", "xmlns", "viewbox",
9
+ "d", "fill", "stroke", "transform", "points", "path", "width", "height", "slot", "is", "form", "list", "enctype", "media",
10
+ "sizes", "poster", "download", "ping", "referrerpolicy", "loading", "decoding", "crossorigin", "integrity", "nonce", "tabindex",
11
+ "v-bind", "v-model", "itemprop", "itemtype", "property", "http-equiv", "charset", "variant", "size", "color", "icon", "mode",
12
+ ]);
13
+ const NON_TEXT_SUFFIX = /(classname|class|href|url|uri|src|id|key|pattern|path|icon|variant|color|size|mode|type|format|locale|dir|lang)$/i;
14
+ export function isTextAttribute(name, extraIgnored = []) {
15
+ const n = name.toLowerCase();
16
+ if (NON_TEXT_ATTRIBUTES.has(n) || n.startsWith("data-") || n.startsWith("on") && /^on[A-Z:-]/.test(name))
17
+ return false;
18
+ if (n.includes(":") && !n.startsWith("aria"))
19
+ return false; // v-bind:، on:click، xlink:href
20
+ if (NON_TEXT_SUFFIX.test(name) && !/^(title|label|aria-.*)$/i.test(name))
21
+ return false;
22
+ return !extraIgnored.some((x) => x.toLowerCase() === n);
23
+ }
24
+ /** عنصرهایی که محتوایشان متن نوشتاری نیست */
25
+ const CODE_ELEMENTS = new Set(["code", "pre", "kbd", "samp", "var", "script", "style", "textarea"]);
26
+ /** متدهایی که آرگومان رشته‌ای‌شان دادهٔ مقایسه است، نه متن (جدول تبدیل «ي»←«ی» باید «ي» بماند) */
27
+ const MATCHING_METHODS = new Set([
28
+ "replace", "replaceAll", "split", "includes", "indexOf", "lastIndexOf", "startsWith", "endsWith", "match", "matchAll",
29
+ "search", "test", "localeCompare", "has", "get", "delete", "at", "charCodeAt", "codePointAt", "normalize",
30
+ ]);
31
+ const SKIP_TAGS = /^(css|sql|gql|graphql|keyframes|createGlobalStyle|injectGlobal|styled|tw|html\.raw|svg)$/;
32
+ function calleeName(node) {
33
+ if (!node)
34
+ return "";
35
+ if (node.type === "Identifier")
36
+ return node.name;
37
+ if (node.type === "MemberExpression")
38
+ return `${calleeName(node.object)}.${node.property?.name ?? ""}`;
39
+ if (node.type === "CallExpression")
40
+ return calleeName(node.callee);
41
+ return "";
42
+ }
43
+ /** آیا رشته در جایی است که متن نوشتاری نیست (import، کلید، مقایسه، regex…) */
44
+ function isDataPosition(node) {
45
+ let child = node;
46
+ let parent = node.parent;
47
+ // پرانتز و as و satisfies را رد کن
48
+ while (parent && (parent.type === "TSAsExpression" || parent.type === "TSSatisfiesExpression" || parent.type === "TSNonNullExpression" || parent.type === "ChainExpression")) {
49
+ child = parent;
50
+ parent = parent.parent;
51
+ }
52
+ if (!parent)
53
+ return false;
54
+ switch (parent.type) {
55
+ case "ImportDeclaration":
56
+ case "ExportAllDeclaration":
57
+ case "ExportNamedDeclaration":
58
+ case "ImportExpression":
59
+ case "TSExternalModuleReference":
60
+ case "TSModuleDeclaration":
61
+ case "ImportAttribute":
62
+ return true;
63
+ case "TSLiteralType":
64
+ return parent.parent?.type === "TSImportType";
65
+ case "ExpressionStatement":
66
+ return !!parent.directive;
67
+ case "Property":
68
+ return parent.key === child && !parent.computed;
69
+ case "PropertyDefinition":
70
+ case "MethodDefinition":
71
+ case "TSPropertySignature":
72
+ case "TSEnumMember":
73
+ return parent.key === child || parent.id === child;
74
+ case "MemberExpression":
75
+ return parent.property === child;
76
+ case "BinaryExpression":
77
+ return ["===", "==", "!==", "!=", "in", "instanceof"].includes(parent.operator);
78
+ case "SwitchCase":
79
+ return parent.test === child;
80
+ case "CallExpression":
81
+ case "NewExpression": {
82
+ const name = calleeName(parent.callee);
83
+ if (parent.callee === child)
84
+ return false;
85
+ if (name === "require" || name === "RegExp" || name.endsWith(".require") || name === "Symbol" || name === "Symbol.for")
86
+ return true;
87
+ const method = parent.callee?.type === "MemberExpression" ? parent.callee.property?.name : undefined;
88
+ return !!method && MATCHING_METHODS.has(method);
89
+ }
90
+ case "TaggedTemplateExpression":
91
+ return true;
92
+ }
93
+ return false;
94
+ }
95
+ function jsxName(node) {
96
+ if (!node)
97
+ return "";
98
+ if (node.type === "JSXIdentifier")
99
+ return node.name;
100
+ if (node.type === "JSXNamespacedName")
101
+ return `${node.namespace.name}:${node.name.name}`;
102
+ if (node.type === "JSXMemberExpression")
103
+ return `${jsxName(node.object)}.${jsxName(node.property)}`;
104
+ return "";
105
+ }
106
+ /** آیا متن JSX داخل عنصری است که نباید بررسی شود: <code>، <pre>، lang غیرفارسی، translate="no" */
107
+ function insideSkippedJsx(node) {
108
+ for (let p = node.parent; p; p = p.parent) {
109
+ if (p.type !== "JSXElement")
110
+ continue;
111
+ const open = p.openingElement;
112
+ if (CODE_ELEMENTS.has(jsxName(open.name)))
113
+ return true;
114
+ for (const a of open.attributes ?? []) {
115
+ if (a.type !== "JSXAttribute" || a.value?.type !== "Literal" || typeof a.value.value !== "string")
116
+ continue;
117
+ const n = jsxName(a.name);
118
+ if (n === "lang")
119
+ return !/^fa\b|^fa-|^fa$/i.test(a.value.value);
120
+ if (n === "translate" && a.value.value === "no")
121
+ return true;
122
+ }
123
+ }
124
+ return false;
125
+ }
126
+ function insideSkippedVue(node) {
127
+ for (let p = node.parent; p; p = p.parent) {
128
+ if (p.type !== "VElement")
129
+ continue;
130
+ if (CODE_ELEMENTS.has(String(p.rawName ?? p.name).toLowerCase()))
131
+ return true;
132
+ for (const a of p.startTag?.attributes ?? []) {
133
+ if (a.directive || !a.value)
134
+ continue;
135
+ if (a.key.name === "lang")
136
+ return !/^fa(\b|-|$)/i.test(a.value.value);
137
+ if (a.key.name === "translate" && a.value.value === "no")
138
+ return true;
139
+ }
140
+ }
141
+ return false;
142
+ }
143
+ function insideSkippedSvelte(node) {
144
+ for (let p = node.parent; p; p = p.parent) {
145
+ if (p.type !== "SvelteElement")
146
+ continue;
147
+ const name = p.name?.name ?? p.name?.value ?? "";
148
+ if (CODE_ELEMENTS.has(String(name).toLowerCase()))
149
+ return true;
150
+ for (const a of p.startTag?.attributes ?? []) {
151
+ if (a.type !== "SvelteAttribute" || a.value?.length !== 1 || a.value[0].type !== "SvelteLiteral")
152
+ continue;
153
+ if (a.key.name === "lang")
154
+ return !/^fa(\b|-|$)/i.test(a.value[0].value);
155
+ if (a.key.name === "translate" && a.value[0].value === "no")
156
+ return true;
157
+ }
158
+ }
159
+ return false;
160
+ }
161
+ /** برای هر متن فارسی‌دار فایل onSegment را صدا می‌زند */
162
+ export function textVisitors(context, options, onSegment) {
163
+ const source = context.sourceCode;
164
+ const text = source.text;
165
+ const PERSIAN = /[؀-ۿﭐ-﷿ﹰ-ﻼ]/;
166
+ const emit = (node, kind, start, end) => {
167
+ if (end <= start)
168
+ return;
169
+ const raw = text.slice(start, end);
170
+ if (PERSIAN.test(raw))
171
+ onSegment({ node, kind, start, text: raw });
172
+ };
173
+ const attrOk = (name) => isTextAttribute(name, options.ignoreAttributes);
174
+ const literalInJsxAttr = (node) => {
175
+ let p = node.parent;
176
+ if (p?.type === "JSXExpressionContainer")
177
+ p = p.parent;
178
+ return p?.type === "JSXAttribute" ? jsxName(p.name) : null;
179
+ };
180
+ const listener = {
181
+ Literal(node) {
182
+ if (typeof node.value !== "string")
183
+ return;
184
+ const attr = literalInJsxAttr(node);
185
+ if (attr !== null) {
186
+ if (!attrOk(attr) || insideSkippedJsx(node.parent))
187
+ return;
188
+ emit(node, "jsx-attribute", node.range[0] + 1, node.range[1] - 1);
189
+ return;
190
+ }
191
+ if (isDataPosition(node))
192
+ return;
193
+ emit(node, "string", node.range[0] + 1, node.range[1] - 1);
194
+ },
195
+ TemplateLiteral(node) {
196
+ const parent = node.parent;
197
+ if (parent?.type === "TaggedTemplateExpression") {
198
+ const tag = calleeName(parent.tag);
199
+ if (tag === "String.raw" || SKIP_TAGS.test(tag) || /^styled\b/.test(tag) || /\b(css|sql|gql|graphql)$/.test(tag))
200
+ return;
201
+ }
202
+ else if (isDataPosition(node))
203
+ return;
204
+ const attr = literalInJsxAttr(node);
205
+ if (attr !== null && (!attrOk(attr) || insideSkippedJsx(node.parent)))
206
+ return;
207
+ for (const q of node.quasis) {
208
+ const start = q.range[0] + 1;
209
+ const end = q.range[1] - (q.tail ? 1 : 2);
210
+ emit(q, "template", start, end);
211
+ }
212
+ },
213
+ JSXText(node) {
214
+ if (insideSkippedJsx(node))
215
+ return;
216
+ emit(node, "jsx-text", node.range[0], node.range[1]);
217
+ },
218
+ };
219
+ // قالب Vue
220
+ const services = source.parserServices;
221
+ if (services?.defineTemplateBodyVisitor) {
222
+ return services.defineTemplateBodyVisitor({
223
+ VText(node) {
224
+ if (insideSkippedVue(node))
225
+ return;
226
+ emit(node, "vue-text", node.range[0], node.range[1]);
227
+ },
228
+ VLiteral(node) {
229
+ const attr = node.parent;
230
+ if (attr?.type !== "VAttribute" || attr.directive || !attrOk(attr.key.name) || insideSkippedVue(attr.parent))
231
+ return;
232
+ emit(node, "vue-attribute", node.range[0] + 1, node.range[1] - 1);
233
+ },
234
+ // رشته‌های داخل {{ }} و :prop
235
+ Literal: listener.Literal,
236
+ TemplateLiteral: listener.TemplateLiteral,
237
+ }, listener);
238
+ }
239
+ // Svelte
240
+ listener.SvelteText = (node) => {
241
+ if (insideSkippedSvelte(node))
242
+ return;
243
+ emit(node, "svelte-text", node.range[0], node.range[1]);
244
+ };
245
+ listener.SvelteLiteral = (node) => {
246
+ const attr = node.parent;
247
+ if (attr?.type !== "SvelteAttribute" || !attrOk(attr.key.name) || insideSkippedSvelte(attr.parent))
248
+ return;
249
+ emit(node, "svelte-attribute", node.range[0], node.range[1]);
250
+ };
251
+ return listener;
252
+ }
253
+ // نتیجهٔ lintPersianText برای هر متن یک بار حساب می‌شود، حتی اگر ده قانون آن را بخواهند
254
+ const cache = new WeakMap();
255
+ export function issuesOf(segment, options) {
256
+ const key = JSON.stringify(options);
257
+ let byOpts = cache.get(segment.node);
258
+ if (!byOpts)
259
+ cache.set(segment.node, (byOpts = new Map()));
260
+ const k = `${segment.start}:${key}`;
261
+ let issues = byOpts.get(k);
262
+ if (!issues) {
263
+ issues = lintPersianText(segment.text, options);
264
+ byOpts.set(k, issues);
265
+ }
266
+ return issues;
267
+ }
@@ -0,0 +1,13 @@
1
+ import { KASHI_DATA } from "./generated/kashi-data.js";
2
+ export { KASHI_DATA };
3
+ export declare function isKnownToken(name: string): boolean;
4
+ /** نزدیک‌ترین نام توکن (برای غلط تایپی)، یا undefined */
5
+ export declare function closestToken(name: string): string | undefined;
6
+ /** توکن(های) کاشی برای یک رنگ hex (#abc یا #aabbcc)، یا [] */
7
+ export declare function tokensForColor(hex: string): string[];
8
+ export type SizeKind = "space" | "radius" | "fontSize";
9
+ /** توکن کاشی برای یک اندازه (مثل 1rem یا 16px)، یا undefined */
10
+ export declare function tokenForSize(kind: SizeKind, value: string): string | undefined;
11
+ /** نوع اندازه بر اساس خاصیت CSS (kebab یا camel) */
12
+ export declare function sizeKindOf(prop: string): SizeKind | undefined;
13
+ export declare function isColorProperty(prop: string): boolean;
package/dist/tokens.js ADDED
@@ -0,0 +1,66 @@
1
+ // منطق مشترک قانون‌های توکن (در ESLint و Stylelint همین فایل کپی نمی‌شود؛ stylelint-plugin آن را از این پکیج می‌گیرد)
2
+ import { KASHI_DATA } from "./generated/kashi-data.js";
3
+ export { KASHI_DATA };
4
+ const NAMES = new Set(KASHI_DATA.names);
5
+ export function isKnownToken(name) {
6
+ return NAMES.has(name);
7
+ }
8
+ function distance(a, b) {
9
+ const dp = Array.from({ length: b.length + 1 }, (_, i) => i);
10
+ for (let i = 1; i <= a.length; i++) {
11
+ let prev = dp[0];
12
+ dp[0] = i;
13
+ for (let j = 1; j <= b.length; j++) {
14
+ const tmp = dp[j];
15
+ dp[j] = Math.min(dp[j] + 1, dp[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
16
+ prev = tmp;
17
+ }
18
+ }
19
+ return dp[b.length];
20
+ }
21
+ /** نزدیک‌ترین نام توکن (برای غلط تایپی)، یا undefined */
22
+ export function closestToken(name) {
23
+ let best, bestD = Infinity;
24
+ for (const n of KASHI_DATA.names) {
25
+ const d = distance(name, n);
26
+ if (d < bestD)
27
+ [best, bestD] = [n, d];
28
+ }
29
+ return bestD <= Math.max(2, Math.floor(name.length / 5)) ? best : undefined;
30
+ }
31
+ /** توکن(های) کاشی برای یک رنگ hex (#abc یا #aabbcc)، یا [] */
32
+ export function tokensForColor(hex) {
33
+ let h = hex.toLowerCase();
34
+ if (/^#[0-9a-f]{3}$/.test(h))
35
+ h = "#" + [...h.slice(1)].map((c) => c + c).join("");
36
+ // سفید و سیاه خالص عمداً ثابت‌اند (متن روی عکس، چاپ، سایه در color-mix) و نباید با تم عوض شوند
37
+ if (h === "#ffffff" || h === "#000000")
38
+ return [];
39
+ return KASHI_DATA.colors[h] ?? [];
40
+ }
41
+ /** توکن کاشی برای یک اندازه (مثل 1rem یا 16px)، یا undefined */
42
+ export function tokenForSize(kind, value) {
43
+ const m = /^(-?[\d.]+)(px|rem)$/.exec(value.trim());
44
+ if (!m || Number(m[1]) <= 0)
45
+ return undefined;
46
+ // کمتر از ۴px (۰٫۲۵rem) خط مو و تنظیم ریز است، نه فاصله‌گذاری طراحی
47
+ if (kind === "space" && (m[2] === "px" ? Number(m[1]) < 4 : Number(m[1]) < 0.25))
48
+ return undefined;
49
+ return KASHI_DATA[kind][`${+Number(m[1]).toFixed(4)}${m[2]}`];
50
+ }
51
+ /** نوع اندازه بر اساس خاصیت CSS (kebab یا camel) */
52
+ export function sizeKindOf(prop) {
53
+ const p = prop.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase());
54
+ // inset/top/left مختصات جای‌گذاری‌اند، نه فاصله‌گذاری؛ توکن فاصله برایشان معنا ندارد
55
+ if (/^(margin|padding|gap|row-gap|column-gap|scroll-margin|scroll-padding)(-|$)/.test(p))
56
+ return "space";
57
+ if (/radius$/.test(p))
58
+ return "radius";
59
+ if (p === "font-size")
60
+ return "fontSize";
61
+ return undefined;
62
+ }
63
+ export function isColorProperty(prop) {
64
+ const p = prop.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase());
65
+ return /^(color|background|background-color|border(-[a-z-]+)?-color|border(-(top|right|bottom|left|inline|block)(-start|-end)?)?|outline(-color)?|fill|stroke|caret-color|accent-color|text-decoration-color|column-rule-color|box-shadow|text-shadow|stop-color|flood-color|lighting-color|text-emphasis-color)$/.test(p);
66
+ }
package/dist/util.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { Rule } from "eslint";
2
+ import type { InlineDirection } from "@kashi-ui/persian";
3
+ export declare const DOCS = "https://kashi.sepantapouya.com/docs/lint/";
4
+ export type Locale = "fa" | "en" | "both";
5
+ /** تنظیم مشترک همهٔ قانون‌ها: settings.kashi در پیکربندی ESLint */
6
+ export interface KashiSettings {
7
+ /** زبان پیام‌ها @default "both" */
8
+ locale?: Locale;
9
+ /** جهت اصلی پروژه؛ تعیین می‌کند margin-left کدام سمت منطقی است @default "rtl" */
10
+ direction?: InlineDirection;
11
+ tailwind?: {
12
+ /** نسخهٔ Tailwind (مثل 3، "4.1"، "4.3")؛ بدون آن از tailwindcss نصب‌شده خوانده می‌شود */
13
+ version?: string | number;
14
+ /** پیشوند کلاس‌ها در Tailwind 3 (مثل "tw-") */
15
+ prefix?: string;
16
+ };
17
+ }
18
+ export declare function settings(context: Rule.RuleContext): KashiSettings;
19
+ /** پیام دوزبانه: [فارسی، انگلیسی] */
20
+ export type Bilingual = readonly [fa: string, en: string];
21
+ export declare function format(context: Rule.RuleContext, [fa, en]: Bilingual, data?: Record<string, string>): string;
22
+ /** meta.messages: هر پیام همان {{message}} است که format می‌سازد؛ متن دوزبانه در MESSAGES هر قانون است */
23
+ export declare function metaMessages<T extends string>(messages: Record<T, Bilingual>): Record<T, string>;
24
+ export interface ReportArgs<T extends string> {
25
+ node?: any;
26
+ loc?: {
27
+ start: {
28
+ line: number;
29
+ column: number;
30
+ };
31
+ end: {
32
+ line: number;
33
+ column: number;
34
+ };
35
+ };
36
+ messageId: T;
37
+ data?: Record<string, string>;
38
+ fix?: Rule.ReportFixer | null;
39
+ suggest?: Rule.SuggestionReportDescriptor[];
40
+ }
41
+ export declare function reporter<T extends string>(context: Rule.RuleContext, messages: Record<T, Bilingual>): (descriptor: ReportArgs<T>) => void;
42
+ /** نمایش نویسه‌های نامرئی در پیام */
43
+ export declare function visible(s: string): string;
44
+ /** نسخهٔ tailwindcss نصب‌شده در پروژه (از cwd)، یا null */
45
+ export declare function installedTailwind(cwd: string): string | null;
46
+ /** نسخهٔ Tailwind به شکل [major, minor] */
47
+ export declare function tailwindVersion(context: Rule.RuleContext): [number, number] | null;
package/dist/util.js ADDED
@@ -0,0 +1,67 @@
1
+ import { createRequire } from "node:module";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ export const DOCS = "https://kashi.sepantapouya.com/docs/lint/";
5
+ export function settings(context) {
6
+ return context.settings?.kashi ?? {};
7
+ }
8
+ export function format(context, [fa, en], data = {}) {
9
+ const fill = (s) => s.replace(/\{\{\s*(\w+)\s*\}\}/g, (_, k) => data[k] ?? "");
10
+ const locale = settings(context).locale ?? "both";
11
+ if (locale === "fa")
12
+ return fill(fa);
13
+ if (locale === "en")
14
+ return fill(en);
15
+ return `${fill(fa)} (${fill(en)})`;
16
+ }
17
+ /** meta.messages: هر پیام همان {{message}} است که format می‌سازد؛ متن دوزبانه در MESSAGES هر قانون است */
18
+ export function metaMessages(messages) {
19
+ return Object.fromEntries(Object.keys(messages).map((k) => [k, "{{message}}"]));
20
+ }
21
+ export function reporter(context, messages) {
22
+ return (descriptor) => {
23
+ const { messageId, data, suggest, ...rest } = descriptor;
24
+ const message = format(context, messages[messageId], data);
25
+ if (suggest) {
26
+ rest.suggest = suggest.map((s) => {
27
+ const id = s.messageId;
28
+ return id && messages[id] ? { ...s, data: { ...s.data, message: format(context, messages[id], s.data) } } : s;
29
+ });
30
+ }
31
+ context.report({ ...rest, messageId, data: { ...data, message } });
32
+ };
33
+ }
34
+ /** نمایش نویسه‌های نامرئی در پیام */
35
+ export function visible(s) {
36
+ return s
37
+ .replace(/‌/g, "[ZWNJ]")
38
+ .replace(/​/g, "[ZWSP]")
39
+ .replace(/ـ/g, "ـ")
40
+ .replace(/[\u200E\u200F\u061C\u202A-\u202E\u2066-\u2069]/g, (c) => `[U+${c.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}]`)
41
+ .replace(/^ +| +$/g, (m) => "␣".repeat(m.length));
42
+ }
43
+ const twCache = new Map();
44
+ /** نسخهٔ tailwindcss نصب‌شده در پروژه (از cwd)، یا null */
45
+ export function installedTailwind(cwd) {
46
+ if (twCache.has(cwd))
47
+ return twCache.get(cwd);
48
+ let v = null;
49
+ try {
50
+ const req = createRequire(join(cwd, "package.json"));
51
+ v = JSON.parse(readFileSync(req.resolve("tailwindcss/package.json"), "utf8")).version;
52
+ }
53
+ catch {
54
+ v = null;
55
+ }
56
+ twCache.set(cwd, v);
57
+ return v;
58
+ }
59
+ /** نسخهٔ Tailwind به شکل [major, minor] */
60
+ export function tailwindVersion(context) {
61
+ const s = settings(context).tailwind?.version ?? installedTailwind(context.cwd ?? process.cwd());
62
+ if (s === null || s === undefined)
63
+ return null;
64
+ const [maj, min] = String(s).split(".").map((n) => Number.parseInt(n, 10));
65
+ // فقط نسخهٔ اصلی (مثل 4) یعنی تازه‌ترین نسخهٔ همان شاخه
66
+ return Number.isFinite(maj) ? [maj, Number.isFinite(min) ? min : 99] : null;
67
+ }