eslint-plugin-twig-lint 0.1.0 → 0.1.1

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/README.md CHANGED
@@ -85,6 +85,19 @@ export default [
85
85
  ];
86
86
  ```
87
87
 
88
+ If your config has entries without `files`, such as `js.configs.recommended` or a shared config, limit them to
89
+ your JavaScript files. Otherwise ESLint also runs their JavaScript rules on `.twig` files, which fails:
90
+
91
+ ```js
92
+ const jsFiles = ["**/*.{js,jsx,mjs,cjs,ts,tsx,mts,cts}"];
93
+
94
+ export default [
95
+ { ...js.configs.recommended, files: jsFiles },
96
+ twigLint.configs.recommended,
97
+ twigLint.configs.drupal,
98
+ ];
99
+ ```
100
+
88
101
  Then run ESLint as usual:
89
102
 
90
103
  ```sh
@@ -175,6 +188,7 @@ automatically. Two of them offer a suggestion that you can apply in the editor.
175
188
  | [`twig-lint/isolated-include`](docs/rules/isolated-include.md) | `include()` with `with_context: false` and `{% include %}` with `only`. Option `embed`. The editor suggests the fix | no |
176
189
  | [`twig-lint/defined-check`](docs/rules/defined-check.md) | `x is defined and x is not empty` → `x is not empty`. Option `mode`: `simplify`, `require` or `allow`. The editor suggests the fix | no |
177
190
  | [`twig-lint/variable-name`](docs/rules/variable-name.md) | `snake_case` for variables, loop variables, macros and arrow function parameters created in the template | no |
191
+ | [`twig-lint/no-debug`](docs/rules/no-debug.md) | Warns about Twig's `dump()`. Options `additionalFunctions` and `functions`. The editor suggests removing it | no |
178
192
  | [`twig-lint/no-raw`](docs/rules/no-raw.md) | Warns about `\|raw`, which turns off escaping. Option `allow` for known-safe values | no |
179
193
  | [`twig-lint/deprecated-spaceless`](docs/rules/deprecated-spaceless.md) | Warns about the `spaceless` filter, deprecated since Twig 3.12 | no |
180
194
 
@@ -186,6 +200,7 @@ Enabled by the `drupal` preset.
186
200
  |---|---|---|---|
187
201
  | [`twig-lint/drupal/attach-library-format`](docs/rules/drupal/attach-library-format.md) | `attach_library('extension/library')`, not a component ID like `'theme:button'` | no | error |
188
202
  | [`twig-lint/drupal/no-translate-variable`](docs/rules/drupal/no-translate-variable.md) | `\|t` on a variable cannot be extracted for translation | no | warn |
203
+ | [`twig-lint/drupal/no-debug`](docs/rules/drupal/no-debug.md) | Debug output from Devel and Twig Tweak, such as `kint()`, `dpm()` and `dd()`. Options `additionalFunctions` and `functions` | no | warn |
189
204
  | [`twig-lint/drupal/component-reference`](docs/rules/drupal/component-reference.md) | Include components by SDC ID, not by file path. Option `folders` | no | off (opt-in) |
190
205
 
191
206
  ### Examples
