eslint-plugin-kerfjs 5.0.0-beta.13 → 5.0.0-beta.131

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 (37) hide show
  1. package/README.md +85 -21
  2. package/docs/rules/ai-assistant-configs.md +17 -6
  3. package/docs/rules/no-generated-view-edits.md +42 -0
  4. package/docs/rules/no-inline-jsx-event-handlers.md +2 -2
  5. package/docs/rules/no-nested-mount.md +6 -1
  6. package/docs/rules/no-raw-with-dynamic-arg.md +7 -7
  7. package/docs/rules/prefer-attr-selector.md +7 -7
  8. package/docs/rules/prefer-module-jsx-augmentation.md +8 -4
  9. package/docs/rules/require-data-key-in-each.md +16 -6
  10. package/docs/rules/require-delegate-disposer.md +10 -5
  11. package/docs/rules/ui-component-ownership.md +43 -0
  12. package/docs/rules/ui-composition.md +116 -0
  13. package/docs/rules/ui-css-values.md +51 -0
  14. package/docs/rules/ui-exceptional-shorthands.md +22 -0
  15. package/docs/rules/ui-preferences.md +41 -0
  16. package/docs/rules/ui-public-boundaries.md +48 -0
  17. package/docs/rules/ui-wiring.md +57 -0
  18. package/index.js +51 -1
  19. package/lib/html-template-classes.js +104 -0
  20. package/lib/rules/ai-assistant-configs.js +184 -23
  21. package/lib/rules/no-generated-view-edits.js +81 -0
  22. package/lib/rules/no-inline-jsx-event-handlers.js +1 -1
  23. package/lib/rules/no-nested-mount.js +2 -1
  24. package/lib/rules/no-raw-with-dynamic-arg.js +7 -6
  25. package/lib/rules/prefer-module-jsx-augmentation.js +3 -2
  26. package/lib/rules/require-data-key-in-each.js +38 -3
  27. package/lib/rules/require-delegate-disposer.js +2 -1
  28. package/lib/rules/ui-component-ownership.js +211 -0
  29. package/lib/rules/ui-composition.js +425 -0
  30. package/lib/rules/ui-css-values.js +3 -0
  31. package/lib/rules/ui-exceptional-shorthands.js +3 -0
  32. package/lib/rules/ui-preferences.js +116 -0
  33. package/lib/rules/ui-public-boundaries.js +196 -0
  34. package/lib/rules/ui-wiring.js +440 -0
  35. package/lib/ui-contract.js +643 -0
  36. package/lib/ui-css-value-contracts.js +317 -0
  37. package/package.json +8 -2
