eslint-plugin-twig-lint 0.0.0-stage → 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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +309 -2
  3. package/dist/index.d.ts +66 -0
  4. package/dist/index.js +53 -0
  5. package/dist/language/html.d.ts +34 -0
  6. package/dist/language/html.js +107 -0
  7. package/dist/language/lexer.d.ts +34 -0
  8. package/dist/language/lexer.js +219 -0
  9. package/dist/language/parse.d.ts +46 -0
  10. package/dist/language/parse.js +254 -0
  11. package/dist/language/twig-language.d.ts +36 -0
  12. package/dist/language/twig-language.js +35 -0
  13. package/dist/language/twig-source-code.d.ts +70 -0
  14. package/dist/language/twig-source-code.js +121 -0
  15. package/dist/rules/attribute-spacing.d.ts +3 -0
  16. package/dist/rules/attribute-spacing.js +41 -0
  17. package/dist/rules/attribute-wrap.d.ts +3 -0
  18. package/dist/rules/attribute-wrap.js +15 -0
  19. package/dist/rules/blank-line-after-block.d.ts +6 -0
  20. package/dist/rules/blank-line-after-block.js +39 -0
  21. package/dist/rules/block-indent.d.ts +3 -0
  22. package/dist/rules/block-indent.js +14 -0
  23. package/dist/rules/defined-check.d.ts +2 -0
  24. package/dist/rules/defined-check.js +91 -0
  25. package/dist/rules/delimiter-spacing.d.ts +3 -0
  26. package/dist/rules/delimiter-spacing.js +31 -0
  27. package/dist/rules/deprecated-spaceless.d.ts +6 -0
  28. package/dist/rules/deprecated-spaceless.js +33 -0
  29. package/dist/rules/drupal/attach-library-format.d.ts +6 -0
  30. package/dist/rules/drupal/attach-library-format.js +37 -0
  31. package/dist/rules/drupal/component-reference.d.ts +6 -0
  32. package/dist/rules/drupal/component-reference.js +37 -0
  33. package/dist/rules/drupal/index.d.ts +7 -0
  34. package/dist/rules/drupal/index.js +11 -0
  35. package/dist/rules/drupal/no-debug.d.ts +3 -0
  36. package/dist/rules/drupal/no-debug.js +8 -0
  37. package/dist/rules/drupal/no-translate-variable.d.ts +8 -0
  38. package/dist/rules/drupal/no-translate-variable.js +31 -0
  39. package/dist/rules/empty-lines.d.ts +2 -0
  40. package/dist/rules/empty-lines.js +23 -0
  41. package/dist/rules/endblock-name.d.ts +6 -0
  42. package/dist/rules/endblock-name.js +43 -0
  43. package/dist/rules/expression-wrap.d.ts +3 -0
  44. package/dist/rules/expression-wrap.js +12 -0
  45. package/dist/rules/final-newline.d.ts +2 -0
  46. package/dist/rules/final-newline.js +17 -0
  47. package/dist/rules/hash-key-quotes.d.ts +6 -0
  48. package/dist/rules/hash-key-quotes.js +30 -0
  49. package/dist/rules/hash-spacing.d.ts +3 -0
  50. package/dist/rules/hash-spacing.js +18 -0
  51. package/dist/rules/include-style.d.ts +7 -0
  52. package/dist/rules/include-style.js +140 -0
  53. package/dist/rules/index.d.ts +27 -0
  54. package/dist/rules/index.js +52 -0
  55. package/dist/rules/isolated-include.d.ts +6 -0
  56. package/dist/rules/isolated-include.js +78 -0
  57. package/dist/rules/named-arguments.d.ts +6 -0
  58. package/dist/rules/named-arguments.js +31 -0
  59. package/dist/rules/nested-indent.d.ts +3 -0
  60. package/dist/rules/nested-indent.js +14 -0
  61. package/dist/rules/no-debug.d.ts +3 -0
  62. package/dist/rules/no-debug.js +8 -0
  63. package/dist/rules/no-raw.d.ts +3 -0
  64. package/dist/rules/no-raw.js +47 -0
  65. package/dist/rules/operator-spacing.d.ts +6 -0
  66. package/dist/rules/operator-spacing.js +21 -0
  67. package/dist/rules/punctuation-spacing.d.ts +3 -0
  68. package/dist/rules/punctuation-spacing.js +18 -0
  69. package/dist/rules/single-quotes.d.ts +6 -0
  70. package/dist/rules/single-quotes.js +22 -0
  71. package/dist/rules/trailing-comma.d.ts +8 -0
  72. package/dist/rules/trailing-comma.js +47 -0
  73. package/dist/rules/trailing-whitespace.d.ts +2 -0
  74. package/dist/rules/trailing-whitespace.js +17 -0
  75. package/dist/rules/variable-name.d.ts +3 -0
  76. package/dist/rules/variable-name.js +76 -0
  77. package/dist/util/debug.d.ts +7 -0
  78. package/dist/util/debug.js +53 -0
  79. package/dist/util/indent.d.ts +16 -0
  80. package/dist/util/indent.js +101 -0
  81. package/dist/util/rule.d.ts +99 -0
  82. package/dist/util/rule.js +65 -0
  83. package/dist/util/spacing.d.ts +15 -0
  84. package/dist/util/spacing.js +44 -0
  85. package/dist/util/syntax.d.ts +26 -0
  86. package/dist/util/syntax.js +107 -0
  87. package/dist/util/wrap.d.ts +16 -0
  88. package/dist/util/wrap.js +382 -0
  89. package/package.json +50 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anders Niemi Brundin
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,310 @@
1
- # Temporary Holding Version
1
+ <h1 align="center" alt="title">eslint-plugin-twig-lint</h1>
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
+ <p align="center">
4
+ <a href="https://www.npmjs.com/package/eslint-plugin-twig-lint"><img src="https://img.shields.io/npm/v/eslint-plugin-twig-lint?style=flat&colorA=111111&colorB=000000" alt="Version" /></a>
5
+ <a href="https://www.npmjs.com/package/eslint-plugin-twig-lint"><img src="https://img.shields.io/npm/dt/eslint-plugin-twig-lint.svg?style=flat&colorA=222222&colorB=000000" alt="Downloads" /></a>
6
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-000000?style=flat&colorA=333333" alt="License" /></a>
7
+ </p>
8
+
9
+ Lint and format Twig templates with ESLint.
10
+
11
+ ## Table of Contents
12
+
13
+ - [Features](#features)
14
+ - [Installation](#installation)
15
+ - [Install](#install)
16
+ - [Setup](#setup)
17
+ - [Editor Integration](#editor-integration)
18
+ - [Presets](#presets)
19
+ - [Settings](#settings)
20
+ - [Rules](#rules)
21
+ - [Layout](#layout)
22
+ - [Syntax](#syntax)
23
+ - [Best Practices](#best-practices)
24
+ - [Drupal](#drupal)
25
+ - [Examples](#examples)
26
+ - [Disabling Rules](#disabling-rules)
27
+ - [FAQ](#faq)
28
+ - [Disclaimer](#disclaimer)
29
+ - [Contributing](#contributing)
30
+ - [License](#license)
31
+
32
+ ## Features
33
+
34
+ - **Respectful**: Fixes what is wrong and keeps the rest of your style. Multi-line expressions are re-indented,
35
+ never collapsed into one line.
36
+ - **Safe**: Only changes whitespace that does not affect the rendered page. The content of `<pre>`, `<textarea>`,
37
+ `<script>`, `<style>`, comments and `{% trans %}` is never touched, and a file that cannot be parsed is left
38
+ untouched.
39
+ - **Native ESLint**: Twig is a real ESLint language, so you get ESLint's CLI, config, `--fix`, disable comments,
40
+ output formats and editor integration.
41
+ - **Configurable**: Every rule can be turned off or set to `warn` or `error`, and shared settings control
42
+ indentation and line width.
43
+
44
+ ## Installation
45
+
46
+ > [!NOTE]
47
+ > eslint-plugin-twig-lint requires the following minimum versions:
48
+ >
49
+ > - Node.js: 20.19.0
50
+ > - ESLint: 9.15.0
51
+
52
+ ### Install
53
+
54
+ ```sh
55
+ npm install --save-dev eslint eslint-plugin-twig-lint
56
+ ```
57
+
58
+ ### Setup
59
+
60
+ ```js
61
+ // eslint.config.js
62
+
63
+ import twigLint from "eslint-plugin-twig-lint";
64
+
65
+ export default [
66
+ // Parse **/*.twig as Twig and enable the general rules.
67
+ twigLint.configs.recommended,
68
+
69
+ // Optional: rules for Drupal themes and modules.
70
+ twigLint.configs.drupal,
71
+
72
+ {
73
+ files: ["**/*.twig"],
74
+
75
+ // Optional shared settings (defaults shown).
76
+ settings: {
77
+ "twig-lint": { indentSize: 2, useTabs: false, printWidth: 80 },
78
+ },
79
+
80
+ // Custom rule overrides (change rule levels or turn rules off).
81
+ rules: {
82
+ "twig-lint/blank-line-after-block": "warn",
83
+ },
84
+ },
85
+ ];
86
+ ```
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
+
101
+ Then run ESLint as usual:
102
+
103
+ ```sh
104
+ npx eslint "templates/**/*.twig"
105
+ npx eslint --fix "templates/**/*.twig"
106
+ ```
107
+
108
+ ### Editor Integration
109
+
110
+ In VS Code, install the [ESLint extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)
111
+ and add this to `.vscode/settings.json`:
112
+
113
+ ```jsonc
114
+ {
115
+ "eslint.validate": ["twig", "html.twig"],
116
+ "eslint.format.enable": true,
117
+ "[twig]": { "editor.defaultFormatter": "dbaeumer.vscode-eslint" }
118
+ }
119
+ ```
120
+
121
+ The language id depends on which Twig extension you use. Check the language mode in the status bar.
122
+ [`examples/vscode-demo`](examples/vscode-demo) is a ready-made setup.
123
+
124
+ ## Presets
125
+
126
+ - `recommended`\
127
+ Parse `**/*.twig` with the Twig language and enable the general rules. Layout and syntax rules are `error`,
128
+ best practices are `warn`.
129
+
130
+ - `drupal`\
131
+ Enable the [Drupal rules](#drupal). Use it together with `recommended`. Opt-in rules such as
132
+ `drupal/component-reference` stay off until you enable them.
133
+
134
+ ## Settings
135
+
136
+ Shared settings go in `settings["twig-lint"]`. Every rule also accepts them as options, which take precedence.
137
+
138
+ | Setting | Default | Description |
139
+ |---|---|---|
140
+ | `indentSize` | `2` | Columns per indentation step |
141
+ | `useTabs` | `false` | Indent with tabs instead of spaces |
142
+ | `printWidth` | `80` | Line width used by `attribute-wrap` and `expression-wrap` |
143
+
144
+ ## Rules
145
+
146
+ All general rules are in `recommended`. Fixable rules are fixed by `--fix` and by formatting in the editor.
147
+
148
+ ### Layout
149
+
150
+ Enabled as `error`.
151
+
152
+ | Rule | Description | Fixable |
153
+ |---|---|---|
154
+ | [`twig-lint/block-indent`](docs/rules/block-indent.md) | Indentation of Twig blocks and HTML elements | yes |
155
+ | [`twig-lint/nested-indent`](docs/rules/nested-indent.md) | Indentation inside multi-line expressions: one step per line that opens brackets | yes |
156
+ | [`twig-lint/attribute-spacing`](docs/rules/attribute-spacing.md) | `<p{{ attrs }}>` → `<p {{ attrs }}>`. Option `mode`: `space` (default) or `tight` | yes |
157
+ | [`twig-lint/attribute-wrap`](docs/rules/attribute-wrap.md) | One attribute per line when an opening tag is longer than `printWidth`. Option `minAttributes` (default 2) | yes |
158
+ | [`twig-lint/expression-wrap`](docs/rules/expression-wrap.md) | Breaks Twig expressions longer than `printWidth`: maps, `set`, `if` and call arguments | yes |
159
+ | [`twig-lint/delimiter-spacing`](docs/rules/delimiter-spacing.md) | Exactly one space inside `{{ }}`, `{% %}` and `{# #}` | yes |
160
+ | [`twig-lint/blank-line-after-block`](docs/rules/blank-line-after-block.md) | An empty line after `{% endif %}`, `{% endfor %}` and similar closing tags | yes |
161
+ | [`twig-lint/empty-lines`](docs/rules/empty-lines.md) | At most one empty line in a row | yes |
162
+ | [`twig-lint/trailing-whitespace`](docs/rules/trailing-whitespace.md) | No whitespace at the end of lines | yes |
163
+ | [`twig-lint/final-newline`](docs/rules/final-newline.md) | Exactly one newline at the end of the file | yes |
164
+
165
+ ### Syntax
166
+
167
+ Enabled as `error`.
168
+
169
+ | Rule | Description | Fixable |
170
+ |---|---|---|
171
+ | [`twig-lint/operator-spacing`](docs/rules/operator-spacing.md) | One space around binary operators, none around `.`, `\|` and `..` | yes |
172
+ | [`twig-lint/punctuation-spacing`](docs/rules/punctuation-spacing.md) | One space after commas, none inside brackets | yes |
173
+ | [`twig-lint/hash-spacing`](docs/rules/hash-spacing.md) | `{key: value}` and `name: value`: no space before the colon, one after | yes |
174
+ | [`twig-lint/single-quotes`](docs/rules/single-quotes.md) | `'single'` quotes unless the string contains `'` or uses interpolation | yes |
175
+ | [`twig-lint/hash-key-quotes`](docs/rules/hash-key-quotes.md) | No quotes around plain hash keys: `{'class': x}` → `{class: x}` | yes |
176
+ | [`twig-lint/trailing-comma`](docs/rules/trailing-comma.md) | A trailing comma when the closing bracket is on its own line. Option `multiline` | yes |
177
+ | [`twig-lint/named-arguments`](docs/rules/named-arguments.md) | `with_context: false` instead of the deprecated `with_context = false` | yes |
178
+ | [`twig-lint/endblock-name`](docs/rules/endblock-name.md) | `{% endblock content %}` and `{% endmacro card %}`. Options `mode`: `always` (default) or `never`, and `minLines` | yes |
179
+ | [`twig-lint/include-style`](docs/rules/include-style.md) | `{{ include() }}` or `{% include %}`. Option `style`: `both` (default), `function` or `tag` | yes |
180
+
181
+ ### Best Practices
182
+
183
+ Enabled as `warn`. These rules point out code that works but may cause problems, so they are never fixed
184
+ automatically. Two of them offer a suggestion that you can apply in the editor.
185
+
186
+ | Rule | Description | Fixable |
187
+ |---|---|---|
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 |
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 |
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 |
192
+ | [`twig-lint/no-raw`](docs/rules/no-raw.md) | Warns about `\|raw`, which turns off escaping. Option `allow` for known-safe values | no |
193
+ | [`twig-lint/deprecated-spaceless`](docs/rules/deprecated-spaceless.md) | Warns about the `spaceless` filter, deprecated since Twig 3.12 | no |
194
+
195
+ ### Drupal
196
+
197
+ Enabled by the `drupal` preset.
198
+
199
+ | Rule | Description | Fixable | Level |
200
+ |---|---|---|---|
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 |
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 |
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) |
205
+
206
+ ### Examples
207
+
208
+ Nested indentation is fixed without collapsing the expression:
209
+
210
+ ```twig
211
+ {# before #}
212
+ {% set heading_attributes = create_attribute({
213
+ class: [
214
+ 'teaser__heading',
215
+ ],
216
+ }, title_attributes) %}
217
+
218
+ {# after #}
219
+ {% set heading_attributes = create_attribute({
220
+ class: [
221
+ 'teaser__heading',
222
+ ],
223
+ }, title_attributes) %}
224
+ ```
225
+
226
+ Long opening tags get one attribute per line, and an `{% if %}` between attributes becomes a block:
227
+
228
+ ```twig
229
+ <li
230
+ class="card-grid__item card-grid__item--featured"
231
+ {% if is_mixed %}
232
+ style="--card-grid-index: {{ loop.index }};"
233
+ {% endif %}
234
+ >
235
+ {{ item }}
236
+ </li>
237
+ ```
238
+
239
+ Long conditions break at the lowest-precedence operator:
240
+
241
+ ```twig
242
+ {% if has_choices
243
+ or (visible_choices is iterable
244
+ and visible_choices|length > 0
245
+ )
246
+ %}
247
+ ```
248
+
249
+ More examples are in [`test/fixtures`](test/fixtures), where each `input.twig` has an `expected.twig`.
250
+
251
+ ### Disabling Rules
252
+
253
+ ESLint's disable comments work inside Twig comments:
254
+
255
+ ```twig
256
+ {# eslint-disable-next-line twig-lint/attribute-wrap -- generated markup #}
257
+ <div class="…very long…">
258
+
259
+ {# eslint-disable twig-lint/blank-line-after-block #}
260
+ ```
261
+
262
+ ## FAQ
263
+
264
+ **Is it only for Drupal?**\
265
+ No. The general rules work on any Twig template, and Drupal-style templates (`create_attribute()`,
266
+ `<p {{ attributes }}>`, `{% trans %}`) are well covered by the tests. Rules that only make sense in Drupal are
267
+ under `twig-lint/drupal/` and only run with the `drupal` preset.
268
+
269
+ **What happens with a file that cannot be parsed?**\
270
+ ESLint reports a fatal parsing error with the line and column, and `--fix` leaves the file untouched.
271
+
272
+ **Does `--fix` change the rendered HTML?**\
273
+ It should not. The fixtures are checked by rendering both `input.twig` and `expected.twig` with Twig and
274
+ comparing the HTML trees (see [Contributing](#contributing)).
275
+
276
+ ## Disclaimer
277
+
278
+ This project is not affiliated with or endorsed by Symfony, the Twig project or the ESLint project.
279
+
280
+ ## Contributing
281
+
282
+ Contributions are welcome! Open an issue or a pull request.
283
+
284
+ ```sh
285
+ npm install
286
+ npm test # all fixtures and plugin tests via ESLint's API
287
+ npm run coverage # the same, with a coverage report
288
+ npm run typecheck
289
+ npm run build # compiles to dist/
290
+ ```
291
+
292
+ CI runs the tests on Node 22 and 24 with ESLint 9.15, 9 and 10, checks that the packed package works on its
293
+ own, and runs the PHP checks below.
294
+
295
+ The source is TypeScript that Node runs directly (type stripping, Node 22.18+). The published package
296
+ contains compiled JavaScript in `dist/`.
297
+
298
+ A new formatting case is a folder in [`test/fixtures`](test/fixtures) with an `input.twig` and an
299
+ `expected.twig` (or an `expected-error.txt` for a file that must be left untouched). Two PHP scripts check
300
+ that every `expected.twig` is valid Twig and renders the same HTML as its `input.twig`. They need a Composer
301
+ project with `twig/twig`:
302
+
303
+ ```sh
304
+ TWIG_AUTOLOAD=/path/to/vendor/autoload.php php test/parse-check.php test/fixtures/*/expected.twig
305
+ TWIG_AUTOLOAD=/path/to/vendor/autoload.php php test/render-check.php test/fixtures/*/
306
+ ```
307
+
308
+ ## License
309
+
310
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,66 @@
1
+ import { TwigLanguage } from './language/twig-language.ts';
2
+ import type { TwigRuleDefinition } from './util/rule.ts';
3
+ export { TwigLanguage } from './language/twig-language.ts';
4
+ export { TwigSourceCode, type TwigNode } from './language/twig-source-code.ts';
5
+ export type { SharedSettings } from './util/rule.ts';
6
+ type Level = 'error' | 'warn';
7
+ declare const plugin: {
8
+ meta: {
9
+ name: string;
10
+ version: string;
11
+ namespace: string;
12
+ };
13
+ languages: {
14
+ twig: TwigLanguage;
15
+ };
16
+ rules: {
17
+ 'drupal/attach-library-format': TwigRuleDefinition;
18
+ 'drupal/component-reference': TwigRuleDefinition;
19
+ 'drupal/no-debug': TwigRuleDefinition;
20
+ 'drupal/no-translate-variable': TwigRuleDefinition;
21
+ 'attribute-spacing': TwigRuleDefinition;
22
+ 'attribute-wrap': TwigRuleDefinition;
23
+ 'blank-line-after-block': TwigRuleDefinition;
24
+ 'block-indent': TwigRuleDefinition;
25
+ 'defined-check': TwigRuleDefinition;
26
+ 'delimiter-spacing': TwigRuleDefinition;
27
+ 'deprecated-spaceless': TwigRuleDefinition;
28
+ 'empty-lines': TwigRuleDefinition;
29
+ 'endblock-name': TwigRuleDefinition;
30
+ 'expression-wrap': TwigRuleDefinition;
31
+ 'final-newline': TwigRuleDefinition;
32
+ 'hash-key-quotes': TwigRuleDefinition;
33
+ 'hash-spacing': TwigRuleDefinition;
34
+ 'include-style': TwigRuleDefinition;
35
+ 'isolated-include': TwigRuleDefinition;
36
+ 'named-arguments': TwigRuleDefinition;
37
+ 'nested-indent': TwigRuleDefinition;
38
+ 'no-debug': TwigRuleDefinition;
39
+ 'no-raw': TwigRuleDefinition;
40
+ 'operator-spacing': TwigRuleDefinition;
41
+ 'punctuation-spacing': TwigRuleDefinition;
42
+ 'single-quotes': TwigRuleDefinition;
43
+ 'trailing-comma': TwigRuleDefinition;
44
+ 'trailing-whitespace': TwigRuleDefinition;
45
+ 'variable-name': TwigRuleDefinition;
46
+ };
47
+ configs: {
48
+ /** Parses `**\/*.twig` as Twig and enables the general rules. */
49
+ recommended: {
50
+ name: string;
51
+ files: string[];
52
+ plugins: Record<string, unknown>;
53
+ language: string;
54
+ rules: Record<string, Level>;
55
+ };
56
+ /** Enables the `twig-lint/drupal/*` rules. Use it together with `recommended`. */
57
+ drupal: {
58
+ name: string;
59
+ files: string[];
60
+ plugins: Record<string, unknown>;
61
+ language: string;
62
+ rules: Record<string, Level>;
63
+ };
64
+ };
65
+ };
66
+ export default plugin;
package/dist/index.js ADDED
@@ -0,0 +1,53 @@
1
+ // eslint-plugin-twig-lint: Twig as an ESLint language, plus rules for formatting and linting.
2
+ //
3
+ // import twigLint from 'eslint-plugin-twig-lint';
4
+ // export default [twigLint.configs.recommended]; // any Twig
5
+ // export default [twigLint.configs.recommended, twigLint.configs.drupal]; // Drupal themes and modules
6
+ import { TwigLanguage } from "./language/twig-language.js";
7
+ import { drupalRules } from "./rules/drupal/index.js";
8
+ import { rules as generalRules } from "./rules/index.js";
9
+ export { TwigLanguage } from "./language/twig-language.js";
10
+ export { TwigSourceCode } from "./language/twig-source-code.js";
11
+ /** `twig-lint/<id>` → the rule's level in its preset. Opt-in rules (`off`) are left out. */
12
+ function presetRules(rules) {
13
+ const out = {};
14
+ for (const [id, rule] of Object.entries(rules)) {
15
+ const level = rule.meta.docs.level;
16
+ if (level !== 'off')
17
+ out[`twig-lint/${id}`] = level;
18
+ }
19
+ return out;
20
+ }
21
+ const rules = { ...generalRules, ...drupalRules };
22
+ const plugin = {
23
+ meta: {
24
+ name: 'eslint-plugin-twig-lint',
25
+ version: '0.1.1',
26
+ namespace: 'twig-lint',
27
+ },
28
+ languages: {
29
+ twig: new TwigLanguage(),
30
+ },
31
+ rules,
32
+ configs: {
33
+ /** Parses `**\/*.twig` as Twig and enables the general rules. */
34
+ recommended: {
35
+ name: 'twig-lint/recommended',
36
+ files: ['**/*.twig'],
37
+ plugins: {},
38
+ language: 'twig-lint/twig',
39
+ rules: presetRules(generalRules),
40
+ },
41
+ /** Enables the `twig-lint/drupal/*` rules. Use it together with `recommended`. */
42
+ drupal: {
43
+ name: 'twig-lint/drupal',
44
+ files: ['**/*.twig'],
45
+ plugins: {},
46
+ language: 'twig-lint/twig',
47
+ rules: presetRules(drupalRules),
48
+ },
49
+ },
50
+ };
51
+ plugin.configs.recommended.plugins['twig-lint'] = plugin;
52
+ plugin.configs.drupal.plugins['twig-lint'] = plugin;
53
+ export default plugin;
@@ -0,0 +1,34 @@
1
+ import { type Segment } from './lexer.ts';
2
+ export interface Range {
3
+ start: number;
4
+ end: number;
5
+ }
6
+ export interface HtmlTag {
7
+ start: number;
8
+ end: number;
9
+ name: string;
10
+ nameStart: number;
11
+ nameEnd: number;
12
+ closing: boolean;
13
+ selfClosing: boolean;
14
+ void: boolean;
15
+ /** The tag name is a Twig expression, e.g. `<{{ type }}>`. */
16
+ dynamic: boolean;
17
+ /** Position of `>`, or of `/` in `/>`. */
18
+ closeStart: number;
19
+ /** Quoted attribute values, including the quotes. */
20
+ attrValues: Range[];
21
+ }
22
+ export interface RawElement {
23
+ open: HtmlTag;
24
+ close: HtmlTag;
25
+ }
26
+ export interface HtmlScan {
27
+ tags: HtmlTag[];
28
+ raw: RawElement[];
29
+ comments: Range[];
30
+ }
31
+ export declare const VOID_ELEMENTS: Set<string>;
32
+ export declare const RAW_ELEMENTS: Set<string>;
33
+ export declare function maskTwig(src: string, segments: Segment[]): string;
34
+ export declare function scanHtml(src: string, masked: string): HtmlScan;
@@ -0,0 +1,107 @@
1
+ // HTML scanning on a masked copy of the source. Twig segments are replaced with \0 (newlines are kept),
2
+ // so positions match the original and Twig expressions do not interfere with the scan.
3
+ import { TwigParseError, lineAt } from "./lexer.js";
4
+ export const VOID_ELEMENTS = new Set([
5
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr',
6
+ ]);
7
+ export const RAW_ELEMENTS = new Set(['pre', 'textarea', 'script', 'style']);
8
+ export function maskTwig(src, segments) {
9
+ const chars = src.split('');
10
+ for (const seg of segments) {
11
+ if (seg.kind === 'text' && !seg.verbatim)
12
+ continue;
13
+ for (let i = seg.start; i < seg.end; i++)
14
+ if (chars[i] !== '\n')
15
+ chars[i] = '\0';
16
+ }
17
+ return chars.join('');
18
+ }
19
+ const NAME_CHAR = /[a-zA-Z0-9:_.-]/;
20
+ export function scanHtml(src, masked) {
21
+ const tags = [];
22
+ const raw = [];
23
+ const comments = [];
24
+ const lower = masked.toLowerCase();
25
+ let i = 0;
26
+ while ((i = masked.indexOf('<', i)) >= 0) {
27
+ if (masked.startsWith('<!--', i)) {
28
+ const e = masked.indexOf('-->', i + 4);
29
+ const end = e < 0 ? masked.length : e + 3;
30
+ comments.push({ start: i, end });
31
+ i = end;
32
+ continue;
33
+ }
34
+ const next = masked[i + 1];
35
+ if (next === '!' || next === '?') {
36
+ const e = masked.indexOf('>', i);
37
+ i = e < 0 ? masked.length : e + 1;
38
+ continue;
39
+ }
40
+ const closing = next === '/';
41
+ const nameStart = i + (closing ? 2 : 1);
42
+ let j = nameStart;
43
+ const first = masked[j];
44
+ let dynamic = false;
45
+ if (first !== undefined && /[a-zA-Z]/.test(first)) {
46
+ while (j < masked.length && NAME_CHAR.test(masked[j]))
47
+ j++;
48
+ }
49
+ else if (first === '\0') {
50
+ dynamic = true;
51
+ while (j < masked.length && masked[j] === '\0')
52
+ j++;
53
+ }
54
+ else {
55
+ i++;
56
+ continue;
57
+ }
58
+ const nameEnd = j;
59
+ const attrValues = [];
60
+ let lastNonWs = '';
61
+ while (j < masked.length && masked[j] !== '>') {
62
+ const ch = masked[j];
63
+ if ((ch === '"' || ch === "'") && lastNonWs === '=') {
64
+ const e = masked.indexOf(ch, j + 1);
65
+ if (e < 0)
66
+ break;
67
+ attrValues.push({ start: j, end: e + 1 });
68
+ j = e + 1;
69
+ lastNonWs = ch;
70
+ continue;
71
+ }
72
+ if (!/\s/.test(ch))
73
+ lastNonWs = ch;
74
+ j++;
75
+ }
76
+ if (j >= masked.length) {
77
+ throw new TwigParseError(`HTML tag "${src.slice(i, nameEnd)}" on line ${lineAt(src, i)} is never closed`, i);
78
+ }
79
+ const selfClosing = masked[j - 1] === '/';
80
+ const name = dynamic ? src.slice(nameStart, nameEnd) : src.slice(nameStart, nameEnd).toLowerCase();
81
+ const tag = {
82
+ start: i, end: j + 1, name, nameStart, nameEnd, closing, selfClosing,
83
+ void: !dynamic && VOID_ELEMENTS.has(name), dynamic,
84
+ closeStart: selfClosing ? j - 1 : j, attrValues,
85
+ };
86
+ tags.push(tag);
87
+ i = j + 1;
88
+ if (!closing && !selfClosing && !dynamic && RAW_ELEMENTS.has(name)) {
89
+ const c = lower.indexOf(`</${name}`, i);
90
+ if (c < 0) {
91
+ throw new TwigParseError(`<${name}> on line ${lineAt(src, tag.start)} is never closed`, tag.start);
92
+ }
93
+ const e = masked.indexOf('>', c);
94
+ if (e < 0) {
95
+ throw new TwigParseError(`</${name} on line ${lineAt(src, c)} is never closed`, c);
96
+ }
97
+ const close = {
98
+ start: c, end: e + 1, name, nameStart: c + 2, nameEnd: c + 2 + name.length, closing: true,
99
+ selfClosing: false, void: false, dynamic: false, closeStart: e, attrValues: [],
100
+ };
101
+ tags.push(close);
102
+ raw.push({ open: tag, close });
103
+ i = e + 1;
104
+ }
105
+ }
106
+ return { tags, raw, comments };
107
+ }
@@ -0,0 +1,34 @@
1
+ export type TokenType = 'name' | 'number' | 'string' | 'operator' | 'punctuation';
2
+ export interface Token {
3
+ type: TokenType;
4
+ value: string;
5
+ start: number;
6
+ end: number;
7
+ /** For opening brackets: index of the matching closing bracket in the same segment. */
8
+ match?: number;
9
+ }
10
+ export type SegmentKind = 'text' | 'output' | 'block' | 'comment';
11
+ export interface Segment {
12
+ kind: SegmentKind;
13
+ start: number;
14
+ end: number;
15
+ /** Twig segments: position right after the opening delimiter (including `-`/`~`). */
16
+ innerStart: number;
17
+ /** Twig segments: start of the closing delimiter (including `-`/`~`). */
18
+ closeStart: number;
19
+ /** The opening delimiter, e.g. `{{`, `{%-`. Empty for text. */
20
+ open: string;
21
+ /** The closing delimiter, e.g. `}}`, `-%}`. Empty for text. */
22
+ close: string;
23
+ tokens: Token[];
24
+ /** Block segments: the tag name (first name token). */
25
+ tag: string;
26
+ /** Text inside {% verbatim %}/{% raw %}. */
27
+ verbatim: boolean;
28
+ }
29
+ export declare class TwigParseError extends Error {
30
+ offset: number;
31
+ constructor(message: string, offset: number);
32
+ }
33
+ export declare function lineAt(src: string, pos: number): number;
34
+ export declare function lex(src: string): Segment[];