@jupyter/eslint-plugin 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/lib/index.d.ts +68 -0
  2. package/lib/index.js +42 -11
  3. package/lib/rules/galata-prefer-filebrowser-helper.d.ts +5 -0
  4. package/lib/rules/galata-prefer-filebrowser-helper.js +105 -0
  5. package/lib/rules/incorrect-translator-usage.d.ts +4 -0
  6. package/lib/rules/incorrect-translator-usage.js +208 -0
  7. package/lib/rules/no-dynamic-translation.d.ts +4 -0
  8. package/lib/rules/no-dynamic-translation.js +92 -0
  9. package/lib/rules/no-pageconfig-base-url.d.ts +4 -0
  10. package/lib/rules/no-pageconfig-base-url.js +37 -0
  11. package/lib/rules/no-translation-concatenation.js +46 -84
  12. package/lib/rules/no-untranslated-string.js +7 -4
  13. package/lib/rules/plugin-activation-args.js +6 -2
  14. package/lib/rules/prefer-signal-this-arg.d.ts +7 -0
  15. package/lib/rules/prefer-signal-this-arg.js +196 -0
  16. package/lib/rules/require-disposable-ownership.d.ts +5 -0
  17. package/lib/rules/require-disposable-ownership.js +120 -0
  18. package/lib/rules/require-disposable-transfer.d.ts +5 -0
  19. package/lib/rules/require-disposable-transfer.js +223 -0
  20. package/lib/rules/require-signal-cleanup.d.ts +8 -0
  21. package/lib/rules/require-signal-cleanup.js +164 -0
  22. package/lib/rules/require-signal-this-arg.d.ts +5 -0
  23. package/lib/rules/require-signal-this-arg.js +74 -0
  24. package/lib/rules/token-format.js +1 -2
  25. package/lib/utils/disposables.d.ts +64 -0
  26. package/lib/utils/disposables.js +1723 -0
  27. package/lib/utils/playwright-selectors.d.ts +66 -0
  28. package/lib/utils/playwright-selectors.js +193 -0
  29. package/lib/utils/signal-lifetime.d.ts +158 -0
  30. package/lib/utils/signal-lifetime.js +755 -0
  31. package/lib/utils/signals.d.ts +143 -0
  32. package/lib/utils/signals.js +601 -0
  33. package/lib/utils/translation.d.ts +45 -0
  34. package/lib/utils/translation.js +122 -0
  35. package/package.json +11 -4
