@jupyter/eslint-plugin 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/lib/index.d.ts +49 -2
  2. package/lib/index.js +35 -5
  3. package/lib/rules/galata-prefer-context-menu-helper.d.ts +6 -0
  4. package/lib/rules/galata-prefer-context-menu-helper.js +394 -0
  5. package/lib/rules/galata-prefer-menu-helper.d.ts +6 -0
  6. package/lib/rules/galata-prefer-menu-helper.js +394 -0
  7. package/lib/rules/galata-prefer-notebook-cell-helper.d.ts +6 -0
  8. package/lib/rules/galata-prefer-notebook-cell-helper.js +403 -0
  9. package/lib/rules/galata-prefer-sidebar-activity-helper.d.ts +6 -0
  10. package/lib/rules/galata-prefer-sidebar-activity-helper.js +332 -0
  11. package/lib/rules/no-schema-enum.d.ts +1 -1
  12. package/lib/rules/no-schema-enum.js +54 -2
  13. package/lib/rules/no-untranslated-string.d.ts +2 -1
  14. package/lib/rules/no-untranslated-string.js +191 -113
  15. package/lib/rules/plugin-id-convention.d.ts +7 -0
  16. package/lib/rules/plugin-id-convention.js +296 -0
  17. package/lib/rules/prefer-lazy-imports.d.ts +6 -0
  18. package/lib/rules/prefer-lazy-imports.js +476 -0
  19. package/lib/rules/require-disposable-ownership.js +1 -16
  20. package/lib/rules/require-disposable-transfer.js +7 -2
  21. package/lib/utils/ast.d.ts +12 -0
  22. package/lib/utils/ast.js +49 -0
  23. package/lib/utils/disposables.d.ts +12 -0
  24. package/lib/utils/disposables.js +101 -10
  25. package/lib/utils/lazy-imports.d.ts +93 -0
  26. package/lib/utils/lazy-imports.js +600 -0
  27. package/lib/utils/module-size.d.ts +18 -0
  28. package/lib/utils/module-size.js +249 -0
  29. package/lib/utils/package-json.d.ts +8 -0
  30. package/lib/utils/package-json.js +76 -0
  31. package/lib/utils/playwright-selectors.d.ts +56 -5
  32. package/lib/utils/playwright-selectors.js +205 -12
  33. package/lib/utils/plugin-utils.d.ts +50 -2
  34. package/lib/utils/plugin-utils.js +221 -38
  35. package/lib/utils/shared-packages.d.ts +9 -0
  36. package/lib/utils/shared-packages.js +128 -0
  37. package/lib/utils/signal-lifetime.js +66 -5
  38. package/lib/utils/signals.d.ts +2 -8
  39. package/lib/utils/signals.js +7 -42
  40. package/package.json +1 -1