package/dist/index.d.ts CHANGED
@@ -16,6 +16,7 @@ declare const plugin: {
16
16
  rules: {
17
17
  'drupal/attach-library-format': TwigRuleDefinition;
18
18
  'drupal/component-reference': TwigRuleDefinition;
19
+ 'drupal/no-debug': TwigRuleDefinition;
19
20
  'drupal/no-translate-variable': TwigRuleDefinition;
20
21
  'attribute-spacing': TwigRuleDefinition;
21
22
  'attribute-wrap': TwigRuleDefinition;
@@ -34,6 +35,7 @@ declare const plugin: {
34
35
  'isolated-include': TwigRuleDefinition;
35
36
  'named-arguments': TwigRuleDefinition;
36
37
  'nested-indent': TwigRuleDefinition;
38
+ 'no-debug': TwigRuleDefinition;
37
39
  'no-raw': TwigRuleDefinition;
38
40
  'operator-spacing': TwigRuleDefinition;
39
41
  'punctuation-spacing': TwigRuleDefinition;
package/dist/index.js CHANGED
@@ -22,7 +22,7 @@ const rules = { ...generalRules, ...drupalRules };
22
22
  const plugin = {
23
23
  meta: {
24
24
  name: 'eslint-plugin-twig-lint',
25
- version: '0.1.0',
25
+ version: '0.1.1',
26
26
  namespace: 'twig-lint',
27
27
  },
28
28
  languages: {
@@ -24,7 +24,12 @@ export declare class TwigLanguage {
24
24
  readonly nodeTypeKey = "type";
25
25
  readonly visitorKeys: Record<import("./twig-source-code.ts").TwigNodeType, string[]>;
26
26
  readonly defaultLanguageOptions: {};
27
- validateLanguageOptions(options: Record<string, unknown>): void;
27
+ /**
28
+ * Twig has no language options. Options meant for other languages are ignored rather than rejected:
29
+ * configs without `files`, such as `js.configs.recommended`, pass their JavaScript options
30
+ * (`ecmaVersion`, `sourceType` …) to every file ESLint lints, including `.twig` files.
31
+ */
32
+ validateLanguageOptions(_options: Record<string, unknown>): void;
28
33
  parse(file: File): TwigParseOk | TwigParseFail;
29
34
  createSourceCode(file: File, result: TwigParseOk): TwigSourceCode;
30
35
  }
@@ -9,11 +9,12 @@ export class TwigLanguage {
9
9
  nodeTypeKey = 'type';
10
10
  visitorKeys = visitorKeys;
11
11
  defaultLanguageOptions = {};
12
- validateLanguageOptions(options) {
13
- const keys = Object.keys(options ?? {});
14
- if (keys.length)
15
- throw new TypeError(`twig-lint/twig has no language options (got: ${keys.join(', ')}).`);
16
- }
12
+ /**
13
+ * Twig has no language options. Options meant for other languages are ignored rather than rejected:
14
+ * configs without `files`, such as `js.configs.recommended`, pass their JavaScript options
15
+ * (`ecmaVersion`, `sourceType` …) to every file ESLint lints, including `.twig` files.
16
+ */
17
+ validateLanguageOptions(_options) { }
17
18
  parse(file) {
18
19
  const text = String(file.body);
19
20
  try {
@@ -42,7 +42,7 @@ export default createRule({
42
42
  optionsSchema: { mode: { enum: ['simplify', 'allow', 'require'] } },
43
43
  defaultOptions: { mode: 'simplify' },
44
44
  messages: {
45
- simplify: '"{{x}} is defined and {{x}} is not empty" can be written "{{x}} is not empty".',
45
+ simplify: '"{{x}} is defined and {{x}} is not empty" can be written "{{x}} is not empty" when strict_variables is off (Drupal\'s default).',
46
46
  require: '"{{x}} is not empty" should be preceded by "{{x}} is defined and" when strict_variables is on.',
47
47
  useSimplified: 'Replace with "{{x}} is not empty".',
48
48
  addDefined: 'Add "{{x}} is defined and".',
@@ -2,5 +2,6 @@
2
2
  export declare const drupalRules: {
3
3
  'drupal/attach-library-format': import("../../util/rule.ts").TwigRuleDefinition;
4
4
  'drupal/component-reference': import("../../util/rule.ts").TwigRuleDefinition;
5
+ 'drupal/no-debug': import("../../util/rule.ts").TwigRuleDefinition;
5
6
  'drupal/no-translate-variable': import("../../util/rule.ts").TwigRuleDefinition;
6
7
  };
@@ -1,9 +1,11 @@
1
1
  import attachLibraryFormat from "./attach-library-format.js";
2
2
  import componentReference from "./component-reference.js";
3
+ import noDebug from "./no-debug.js";
3
4
  import noTranslateVariable from "./no-translate-variable.js";
4
5
  /** Drupal-only rules, registered as `twig-lint/drupal/<name>` and enabled by `configs.drupal`. */
5
6
  export const drupalRules = {
6
7
  'drupal/attach-library-format': attachLibraryFormat,
7
8
  'drupal/component-reference': componentReference,
9
+ 'drupal/no-debug': noDebug,
8
10
  'drupal/no-translate-variable': noTranslateVariable,
9
11
  };
@@ -0,0 +1,3 @@
1
+ /** Debug helpers from Drupal's Devel and Twig Tweak modules should not be committed. */
2
+ declare const _default: import("../../util/rule.ts").TwigRuleDefinition;
3
+ export default _default;
@@ -0,0 +1,8 @@
1
+ import { createDebugRule } from "../../util/debug.js";
2
+ /** Debug helpers from Drupal's Devel and Twig Tweak modules should not be committed. */
3
+ export default createDebugRule({
4
+ name: 'drupal/no-debug',
5
+ description: 'Disallow debug output from Devel and Twig Tweak, such as kint() and dd()',
6
+ defaults: ['kint', 'ksm', 'kpr', 'dpm', 'dsm', 'devel_dump', 'devel_message', 'devel_breakpoint', 'dd', 'drupal_dump'],
7
+ level: 'warn',
8
+ });
@@ -1,7 +1,8 @@
1
1
  /**
2
- * `|t` and `|trans` translate a string literal. On a variable, Drupal's string extraction (used to build
3
- * translation files) cannot see the text, so it never gets translated. Pass translated strings in from PHP,
4
- * or use a literal with placeholders: `'Hello @name'|t({'@name': name})`.
2
+ * `|t` and `|trans` on a variable cannot be found by string extraction (translation files, potx,
3
+ * localize.drupal.org), because the text is not in the template. Drupal only registers the string when it is
4
+ * rendered, and it is translated once someone translates it under Interface translation. Use a literal with
5
+ * placeholders, translate in PHP, or use content translation for content such as taxonomy terms.
5
6
  */
6
7
  declare const _default: import("../../util/rule.ts").TwigRuleDefinition;
7
8
  export default _default;
@@ -1,9 +1,10 @@
1
1
  import { createRule } from "../../util/rule.js";
2
2
  const TRANSLATE_FILTERS = new Set(['t', 'trans']);
3
3
  /**
4
- * `|t` and `|trans` translate a string literal. On a variable, Drupal's string extraction (used to build
5
- * translation files) cannot see the text, so it never gets translated. Pass translated strings in from PHP,
6
- * or use a literal with placeholders: `'Hello @name'|t({'@name': name})`.
4
+ * `|t` and `|trans` on a variable cannot be found by string extraction (translation files, potx,
5
+ * localize.drupal.org), because the text is not in the template. Drupal only registers the string when it is
6
+ * rendered, and it is translated once someone translates it under Interface translation. Use a literal with
7
+ * placeholders, translate in PHP, or use content translation for content such as taxonomy terms.
7
8
  */
8
9
  export default createRule({
9
10
  name: 'drupal/no-translate-variable',
@@ -11,7 +12,9 @@ export default createRule({
11
12
  type: 'problem',
12
13
  level: 'warn',
13
14
  fixable: false,
14
- messages: { variable: '|{{filter}} on something other than a string literal cannot be extracted for translation.' },
15
+ messages: {
16
+ variable: '|{{filter}} on a variable cannot be extracted for translation. The string is only translatable after it has been rendered once and translated under Interface translation.',
17
+ },
15
18
  check({ doc, report }) {
16
19
  for (const seg of doc.segments) {
17
20
  seg.tokens.forEach((t, i) => {
@@ -16,6 +16,7 @@ export declare const rules: {
16
16
  'isolated-include': import("../util/rule.ts").TwigRuleDefinition;
17
17
  'named-arguments': import("../util/rule.ts").TwigRuleDefinition;
18
18
  'nested-indent': import("../util/rule.ts").TwigRuleDefinition;
19
+ 'no-debug': import("../util/rule.ts").TwigRuleDefinition;
19
20
  'no-raw': import("../util/rule.ts").TwigRuleDefinition;
20
21
  'operator-spacing': import("../util/rule.ts").TwigRuleDefinition;
21
22
  'punctuation-spacing': import("../util/rule.ts").TwigRuleDefinition;
@@ -15,6 +15,7 @@ import includeStyle from "./include-style.js";
15
15
  import isolatedInclude from "./isolated-include.js";
16
16
  import namedArguments from "./named-arguments.js";
17
17
  import nestedIndent from "./nested-indent.js";
18
+ import noDebug from "./no-debug.js";
18
19
  import noRaw from "./no-raw.js";
19
20
  import operatorSpacing from "./operator-spacing.js";
20
21
  import punctuationSpacing from "./punctuation-spacing.js";
@@ -40,6 +41,7 @@ export const rules = {
40
41
  'isolated-include': isolatedInclude,
41
42
  'named-arguments': namedArguments,
42
43
  'nested-indent': nestedIndent,
44
+ 'no-debug': noDebug,
43
45
  'no-raw': noRaw,
44
46
  'operator-spacing': operatorSpacing,
45
47
  'punctuation-spacing': punctuationSpacing,
@@ -0,0 +1,3 @@
1
+ /** Twig's own debug output, `{{ dump(x) }}`, should not be committed. Drupal's helpers are in `drupal/no-debug`. */
2
+ declare const _default: import("../util/rule.ts").TwigRuleDefinition;
3
+ export default _default;
@@ -0,0 +1,8 @@
1
+ import { createDebugRule } from "../util/debug.js";
2
+ /** Twig's own debug output, `{{ dump(x) }}`, should not be committed. Drupal's helpers are in `drupal/no-debug`. */
3
+ export default createDebugRule({
4
+ name: 'no-debug',
5
+ description: "Disallow Twig's dump() debug output",
6
+ defaults: ['dump'],
7
+ level: 'warn',
8
+ });
@@ -0,0 +1,7 @@
1
+ import { type TwigRuleDefinition } from './rule.ts';
2
+ export declare function createDebugRule(def: {
3
+ name: string;
4
+ description: string;
5
+ defaults: string[];
6
+ level: 'error' | 'warn';
7
+ }): TwigRuleDefinition;
@@ -0,0 +1,53 @@
1
+ // Shared implementation of `no-debug` (Twig's own debug functions) and `drupal/no-debug` (Drupal's).
2
+ import { createRule } from "./rule.js";
3
+ export function createDebugRule(def) {
4
+ return createRule({
5
+ name: def.name,
6
+ description: def.description,
7
+ type: 'problem',
8
+ level: def.level,
9
+ fixable: false,
10
+ hasSuggestions: true,
11
+ optionsSchema: {
12
+ functions: { type: 'array', items: { type: 'string', minLength: 1 } },
13
+ additionalFunctions: { type: 'array', items: { type: 'string', minLength: 1 } },
14
+ },
15
+ defaultOptions: { functions: def.defaults, additionalFunctions: [] },
16
+ messages: {
17
+ debug: 'Remove the debug output "{{name}}" before committing.',
18
+ remove: 'Remove this debug output.',
19
+ },
20
+ check({ doc, options, suggest }) {
21
+ const names = new Set([...options.functions, ...options.additionalFunctions]);
22
+ const { src } = doc;
23
+ for (const seg of doc.segments) {
24
+ if (seg.kind !== 'output' && seg.kind !== 'block')
25
+ continue;
26
+ const tokens = seg.tokens;
27
+ tokens.forEach((t, i) => {
28
+ if (t.type !== 'name' || !names.has(t.value))
29
+ return;
30
+ const prev = tokens[i - 1];
31
+ const next = tokens[i + 1];
32
+ const isFilter = prev?.type === 'punctuation' && prev.value === '|';
33
+ const isCall = next?.type === 'punctuation' && next.value === '(' && !(prev && prev.value === '.');
34
+ if (!isFilter && !isCall)
35
+ return;
36
+ // Suggest removing the whole tag when it holds nothing but the debug call: {{ dump(x) }}.
37
+ const suggestions = [];
38
+ if (seg.kind === 'output' && isCall && i === 0 && next.match === tokens.length - 1) {
39
+ const lineStart = src.lastIndexOf('\n', seg.start - 1) + 1;
40
+ const newline = src.indexOf('\n', seg.end);
41
+ const lineEnd = newline < 0 ? src.length : newline;
42
+ const alone = src.slice(lineStart, seg.start).trim() === '' && src.slice(seg.end, lineEnd).trim() === '';
43
+ const edit = alone
44
+ ? { start: lineStart, end: newline < 0 ? src.length : newline + 1, text: '' }
45
+ : { start: seg.start, end: seg.end, text: '' };
46
+ suggestions.push({ messageId: 'remove', edits: [edit] });
47
+ }
48
+ suggest(t.start, 'debug', { name: isFilter ? `|${t.value}` : `${t.value}()` }, suggestions);
49
+ });
50
+ }
51
+ },
52
+ });
53
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-twig-lint",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "ESLint plugin that lints and formats Twig templates: indentation, line wrapping and spacing.",
5
5
  "keywords": [
6
6
  "eslint",