@starci/eslint-canon-be 3.12.0 → 3.14.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.
@@ -241,8 +241,38 @@ function appendEdge(from, sourceFile, project, owningWorkspace, reference, actua
241
241
  errors.push(helpers.boundaryViolation(config.root, edge, owningWorkspace, targetWorkspace, 'ARCH_PACKAGE_EXPORT_BYPASS', 'Cross-package imports must use the target package name and a declared package export.'));
242
242
  }
243
243
  }
244
+ /**
245
+ * An import of one of the app's root workspace packages (`@scope/agent-sdk`, `@scope/agent-sdk/workbench`). The package lies outside the side
246
+ * folder, yet it is first-party source both sides may import: through its package entry points (the `exports` of its manifest) and never past
247
+ * them. An entry point is no import that leaves the side and adds no edge (the package is not part of this side's graph; the package's own
248
+ * lint judges its files); a path into the package's source is refused. Returns true when the reference was settled here.
249
+ */
250
+ function rootPackageReference(sourceFile, project, reference, state) {
251
+ const { config, errors, helpers, host, ts } = state;
252
+ if (!config.rootPackages?.length)
253
+ return false;
254
+ const item = helpers.rootPackageOf(config, reference.specifier);
255
+ if (item === null)
256
+ return false;
257
+ if (!helpers.rootPackageEntryDeclared(item, reference.specifier)) {
258
+ errors.push({
259
+ ruleId: 'ARCH_INTERNAL_IMPORT_OUTSIDE',
260
+ project: project.relative,
261
+ path: helpers.relativePath(config.root, sourceFile.fileName),
262
+ ...helpers.sourceLocation(sourceFile, reference.node),
263
+ specifier: reference.specifier,
264
+ message: `Internal import ${reference.specifier} reaches into the package ${item.name} past its package entry points; import ${helpers.rootPackageEntries(item).join(', ')} instead.`,
265
+ });
266
+ return true;
267
+ }
268
+ // An entry point that a path alias sends outside the package is no entry point: the ordinary boundary judges it.
269
+ const resolved = helpers.resolveTypeScriptModule(ts, reference.specifier, sourceFile.fileName, project.options, host, resolutionCache(state, project));
270
+ return resolved === undefined || helpers.isInside(item.root, helpers.canonical(resolved));
271
+ }
244
272
  function processReference(from, sourceFile, project, owningWorkspace, reference, state) {
245
273
  const { config, ts, workspaceNames, workspaces, host, errors, helpers } = state;
274
+ if (rootPackageReference(sourceFile, project, reference, state))
275
+ return;
246
276
  // A workspace package is read at its source, never at its build: the same import resolves whether or not dist exists.
247
277
  const workspaceTarget = workspaces.filter(item => item.root !== helpers.canonical(config.root)).map(item => helpers.workspaceSourceEntry(ts, item, reference.specifier)).find(Boolean);
248
278
  const resolvedName = workspaceTarget ?? helpers.resolveTypeScriptModule(ts, reference.specifier, sourceFile.fileName, project.options, host, resolutionCache(state, project));
@@ -385,6 +385,26 @@ function packageExported(ts, workspace, specifier, actualTarget) {
385
385
  return expected === canonical(actualTarget) || sourceOfTarget(ts, workspace, target) === canonical(actualTarget);
386
386
  });
387
387
  }