@@ -0,0 +1,643 @@
1
+ import { existsSync, readFileSync, statSync } from 'node:fs';
2
+ import { dirname, extname, relative, resolve } from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import process from 'node:process';
5
+
6
+ const PROFILE = '.kerf-ui-profile.json';
7
+ const loadCommonJs = createRequire(import.meta.url);
8
+
9
+ export const UI_CONTRACT_LOAD_CODE = 'KUI-L090';
10
+
11
+ // A catalog entry's `publicExports` mixes the component render function with
12
+ // helpers the component's props consume (`Select` ships `uiColor`, `List`
13
+ // ships `px`/`rem`/`flex`). Only the render function stands for the entry, so
14
+ // only it may carry the entry's contracts. A component export is one whose
15
+ // name starts with an uppercase letter: JSX itself treats a lowercase tag as an
16
+ // intrinsic element, so a lowercase export can never be a component tag, and
17
+ // `@kerfjs/ui`'s catalog check (`check-component-catalog.mjs`) enforces the
18
+ // converse for the package: every uppercase runtime export returns `SafeHtml`
19
+ // and every lowercase one does not. A default import has no name to inspect
20
+ // and keeps its subpath's entry.
21
+ export function isComponentExport(name) {
22
+ return name === 'default' || /^[A-Z]/.test(name);
23
+ }
24
+
25
+ const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));
26
+
27
+ // A file's modification time, or null when it does not exist (yet).
28
+ function mtimeOf(path) {
29
+ try {
30
+ return statSync(path).mtimeMs;
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ // The loaded contract, keyed by what it is built from rather than by the file
37
+ // being linted: the workspace, the settings, and the profile layers that apply
38
+ // to the file's directory. Each entry also records the modification time of
39
+ // every JSON file it read, so a long-running editor ESLint server picks up a
40
+ // regenerated catalog or an edited profile on its next lint. A failed load is
41
+ // never cached: the next lint retries it.
42
+ const cache = new Map();
43
+ // Settings objects are usually shared across every linted file, so their
44
+ // serialized form is computed once per object rather than on every call.
45
+ const settingsKeys = new WeakMap();
46
+ function settingsKey(settings) {
47
+ let key = settingsKeys.get(settings);
48
+ if (key === undefined) {
49
+ key = JSON.stringify(settings);
50
+ settingsKeys.set(settings, key);
51
+ }
52
+ return key;
53
+ }
54
+ const isFresh = (stamps) =>
55
+ stamps.every(([path, mtime]) => mtimeOf(path) === mtime);
56
+
57
+ /** Test seam: forget every loaded contract. */
58
+ export function clearUiContractCache() {
59
+ cache.clear();
60
+ }
61
+
62
+ // The directory whose package.json names `packageName`, searched upward from a
63
+ // catalog file; a catalog's `source` paths are relative to that package root.
64
+ function packageRootOf(start, packageName) {
65
+ for (let directory = dirname(start); ; directory = dirname(directory)) {
66
+ const manifest = resolve(directory, 'package.json');
67
+ if (existsSync(manifest)) {
68
+ try {
69
+ if (readJson(manifest).name === packageName) return directory;
70
+ } catch {
71
+ // An unreadable manifest is not the owner; keep searching.
72
+ }
73
+ }
74
+ if (dirname(directory) === directory) return dirname(start);
75
+ }
76
+ }
77
+
78
+ const exportName = (item) => (typeof item === 'string' ? item : item?.name);
79
+
80
+ // Application and third-party composition catalogs a profile declares, beyond
81
+ // the @kerfjs/ui catalog the rules load directly. Their entries join the
82
+ // contract, and their components resolve by package subpath (a bare import)
83
+ // or by source file (an app's relative import).
84
+ function profileCatalogs(loadedProfile, basePackage, read) {
85
+ const catalogs = [];
86
+ for (const catalog of loadedProfile.profile?.catalogs ?? []) {
87
+ if (catalog.package === basePackage) continue;
88
+ const owner = loadedProfile.provenance?.[`$catalogs.${catalog.package}`];
89
+ if (!owner || !catalog.composition?.path || owner.startsWith('<')) continue;
90
+ const path = resolve(dirname(owner), catalog.composition.path);
91
+ const artifact = read(path);
92
+ catalogs.push({ artifact, root: packageRootOf(path, catalog.package) });
93
+ }
94
+ return catalogs;
95
+ }
96
+
97
+ // The files a relative import specifier may name, in the order TypeScript's
98
+ // ESM resolution tries them (a `.js` specifier also names its `.ts`/`.tsx`).
99
+ const SCRIPT_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mts', '.mjs'];
100
+ export function relativeImportCandidates(fromFile, specifier) {
101
+ const base = resolve(dirname(fromFile), specifier);
102
+ const extension = extname(base);
103
+ const stem = SCRIPT_EXTENSIONS.includes(extension)
104
+ ? base.slice(0, -extension.length)
105
+ : base;
106
+ return [
107
+ base,
108
+ ...SCRIPT_EXTENSIONS.map((candidate) => `${stem}${candidate}`),
109
+ ...SCRIPT_EXTENSIONS.map((candidate) => resolve(base, `index${candidate}`)),
110
+ ];
111
+ }
112
+
113
+ function packageAsset(cwd, name) {
114
+ try {
115
+ return createRequire(resolve(cwd, 'package.json')).resolve(
116
+ `@kerfjs/ui/ai/${name}`,
117
+ );
118
+ } catch {
119
+ return undefined;
120
+ }
121
+ }
122
+
123
+ // The profile layers that apply to `filename`, outermost first, without
124
+ // reading them: the shipped package defaults, then every `.kerf-ui-profile.json`
125
+ // from the workspace root down to the file's directory. Files whose directories
126
+ // see the same layers share one loaded contract.
127
+ function profileLayers(cwd, filename, settings) {
128
+ if (settings.profile || settings.profilePath) return [];
129
+ const layers = [];
130
+ const defaultsPath =
131
+ settings.profileDefaultsPath ??
132
+ packageAsset(cwd, 'application-ui-profile.defaults.json');
133
+ if (defaultsPath && existsSync(defaultsPath))
134
+ layers.push({ path: defaultsPath, scope: 'package' });
135
+ const workspace = resolve(settings.workspaceRoot ?? cwd);
136
+ const target = resolve(dirname(filename));
137
+ if (relative(workspace, target).startsWith('..')) return layers;
138
+ const directories = [];
139
+ let directory = target;
140
+ while (true) {
141
+ directories.push(directory);
142
+ if (directory === workspace) break;
143
+ directory = dirname(directory);
144
+ }
145
+ for (const candidate of directories.reverse()) {
146
+ const path = resolve(candidate, PROFILE);
147
+ if (existsSync(path))
148
+ layers.push({
149
+ path,
150
+ scope: candidate === workspace ? 'workspace' : 'directory',
151
+ });
152
+ }
153
+ return layers;
154
+ }
155
+
156
+ function readProfiles(settings, layers, read) {
157
+ if (settings.profilePath)
158
+ return [
159
+ { source: settings.profilePath, profile: read(settings.profilePath) },
160
+ ];
161
+ if (settings.profile)
162
+ return [
163
+ {
164
+ source: '<eslint settings kerfjs.ui.profile>',
165
+ profile: settings.profile,
166
+ },
167
+ ];
168
+ return layers.map(({ path, scope }) => {
169
+ const profile = read(path);
170
+ if (profile.scope !== scope)
171
+ throw new Error(
172
+ `${path} must have profile scope ${scope}, received ${profile.scope ?? 'missing'}`,
173
+ );
174
+ return { source: path, profile };
175
+ });
176
+ }
177
+
178
+ // `@kerfjs/ui`'s class-to-component rule ships beside its profile contract.
179
+ // An older `@kerfjs/ui` without it cannot report KUI-L103 consistently, so it
180
+ // fails the contract load instead of guessing.
181
+ function loadClassOwnership(profileContractPath) {
182
+ const path = resolve(
183
+ dirname(profileContractPath),
184
+ 'component-class-owners.cjs',
185
+ );
186
+ if (!existsSync(path))
187
+ throw new Error(
188
+ `Cannot find ${path}; install an @kerfjs/ui release that matches eslint-plugin-kerfjs.`,
189
+ );
190
+ const { componentClassOwnership } = loadCommonJs(path);
191
+ if (typeof componentClassOwnership !== 'function')
192
+ throw new Error(`${path} does not export componentClassOwnership.`);
193
+ return componentClassOwnership;
194
+ }
195
+
196
+ export function loadUiContract(context) {
197
+ const settings = context.settings?.kerfjs?.ui ?? {};
198
+ const packageCwd = context.cwd ?? process.cwd();
199
+ const cwd = resolve(settings.workspaceRoot ?? packageCwd);
200
+ const filename = context.filename ?? context.getFilename();
201
+ const layers = profileLayers(packageCwd, filename, settings);
202
+ const key = JSON.stringify([
203
+ cwd,
204
+ packageCwd,
205
+ settingsKey(settings),
206
+ layers.map(({ path }) => path),
207
+ ]);
208
+ const cached = cache.get(key);
209
+ if (cached && isFresh(cached.stamps)) return cached.value;
210
+ cache.delete(key);
211
+ // Every JSON file the contract is built from, with the modification time
212
+ // read just before the file itself.
213
+ const stamps = [];
214
+ const read = (path) => {
215
+ stamps.push([path, mtimeOf(path)]);
216
+ return readJson(path);
217
+ };
218
+ try {
219
+ const catalog =
220
+ settings.catalog ??
221
+ read(
222
+ settings.catalogPath ??
223
+ packageAsset(packageCwd, 'component-composition.json'),
224
+ );
225
+ const selection =
226
+ settings.selectionCatalog ??
227
+ read(
228
+ settings.selectionCatalogPath ??
229
+ packageAsset(packageCwd, 'component-catalog.json'),
230
+ );
231
+ const profiles = readProfiles(settings, layers, read);
232
+ const profileContractPath =
233
+ settings.profileContractPath ??
234
+ packageAsset(packageCwd, 'application-ui-profile-sync.cjs');
235
+ if (!profileContractPath)
236
+ throw new Error(
237
+ 'Cannot resolve @kerfjs/ui/ai/application-ui-profile-sync.cjs; install @kerfjs/ui or set kerfjs.ui.profileContractPath.',
238
+ );
239
+ const { loadApplicationUiProfileSync } = loadCommonJs(profileContractPath);
240
+ const diagnosticRegistryPath =
241
+ settings.diagnosticRegistryPath ??
242
+ resolve(
243
+ dirname(profileContractPath),
244
+ 'application-ui-diagnostic-ids-v1.json',
245
+ );
246
+ const diagnosticRegistry = read(diagnosticRegistryPath);
247
+ if (
248
+ diagnosticRegistry.schemaVersion !== 1 ||
249
+ !Array.isArray(diagnosticRegistry.ids)
250
+ )
251
+ throw new Error(
252
+ `${diagnosticRegistryPath} must be an application UI diagnostic registry with schemaVersion 1.`,
253
+ );
254
+ const loadedProfile = loadApplicationUiProfileSync(profiles, {
255
+ fallbackCatalogs: [catalog],
256
+ knownRules: diagnosticRegistry.ids,
257
+ });
258
+ if (loadedProfile.diagnostics.length) {
259
+ const diagnostic = loadedProfile.diagnostics[0];
260
+ throw new Error(
261
+ `${diagnostic.source} ${diagnostic.path} ${diagnostic.code}: ${diagnostic.message}`,
262
+ );
263
+ }
264
+ const profile = loadedProfile.profile;
265
+ const entries = new Map(catalog.entries.map((entry) => [entry.key, entry]));
266
+ // Declared application/third-party components: `packageExports` maps
267
+ // `<package or package/subpath>\0<Export>` and `sourceExports` maps
268
+ // `<absolute source file>\0<Export>` to the entry key.
269
+ const packageExports = new Map();
270
+ const sourceExports = new Map();
271
+ const helperSourceFiles = new Map();
272
+ // Source files of declared components: a wrapper's own source may render
273
+ // the element it wraps (an application wrapper around a `wa-dropdown`).
274
+ const componentSources = new Set();
275
+ // Every cataloged entry whose public classes may be a component's rendered
276
+ // anatomy: the base catalog's (exports from the selection catalog) and each
277
+ // declared application/third-party catalog's (exports on the entry).
278
+ const classOwnerEntries = catalog.entries.map((entry) => ({
279
+ key: entry.key,
280
+ name: entry.name,
281
+ boundaries: entry.boundaries,
282
+ exports: (
283
+ selection.entries.find(({ id }) => id === entry.id)?.publicExports ?? []
284
+ ).map(exportName),
285
+ }));
286
+ for (const { artifact, root } of profileCatalogs(
287
+ loadedProfile,
288
+ selection.package,
289
+ read,
290
+ ))
291
+ for (const entry of artifact.entries ?? []) {
292
+ const key = entry.key ?? `${artifact.package}:${entry.id}`;
293
+ entries.set(key, entry);
294
+ classOwnerEntries.push({
295
+ key,
296
+ name: entry.name,
297
+ boundaries: entry.boundaries,
298
+ exports: (entry.publicExports ?? []).map(exportName),
299
+ // The component's own source renders its anatomy classes; L103
300
+ // applies only outside it.
301
+ ...(entry.source ? { source: resolve(root, entry.source) } : {}),
302
+ });
303
+ for (const item of entry.publicExports ?? []) {
304
+ const name = exportName(item);
305
+ if (!name || !isComponentExport(name)) continue;
306
+ const subpath = typeof item === 'string' ? '.' : item.subpath;
307
+ // A private application's export has no subpath: it is never
308
+ // imported by package name, only through its source file below.
309
+ if (typeof subpath === 'string') {
310
+ const specifier =
311
+ subpath !== '.'
312
+ ? `${entry.package ?? artifact.package}/${subpath.replace(/^\.\//, '')}`
313
+ : (entry.package ?? artifact.package);
314
+ packageExports.set(`${specifier}\0${name}`, key);
315
+ }
316
+ if (entry.source) {
317
+ sourceExports.set(`${resolve(root, entry.source)}\0${name}`, key);
318
+ componentSources.add(resolve(root, entry.source));
319
+ }
320
+ }
321
+ for (const helper of entry.wiring?.sources ?? [])
322
+ helperSourceFiles.set(
323
+ `${resolve(root, helper.source)}\0${helper.export}`,
324
+ {
325
+ imported: helper.export,
326
+ returnsDisposer: helper.returnsDisposer !== false,
327
+ },
328
+ );
329
+ }
330
+ const imports = new Map();
331
+ const exports = new Map();
332
+ // Custom-element tag -> entry key, for elements authored directly in JSX
333
+ // (`<wa-dropdown>`) rather than through an imported component.
334
+ const customElements = new Map();
335
+ const helperSources = new Map();
336
+ const helperProviders = new Map();
337
+ const addHelperSource = (name, source) => {
338
+ const sources = helperSources.get(name) ?? new Set();
339
+ sources.add(source);
340
+ helperSources.set(name, sources);
341
+ };
342
+ for (const entry of selection.entries) {
343
+ const key = `${selection.package}:${entry.id}`;
344
+ if (entry.customElement) customElements.set(entry.customElement, key);
345
+ if (entry.delivery?.browserImport)
346
+ imports.set(entry.delivery.browserImport, key);
347
+ if (entry.delivery?.moduleImport)
348
+ imports.set(entry.delivery.moduleImport, key);
349
+ for (const name of entry.publicExports ?? []) {
350
+ if (isComponentExport(name)) exports.set(name, key);
351
+ addHelperSource(name, selection.package);
352
+ }
353
+ for (const wiring of entry.wiring ?? [])
354
+ addHelperSource(wiring.export, wiring.import);
355
+ }
356
+ for (const provider of selection.wiringProviders ?? []) {
357
+ addHelperSource(provider.export, provider.import);
358
+ for (const helper of provider.provides) {
359
+ const providers = helperProviders.get(helper) ?? new Set();
360
+ providers.add(provider.export);
361
+ helperProviders.set(helper, providers);
362
+ }
363
+ }
364
+ const value = {
365
+ entries,
366
+ package: selection.package,
367
+ imports,
368
+ exports,
369
+ packageExports,
370
+ sourceExports,
371
+ componentSources,
372
+ customElements,
373
+ helperSources,
374
+ helperProviders,
375
+ helperSourceFiles,
376
+ profile,
377
+ cwd,
378
+ publicClasses: new Set(
379
+ catalog.entries.flatMap((entry) => entry.boundaries.publicClasses),
380
+ ),
381
+ componentClasses: componentClassOwners(
382
+ classOwnerEntries,
383
+ loadClassOwnership(profileContractPath),
384
+ ),
385
+ publicTokens: new Set(
386
+ catalog.entries.flatMap((entry) => entry.boundaries.publicTokens),
387
+ ),
388
+ error: undefined,
389
+ };
390
+ cache.set(key, { stamps, value });
391
+ return value;
392
+ } catch (error) {
393
+ return { error: error.message };
394
+ }
395
+ }
396
+
397
+ // Public classes that are a component's rendered anatomy — `@kerfjs/ui`'s
398
+ // `kui-*` classes and any class a declared application or third-party catalog
399
+ // lists (`acme-meter`) — mapped to the entry and the export that renders it.
400
+ // Which classes an entry owns, and which export renders each, is
401
+ // `@kerfjs/ui`'s shared rule (`ai/component-class-owners.cjs`), the same one
402
+ // its generated component reference pages use. The first catalog to claim a
403
+ // class owns it, so the base catalog wins over a declared one.
404
+ function componentClassOwners(classOwnerEntries, componentClassOwnership) {
405
+ const owners = new Map();
406
+ for (const entry of classOwnerEntries)
407
+ for (const { className, render, element } of componentClassOwnership({
408
+ name: entry.name,
409
+ exports: entry.exports,
410
+ publicClasses: entry.boundaries?.publicClasses,
411
+ placeableClasses: entry.boundaries?.placeableClasses,
412
+ rootElement: entry.boundaries?.rootElement,
413
+ }))
414
+ if (!owners.has(className))
415
+ owners.set(className, {
416
+ key: entry.key,
417
+ render,
418
+ ...(element ? { element } : {}),
419
+ ...(entry.source ? { source: entry.source } : {}),
420
+ });
421
+ return owners;
422
+ }
423
+
424
+ export function importRegistry(program, contract, filename) {
425
+ const locals = new Map();
426
+ const namespaces = new Map();
427
+ const helpers = new Map();
428
+ const sources = new Set();
429
+ for (const node of program.body) {
430
+ if (node.type !== 'ImportDeclaration') continue;
431
+ const source = node.source.value;
432
+ sources.add(source);
433
+ const directKey = contract.imports?.get(source);
434
+ for (const specifier of node.specifiers) {
435
+ if (specifier.type === 'ImportNamespaceSpecifier') {
436
+ namespaces.set(specifier.local.name, source);
437
+ continue;
438
+ }
439
+ const imported =
440
+ specifier.type === 'ImportDefaultSpecifier'
441
+ ? 'default'
442
+ : (specifier.imported.name ?? specifier.imported.value);
443
+ const key = !isComponentExport(imported)
444
+ ? undefined
445
+ : (directKey ??
446
+ (source === contract.package
447
+ ? contract.exports?.get(imported)
448
+ : declaredComponentKey(contract, source, imported, filename)));
449
+ if (key) locals.set(specifier.local.name, key);
450
+ helpers.set(specifier.local.name, { imported, source });
451
+ }
452
+ }
453
+ return { locals, namespaces, helpers, sources };
454
+ }
455
+
456
+ // An application or third-party component declared in a profile catalog.
457
+ function declaredComponentKey(contract, source, imported, filename) {
458
+ const byPackage = contract.packageExports?.get(`${source}\0${imported}`);
459
+ if (byPackage) return byPackage;
460
+ if (!filename || !source.startsWith('.') || !contract.sourceExports?.size)
461
+ return undefined;
462
+ return sourceComponentKey(contract, filename, source, imported, new Set());
463
+ }
464
+
465
+ // A relative import names a cataloged component by its defining source file,
466
+ // or through relative re-exports (`export { X } from './x.js'`, `export * from
467
+ // './x.js'`, chains of either) that reach one: apps commonly import wrappers
468
+ // through a components barrel. Anything else — a bare re-export, a local
469
+ // definition, a file that cannot be read — stays unresolved.
470
+ const MAX_REEXPORT_VISITS = 64;
471
+ function sourceComponentKey(contract, fromFile, specifier, imported, seen) {
472
+ return sourceExportKey(
473
+ contract.sourceExports,
474
+ fromFile,
475
+ specifier,
476
+ imported,
477
+ seen,
478
+ );
479
+ }
480
+
481
+ function sourceExportKey(exports, fromFile, specifier, imported, seen) {
482
+ const candidates = relativeImportCandidates(fromFile, specifier);
483
+ for (const candidate of candidates) {
484
+ const key = exports.get(`${candidate}\0${imported}`);
485
+ if (key) return key;
486
+ }
487
+ // `seen` holds each (file, name) already followed: it breaks re-export
488
+ // cycles and bounds the work a pathological barrel graph can cost.
489
+ if (seen.size >= MAX_REEXPORT_VISITS) return undefined;
490
+ for (const candidate of candidates) {
491
+ const reExports = relativeReExports(candidate);
492
+ if (!reExports) continue;
493
+ const visit = `${candidate}\0${imported}`;
494
+ if (seen.has(visit)) return undefined;
495
+ seen.add(visit);
496
+ for (const { name, local, from } of reExports) {
497
+ if (name !== undefined && name !== imported) continue;
498
+ const key = sourceExportKey(
499
+ exports,
500
+ candidate,
501
+ from,
502
+ name === undefined ? imported : local,
503
+ seen,
504
+ );
505
+ if (key) return key;
506
+ }
507
+ // The first file that exists is the one the import resolves to.
508
+ return undefined;
509
+ }
510
+ return undefined;
511
+ }
512
+
513
+ // The relative value re-exports of one module file, read from its source text:
514
+ // `{ name, local, from }` for `export { local as name } from`, and
515
+ // `{ from }` (every name) for `export * from`. Type-only re-exports and
516
+ // namespace re-exports (`export * as ns`) are skipped. Cached by modification
517
+ // time, so a long-lived editor session sees barrel edits. Undefined when the
518
+ // file does not exist.
519
+ const reExportCache = new Map();
520
+ function relativeReExports(file) {
521
+ let mtime;
522
+ try {
523
+ const stats = statSync(file);
524
+ if (!stats.isFile()) return undefined;
525
+ mtime = stats.mtimeMs;
526
+ } catch {
527
+ return undefined;
528
+ }
529
+ const cached = reExportCache.get(file);
530
+ if (cached?.mtime === mtime) return cached.reExports;
531
+ let text;
532
+ try {
533
+ text = readFileSync(file, 'utf8');
534
+ } catch {
535
+ return undefined;
536
+ }
537
+ const code = text
538
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
539
+ .replace(/(^|[^:\\])\/\/[^\n]*/g, '$1');
540
+ const reExports = [];
541
+ const named = /\bexport\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"]+)\3/g;
542
+ for (const match of code.matchAll(named)) {
543
+ const [, typeOnly, list, , from] = match;
544
+ if (typeOnly || !from.startsWith('.')) continue;
545
+ for (const raw of list.split(',')) {
546
+ const part = raw.trim();
547
+ if (!part || /^type\s/.test(part)) continue;
548
+ const [local, name = local] = part.split(/\s+as\s+/).map((x) => x.trim());
549
+ reExports.push({ name, local, from });
550
+ }
551
+ }
552
+ const star = /\bexport\s+\*\s+from\s*(['"])([^'"]+)\1/g;
553
+ for (const match of code.matchAll(star)) {
554
+ const from = match[2];
555
+ if (from.startsWith('.')) reExports.push({ from });
556
+ }
557
+ reExportCache.set(file, { mtime, reExports });
558
+ return reExports;
559
+ }
560
+
561
+ export function jsxKey(name, registry, contract) {
562
+ if (name.type === 'JSXIdentifier') return registry.locals.get(name.name);
563
+ if (
564
+ name.type === 'JSXMemberExpression' &&
565
+ name.object.type === 'JSXIdentifier' &&
566
+ name.property.type === 'JSXIdentifier' &&
567
+ registry.namespaces.has(name.object.name)
568
+ ) {
569
+ const source = registry.namespaces.get(name.object.name);
570
+ const exportedKey = contract.exports.get(name.property.name);
571
+ if (source === contract.package) return exportedKey;
572
+ if (contract.imports.get(source) === exportedKey) return exportedKey;
573
+ }
574
+ return undefined;
575
+ }
576
+
577
+ /** Imported export name behind a JSX tag, including aliases and namespaces. */
578
+ export function jsxExportName(name, registry) {
579
+ if (name.type === 'JSXIdentifier')
580
+ return registry.helpers.get(name.name)?.imported;
581
+ if (
582
+ name.type === 'JSXMemberExpression' &&
583
+ name.object.type === 'JSXIdentifier' &&
584
+ name.property.type === 'JSXIdentifier'
585
+ )
586
+ return name.property.name;
587
+ return undefined;
588
+ }
589
+
590
+ // A custom element authored directly as a lowercase JSX tag resolves to its
591
+ // selection-catalog entry. Kept separate from `jsxKey` so composition rules
592
+ // keep treating raw elements as application-owned markup.
593
+ export function customElementKey(name, contract) {
594
+ if (name.type !== 'JSXIdentifier' || !name.name.includes('-')) return;
595
+ return contract.customElements?.get(name.name);
596
+ }
597
+
598
+ export function helperCall(callee, registry, contract, filename) {
599
+ let imported;
600
+ let source;
601
+ if (callee.type === 'Identifier') {
602
+ ({ imported, source } = registry.helpers.get(callee.name) ?? {});
603
+ } else if (
604
+ callee.type === 'MemberExpression' &&
605
+ !callee.computed &&
606
+ callee.object.type === 'Identifier' &&
607
+ callee.property.type === 'Identifier'
608
+ ) {
609
+ imported = callee.property.name;
610
+ source = registry.namespaces.get(callee.object.name);
611
+ }
612
+ if (!imported || !source) return undefined;
613
+ if (contract.helperSources.get(imported)?.has(source))
614
+ return { imported, source };
615
+ if (filename && source.startsWith('.') && contract.helperSourceFiles?.size) {
616
+ const resolved = sourceExportKey(
617
+ contract.helperSourceFiles,
618
+ filename,
619
+ source,
620
+ imported,
621
+ new Set(),
622
+ );
623
+ if (resolved) return { ...resolved, source };
624
+ }
625
+ return undefined;
626
+ }
627
+
628
+ export function isExcepted(contract, code, filename) {
629
+ const projectPath = relative(contract.cwd, filename).replaceAll('\\', '/');
630
+ return (contract.profile?.exceptions ?? []).some((exception) => {
631
+ if (!exception.rules.includes(code)) return false;
632
+ const target = exception.target.replace(/^\.\//, '').replace(/\/$/, '');
633
+ return projectPath === target || projectPath.startsWith(`${target}/`);
634
+ });
635
+ }
636
+
637
+ export const UI_RULE_SCHEMA = [
638
+ {
639
+ type: 'object',
640
+ properties: {},
641
+ additionalProperties: false,
642
+ },
643
+ ];