@@ -0,0 +1,403 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) Jupyter Development Team.
4
+ * Distributed under the terms of the Modified BSD License.
5
+ */
6
+ const utils_1 = require("@typescript-eslint/utils");
7
+ const create_rule_1 = require("../utils/create-rule");
8
+ const playwright_selectors_1 = require("../utils/playwright-selectors");
9
+ // A cell *root* token, required somewhere in the selector chain. The list of
10
+ // `jp-Cell-` names is closed: an open tail would also accept `jp-CellToolbar`,
11
+ // `jp-CellTags` and the `jp-Cell-diff`/`jp-Cell-merge` rows nbdime renders,
12
+ // none of which is a notebook cell.
13
+ const CELL_CONTEXT_PATTERN = /\.jp-(?:Cell|CodeCell|MarkdownCell|RawCell)(?![\w-])|\.jp-Cell-(?:footer|header|input(?:Area|Collapser|Wrapper)|output(?:Area|Collapser|Wrapper))(?![\w-])|\.jp-Notebook-cell(?![\w-])/;
14
+ // Widgets that reuse cell markup but that `page.notebook` does not drive: the
15
+ // console hosts real `.jp-Cell` widgets, and the file selector dialog embeds
16
+ // notebook-ish markup of its own.
17
+ const FOREIGN_CONTEXT_PATTERN = /jp-CodeConsole|jp-Dialog\b|jp-FileEditor|jp-Terminal\b/;
18
+ // The editor host inside a cell input area. Only consulted once
19
+ // CELL_CONTEXT_PATTERN has already proven a cell root is in the same chain.
20
+ const EDITOR_TARGET_PATTERN = /\.jp-Cell-inputArea(?![\w-])|\.jp-InputArea-editor(?![\w-])|\.jp-CodeMirrorEditor(?![\w-])|\.cm-editor(?![\w-])|\.cm-content(?![\w-])/;
21
+ // A cell's output area. JupyterLab itself puts no editor there, but a mime
22
+ // renderer or a widget can, so an editor target scoped to an output is not the
23
+ // cell's own input and has no `setCell()` to suggest.
24
+ const OUTPUT_AREA_PATTERN = /\.jp-Cell-outputArea|\.jp-OutputArea/;
25
+ // The cell element itself, not a widget rendered inside it. The `(?![\w-])`
26
+ // anchors keep `jp-Cell-inputCollapser`, `jp-CellToolbar`, … out. The input
27
+ // prompt counts: `selectCells()` clicks the cell at `{ x: 15, y: 5 }`, which is
28
+ // that same gutter, so clicking it *is* the helper's own gesture. Both prompt
29
+ // names select the one element: `InputArea` adds `jp-InputArea-prompt` to the
30
+ // widget whose own constructor added `jp-InputPrompt`.
31
+ const CELL_TARGET_PATTERN = /\.jp-(?:Cell|CodeCell|MarkdownCell|RawCell)(?![\w-])|\.jp-Notebook-cell(?![\w-])|\.jp-Input(?:Area-prompt|Prompt)(?![\w-])/;
32
+ // The JupyterLab notebook run shortcuts. `ControlOrMeta+Enter` is Playwright's
33
+ // platform-neutral spelling. Any other key on a cell is not a run.
34
+ const RUN_SHORTCUT_PATTERN = /^(?:Shift|Control|Alt|Meta|ControlOrMeta)\+Enter$/;
35
+ // Playwright selector engines whose argument is matched against page content
36
+ // rather than markup, in the `engine=body` form. A bare `"quoted"` segment is
37
+ // the text engine's shorthand.
38
+ const CONTENT_ENGINE_PATTERN = /^(?:text|id|data-testid|data-test-id|data-test|role|xpath)\s*=|^["']/;
39
+ // Playwright engines that only *filter* the preceding segment rather than
40
+ // selecting anything of their own, so the real target is the segment before.
41
+ const PASSTHROUGH_ENGINE_PATTERN = /^(?:nth|visible)\s*=/;
42
+ // The argument of a pseudo-class is a different selector branch, or page
43
+ // content: `.widget:not(.jp-Cell)` is not a cell and `:has-text("x")` is text.
44
+ // Stripping innermost-first also unwraps nesting such as `:not(:has(.jp-Cell))`.
45
+ const PSEUDO_ARGUMENT_PATTERN = /:[\w-]+\([^()]*\)/g;
46
+ // Quoted attribute *values* are content too: `[title="jp-Cell"]` is not a cell.
47
+ const QUOTED_VALUE_PATTERN = /"[^"]*"|'[^']*'/g;
48
+ // A union (`.other, .jp-Cell`) or a sibling combinator (`.jp-Cell + .cm-editor`)
49
+ // breaks the ancestor relationship the token checks assume: the cell token can
50
+ // then sit in a branch the gesture never lands in. Checked after the content
51
+ // strip above, so `:nth-child(2n+1)` and `:has-text("a, b")` are unaffected.
52
+ const AMBIGUOUS_STRUCTURE_PATTERN = /[,+~]/;
53
+ const EDIT_GESTURES = new Set([
54
+ 'fill',
55
+ 'type',
56
+ 'pressSequentially'
57
+ ]);
58
+ const CLICK_GESTURES = new Set(['click', 'dblclick']);
59
+ /** Removes the page content and side branches embedded in a CSS segment. */
60
+ function stripContent(cssSegment) {
61
+ let stripped = cssSegment;
62
+ for (;;) {
63
+ const next = stripped.replace(PSEUDO_ARGUMENT_PATTERN, '');
64
+ if (next === stripped) {
65
+ break;
66
+ }
67
+ stripped = next;
68
+ }
69
+ return stripped.replace(QUOTED_VALUE_PATTERN, '');
70
+ }
71
+ /**
72
+ * True when a literal is a `modifiers` entry `selectCells()` reproduces.
73
+ * `selectCells(start, end)` shift-clicks the end cell, so `['Shift']` is
74
+ * covered; `Control`/`Meta` toggle an individual cell into the selection,
75
+ * which has no helper at all.
76
+ */
77
+ function isSupportedModifier(element) {
78
+ return element?.type === 'Literal' && element.value === 'Shift';
79
+ }
80
+ // Options that change only how long Playwright waits, never what the gesture
81
+ // does, so the notebook helper still reproduces it. Every other key is checked
82
+ // by name below or rejected: `clickCount` makes a triple click that selects
83
+ // editor text, `force` skips the actionability checks the helper relies on, and
84
+ // `position` aims somewhere other than the gutter `selectCells()` clicks.
85
+ const NEUTRAL_OPTION_KEYS = new Set([
86
+ 'timeout',
87
+ 'noWaitAfter',
88
+ 'delay'
89
+ ]);
90
+ /**
91
+ * True when the interaction's options object holds anything the notebook
92
+ * helper cannot reproduce, so that only the plain gesture is ever reported:
93
+ *
94
+ * - `button` — only a primary click selects a cell; a right click opens the
95
+ * context menu and a middle click has no cell binding at all.
96
+ * - `modifiers` — see `isSupportedModifier`.
97
+ * - `trial` — Playwright runs the actionability checks and then performs no
98
+ * click, so suggesting `selectCells()` would turn a no-op into a selection.
99
+ *
100
+ * Any other key is unsupported unless it is in `NEUTRAL_OPTION_KEYS`, and a
101
+ * computed key or a spread is unsupported because it could carry any of them.
102
+ */
103
+ function hasUnsupportedOptions(node) {
104
+ for (const arg of node.arguments) {
105
+ if (arg.type !== 'ObjectExpression') {
106
+ continue;
107
+ }
108
+ for (const prop of arg.properties) {
109
+ if (prop.type === 'SpreadElement' || prop.computed) {
110
+ return true;
111
+ }
112
+ const key = prop.key.type === 'Identifier'
113
+ ? prop.key.name
114
+ : prop.key.type === 'Literal'
115
+ ? prop.key.value
116
+ : null;
117
+ if (key === 'button') {
118
+ if (!(prop.value.type === 'Literal' && prop.value.value === 'left')) {
119
+ return true;
120
+ }
121
+ }
122
+ else if (key === 'modifiers') {
123
+ if (prop.value.type !== 'ArrayExpression' ||
124
+ !prop.value.elements.every(isSupportedModifier)) {
125
+ return true;
126
+ }
127
+ }
128
+ else if (key === 'trial') {
129
+ if (!(prop.value.type === 'Literal' && prop.value.value === false)) {
130
+ return true;
131
+ }
132
+ }
133
+ else if (typeof key !== 'string' || !NEUTRAL_OPTION_KEYS.has(key)) {
134
+ return true;
135
+ }
136
+ }
137
+ }
138
+ return false;
139
+ }
140
+ /**
141
+ * The selector chain flattened into engine segments, root-to-tip, with each
142
+ * one marked as markup or as matched page content.
143
+ *
144
+ * A class name found in page content proves nothing about the widget being
145
+ * driven — `page.getByText('jp-Cell')` clicks the literal text `jp-Cell`
146
+ * wherever it is rendered — so content segments are kept out of every token
147
+ * test. Returns null when any part does not resolve to a static string, since
148
+ * an interpolated selector hides the scope it was written with. Resolution
149
+ * follows `const` bindings, so the shared
150
+ * ``const cellSelector = '… .jp-Cell'`` idiom is still seen through.
151
+ */
152
+ function selectorSegments(match, scope) {
153
+ const segments = [];
154
+ for (const { method, argNode } of match.selectorParts) {
155
+ const resolved = utils_1.ASTUtils.getStaticValue(argNode, scope);
156
+ if (!resolved || typeof resolved.value !== 'string') {
157
+ return null;
158
+ }
159
+ const raw = resolved.value;
160
+ // In a locator chain only `locator()` takes a selector; `getByText()`,
161
+ // `getByTestId()`, … all match content. A direct `page.click(sel)` call
162
+ // always takes a selector.
163
+ if (match.viaLocatorChain && method !== 'locator') {
164
+ segments.push({ raw, text: raw, isCss: false });
165
+ continue;
166
+ }
167
+ // A selector string may itself chain engines with `>>`.
168
+ for (const piece of raw.split('>>')) {
169
+ const trimmed = piece.trim();
170
+ if (trimmed.length === 0 || PASSTHROUGH_ENGINE_PATTERN.test(trimmed)) {
171
+ // `>> nth=0` filters the preceding segment; it is not a target.
172
+ continue;
173
+ }
174
+ segments.push(CONTENT_ENGINE_PATTERN.test(trimmed)
175
+ ? { raw: trimmed, text: trimmed, isCss: false }
176
+ : { raw: trimmed, text: stripContent(trimmed), isCss: true });
177
+ }
178
+ }
179
+ return segments.length > 0 ? segments : null;
180
+ }
181
+ /**
182
+ * The element the gesture actually lands on: the last simple selector of the
183
+ * trailing segment, after any descendant/child/sibling combinator.
184
+ */
185
+ function targetToken(segment) {
186
+ const simples = segment.text.split(/[\s>+~]+/).filter(Boolean);
187
+ return simples[simples.length - 1] ?? '';
188
+ }
189
+ /** The string value of an argument, or null when it is not a static string. */
190
+ function staticStringArgument(node, index) {
191
+ const arg = node.arguments[index];
192
+ if (!arg) {
193
+ return null;
194
+ }
195
+ if (arg.type === 'Literal') {
196
+ return typeof arg.value === 'string' ? arg.value : null;
197
+ }
198
+ if (arg.type === 'TemplateLiteral' && arg.expressions.length === 0) {
199
+ return arg.quasis[0]?.value.cooked ?? null;
200
+ }
201
+ return null;
202
+ }
203
+ /** True for a `page.keyboard.press(...)` call. */
204
+ function isKeyboardPress(node) {
205
+ const { callee } = node;
206
+ return (callee.type === 'MemberExpression' &&
207
+ !callee.computed &&
208
+ callee.property.type === 'Identifier' &&
209
+ callee.property.name === 'press' &&
210
+ callee.object.type === 'MemberExpression' &&
211
+ !callee.object.computed &&
212
+ callee.object.object.type === 'Identifier' &&
213
+ callee.object.object.name === 'page' &&
214
+ callee.object.property.type === 'Identifier' &&
215
+ callee.object.property.name === 'keyboard');
216
+ }
217
+ /**
218
+ * The statement containing `node` that sits directly in a block or program
219
+ * body, so that sibling statements can be compared.
220
+ */
221
+ function enclosingBodyStatement(node) {
222
+ let current = node;
223
+ while (current) {
224
+ const parent = current.parent;
225
+ if (parent &&
226
+ (parent.type === 'BlockStatement' || parent.type === 'Program')) {
227
+ return current;
228
+ }
229
+ current = parent;
230
+ }
231
+ return null;
232
+ }
233
+ /**
234
+ * True for a statement that only asserts: `expect(x).toBe(y)`,
235
+ * `await expect(x).toBeVisible()`, `await expect.soft(x).not.toBeInViewport()`.
236
+ * An assertion performs no gesture of its own, so a run shortcut written after
237
+ * one is still finishing the interaction before it.
238
+ */
239
+ function isAssertionStatement(statement) {
240
+ if (statement.type !== 'ExpressionStatement') {
241
+ return false;
242
+ }
243
+ let current = statement.expression;
244
+ if (current.type === 'AwaitExpression') {
245
+ current = current.argument;
246
+ }
247
+ // Walk the call chain down to its root: `expect(x).not.toBe(y)` → `expect`.
248
+ while (current.type === 'CallExpression' ||
249
+ current.type === 'MemberExpression') {
250
+ current =
251
+ current.type === 'CallExpression' ? current.callee : current.object;
252
+ }
253
+ return current.type === 'Identifier' && current.name === 'expect';
254
+ }
255
+ function previousSiblingStatement(statement) {
256
+ const parent = statement.parent;
257
+ if (!parent ||
258
+ (parent.type !== 'BlockStatement' && parent.type !== 'Program')) {
259
+ return null;
260
+ }
261
+ const body = parent.body;
262
+ const index = body.indexOf(statement);
263
+ return index > 0 ? body[index - 1] : null;
264
+ }
265
+ const galataPreferNotebookCellHelper = (0, create_rule_1.createRule)({
266
+ name: 'galata-prefer-notebook-cell-helper',
267
+ meta: {
268
+ type: 'suggestion',
269
+ docs: {
270
+ description: 'Prefer the Galata notebook helper over raw Playwright selectors and run shortcuts for notebook cell operations'
271
+ },
272
+ messages: {
273
+ preferSetCell: 'Prefer `page.notebook.setCell(index, type, source)` (or `page.notebook.addCell(type, source)`) over typing into a cell editor directly.',
274
+ preferEnterCellEditingMode: 'Prefer `page.notebook.enterCellEditingMode(index)` over clicking into a cell editor directly.',
275
+ preferSelectCells: 'Prefer `page.notebook.selectCells(startIndex, endIndex)` (or `page.notebook.getCellLocator(index)`) over clicking a notebook cell directly.',
276
+ preferRunCell: 'Prefer `page.notebook.runCell(index)` (or `page.notebook.run()`) over pressing the run shortcut.'
277
+ },
278
+ schema: []
279
+ },
280
+ defaultOptions: [],
281
+ create(context) {
282
+ // Statements this rule has already reported on, so that a bare
283
+ // `page.keyboard.press('Shift+Enter')` can tell whether it is finishing a
284
+ // raw cell interaction (report) or doing something deliberate (stay
285
+ // silent).
286
+ const reportedStatements = new Set();
287
+ function report(node, messageId) {
288
+ const statement = enclosingBodyStatement(node);
289
+ // Only an interaction that is a statement in its own right can be
290
+ // compared with its siblings: `if (hasCell) await cell.click();` hangs
291
+ // off an `IfStatement`, so a shortcut after the `if` runs even when the
292
+ // click did not and must not be armed by it. Two statements sharing a
293
+ // block do always run together, conditional block or not.
294
+ if (statement?.type === 'ExpressionStatement') {
295
+ reportedStatements.add(statement);
296
+ }
297
+ context.report({ node, messageId });
298
+ }
299
+ function checkKeyboardPress(node) {
300
+ const key = staticStringArgument(node, 0);
301
+ if (key === null || !RUN_SHORTCUT_PATTERN.test(key)) {
302
+ return;
303
+ }
304
+ // A bare keyboard press carries no context whatsoever: there is no
305
+ // selector to say whether the focus is in a notebook, a console or a
306
+ // file editor's console panel, no cell index to put in the suggested
307
+ // `runCell(index)`, and no way to tell whether the binding is itself
308
+ // the thing under test. The only unambiguous shape
309
+ // is the shortcut completing a raw cell interaction already flagged
310
+ // here.
311
+ const statement = enclosingBodyStatement(node);
312
+ if (statement?.type !== 'ExpressionStatement') {
313
+ return;
314
+ }
315
+ // Assertions in between are stepped over: a test routinely checks the
316
+ // state the interaction left before running the cell.
317
+ let previous = previousSiblingStatement(statement);
318
+ while (previous && isAssertionStatement(previous)) {
319
+ previous = previousSiblingStatement(previous);
320
+ }
321
+ if (!previous || !reportedStatements.has(previous)) {
322
+ return;
323
+ }
324
+ report(node, 'preferRunCell');
325
+ }
326
+ function checkSelectorInteraction(node) {
327
+ // Most call expressions are not interactions at all, and
328
+ // `matchSelectorInteraction` rejects them on the callee alone, so the
329
+ // scope is looked up only once something actually needs it.
330
+ let scope = null;
331
+ const currentScope = () => (scope ?? (scope = context.sourceCode.getScope(node)));
332
+ const match = (0, playwright_selectors_1.matchSelectorInteraction)(node, identifier => (0, playwright_selectors_1.resolveLocatorBinding)(identifier, currentScope()));
333
+ if (!match) {
334
+ return;
335
+ }
336
+ if (hasUnsupportedOptions(node)) {
337
+ return;
338
+ }
339
+ const segments = selectorSegments(match, currentScope());
340
+ if (segments === null) {
341
+ return;
342
+ }
343
+ // The console, the file editor and dialogs reuse cell markup.
344
+ if (segments.some(segment => FOREIGN_CONTEXT_PATTERN.test(segment.raw))) {
345
+ return;
346
+ }
347
+ // A union or a sibling combinator puts the cell token in a branch the
348
+ // gesture need not land in, so the chain proves nothing about the target.
349
+ if (segments.some(segment => segment.isCss && AMBIGUOUS_STRUCTURE_PATTERN.test(segment.text))) {
350
+ return;
351
+ }
352
+ // Without a cell root token somewhere in the chain there is no proof
353
+ // this is a notebook cell at all.
354
+ if (!segments.some(segment => segment.isCss && CELL_CONTEXT_PATTERN.test(segment.text))) {
355
+ return;
356
+ }
357
+ // `page.notebook` has nothing to offer for a widget merely *rendered
358
+ // inside* a cell (an output link, the delete-cell button, the input
359
+ // collapser), nor for a gesture aimed at matched text, so the gesture
360
+ // has to land on the cell or its editor.
361
+ const lastSegment = segments[segments.length - 1];
362
+ if (!lastSegment.isCss) {
363
+ return;
364
+ }
365
+ const target = targetToken(lastSegment);
366
+ // An editor scoped to the cell's output is not the cell's input.
367
+ const targetsEditor = EDITOR_TARGET_PATTERN.test(target) &&
368
+ !segments.some(segment => segment.isCss && OUTPUT_AREA_PATTERN.test(segment.text));
369
+ const targetsCell = CELL_TARGET_PATTERN.test(target);
370
+ if (!targetsEditor && !targetsCell) {
371
+ return;
372
+ }
373
+ const gesture = match.interactionMethod;
374
+ if (gesture === 'press') {
375
+ // `page.press(selector, key)` vs `page.locator(selector).press(key)`.
376
+ const key = staticStringArgument(node, match.viaLocatorChain ? 0 : 1);
377
+ if (key !== null && RUN_SHORTCUT_PATTERN.test(key)) {
378
+ report(node, 'preferRunCell');
379
+ }
380
+ return;
381
+ }
382
+ if (EDIT_GESTURES.has(gesture)) {
383
+ if (targetsEditor) {
384
+ report(node, 'preferSetCell');
385
+ }
386
+ return;
387
+ }
388
+ if (CLICK_GESTURES.has(gesture)) {
389
+ report(node, targetsEditor ? 'preferEnterCellEditingMode' : 'preferSelectCells');
390
+ }
391
+ }
392
+ return {
393
+ CallExpression(node) {
394
+ if (isKeyboardPress(node)) {
395
+ checkKeyboardPress(node);
396
+ return;
397
+ }
398
+ checkSelectorInteraction(node);
399
+ }
400
+ };
401
+ }
402
+ });
403
+ module.exports = galataPreferNotebookCellHelper;
@@ -0,0 +1,6 @@
1
+ import { TSESLint } from '@typescript-eslint/utils';
2
+ type MessageIds = 'preferSidebarHelper' | 'preferActivityHelper';
3
+ declare const galataPreferSidebarActivityHelper: TSESLint.RuleModule<MessageIds, [], unknown, TSESLint.RuleListener> & {
4
+ name: string;
5
+ };
6
+ export = galataPreferSidebarActivityHelper;