388
+ /** The root workspace package of the app (`packages/agent-sdk`) a specifier names, its name or a subpath of it; the longest name when several match. */
389
+ export function rootPackageOf(config, specifier) {
390
+ let found = null;
391
+ for (const item of config.rootPackages ?? [])
392
+ if (sameOrUnder(specifier, item.name) && (found === null || item.name.length > found.name.length))
393
+ found = item;
394
+ return found;
395
+ }
396
+ /** Whether a specifier into a root package names one of its entry points: a subpath its `exports` declare, or its root through `exports`, `main`/`types` or `src/index`. A path into its source is not an entry point. */
397
+ export function rootPackageEntryDeclared(item, specifier) {
398
+ if (exportCandidates(item, specifier).length > 0)
399
+ return true;
400
+ return specifier === item.name && !item.exports && (manifestEntryTargets(item.manifest).length > 0 || packageIndexSource(item) !== null);
401
+ }
402
+ /** The subpaths a root package declares for import (`.` first), for the message of a refused deep import. */
403
+ export function rootPackageEntries(item) {
404
+ const declaration = item.exports;
405
+ const keys = declaration && typeof declaration === 'object' && !Array.isArray(declaration) ? Object.keys(declaration).filter(key => key.startsWith('.')) : ['.'];
406
+ return (keys.length ? keys : ['.']).map(key => (key === '.' ? item.name : `${item.name}${key.slice(1)}`));
407
+ }
388
408
  function boundaryViolation(root, edge, fromWorkspace, toWorkspace, ruleId, message) {
389
409
  return {
390
410
  ruleId,
@@ -413,7 +433,7 @@ function typeScriptContext(config, loaded, paths) {
413
433
  canonical, compilerError, isInside, slash, readTypeScriptProject, typeScriptProjectReferencePath,
414
434
  sameOrUnder, createTypeScriptProgram, isProductionSource, sourceLocation, workspaceMetadata, workspaceOf,
415
435
  pathAliasMatches, moduleReferences, workspaceSourceEntry, resolveTypeScriptModule, crossesSide, assetExtension: ASSET_EXTENSION,
416
- relativePath, packageExported, boundaryViolation,
436
+ relativePath, packageExported, boundaryViolation, rootPackageOf, rootPackageEntryDeclared, rootPackageEntries,
417
437
  });
418
438
  }