@@ -0,0 +1,755 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) Jupyter Development Team.
4
+ * Distributed under the terms of the Modified BSD License.
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.DEFAULT_LONG_LIVED_TYPES = void 0;
41
+ exports.buildSenderChain = buildSenderChain;
42
+ exports.collectClassOwnershipFacts = collectClassOwnershipFacts;
43
+ exports.classHasDisposalProtocol = classHasDisposalProtocol;
44
+ exports.analyzeSender = analyzeSender;
45
+ exports.classifyCallbackShape = classifyCallbackShape;
46
+ exports.hasMatchingDisconnect = hasMatchingDisconnect;
47
+ exports.isSelfTerminatingSignal = isSelfTerminatingSignal;
48
+ const utils_1 = require("@typescript-eslint/utils");
49
+ const ts = __importStar(require("typescript"));
50
+ const signals_1 = require("./signals");
51
+ /**
52
+ * Application-lifetime service types. A connection to a signal owned by one of
53
+ * these outlives any per-document or per-widget receiver.
54
+ *
55
+ * Deliberately short and curated. Notably absent: `DocumentRegistry.Context`
56
+ * and `JupyterFrontEnd` — both are routinely *shorter*-lived than the objects
57
+ * that hold them, and including them re-introduces false positives.
58
+ */
59
+ exports.DEFAULT_LONG_LIVED_TYPES = [
60
+ 'CommandRegistry',
61
+ 'IDebugger',
62
+ 'IDocumentManager',
63
+ 'ILSPConnection',
64
+ 'ILabShell',
65
+ 'ILanguageServerManager',
66
+ 'IRenderMimeRegistry',
67
+ 'ISettingRegistry',
68
+ 'IShell',
69
+ 'IStateDB',
70
+ 'IThemeManager',
71
+ 'ServiceManager'
72
+ ];
73
+ /**
74
+ * JupyterLab's MVC convention: `Foo`/`FooModel` pairs where the model is
75
+ * created by the document/context and the view is disposed independently
76
+ * (notebook windowing, "New View for Notebook", output area recycling).
77
+ */
78
+ const MODEL_SEGMENT = /^_?(model|sharedModel|context)$/;
79
+ const MODEL_TYPE_NAME = /(Model|Context)$|^ISharedDocument$/;
80
+ /** Properties a Lumino `Widget` intrinsically owns and disposes. */
81
+ const WIDGET_INTRINSICS = new Set(['title']);
82
+ /** Members that adopt a widget into a parent that will dispose it. */
83
+ const ADOPTION_METHODS = new Set([
84
+ 'addWidget',
85
+ 'insertWidget',
86
+ 'addItem',
87
+ 'insertItem'
88
+ ]);
89
+ /** Method names that read as "construct a fresh object I now own". */
90
+ const FACTORY_METHOD = /^create([A-Z]|$)/;
91
+ /** Strips wrappers that do not change the runtime value of an expression. */
92
+ function unwrap(node) {
93
+ let current = node;
94
+ for (;;) {
95
+ switch (current.type) {
96
+ case 'ChainExpression':
97
+ case 'TSNonNullExpression':
98
+ case 'TSAsExpression':
99
+ case 'TSSatisfiesExpression':
100
+ case 'TSTypeAssertion':
101
+ case 'TSInstantiationExpression':
102
+ current = current.expression;
103
+ break;
104
+ default:
105
+ return current;
106
+ }
107
+ }
108
+ }
109
+ function propertyName(node) {
110
+ if (node.type === 'Identifier' || node.type === 'PrivateIdentifier') {
111
+ return node.name;
112
+ }
113
+ if (node.type === 'Literal' && typeof node.value === 'string') {
114
+ return node.value;
115
+ }
116
+ return null;
117
+ }
118
+ /**
119
+ * Splits the receiver of a `.connect()` call into the signal name and the
120
+ * object path that owns it. Returns null when the receiver is not a
121
+ * `<object>.<signal>` member expression (a bare `signal.connect(cb)` on a
122
+ * local has no identifiable sender).
123
+ */
124
+ function buildSenderChain(signalExpr) {
125
+ const signal = unwrap(signalExpr);
126
+ if (signal.type !== 'MemberExpression') {
127
+ return null;
128
+ }
129
+ // Computed access is fine — `connection.serverNotifications['window/logMessage']`
130
+ // still identifies `connection.serverNotifications` as the sender. Only the
131
+ // signal's own name is unknown.
132
+ const signalName = signal.computed ? null : propertyName(signal.property);
133
+ const prefixes = [];
134
+ const path = [];
135
+ let hasCall = false;
136
+ let root = null;
137
+ let current = unwrap(signal.object);
138
+ for (;;) {
139
+ prefixes.push(current);
140
+ if (current.type === 'MemberExpression') {
141
+ path.push(current.computed ? null : propertyName(current.property));
142
+ current = unwrap(current.object);
143
+ continue;
144
+ }
145
+ if (current.type === 'ThisExpression' || current.type === 'Identifier') {
146
+ root = current;
147
+ }
148
+ else if (current.type === 'CallExpression' ||
149
+ current.type === 'NewExpression') {
150
+ hasCall = true;
151
+ }
152
+ break;
153
+ }
154
+ prefixes.reverse();
155
+ path.reverse();
156
+ return {
157
+ sender: unwrap(signal.object),
158
+ prefixes,
159
+ root,
160
+ path,
161
+ hasCall,
162
+ signalName
163
+ };
164
+ }
165
+ /** Whitespace/assertion-insensitive source text, for path comparisons. */
166
+ function normalizeText(sourceCode, node) {
167
+ return sourceCode
168
+ .getText(node)
169
+ .replace(/\s+/g, '')
170
+ .replace(/!/g, '')
171
+ .replace(/\?\./g, '.');
172
+ }
173
+ /**
174
+ * Does this initializer expression read as "a fresh object this scope now
175
+ * owns"? Covers `new X()`, factory calls, and the `??`/ternary/nested-assignment
176
+ * wrappers JupyterLab writes them in — notably
177
+ * `const output = (this._output = new OutputArea({...}))`.
178
+ */
179
+ function isOwningInitializer(node) {
180
+ if (!node) {
181
+ return false;
182
+ }
183
+ const value = unwrap(node);
184
+ switch (value.type) {
185
+ case 'NewExpression':
186
+ return true;
187
+ case 'AwaitExpression':
188
+ return isOwningInitializer(value.argument);
189
+ case 'AssignmentExpression':
190
+ return isOwningInitializer(value.right);
191
+ case 'LogicalExpression':
192
+ return (isOwningInitializer(value.left) || isOwningInitializer(value.right));
193
+ case 'ConditionalExpression':
194
+ return (isOwningInitializer(value.consequent) ||
195
+ isOwningInitializer(value.alternate));
196
+ case 'CallExpression': {
197
+ const callee = unwrap(value.callee);
198
+ if (callee.type === 'MemberExpression' && !callee.computed) {
199
+ const name = propertyName(callee.property);
200
+ return name !== null && FACTORY_METHOD.test(name);
201
+ }
202
+ return false;
203
+ }
204
+ default:
205
+ return false;
206
+ }
207
+ }
208
+ const SENDER_CLEANUP_STATICS = new Set([
209
+ 'clearData',
210
+ 'disconnectAll',
211
+ 'disconnectSender'
212
+ ]);
213
+ /**
214
+ * Collects, for one class body, which fields it owns and which senders it
215
+ * tears down. Both are *suppression* evidence: any hit means a connection to
216
+ * that sender cannot outlive the receiver, so nothing is reported.
217
+ */
218
+ function collectClassOwnershipFacts(classNode, sourceCode, signalLocalNames) {
219
+ const ownedFields = new Set();
220
+ const torndownSenders = [];
221
+ const getterAliases = new Map();
222
+ const noteOwnedTarget = (node) => {
223
+ const target = unwrap(node);
224
+ if (target.type === 'MemberExpression' &&
225
+ target.object.type === 'ThisExpression' &&
226
+ !target.computed) {
227
+ const name = propertyName(target.property);
228
+ if (name !== null) {
229
+ ownedFields.add(name);
230
+ }
231
+ }
232
+ };
233
+ for (const member of classNode.body.body) {
234
+ if (member.type === 'PropertyDefinition' &&
235
+ !member.static &&
236
+ isOwningInitializer(member.value)) {
237
+ const name = propertyName(member.key);
238
+ if (name !== null) {
239
+ ownedFields.add(name);
240
+ }
241
+ }
242
+ if (member.type === 'MethodDefinition' &&
243
+ member.kind === 'get' &&
244
+ member.value.body) {
245
+ const body = member.value.body.body;
246
+ const name = propertyName(member.key);
247
+ if (name !== null &&
248
+ body.length === 1 &&
249
+ body[0].type === 'ReturnStatement') {
250
+ const returned = unwrap(body[0].argument ?? member.value);
251
+ if (returned.type === 'MemberExpression' &&
252
+ returned.object.type === 'ThisExpression' &&
253
+ !returned.computed) {
254
+ const field = propertyName(returned.property);
255
+ if (field !== null && field !== name) {
256
+ getterAliases.set(name, field);
257
+ }
258
+ }
259
+ }
260
+ }
261
+ }
262
+ (0, signals_1.walkFrom)(classNode.body, node => {
263
+ if (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') {
264
+ return 'skip-children';
265
+ }
266
+ if (node.type === 'AssignmentExpression' &&
267
+ isOwningInitializer(node.right)) {
268
+ noteOwnedTarget(node.left);
269
+ return undefined;
270
+ }
271
+ if (node.type !== 'CallExpression') {
272
+ return undefined;
273
+ }
274
+ const callee = unwrap(node.callee);
275
+ if (callee.type !== 'MemberExpression' || callee.computed) {
276
+ return undefined;
277
+ }
278
+ const method = propertyName(callee.property);
279
+ if (method === null) {
280
+ return undefined;
281
+ }
282
+ // `x.dispose()` — the class tears the sender down itself.
283
+ if (method === 'dispose' && node.arguments.length === 0) {
284
+ noteOwnedTarget(callee.object);
285
+ torndownSenders.push({
286
+ text: normalizeText(sourceCode, callee.object),
287
+ node: callee.object
288
+ });
289
+ return undefined;
290
+ }
291
+ // `this.addWidget(x)` / `layout.insertWidget(i, x)` — adopted by a parent
292
+ // that will dispose it.
293
+ if (ADOPTION_METHODS.has(method)) {
294
+ for (const argument of node.arguments) {
295
+ noteOwnedTarget(argument);
296
+ torndownSenders.push({
297
+ text: normalizeText(sourceCode, argument),
298
+ node: argument
299
+ });
300
+ }
301
+ return undefined;
302
+ }
303
+ // `Signal.clearData(x)` and friends, for any sender that is not `this`
304
+ // (clearing by receiver says nothing about the sender's lifetime).
305
+ if ((0, signals_1.isSignalNamespaceCleanupCall)(node, signalLocalNames) &&
306
+ SENDER_CLEANUP_STATICS.has(method)) {
307
+ const target = node.arguments[0];
308
+ if (target &&
309
+ target.type !== 'ThisExpression' &&
310
+ target.type !== 'SpreadElement') {
311
+ noteOwnedTarget(target);
312
+ torndownSenders.push({
313
+ text: normalizeText(sourceCode, target),
314
+ node: target
315
+ });
316
+ }
317
+ }
318
+ return undefined;
319
+ });
320
+ return { ownedFields, torndownSenders, getterAliases };
321
+ }
322
+ /**
323
+ * Does this class have somewhere to put a disconnect at all — a `dispose()`
324
+ * method, an `isDisposed` member, or an `implements ...Disposable` clause?
325
+ *
326
+ * A class with no teardown protocol whatsoever is almost always a plugin-scope
327
+ * singleton (`MermaidManager`, `ThemeManager`, `LayoutRestorer`): it is created
328
+ * once in an `activate()` and lives as long as the services it connects to, so
329
+ * the connection never leaks and there is no `dispose()` in which to write the
330
+ * fix. It is indistinguishable, from inside the file, from a genuinely
331
+ * short-lived class that forgot to implement disposal — so both stay silent.
332
+ */
333
+ function classHasDisposalProtocol(classNode) {
334
+ for (const clause of classNode.implements ?? []) {
335
+ const expression = clause.expression;
336
+ const name = expression.type === 'Identifier'
337
+ ? expression.name
338
+ : expression.type === 'MemberExpression' && !expression.computed
339
+ ? propertyName(expression.property)
340
+ : null;
341
+ if (name && /Disposable$/.test(name)) {
342
+ return true;
343
+ }
344
+ }
345
+ for (const member of classNode.body.body) {
346
+ if ((member.type === 'MethodDefinition' ||
347
+ member.type === 'PropertyDefinition') &&
348
+ !member.static) {
349
+ const name = propertyName(member.key);
350
+ if (name === 'dispose' || name === 'isDisposed') {
351
+ return true;
352
+ }
353
+ }
354
+ }
355
+ return false;
356
+ }
357
+ /** Resolves the symbol name of an expression's static type, if available. */
358
+ function typeNameOf(node, context) {
359
+ const { checker, services } = context;
360
+ if (!checker || !services || !services.esTreeNodeToTSNodeMap) {
361
+ return null;
362
+ }
363
+ try {
364
+ const tsNode = services.esTreeNodeToTSNodeMap.get(node);
365
+ if (!tsNode) {
366
+ return null;
367
+ }
368
+ let type = checker.getTypeAtLocation(tsNode);
369
+ if (type.isUnion()) {
370
+ const candidates = type.types.filter(t => !(t.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)));
371
+ if (candidates.length !== 1) {
372
+ return null;
373
+ }
374
+ type = candidates[0];
375
+ }
376
+ let symbol = type.aliasSymbol ?? type.getSymbol();
377
+ if (!symbol) {
378
+ return null;
379
+ }
380
+ if (symbol.flags & ts.SymbolFlags.Alias) {
381
+ try {
382
+ symbol = checker.getAliasedSymbol(symbol);
383
+ }
384
+ catch {
385
+ // Keep the un-aliased symbol.
386
+ }
387
+ }
388
+ return symbol.getName();
389
+ }
390
+ catch {
391
+ return null;
392
+ }
393
+ }
394
+ function isWidgetTyped(node, context) {
395
+ const { checker, services } = context;
396
+ if (!checker || !services || !services.esTreeNodeToTSNodeMap) {
397
+ return false;
398
+ }
399
+ try {
400
+ const tsNode = services.esTreeNodeToTSNodeMap.get(node);
401
+ if (!tsNode) {
402
+ return false;
403
+ }
404
+ return (0, signals_1.typeExtendsLuminoWidget)(checker.getTypeAtLocation(tsNode), checker);
405
+ }
406
+ catch {
407
+ return false;
408
+ }
409
+ }
410
+ /** Resolves a `this.<field>` name through single-expression getters. */
411
+ function resolveFieldName(name, facts) {
412
+ const seen = new Set();
413
+ let current = name;
414
+ while (facts.getterAliases.has(current) && !seen.has(current)) {
415
+ seen.add(current);
416
+ current = facts.getterAliases.get(current);
417
+ }
418
+ return current;
419
+ }
420
+ /**
421
+ * Index of the deepest prefix in the chain that the enclosing scope provably
422
+ * owns — constructs, adopts, or disposes — or -1 when nothing in the chain is
423
+ * owned.
424
+ *
425
+ * Ownership is a property of one object in the path, not of the whole path.
426
+ * `const input = (this._input = new InputArea(...))` makes the class the owner
427
+ * of `input`, but `input.model` is a cell model owned by the *notebook* model
428
+ * and outlives every view built on it. Recording the depth is what lets
429
+ * `analyzeSender` tell those two apart.
430
+ */
431
+ function ownedPrefixDepth(chain, context) {
432
+ let depth = -1;
433
+ const root = chain.root;
434
+ if (root?.type === 'ThisExpression') {
435
+ const first = chain.path[0];
436
+ if (first !== null &&
437
+ first !== undefined &&
438
+ context.facts.ownedFields.has(resolveFieldName(first, context.facts))) {
439
+ // prefixes[0] is `this`; prefixes[1] is `this.<first>`.
440
+ depth = 1;
441
+ }
442
+ }
443
+ else if (root?.type === 'Identifier' &&
444
+ identifierIsOwned(root, context, new Set())) {
445
+ depth = 0;
446
+ }
447
+ for (let i = 0; i < chain.prefixes.length; i++) {
448
+ if (isTornDown(chain.prefixes[i], context)) {
449
+ depth = Math.max(depth, i);
450
+ }
451
+ }
452
+ return depth;
453
+ }
454
+ /** The `this`/identifier at the base of an expression, if it has one. */
455
+ function expressionRoot(node) {
456
+ let current = unwrap(node);
457
+ while (current.type === 'MemberExpression') {
458
+ current = unwrap(current.object);
459
+ }
460
+ return current.type === 'ThisExpression' || current.type === 'Identifier'
461
+ ? current
462
+ : null;
463
+ }
464
+ /**
465
+ * Measure D: does the class tear this exact expression down? Texts must match
466
+ * *and*, for identifier-rooted expressions, both roots must resolve to the same
467
+ * variable — the same name in two methods is routinely two different objects.
468
+ */
469
+ function isTornDown(expression, context) {
470
+ const text = normalizeText(context.sourceCode, expression);
471
+ const root = expressionRoot(expression);
472
+ for (const record of context.facts.torndownSenders) {
473
+ if (record.text !== text) {
474
+ continue;
475
+ }
476
+ const recordRoot = expressionRoot(record.node);
477
+ if (root?.type === 'ThisExpression' &&
478
+ recordRoot?.type === 'ThisExpression') {
479
+ // Fields are class-scoped: same text, same object.
480
+ return true;
481
+ }
482
+ if (root?.type !== 'Identifier' || recordRoot?.type !== 'Identifier') {
483
+ continue;
484
+ }
485
+ const a = utils_1.ASTUtils.findVariable(context.sourceCode.getScope(root), root);
486
+ const b = utils_1.ASTUtils.findVariable(context.sourceCode.getScope(recordRoot), recordRoot);
487
+ if (a !== null && a === b) {
488
+ return true;
489
+ }
490
+ }
491
+ return false;
492
+ }
493
+ function identifierIsOwned(identifier, context, seen) {
494
+ if (seen.has(identifier.name)) {
495
+ return false;
496
+ }
497
+ seen.add(identifier.name);
498
+ const variable = utils_1.ASTUtils.findVariable(context.scope, identifier);
499
+ if (!variable || variable.defs.length === 0) {
500
+ return false;
501
+ }
502
+ for (const def of variable.defs) {
503
+ if (def.type !== utils_1.TSESLint.Scope.DefinitionType.Variable) {
504
+ // Parameters, imports and class names carry no ownership evidence.
505
+ continue;
506
+ }
507
+ const init = def.node.init;
508
+ if (isOwningInitializer(init)) {
509
+ return true;
510
+ }
511
+ if (!init) {
512
+ continue;
513
+ }
514
+ // `const input = this._input;` / `const cell = other.child;` — follow the
515
+ // alias one step so ownership of the underlying field is still seen.
516
+ const aliasChain = buildAliasChain(init);
517
+ if (!aliasChain) {
518
+ continue;
519
+ }
520
+ if (aliasChain.root?.type === 'ThisExpression') {
521
+ const first = aliasChain.path[0];
522
+ if (first &&
523
+ context.facts.ownedFields.has(resolveFieldName(first, context.facts))) {
524
+ return true;
525
+ }
526
+ }
527
+ else if (aliasChain.root?.type === 'Identifier' &&
528
+ identifierIsOwned(aliasChain.root, context, seen)) {
529
+ return true;
530
+ }
531
+ }
532
+ return false;
533
+ }
534
+ /** Like `buildSenderChain`, but for a whole expression rather than a signal. */
535
+ function buildAliasChain(expression) {
536
+ const path = [];
537
+ let current = unwrap(expression);
538
+ for (;;) {
539
+ if (current.type === 'MemberExpression') {
540
+ path.push(current.computed ? null : propertyName(current.property));
541
+ current = unwrap(current.object);
542
+ continue;
543
+ }
544
+ if (current.type === 'ThisExpression' || current.type === 'Identifier') {
545
+ path.reverse();
546
+ return { root: current, path };
547
+ }
548
+ return null;
549
+ }
550
+ }
551
+ /** The property name that produced `prefixes[index]`, if statically known. */
552
+ function segmentNameAt(chain, index) {
553
+ if (index === 0) {
554
+ return chain.root?.type === 'Identifier' ? chain.root.name : null;
555
+ }
556
+ return chain.path[index - 1];
557
+ }
558
+ /**
559
+ * Does this link in the chain read as a model, shared model, or context —
560
+ * either by JupyterLab's naming convention or by its declared type?
561
+ */
562
+ function prefixIsModelLike(chain, index, context) {
563
+ const segment = segmentNameAt(chain, index);
564
+ if (segment && MODEL_SEGMENT.test(segment)) {
565
+ return true;
566
+ }
567
+ const typeName = typeNameOf(chain.prefixes[index], context);
568
+ return typeName !== null && MODEL_TYPE_NAME.test(typeName);
569
+ }
570
+ /**
571
+ * B1 — MVC dominance. JupyterLab's invariant is that models outlive views: a
572
+ * widget is disposed by windowing, by "New View for Notebook", or by output
573
+ * recycling while its model stays owned by the document. Only applies inside a
574
+ * Lumino `Widget` subclass, and only to links in the chain that are *deeper*
575
+ * than anything the class owns — owning the view says nothing about the model
576
+ * hanging off it.
577
+ */
578
+ function isLongLivedModel(chain, ownedDepth, context) {
579
+ if (!(0, signals_1.classExtendsLuminoWidget)(context.classNode, context.checker, context.services)) {
580
+ return false;
581
+ }
582
+ // As in `isLongLivedService`, a `this` root is the enclosing instance and is
583
+ // never the long-lived counterpart: a class that is itself named `...Model`
584
+ // says nothing about the lifetime of the field hanging off it.
585
+ const start = Math.max(ownedDepth + 1, chain.root?.type === 'ThisExpression' ? 1 : 0);
586
+ for (let i = start; i < chain.prefixes.length; i++) {
587
+ if (prefixIsModelLike(chain, i, context)) {
588
+ return true;
589
+ }
590
+ }
591
+ return false;
592
+ }
593
+ /**
594
+ * B2 — injected application service. Walks the sender path from the root
595
+ * outward and admits it when some prefix has an allowlisted service type, as
596
+ * long as no hop past that prefix is itself a widget (a widget reached through
597
+ * a service is not long-lived — `shell.currentWidget` is the canonical case).
598
+ *
599
+ * Requires type information; without it the answer is always "no".
600
+ */
601
+ function isLongLivedService(chain, context) {
602
+ if (!context.checker) {
603
+ return null;
604
+ }
605
+ // `prefixes[0]` is the root of the path. When that root is `this` it is the
606
+ // enclosing instance, which cannot outlive itself — skip it, so a class whose
607
+ // own type name is allowlisted (`CommandRegistry`, `ServiceManager`, or a
608
+ // configured entry) is not matched against itself.
609
+ const start = chain.root?.type === 'ThisExpression' ? 1 : 0;
610
+ for (let i = start; i < chain.prefixes.length; i++) {
611
+ const name = typeNameOf(chain.prefixes[i], context);
612
+ if (!name || !context.longLivedTypes.has(name)) {
613
+ continue;
614
+ }
615
+ let blocked = false;
616
+ for (let j = i + 1; j < chain.prefixes.length; j++) {
617
+ if (isWidgetTyped(chain.prefixes[j], context)) {
618
+ blocked = true;
619
+ break;
620
+ }
621
+ }
622
+ if (!blocked) {
623
+ return name;
624
+ }
625
+ }
626
+ return null;
627
+ }
628
+ /**
629
+ * Classifies the sender of a `.connect()` call. Everything that cannot be
630
+ * proven long-lived comes back as `'unknown'`, `'self'`, or `'owned'` — all of
631
+ * which the rules treat as silence.
632
+ */
633
+ function analyzeSender(signalExpr, context) {
634
+ const chain = buildSenderChain(signalExpr);
635
+ const senderText = chain
636
+ ? context.sourceCode.getText(chain.sender)
637
+ : context.sourceCode.getText(signalExpr);
638
+ if (!chain || chain.hasCall || !chain.root) {
639
+ // A call in the path, or a bare `signal.connect(cb)` on a local: the
640
+ // sender object is not identifiable, so nothing can be proven.
641
+ return { lifetime: 'unknown', senderText, typeName: null };
642
+ }
643
+ if (chain.root.type === 'ThisExpression') {
644
+ const first = chain.path[0];
645
+ if (first === undefined) {
646
+ // `this.somethingChanged` — the class's own signal. `Signal.clearData(this)`
647
+ // on the sender side already removes every connection to it.
648
+ return { lifetime: 'self', senderText, typeName: null };
649
+ }
650
+ if (first !== null && WIDGET_INTRINSICS.has(first)) {
651
+ return { lifetime: 'self', senderText, typeName: null };
652
+ }
653
+ }
654
+ const ownedDepth = ownedPrefixDepth(chain, context);
655
+ if (ownedDepth >= 0) {
656
+ if (ownedDepth === chain.prefixes.length - 1) {
657
+ // The sender itself is constructed, adopted, or disposed here: it dies
658
+ // with the receiver, so the connection is collected either way.
659
+ return { lifetime: 'owned', senderText, typeName: null };
660
+ }
661
+ if (prefixIsModelLike(chain, ownedDepth, context)) {
662
+ // The owned link is itself a model, so everything hanging off it
663
+ // (`this._model.sharedModel`, `this._model.cells`) is owned too.
664
+ return { lifetime: 'owned', senderText, typeName: null };
665
+ }
666
+ // Otherwise the class owns a *view* and the sender lives deeper — fall
667
+ // through: `input.model` is not owned just because `input` is.
668
+ }
669
+ const serviceName = isLongLivedService(chain, context);
670
+ if (serviceName) {
671
+ return {
672
+ lifetime: 'long-lived-service',
673
+ senderText,
674
+ typeName: serviceName
675
+ };
676
+ }
677
+ if (isLongLivedModel(chain, ownedDepth, context)) {
678
+ return { lifetime: 'long-lived-model', senderText, typeName: null };
679
+ }
680
+ return { lifetime: 'unknown', senderText, typeName: null };
681
+ }
682
+ /**
683
+ * How a connected callback can be removed later.
684
+ *
685
+ * - `bound`: `fn.bind(this)` allocates a fresh function, so no
686
+ * `disconnect(callback, ...)` can ever match it by identity.
687
+ * - `inline`: an arrow or function expression — same problem, unless the
688
+ * connection carries a `thisArg` that receiver-side cleanup can match.
689
+ * - `referenced`: a stable identifier or member expression, removable by a
690
+ * matching `disconnect()`.
691
+ */
692
+ function classifyCallbackShape(callback) {
693
+ const value = unwrap(callback);
694
+ if (value.type === 'CallExpression' &&
695
+ value.callee.type === 'MemberExpression' &&
696
+ !value.callee.computed &&
697
+ propertyName(value.callee.property) === 'bind') {
698
+ return 'bound';
699
+ }
700
+ if (value.type === 'ArrowFunctionExpression' ||
701
+ value.type === 'FunctionExpression') {
702
+ return 'inline';
703
+ }
704
+ if (value.type === 'Identifier' || value.type === 'MemberExpression') {
705
+ return 'referenced';
706
+ }
707
+ return 'opaque';
708
+ }
709
+ /**
710
+ * Measure C: is there a `.disconnect()` anywhere in the file that removes this
711
+ * callback?
712
+ *
713
+ * Searches the whole `Program` — including nested arrow functions, returned
714
+ * `DisposableDelegate` bodies and helper closures — and matches on the
715
+ * normalized text of the callback expression rather than on the sender chain.
716
+ * `@jupyterlab/lsp`'s `registerProvider` connects
717
+ * `registration.provider.sessionsChanged` and disconnects
718
+ * `provider.sessionsChanged` with the same `registration.onSessionsChanged`
719
+ * callback; comparing senders misses it, comparing callbacks does not.
720
+ *
721
+ * `arity` is the argument count the disconnect must have to match the connect:
722
+ * Lumino matches on the exact `(signal, slot, thisArg)` triple, so a
723
+ * one-argument `connect(cb)` is only undone by a one-argument
724
+ * `disconnect(cb)`.
725
+ */
726
+ function hasMatchingDisconnect(program, callback, sourceCode, arity) {
727
+ if (classifyCallbackShape(callback) !== 'referenced') {
728
+ // Inline and bound callbacks have no stable identity to disconnect by.
729
+ return false;
730
+ }
731
+ const wanted = normalizeText(sourceCode, callback);
732
+ let found = false;
733
+ (0, signals_1.walkFrom)(program, node => {
734
+ if (node.type === 'CallExpression' &&
735
+ node.callee.type === 'MemberExpression' &&
736
+ !node.callee.computed &&
737
+ propertyName(node.callee.property) === 'disconnect' &&
738
+ node.arguments.length === arity &&
739
+ normalizeText(sourceCode, node.arguments[0]) === wanted) {
740
+ found = true;
741
+ return 'stop';
742
+ }
743
+ return undefined;
744
+ });
745
+ return found;
746
+ }
747
+ /**
748
+ * Measure E: `disposed`-style wiring is cleaned up sender-side — the signal
749
+ * fires exactly as its sender is torn down, and Lumino's own
750
+ * `Widget.dispose()` clears the connection immediately afterwards. This is the
751
+ * pattern the docs recommend, so neither rule may flag it.
752
+ */
753
+ function isSelfTerminatingSignal(chain) {
754
+ return chain?.signalName === 'disposed';
755
+ }