419
439
  export function relativePath(root, fileName) {
@@ -6,7 +6,7 @@ const HINTS = {
6
6
  'parameter type': 'Give the parameter a type: `(value: Input)`.',
7
7
  'property type': 'Give the property a type: `name: Result = ...`.',
8
8
  'accessor type': 'Give the accessor a type: `get name(): Result` (a setter takes it from its parameter).',
9
- 'destructured export': 'A destructuring pattern cannot carry a type per name: export each name as its own variable with a type, `export const name: Type = source.name`.',
9
+ 'destructured export': 'A destructuring pattern cannot carry a type per name: export each name as its own variable with a type, `export const name: Type = source.name`; a module definition is `export const { ConfigurableModuleClass, OPTIONS_TYPE } = defineCapabilityModule<XOptions>()` (or `defineConfigurableModule`) of @starci/nest-kit, which states the types (`starci app codemod module-definition` writes it).',
10
10
  'exported value': 'Declare the type (an interface or a type alias) and annotate the export with it: `export const name: Shape = ...`.',
11
11
  };
12
12
  /** The `--isolatedDeclarations` flag name TypeScript ends its reasons with says nothing to the reader. */
@@ -121,7 +121,7 @@ export const MANIFEST_KINDS = [APP_KIND, RUNTIME_KIND];
121
121
  export const manifestKind = (m) => (isPlainObject(m) && m.kind !== undefined ? m.kind : APP_KIND);
122
122
  const strList = (v) => stringList(v);
123
123
 
124
- const APP_SLOT_KEYS = ['id', 'profiles', 'path', 'presence', 'tracked', 'tier', 'tests', 'owner', 'appKind', 'minInstances', 'requiredWhen', 'requiredInstances', 'requires', 'pattern', 'trigger', 'allows', 'forbids', 'layers', 'kinds', 'roles', 'composedBy', 'budget', 'managedBy', 'liteManagedBy', 'rules', 'goesTo', 'why', 'since', 'perConnection', 'parent', 'editions', 'editionWhy', 'litePresence', 'lite', 'provider', 'coverage', 'entries', 'outcomeHome', 'templateNa', 'exemplifiedBy', 'role', 'importedBy', 'logic'];
124
+ const APP_SLOT_KEYS = ['id', 'profiles', 'path', 'presence', 'tracked', 'tier', 'tests', 'owner', 'appKind', 'minInstances', 'requiredWhen', 'requiredInstances', 'requires', 'pattern', 'trigger', 'allows', 'forbids', 'layers', 'kinds', 'roles', 'composedBy', 'budget', 'managedBy', 'liteManagedBy', 'rules', 'goesTo', 'why', 'since', 'perConnection', 'parent', 'editions', 'editionWhy', 'litePresence', 'lite', 'provider', 'coverage', 'entries', 'outcomeHome', 'templateNa', 'exemplifiedBy', 'role', 'importedBy', 'logic', 'managedOnly'];
125
125
  /** The roles a file slot may play that a rule reads (`role`): the entity registry of persistence.md BE-PERSISTENCE-3 (architecture/entity-registry.mjs). */
126
126
  const SLOT_ROLES = ['entity-registry'];
127
127
  /** The fields a slot's `lite` overlay may hold: the same keys it would carry in the slot body, resolved under edition lite. */
@@ -232,7 +232,7 @@ export function readRepoDeclaration(manifest, repoRoot) {
232
232
  function createScopeResolver(manifest, repo) {
233
233
  const profile = repo.profile;
234
234
  const edition = repo.edition ?? 'full';
235
- const slots = manifest.slots.filter((s) => s.profiles.includes(profile) && slotInEdition(manifest, s, edition)).map((s) => effectiveSlot(s, profile, edition));
235
+ const slots = manifest.slots.filter((s) => s.managedOnly !== true && s.profiles.includes(profile) && slotInEdition(manifest, s, edition)).map((s) => effectiveSlot(s, profile, edition));
236
236
  const scope = { manifest, repo, profile, slots, byId: new Map(slots.map((s) => [s.id, s])), variants: slots.flatMap(variantsOf), appKind: new Map(repo.apps.map((a) => [a.name, a.kind])) };
237
237
  const classifyPath = (input) => classifyIn(scope, input);
238
238
  /** tracked | ignored | external for the slot owning `p`, or null when no slot owns it. */
@@ -5,6 +5,7 @@
5
5
  import path from 'node:path';
6
6
  import { allowsFile } from './allows.mjs';
7
7
  import { openHfs } from './slots.mjs';
8
+ import { ROOT_PACKAGE_SLOTS } from './architecture/root-packages.mjs';
8
9
  const posix = (p) => String(p).replaceAll('\\', '/');
9
10
  const isAbsoluteAny = (text) => path.isAbsolute(text) || /^[A-Za-z]:\//.test(text);
10
11
  /**
@@ -69,3 +70,70 @@ export const openHfsView = ({ runtimeRoot, repoRoot }) => hfsView(openHfs({ root
69
70
  * @returns {object} The frozen view.
70
71
  */
71
72
  export const declaredHfsView = ({ runtimeRoot, declaration, repoRoot, side }) => hfsView(openHfs({ root: runtimeRoot, declaration, side }), repoRoot);
73
+ /**
74
+ * The view of the root workspace packages of an app (`packages/<pkg>/src/**`, slots app.packages and app.module-registry), as the lint of one
75
+ * side sees them: the rule parameters, the apps and the Grammar of `side` (a package is judged by the laws of the side whose subpath a file
76
+ * sits in), and the paths of the APP ROOT (`repoRoot` is the app root, not a side folder). The slots answer for the root paths; a file of a
77
+ * package is of the tier `package` and has no owner: the owner laws (one `index.ts` per owner root) are the module folders', a package's public
78
+ * surface being the `exports` of its manifest.
79
+ *
80
+ * @param {object} opened - The result of `openHfs` for the app root (profile app, both sides resolved).
81
+ * @param {string} repoRoot - The absolute app root.
82
+ * @param {string} side - `be` or `fe`: the side whose laws the file is judged by.
83
+ * @returns {object} The frozen view: the profile of the side over the paths of the app root.
84
+ */
85
+ function packagesView(opened, repoRoot, side) {
86
+ const scope = opened.sides?.[side];
87
+ const sideRepo = opened.repo.sides?.[side];
88
+ if (scope === undefined || sideRepo === undefined)
89
+ throw new Error('the view of the root packages needs the declaration of an app with both sides');
90
+ const rel = (file) => {
91
+ const text = posix(file);
92
+ return isAbsoluteAny(text) ? posix(path.relative(repoRoot, file)) : text.replace(/^\.\//, '');
93
+ };
94
+ const cache = new Map();
95
+ const classify = (file) => {
96
+ const key = rel(file);
97
+ if (!cache.has(key))
98
+ cache.set(key, opened.classifyPath(key));
99
+ return cache.get(key);
100
+ };
101
+ const packageOf = (file) => {
102
+ const slot = classify(file).slot;
103
+ const relative = rel(file);
104
+ return slot !== undefined && ROOT_PACKAGE_SLOTS.has(slot) ? relative.split('/').slice(0, 2).join('/') : null;
105
+ };
106
+ return Object.freeze({
107
+ repoRoot,
108
+ profile: side,
109
+ side,
110
+ edition: opened.repo.edition ?? 'full',
111
+ ...(sideRepo.grammar === undefined ? {} : { grammar: sideRepo.grammar }),
112
+ apps: sideRepo.apps,
113
+ connections: sideRepo.connections,
114
+ patterns: Object.freeze([...(sideRepo.patterns ?? [])]),
115
+ ruleParams: scope.ruleParams(),
116
+ relative: rel,
117
+ classify,
118
+ slotOf: (file) => classify(file).slot ?? null,
119
+ tierOf: (file) => (packageOf(file) === null ? null : 'package'),
120
+ // A package is no owner of the module laws (one index.ts at the owner root): its public surface is the `exports` of its manifest, so no file of it has an owner.
121
+ ownerOf: () => null,
122
+ allows: (file) => allowsFile(opened, rel(file)),
123
+ slot: (id) => opened.slot(id),
124
+ });
125
+ }
126
+ /**
127
+ * The view of the root packages of the app at `repoRoot` (the app root, where the root `eslint.config.mjs` lives), for the laws of `side`.
128
+ *
129
+ * @param {{ runtimeRoot: string, repoRoot: string, side: string }} input - Where the manifest copy lives, the app root, and the side whose laws apply.
130
+ * @returns {object} The frozen view.
131
+ */
132
+ export const openPackagesHfsView = ({ runtimeRoot, repoRoot, side }) => packagesView(openHfs({ root: runtimeRoot, repoRoot }), repoRoot, side);
133
+ /**
134
+ * The view of the root packages of an in-memory app declaration (rule tests): no file is read except the manifest.
135
+ *
136
+ * @param {{ runtimeRoot: string, declaration: object, repoRoot: string, side: string }} input - Manifest root, the app hfs.json object, the app root and the side.
137
+ * @returns {object} The frozen view.
138
+ */
139
+ export const declaredPackagesHfsView = ({ runtimeRoot, declaration, repoRoot, side }) => packagesView(openHfs({ root: runtimeRoot, declaration }), repoRoot, side);
@@ -55,6 +55,52 @@ function returnsOnlyJsx(ts, source, start) {
55
55
  ts.forEachChild(fn.body, visit);
56
56
  return only;
57
57
  }
58
+ /** The package whose module-definition helpers return a type they state in their own declaration (R368 accepts a destructured export of their call). */
59
+ export const STATED_SURFACE_PACKAGE = '@starci/nest-kit';
60
+ /** The helpers of that package: each is called with the options type as a type argument and returns the explicitly typed definition. */
61
+ export const STATED_SURFACE_HELPERS = new Set(['defineConfigurableModule', 'defineCapabilityModule']);
62
+ /** The local names under which `source` imports a stated-surface helper from its package (`import { defineConfigurableModule as define }` gives `define`). */
63
+ function statedHelperNames(ts, source) {
64
+ const names = new Set();
65
+ for (const statement of source.statements) {
66
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== STATED_SURFACE_PACKAGE)
67
+ continue;
68
+ const bindings = statement.importClause?.namedBindings;
69
+ if (bindings === undefined || !ts.isNamedImports(bindings))
70
+ continue;
71
+ for (const element of bindings.elements)
72
+ if (STATED_SURFACE_HELPERS.has((element.propertyName ?? element.name).text))
73
+ names.add(element.name.text);
74
+ }
75
+ return names;
76
+ }
77
+ /**
78
+ * Whether the destructured export the diagnostic at `start` points at is `export const { A, B } = helper<Options>()` for a stated-surface helper:
79
+ * each name has the type the helper's declaration gives it, written there, so the file states its surface by naming the helper and the options
80
+ * type, exactly as `export const A: Host["A"] = built.A` states it through `Host`.
81
+ */
82
+ function statesSurfaceThroughHelper(ts, source, start) {
83
+ const helpers = statedHelperNames(ts, source);
84
+ if (helpers.size === 0)
85
+ return null;
86
+ let innermost = source;
87
+ const descend = (node) => {
88
+ if (start < node.getFullStart() || start >= node.end)
89
+ return;
90
+ innermost = node;
91
+ ts.forEachChild(node, descend);
92
+ };
93
+ ts.forEachChild(source, descend);
94
+ for (let node = innermost; node !== undefined && node !== source; node = node.parent) {
95
+ if (!ts.isVariableDeclaration(node))
96
+ continue;
97
+ const call = node.initializer;
98
+ const stated = ts.isObjectBindingPattern(node.name) && call !== undefined && ts.isCallExpression(call) && ts.isIdentifier(call.expression) && helpers.has(call.expression.text)
99
+ && (call.typeArguments?.length ?? 0) > 0 && node.name.elements.every((element) => ts.isIdentifier(element.name) && element.dotDotDotToken === undefined);
100
+ return stated && call !== undefined ? call.getText(source) : null;
101
+ }
102
+ return null;
103
+ }
58
104
  /** What to annotate for each isolated-declaration diagnostic code; any other code asks for the exported value's type. */
59
105
  const ANNOTATE = new Map([
60
106
  [9007, 'return type'], [9008, 'return type'], [9009, 'accessor type'], [9010, 'variable type'], [9011, 'parameter type'], [9012, 'property type'],
@@ -98,7 +144,14 @@ export function declarationSurface(ts, file, text, module) {
98
144
  return { outputText: declared.outputText, problems: [] };
99
145
  const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
100
146
  const problems = [];
147
+ // The emit writes `any` for a destructured export; the call that states its type joins the digest, so a change of the options type reaches the importers.
148
+ const stated = new Set();
101
149
  for (const diagnostic of diagnostics) {
150
+ const call = diagnostic.code === 9019 && diagnostic.start !== undefined ? statesSurfaceThroughHelper(ts, source, diagnostic.start) : null;
151
+ if (call !== null) {
152
+ stated.add(call);
153
+ continue;
154
+ }
102
155
  const exempt = (diagnostic.code === 9007 || diagnostic.code === 9008) && diagnostic.start !== undefined && returnsOnlyJsx(ts, source, diagnostic.start);
103
156
  if (exempt)
104
157
  continue;
@@ -108,5 +161,6 @@ export function declarationSurface(ts, file, text, module) {
108
161
  reason: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n').split('\n')[0] ?? '',
109
162
  });
110
163
  }
111
- return { outputText: declared.outputText, problems };
164
+ const outputText = stated.size === 0 ? declared.outputText : `${declared.outputText}${[...stated].sort().map((call) => `// stated by ${call}\n`).join('')}`;
165
+ return { outputText, problems };
112
166
  }