@r_masseater/msch 0.11.0 → 0.13.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.
package/dist/cli.mjs CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { $ as isTypeAliasDeclaration, A as getTextOfJSDocComment, B as isInterfaceDeclaration, C as API, D as getJSDocTags, E as SyntaxKind, F as isElementAccessExpression, G as isObjectLiteralExpression, H as isModuleDeclaration, I as isEnumDeclaration, J as isSatisfiesExpression, K as isPropertyAccessExpression, L as isExportDeclaration, M as isBinaryExpression, N as isCallExpression, O as getLeadingCommentRanges, P as isClassDeclaration, Q as isStringLiteral, R as isIdentifier, S as uniqueByReference, T as InternalSymbolName, U as isNewExpression, V as isModuleBlock, W as isNumericLiteral, X as isSourceFile, Y as isSignatureDeclaration, Z as isSpreadElement, _ as lineOf, a as problemAt, at as isVariableStatement, b as resolvedSymbol, c as childrenOf$2, d as declarationsOf, et as isTypeLiteralNode, f as descendantsOf, g as isTypeDeclaration, h as isGenericDeclaration, i as formatProblem, it as isVariableDeclarationList, j as isArrayLiteralExpression, k as getNameOfDeclaration, l as columnOf, m as isExternalDeclaration, n as ProblemList, nt as isUnionTypeNode, o as sortProblems, p as importedModulesOf, q as isPropertyAssignment, rt as isVariableDeclaration, s as NODE_MODULES_SEGMENT, tt as isTypeReferenceNode, u as contains, v as propertyNamesOf, w as IndexKind, x as symbolAt, y as referencedSymbols, z as isImportDeclaration } from "./cli-contract-c3l4AjvJ.mjs";
3
- import { a as workspaceDependencies, c as nodeServicesLayer, i as readManifest, n as NODE_MODULES, o as RepositoryFiles, r as dependencyEntries, s as nodeRepositoryFiles, t as MANIFEST_FILE } from "./dependencies-CVEeDVp2.mjs";
4
- import { _ as publishedWorkspaces, c as programOf, d as childrenOf$3, i as hasVerifyTask, m as workspaceDirectories, n as VERIFY_TASK, r as definesTask, v as publicEntriesOf } from "./workspace-tasks-DqSpU9ij.mjs";
5
- import { t as COMMENT_DIRECTIVES } from "./comment-directives-DApQXgQf.mjs";
2
+ import { $ as isTypeLiteralNode, A as isArrayLiteralExpression, B as isModuleBlock, C as IndexKind, D as getLeadingCommentRanges, E as getJSDocTags, F as isEnumDeclaration, G as isPropertyAccessExpression, H as isNewExpression, I as isExportDeclaration, J as isSignatureDeclaration, K as isPropertyAssignment, L as isIdentifier, M as isCallExpression, N as isClassDeclaration, O as getNameOfDeclaration, P as isElementAccessExpression, Q as isTypeAliasDeclaration, R as isImportDeclaration, S as API, T as SyntaxKind, U as isNumericLiteral, V as isModuleDeclaration, W as isObjectLiteralExpression, X as isSpreadElement, Y as isSourceFile, Z as isStringLiteral, _ as propertyNamesOf, a as sortProblems, b as symbolAt, c as columnOf, d as descendantsOf, et as isTypeReferenceNode, f as importedModulesOf, g as lineOf, h as isTypeDeclaration, i as problemAt, it as isVariableStatement, j as isBinaryExpression, k as getTextOfJSDocComment, l as contains, m as isGenericDeclaration, nt as isVariableDeclaration, o as NODE_MODULES_SEGMENT, p as isExternalDeclaration, q as isSatisfiesExpression, r as formatProblem, rt as isVariableDeclarationList, s as childrenOf$2, t as ProblemList, tt as isUnionTypeNode, u as declarationsOf, v as referencedSymbols, w as InternalSymbolName, x as uniqueByReference, y as resolvedSymbol, z as isInterfaceDeclaration } from "./problem-B5LCnsRC.mjs";
3
+ import { i as nodeServicesLayer, n as RepositoryFiles, r as nodeRepositoryFiles, t as NODE_MODULES } from "./repository-files-DcTnXciI.mjs";
4
+ import { C as publishedWorkspaces, D as readManifest, E as dependencyEntries, O as workspaceDependencies, T as MANIFEST_FILE, _ as childrenOf$3, a as hasVerifyTask, b as nestedValues, g as KeySchema, h as workspaceConfigOf, i as definesTask, l as workspaceDirectories, r as VERIFY_TASK, t as namedWorkspaces, v as keyName, w as publicEntriesOf, y as literalOf } from "./workspace-B1-fCPnh.mjs";
5
+ import { t as COMMENT_DIRECTIVES } from "./comment-directives-TN0dNEbg.mjs";
6
6
  import { Array, Cause, Effect, FileSystem, Function, HashMap, HashSet, Layer, Number as Number$1, Option, Order, Path, Predicate, Record, Result, Schema, Stdio, Stream, String as String$1, pipe } from "effect";
7
7
  import { ChildProcess } from "effect/process";
8
8
  import { parse, resolveConfigFromFile } from "vite-plus";
9
- import { LineCounter, Parser, isMap, isScalar, parseAllDocuments, parseDocument } from "yaml";
9
+ import { LineCounter, Parser, isMap, isPair, isScalar, isSeq, parse as parse$1, parseAllDocuments, parseDocument, visit } from "yaml";
10
10
  import path from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import treeSitter from "@vscode/tree-sitter-wasm";
@@ -18,39 +18,7 @@ import { parseTOML } from "toml-eslint-parser";
18
18
  import { runMain } from "@effect/platform-node-shared/NodeRuntime";
19
19
  import { FetchHttpClient } from "effect/http";
20
20
  import { Otlp, OtlpSerialization } from "effect/observability";
21
- // src/slots.ts
22
- const ANNOTATED_KINDS = /* @__PURE__ */ new Set([
23
- SyntaxKind.Parameter,
24
- SyntaxKind.VariableDeclaration,
25
- SyntaxKind.PropertySignature,
26
- SyntaxKind.PropertyDeclaration
27
- ]);
28
- const isAnnotated = (declaration) => ANNOTATED_KINDS.has(declaration.kind);
29
- const annotationOf = (declaration) => Option.liftPredicate(declaration, isAnnotated).pipe(Option.flatMap((annotated) => Option.fromUndefinedOr(annotated.type)));
30
- const argumentSlot = (checker) => (expression) => {
31
- const call = expression.parent;
32
- if (!isCallExpression(call) && !isNewExpression(call)) return Option.none();
33
- const { arguments: listed } = call;
34
- const index = (listed ?? []).indexOf(expression);
35
- return Option.fromUndefinedOr(checker.getResolvedSignature(call).declaration).pipe(Option.flatMap((handle) => Option.fromUndefinedOr(handle.resolve())), Option.filter(isSignatureDeclaration), Option.flatMap((declaration) => Array.get(declaration.parameters, index)));
36
- };
37
- const propertySlot = (checker) => (expression) => {
38
- const assignment = expression.parent;
39
- if (!isPropertyAssignment(assignment) || !isObjectLiteralExpression(assignment.parent)) return Option.none();
40
- return Option.fromUndefinedOr(checker.getContextualType(assignment.parent)).pipe(Option.flatMap((objectType) => Option.fromUndefinedOr(objectType.getProperty(assignment.name.getText()))), Option.flatMap((property) => Array.head(declarationsOf(property))));
41
- };
42
- const variableSlot = (expression) => {
43
- const declaration = expression.parent;
44
- if (!isVariableDeclaration(declaration) || declaration.initializer !== expression) return Option.none();
45
- return Option.some(declaration);
46
- };
47
- const slotOf = (checker) => (expression) => argumentSlot(checker)(expression).pipe(Option.orElse(() => propertySlot(checker)(expression)), Option.orElse(() => variableSlot(expression)));
48
- const contextSymbolsOf = (checker) => (expression) => {
49
- const alias = Option.fromUndefinedOr(checker.getContextualType(expression)).pipe(Option.flatMap((contextual) => Option.fromUndefinedOr(contextual.getAliasSymbol())));
50
- if (Option.isSome(alias)) return [alias.value];
51
- return slotOf(checker)(expression).pipe(Option.flatMap(annotationOf), Option.map((annotation) => referencedSymbols(checker)(annotation)), Option.getOrElse(() => []));
52
- };
53
- // src/values.ts
21
+ // src/shared/lib/values.ts
54
22
  const SCHEMA_TYPE_PROPERTIES = ["Type", "_output"];
55
23
  const MINIMUM_SET_SIZE = 2;
56
24
  const DATA_FIRST_ARITY = 2;
@@ -95,123 +63,7 @@ const valueText = (value) => {
95
63
  return String(value);
96
64
  };
97
65
  const formatValues = (values) => pipe(values, Array.map(valueText), Array.join(" | "));
98
- // src/flows.ts
99
- const SCOPE_PREFIX$1 = "@";
100
- const SCOPED_SEGMENTS$1 = 2;
101
- const UNSCOPED_SEGMENTS = 1;
102
- const MODULE_PREFIX = /^".*?"\./u;
103
- const packageOf$1 = (fileName) => {
104
- const afterModules = pipe(fileName, String$1.lastIndexOf(NODE_MODULES_SEGMENT), Option.match({
105
- onNone: () => fileName,
106
- onSome: (index) => String$1.slice(index + NODE_MODULES_SEGMENT.length)(fileName)
107
- }));
108
- const segments = String$1.split("/")(afterModules);
109
- if (String$1.startsWith(SCOPE_PREFIX$1)(afterModules)) return pipe(Array.take(segments, SCOPED_SEGMENTS$1), Array.join("/"));
110
- return pipe(Array.take(segments, UNSCOPED_SEGMENTS), Array.join("/"));
111
- };
112
- const externalDeclarationOf = (context) => (symbol) => Array.findFirst(declarationsOf(symbol), (declaration) => isExternalDeclaration(context.program)(declaration));
113
- const aliasTarget = (context) => (type) => Option.fromUndefinedOr(type.getAliasSymbol()).pipe(Option.flatMap((alias) => externalDeclarationOf(context)(alias).pipe(Option.map((declaration) => `${String$1.replace(MODULE_PREFIX, "")(context.checker.getFullyQualifiedName(alias))} from ${packageOf$1(declaration.getSourceFile().fileName)}`))));
114
- const isNamedContainer = (node) => isSignatureDeclaration(node) || isInterfaceDeclaration(node) || isClassDeclaration(node);
115
- const slotTarget = (context) => (expression) => slotOf(context.checker)(expression).pipe(Option.filter((slot) => isExternalDeclaration(context.program)(slot)), Option.filter((slot) => Option.isSome(vocabularyOf(context.checker)(context.checker.getTypeAtLocation(slot)))), Option.map((slot) => {
116
- const owner = Option.liftPredicate(slot.parent, isNamedContainer).pipe(Option.flatMap((container) => Option.fromUndefinedOr(getNameOfDeclaration(container))), Option.map((name) => ` of ${name.getText()}`), Option.getOrElse(() => ""));
117
- return `${Option.fromUndefinedOr(getNameOfDeclaration(slot)).pipe(Option.map((found) => found.getText()), Option.getOrElse(() => "value"))}${owner} from ${packageOf$1(slot.getSourceFile().fileName)}`;
118
- }));
119
- const libraryTargetOf = (context) => (expression, contextual) => aliasTarget(context)(contextual).pipe(Option.orElse(() => slotTarget(context)(expression)));
120
- const siteWithin = (context) => (node) => Array.findFirst(context.sites, (site) => contains(node)(site.node));
121
- const aliasSite = (context) => (type) => Option.fromUndefinedOr(type.getAliasSymbol()).pipe(Option.flatMap((alias) => Array.findFirst(declarationsOf(alias), isTypeAliasDeclaration)), Option.flatMap(siteWithin(context)));
122
- const annotationSite = (context) => (expression) => symbolAt(context.checker)(expression).pipe(Option.flatMap((symbol) => Option.fromUndefinedOr(symbol.valueDeclaration)), Option.flatMap((handle) => Option.fromUndefinedOr(handle.resolve())), Option.flatMap(annotationOf), Option.flatMap((annotation) => siteWithin(context)(annotation).pipe(Option.orElse(() => aliasSite(context)(context.checker.getTypeFromTypeNode(annotation))))));
123
- const siteBehind = (context) => (expression) => aliasSite(context)(context.checker.getTypeAtLocation(expression)).pipe(Option.orElse(() => annotationSite(context)(expression)));
124
- const isFlowSource = (node) => isIdentifier(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node);
125
- const flowOf = (context) => (expression) => Option.fromUndefinedOr(context.checker.getContextualType(expression)).pipe(Option.flatMap((contextual) => Option.all([vocabularyOf(context.checker)(contextual), libraryTargetOf(context)(expression, contextual)])), Option.flatMap(([vocabulary, target]) => siteBehind(context)(expression).pipe(Option.filter((site) => isSubsetOf(site.values, vocabulary.values)), Option.map((site) => ({
126
- site,
127
- target
128
- })))));
129
- const flowsIn = (context) => (sourceFile) => Array.getSomes(pipe(descendantsOf(sourceFile), Array.filter((node) => isFlowSource(node)), Array.map((node) => flowOf(context)(node))));
130
- // src/owners.ts
131
- const OWNER_TAG = "msch";
132
- const FIRST_OWNER_COUNT = 1;
133
- const ownerKeyOf = (declaration) => {
134
- if (!isVariableDeclaration(declaration) || !isIdentifier(declaration.name)) return Option.none();
135
- return Option.some(`${declaration.getSourceFile().fileName}#${declaration.name.text}`);
136
- };
137
- const annotationsOf = (node) => pipe(getJSDocTags(node), Array.filter((tag) => tag.tagName.text === OWNER_TAG), Array.map((tag) => ({
138
- node,
139
- conceptId: String$1.trim(getTextOfJSDocComment(tag.comment) ?? "")
140
- })));
141
- const ANNOTATABLE_KINDS = /* @__PURE__ */ new Set([
142
- SyntaxKind.VariableDeclaration,
143
- SyntaxKind.FunctionDeclaration,
144
- SyntaxKind.ClassDeclaration,
145
- SyntaxKind.InterfaceDeclaration,
146
- SyntaxKind.TypeAliasDeclaration,
147
- SyntaxKind.EnumDeclaration,
148
- SyntaxKind.PropertySignature,
149
- SyntaxKind.PropertyAssignment,
150
- SyntaxKind.PropertyDeclaration
151
- ]);
152
- const isAnnotatable = (node) => ANNOTATABLE_KINDS.has(node.kind);
153
- const isConstList = (list) => Option.fromUndefinedOr(list.getFirstToken()).pipe(Option.exists((token) => token.kind === SyntaxKind.ConstKeyword));
154
- const isModuleStatementList = (list) => isVariableStatement(list.parent) && isSourceFile(list.parent.parent);
155
- const isModuleConstList = (node) => isVariableDeclarationList(node) && isModuleStatementList(node) && isConstList(node);
156
- const isModuleConst = (node) => isVariableDeclaration(node) && isIdentifier(node.name) && isModuleConstList(node.parent);
157
- const objectValuesOf = (checker) => (type) => literalValuesOf(pipe(checker.getPropertiesOfType(type), Array.map((property) => checker.getTypeOfSymbol(property))));
158
- const ownerValuesOf = (checker) => (declaration) => {
159
- const type = checker.getTypeAtLocation(declaration.name);
160
- return finiteValuesOf(checker)(type).pipe(Option.orElse(() => objectValuesOf(checker)(type)));
161
- };
162
- const annotationProblem = (message) => problemAt({
163
- rule: "owner-annotation",
164
- message
165
- });
166
- const scanned = (owners, problems) => ({
167
- owners,
168
- problems
169
- });
170
- const ownerOf$1 = (project) => (annotated) => {
171
- const { node, conceptId } = annotated;
172
- if (!isModuleConst(node)) return scanned([], [annotationProblem(`@${OWNER_TAG} registers an owner only on a module-scope const.`)(node)]);
173
- if (conceptId === "") return scanned([], [annotationProblem(`@${OWNER_TAG} needs a concept id.`)(node)]);
174
- const values = ownerValuesOf(project.checker)(node);
175
- return Option.match(Option.all([values, ownerKeyOf(node)]), {
176
- onNone: () => scanned([], [annotationProblem(`The owner of ${conceptId} holds no finite value set.`)(node)]),
177
- onSome: ([ownedValues, key]) => scanned([{
178
- conceptId,
179
- key,
180
- name: node.name.getText(),
181
- file: node.getSourceFile().fileName,
182
- line: lineOf(node),
183
- column: columnOf(node),
184
- packageName: project.packageName,
185
- values: ownedValues
186
- }], [])
187
- });
188
- };
189
- const annotatedIn = (sourceFile) => pipe(descendantsOf(sourceFile), Array.filter((node) => isAnnotatable(node)), Array.flatMap((node) => annotationsOf(node)));
190
- const ownerProblem = (message) => (owner) => ({
191
- file: owner.file,
192
- line: owner.line,
193
- column: owner.column,
194
- rule: "owner-annotation",
195
- message
196
- });
197
- const conflictProblems = (owners) => pipe(owners, Array.flatMap((owner, index) => {
198
- const earlier = Array.take(owners, index);
199
- const sameConcept = pipe(earlier, Array.filter((other) => other.conceptId === owner.conceptId));
200
- const sameSet = pipe(earlier, Array.filter((other) => other.conceptId !== owner.conceptId && sameValues(other.values, owner.values)));
201
- return [...pipe(Array.take(sameConcept, FIRST_OWNER_COUNT), Array.map(() => ownerProblem(`The concept ${owner.conceptId} already has an owner.`)(owner))), ...pipe(Array.take(sameSet, FIRST_OWNER_COUNT), Array.map((other) => ownerProblem(`The values ${formatValues(owner.values)} are already owned by ${other.conceptId}.`)(owner)))];
202
- }));
203
- const ownersIn = (project) => {
204
- const results = pipe(project.sourceFiles, Array.flatMap((sourceFile) => pipe(annotatedIn(sourceFile), Array.map((annotated) => ownerOf$1(project)(annotated)))));
205
- return scanned(pipe(results, Array.flatMap((result) => result.owners)), pipe(results, Array.flatMap((result) => result.problems)));
206
- };
207
- const combineOwnerScans = (scans) => {
208
- const owners = Array.dedupeWith(pipe(scans, Array.flatMap((scan) => scan.owners)), (left, right) => left.key === right.key);
209
- return {
210
- owners,
211
- problems: [...pipe(scans, Array.flatMap((scan) => scan.problems)), ...conflictProblems(owners)]
212
- };
213
- };
214
- // src/library.ts
66
+ // src/entities/project/model/library.ts
215
67
  const NAMESPACE_DEPTH_LIMIT = 8;
216
68
  const EMPTY_INDEX = {
217
69
  vocabularies: [],
@@ -333,343 +185,42 @@ const indexEntry = (cache) => (checker) => (entry) => Effect.sync(() => cache.in
333
185
  "msch.library.shapes": index.shapes.length
334
186
  })), Effect.map(({ index }) => index), Effect.withSpan("indexLibraryEntry", { attributes: { "msch.library.specifier": entry.specifier } }));
335
187
  const libraryIndex = (cache) => (checker) => (entries) => pipe(entries, Effect.forEach(indexEntry(cache)(checker)), Effect.map(mergeIndexes), Effect.withSpan("libraryIndex"));
336
- // src/derivation.ts
337
- const contractOf = (node) => {
338
- const { parent } = node;
339
- if (isSatisfiesExpression(parent) && parent.expression === node) return [parent.type];
340
- if (isVariableDeclaration(parent) && parent.initializer === node) return Option.toArray(Option.fromUndefinedOr(parent.type));
341
- return [];
342
- };
343
- const derivedDeclarationsOf = (checker) => (node) => {
344
- const scopes = Array.prepend(contractOf(node), node);
345
- return new Set(pipe(scopes, Array.flatMap((scope) => referencedSymbols(checker)(scope)), Array.flatMap((symbol) => declarationsOf(symbol)), Array.map((declaration) => declarationKey(locationOf(declaration)))));
346
- };
347
- // src/shapes.ts
348
- const MINIMUM_SHAPE_PROPERTIES = 3;
349
- const EXACT = 0;
350
- const augmentsAModule = (node) => {
351
- const block = node.parent;
352
- return isModuleBlock(block) && isModuleDeclaration(block.parent) && isStringLiteral(block.parent.name);
353
- };
354
- const isPlainInterface = (node) => isInterfaceDeclaration(node) && !isGenericDeclaration(node) && !augmentsAModule(node);
355
- const isPlainTypeLiteral = (node) => isTypeAliasDeclaration(node) && !isGenericDeclaration(node) && isTypeLiteralNode(node.type);
356
- const isDeclaredShape = (node) => isPlainInterface(node) || isPlainTypeLiteral(node);
357
- const declaredShapeOf = (checker) => (node) => Option.liftPredicate(node, isDeclaredShape).pipe(Option.map((declaration) => checker.getTypeAtLocation(declaration.name)));
358
- const schemaShapeOf = (checker) => (node) => {
359
- if (!isCallExpression(node)) return Option.none();
360
- const { arguments: callArguments } = node;
361
- if (!pipe(callArguments, Array.some((argument) => isObjectLiteralExpression(argument)))) return Option.none();
362
- return schemaTypeOf(checker)(checker.getTypeAtLocation(node)).pipe(Option.filter((type) => isObjectType(checker)(type)));
363
- };
364
- const shapeSitesIn = (checker) => (sourceFile) => Array.getSomes(pipe(descendantsOf(sourceFile), Array.map((node) => declaredShapeOf(checker)(node).pipe(Option.orElse(() => schemaShapeOf(checker)(node)), Option.map((type) => ({
365
- node,
366
- type
367
- }))))));
368
- const openTypeIdsOf = (checker) => ({
369
- any: checker.getAnyType().id,
370
- unknown: checker.getUnknownType().id
188
+ // src/entities/project/model/telemetry.ts
189
+ const RSS_LINE = /^VmRSS:\s+(?<kib>\d+) kB$/mu;
190
+ const BYTES_PER_KIB = 1024;
191
+ const UNKNOWN_RSS = 0;
192
+ const kibibytesIn = (status) => Option.fromNullishOr(RSS_LINE.exec(status)).pipe(Option.flatMap((match) => Option.fromUndefinedOr(match.groups)), Option.flatMap((groups) => Option.fromUndefinedOr(groups["kib"])));
193
+ const residentBytesOf = (pid) => Effect.gen(function* residentBytes() {
194
+ const status = yield* (yield* RepositoryFiles).readFile(`/proc/${pid}/status`);
195
+ return pipe(status, Option.flatMap(kibibytesIn), Option.flatMap(Number$1.parse), Option.map((kib) => kib * BYTES_PER_KIB), Option.getOrElse(() => UNKNOWN_RSS));
371
196
  });
372
- const isIndexedDeclaration = (node) => isTypeDeclaration(node) || isVariableDeclaration(node);
373
- const declarationAt = (program) => (location) => Option.fromUndefinedOr(program.getSourceFile(location.file)).pipe(Option.flatMap((sourceFile) => Array.findFirst(descendantsOf(sourceFile), (node) => node.pos === location.pos && node.kind === location.kind && isIndexedDeclaration(node))));
374
- const symbolOfDeclaration = (checker) => (declaration) => Option.fromUndefinedOr(checker.getSymbolAtLocation(declaration.name));
375
- const shapeTypeOf = (context) => (shape) => {
376
- const { checker } = context;
377
- return declarationAt(context.program)(shape.declaration).pipe(Option.flatMap((declaration) => symbolOfDeclaration(checker)(declaration).pipe(Option.flatMap((symbol) => {
378
- if (shape.form === "declared") return Option.some(checker.getDeclaredTypeOfSymbol(symbol));
379
- return schemaTypeOf(checker)(checker.getTypeOfSymbolAtLocation(symbol, declaration));
380
- }))));
381
- };
382
- const hasEveryName = (locals) => (shape) => {
383
- const names = new Set(shape.propertyNames);
384
- return pipe(locals, Array.every((local) => names.has(local.name)));
385
- };
386
- const sameProperty = (checker, open) => (localType, library) => {
387
- const libraryType = checker.getTypeOfSymbol(library);
388
- return libraryType.id !== open.any && libraryType.id !== open.unknown && checker.isTypeAssignableTo(localType, libraryType) && checker.isTypeAssignableTo(libraryType, localType);
389
- };
390
- const matchOf = (context, open) => (locals, shape) => {
391
- const { checker } = context;
392
- if (!shapeTypeOf(context)(shape).pipe(Option.exists((shapeType) => pipe(locals, Array.every((local) => Option.fromUndefinedOr(checker.getPropertyOfType(shapeType, local.name)).pipe(Option.exists((library) => sameProperty(checker, open)(local.type, library)))))))) return Option.none();
393
- return Option.some({
394
- shape,
395
- extra: shape.propertyNames.length - locals.length
197
+ const childPids = Effect.gen(function* childPids() {
198
+ const files = yield* RepositoryFiles;
199
+ const pid = String(process.pid);
200
+ const children = yield* files.readFile(`/proc/${pid}/task/${pid}/children`);
201
+ return pipe(children, Option.map((text) => pipe(String$1.trim(text), String$1.split(" "), Array.filter(String$1.isNonEmpty))), Option.getOrElse(() => []));
202
+ });
203
+ const annotateMemory = Effect.gen(function* annotateMemory() {
204
+ const own = yield* residentBytesOf(String(process.pid));
205
+ const pids = yield* childPids;
206
+ const children = yield* pipe(pids, Effect.forEach((pid) => residentBytesOf(pid)));
207
+ const { heapUsed } = process.memoryUsage();
208
+ yield* Effect.annotateCurrentSpan({
209
+ "process.memory.rss": own,
210
+ "process.memory.heap_used": heapUsed,
211
+ "msch.compiler.memory.rss": Number$1.sumAll(children)
396
212
  });
397
- };
398
- const localPropertiesOf = (checker) => (symbols) => pipe(Array.zip(symbols, checker.getTypeOfSymbol(symbols)), Array.map(([symbol, type]) => ({
399
- name: symbol.name,
400
- type
401
- })));
402
- const matchOrder = Order.mapInput(Order.Number, (match) => match.extra);
403
- const shapeProblem = (site, matches) => {
404
- const shown = pipe(Array.take(matches, 3), Array.map((match) => describeLibraryType(match.shape)), Array.join(", "));
405
- const advice = Option.match(Array.findFirst(matches, (match) => match.extra === EXACT), {
406
- onNone: () => "Derive it from the library type, for example with Pick, instead of copying its properties.",
407
- onSome: () => "Use the library type instead of copying it."
408
- });
409
- return problemAt({
410
- rule: "library-shape",
411
- message: `This shape copies ${shown}. ${advice}`
412
- })(site.node);
413
- };
414
- const candidatesOf = (context, open) => (site, locals) => {
415
- const derived = derivedDeclarationsOf(context.checker)(site.node);
416
- const named = pipe(context.shapes, Array.filter(hasEveryName(locals)));
417
- if (pipe(named, Array.some((shape) => derived.has(declarationKey(shape.declaration))))) return [];
418
- const candidates = pipe(named, Array.map((shape) => matchOf(context, open)(locals, shape)), Array.getSomes);
419
- return Array.sort(candidates, matchOrder);
420
- };
421
- const shapeProblemOf = (context, open) => (site) => {
422
- const symbols = context.checker.getPropertiesOfType(site.type);
423
- if (symbols.length < MINIMUM_SHAPE_PROPERTIES) return Option.none();
424
- const locals = localPropertiesOf(context.checker)(symbols);
425
- return Option.liftPredicate(candidatesOf(context, open)(site, locals), Array.isReadonlyArrayNonEmpty).pipe(Option.map((found) => shapeProblem(site, found)));
426
- };
427
- const shapeProblemsIn = (context) => (sourceFile) => {
428
- const sites = shapeSitesIn(context.checker)(sourceFile);
429
- if (!Array.isReadonlyArrayNonEmpty(sites)) return [];
430
- const open = openTypeIdsOf(context.checker);
431
- return Array.getSomes(pipe(sites, Array.map((site) => shapeProblemOf(context, open)(site))));
432
- };
433
- // src/sites.ts
434
- const namedValuesOf = (checker) => (symbol) => {
435
- if (pipe(declarationsOf(symbol), Array.some((declaration) => isTypeDeclaration(declaration)))) return finiteValuesOf(checker)(checker.getDeclaredTypeOfSymbol(symbol));
436
- return finiteValuesOf(checker)(checker.getTypeOfSymbol(symbol));
437
- };
438
- const hasFiniteContext = (checker) => (node) => Option.fromUndefinedOr(checker.getContextualType(node)).pipe(Option.flatMap(finiteValuesOf(checker)), Option.isSome);
439
- const isNamedValue = (element) => {
440
- if (isSpreadElement(element)) return isNamedValue(element.expression);
441
- return isIdentifier(element) || isPropertyAccessExpression(element) || isElementAccessExpression(element);
442
- };
443
- const namesEveryElement = (array) => pipe(array.elements, Array.every((element) => isNamedValue(element)));
444
- const expressionValuesOf = (checker) => (node) => {
445
- if (hasFiniteContext(checker)(node)) return Option.none();
446
- const type = checker.getTypeAtLocation(node);
447
- if (isArrayLiteralExpression(node)) return Option.liftPredicate(node, (array) => !namesEveryElement(array)).pipe(Option.flatMap(() => finiteValuesOf(checker)(type)));
448
- return schemaTypeOf(checker)(type).pipe(Option.flatMap(literalUnionOf));
449
- };
450
- const selectsKeys = (checker) => (node, values) => {
451
- const { parent } = node;
452
- if (!isTypeReferenceNode(parent)) return false;
453
- const typeArguments = parent.typeArguments ?? [];
454
- return pipe(typeArguments, Array.filter((argument) => argument !== node), Array.some((argument) => isSubsetOf(values, propertyNamesOf(checker)(checker.getTypeFromTypeNode(argument)))));
455
- };
456
- const unionValuesOf = (checker) => (node) => literalUnionOf(checker.getTypeFromTypeNode(node)).pipe(Option.filter((values) => !selectsKeys(checker)(node, values)));
457
- const isExpressionSite = (node) => isArrayLiteralExpression(node) || isCallExpression(node);
458
- const expressionSiteValuesOf = (checker) => (node) => Option.liftPredicate(node, isExpressionSite).pipe(Option.flatMap(expressionValuesOf(checker)));
459
- const siteValuesOf = (checker) => (node) => {
460
- if (isUnionTypeNode(node)) return unionValuesOf(checker)(node);
461
- if (isEnumDeclaration(node)) return literalUnionOf(checker.getTypeAtLocation(node.name));
462
- return expressionSiteValuesOf(checker)(node);
463
- };
464
- const derivationScopeOf = (node) => {
465
- if (isTypeReferenceNode(node.parent)) return node.parent;
466
- return node;
467
- };
468
- const sourcesOf = (checker) => (node) => pipe(referencedSymbols(checker)(derivationScopeOf(node)), Array.filter((symbol) => Option.isSome(namedValuesOf(checker)(symbol))));
469
- const sitesUnder = (checker) => (node) => {
470
- const nested = pipe(childrenOf$2(node), Array.flatMap((child) => sitesUnder(checker)(child)));
471
- if (Array.isReadonlyArrayNonEmpty(nested)) return nested;
472
- return siteValuesOf(checker)(node).pipe(Option.map((values) => ({
473
- node,
474
- values,
475
- sources: sourcesOf(checker)(node)
476
- })), Option.toArray);
477
- };
478
- // src/value-checks.ts
479
- const OWNER_SEARCH_DEPTH = 4;
480
- const NOTHING_HIDDEN = 0;
481
- const directOwners = (context) => (symbol) => {
482
- const keys = Array.getSomes(pipe(declarationsOf(symbol), Array.map((declaration) => ownerKeyOf(declaration))));
483
- return pipe(context.owners, Array.filter((owner) => keys.includes(owner.key)));
484
- };
485
- const isFollowable = (declaration) => !declaration.getSourceFile().isDeclarationFile && (isTypeAliasDeclaration(declaration) || isVariableDeclaration(declaration));
486
- const ownersBehind = (context) => (symbol, ancestors) => {
487
- const direct = directOwners(context)(symbol);
488
- if (Array.isReadonlyArrayNonEmpty(direct) || ancestors.length >= OWNER_SEARCH_DEPTH) return direct;
489
- const visited = [...ancestors, symbol];
490
- return uniqueByReference(pipe(declarationsOf(symbol), Array.filter((declaration) => isFollowable(declaration)), Array.flatMap((declaration) => referencedSymbols(context.checker)(declaration)), Array.filter((referenced) => !visited.includes(referenced)), Array.flatMap((referenced) => ownersBehind(context)(referenced, visited))));
491
- };
492
- const describeOwners = (owners) => pipe(owners, Array.map((owner) => `${owner.conceptId} (${owner.name})`), Array.join(", "));
493
- const verdict = (problems, unowned) => ({
494
- problems,
495
- unowned
496
- });
497
- const derivedVerdict = (context) => (site) => {
498
- const owners = uniqueByReference(pipe(site.sources, Array.flatMap((source) => ownersBehind(context)(source, []))));
499
- const held = pipe(owners, Array.flatMap((owner) => owner.values));
500
- const added = pipe(site.values, Array.filter((value) => !isSubsetOf([value], held)));
501
- if (!Array.isReadonlyArrayNonEmpty(owners) || !Array.isReadonlyArrayNonEmpty(added)) return verdict([], []);
502
- const message = `This set adds ${formatValues(added)} to ${describeOwners(owners)}. Add the values to the owner, or register the wider set as its own concept.`;
503
- return verdict([problemAt({
504
- rule: "owner-extension",
505
- message
506
- })(site.node)], []);
507
- };
508
- const libraryCandidates = (context) => (site) => {
509
- const flowing = Array.dedupe(pipe(context.flows, Array.filter((flow) => flow.site.node === site.node), Array.map((flow) => flow.target)));
510
- if (Array.isReadonlyArrayNonEmpty(flowing)) return flowing;
511
- if (!pipe(site.values, Array.some((value) => typeof value === "string"))) return [];
512
- const imported = importedModulesOf(site.node.getSourceFile());
513
- return Array.dedupe(pipe(context.vocabularies, Array.filter((library) => imported.includes(library.specifier)), Array.filter((library) => isSubsetOf(site.values, library.vocabulary.values)), Array.map((library) => describeLibraryType(library))));
514
- };
515
- const listCandidates = (candidates) => {
516
- const shown = pipe(Array.take(candidates, 3), Array.join(", "));
517
- const hidden = candidates.length - 3;
518
- if (hidden > NOTHING_HIDDEN) return `${shown} and ${String(hidden)} more`;
519
- return shown;
520
- };
521
- const originalVerdict = (context) => (site) => {
522
- const owners = pipe(context.owners, Array.filter((owner) => isSubsetOf(site.values, owner.values)));
523
- if (Array.isReadonlyArrayNonEmpty(owners)) {
524
- const message = `The values ${formatValues(site.values)} are owned by ${describeOwners(owners)}. Derive this set from the owner instead of restating it.`;
525
- return verdict([problemAt({
526
- rule: "owner-value-set",
527
- message
528
- })(site.node)], []);
529
- }
530
- const candidates = libraryCandidates(context)(site);
531
- if (Array.isReadonlyArrayNonEmpty(candidates)) {
532
- const message = `The values ${formatValues(site.values)} restate a dependency type: ${listCandidates(candidates)}. Derive this set from the library type.`;
533
- return verdict([problemAt({
534
- rule: "library-value-set",
535
- message
536
- })(site.node)], []);
537
- }
538
- return verdict([], [site]);
539
- };
540
- const siteVerdict = (context) => (site) => {
541
- if (Array.isReadonlyArrayNonEmpty(site.sources)) return derivedVerdict(context)(site);
542
- return originalVerdict(context)(site);
543
- };
544
- const VALUE_PARENT_KINDS = /* @__PURE__ */ new Set([
545
- SyntaxKind.ReturnStatement,
546
- SyntaxKind.ArrayLiteralExpression,
547
- SyntaxKind.ConditionalExpression,
548
- SyntaxKind.ParenthesizedExpression,
549
- SyntaxKind.ArrowFunction,
550
- SyntaxKind.JsxExpression
551
- ]);
552
- const isCallArgument = (node, parent) => (isCallExpression(parent) || isNewExpression(parent)) && parent.expression !== node;
553
- const isInitializer = (node, parent) => (isPropertyAssignment(parent) || isVariableDeclaration(parent)) && parent.initializer === node;
554
- const isRightOperand = (node, parent) => isBinaryExpression(parent) && parent.right === node;
555
- const VALUE_SLOTS = [
556
- isCallArgument,
557
- isInitializer,
558
- isRightOperand
559
- ];
560
- const isValuePosition = (node) => {
561
- const { parent } = node;
562
- return VALUE_PARENT_KINDS.has(parent.kind) || pipe(VALUE_SLOTS, Array.some((isSlot) => isSlot(node, parent)));
563
- };
564
- const ownedLiteralProblem = (context) => (literal) => Option.fromUndefinedOr(context.checker.getContextualType(literal)).pipe(Option.filter((contextual) => vocabularyOf(context.checker)(contextual).pipe(Option.exists((vocabulary) => !vocabulary.admitsUnnamedValues))), Option.map(() => pipe(contextSymbolsOf(context.checker)(literal), Array.flatMap((symbol) => ownersBehind(context)(symbol, [])), uniqueByReference, Array.filter((owner) => isSubsetOf([literal.text], pipe(owner.values, Array.map(String)))))), Option.filter((owners) => Array.isReadonlyArrayNonEmpty(owners)), Option.map((owners) => problemAt({
565
- rule: "owned-literal",
566
- message: `${literal.getText()} is a value of ${describeOwners(owners)}. Write it through the owner's binding instead of as a literal.`
567
- })(literal)));
568
- const ownedLiteralProblems = (context) => (sourceFile, excluded) => Array.getSomes(pipe(descendantsOf(sourceFile), Array.filter((node) => isStringLiteral(node) || isNumericLiteral(node)), Array.filter((node) => isValuePosition(node)), Array.filter((node) => !pipe(excluded, Array.some((outer) => contains(outer)(node)))), Array.map((node) => ownedLiteralProblem(context)(node))));
569
- // src/analysis.ts
570
- const isVisibleTo = (project) => (owner) => pipe(project.sourceFiles, Array.some((sourceFile) => sourceFile.fileName === owner.file)) || Option.exists(owner.packageName, (name) => Option.contains(project.packageName, name) || project.workspaceDependencies.includes(name));
571
- const ownerDeclarationsIn = (project, owners) => {
572
- const keys = new Set(pipe(owners, Array.map((owner) => owner.key)));
573
- return pipe(project.sourceFiles, Array.flatMap((sourceFile) => pipe(descendantsOf(sourceFile), Array.filter((node) => isVariableDeclaration(node)), Array.filter((declaration) => Option.exists(ownerKeyOf(declaration), (key) => keys.has(key))))));
574
- };
575
- const isInside = (outers) => (node) => pipe(outers, Array.some((outer) => contains(outer)(node)));
576
- const sitesOutside = (checker) => (project, outers) => pipe(project.sourceFiles, Array.flatMap((sourceFile) => sitesUnder(checker)(sourceFile)), Array.filter((site) => !isInside(outers)(site.node)));
577
- const nodesOf = (sites) => pipe(sites, Array.map((site) => site.node));
578
- const analyzeProject = (owners) => (project) => {
579
- const { checker } = project;
580
- const ownerDeclarations = ownerDeclarationsIn(project, owners);
581
- const sites = sitesOutside(checker)(project, ownerDeclarations);
582
- const flowContext = {
583
- checker,
584
- program: project.program,
585
- sites
586
- };
587
- const context = {
588
- checker,
589
- owners: pipe(owners, Array.filter((owner) => isVisibleTo(project)(owner))),
590
- vocabularies: project.library.vocabularies,
591
- flows: pipe(project.sourceFiles, Array.flatMap((sourceFile) => flowsIn(flowContext)(sourceFile)))
592
- };
593
- const verdicts = pipe(sites, Array.map((site) => siteVerdict(context)(site)));
594
- const excluded = [...ownerDeclarations, ...nodesOf(sites)];
595
- const shapeContext = {
596
- checker,
597
- program: project.program,
598
- shapes: project.library.shapes
599
- };
600
- return {
601
- problems: [...pipe(verdicts, Array.flatMap((found) => found.problems)), ...pipe(project.sourceFiles, Array.flatMap((sourceFile) => [...ownedLiteralProblems(context)(sourceFile, excluded), ...shapeProblemsIn(shapeContext)(sourceFile)]))],
602
- unowned: pipe(verdicts, Array.flatMap((found) => found.unowned))
603
- };
604
- };
605
- // src/duplicates.ts
606
- const DUPLICATE_THRESHOLD = 1;
607
- const unownedSiteOf = (scope) => (site) => ({
608
- scope,
609
- file: site.node.getSourceFile().fileName,
610
- start: site.node.getStart(),
611
- line: lineOf(site.node),
612
- column: columnOf(site.node),
613
- values: site.values
614
- });
615
- const canDerive = (left, right) => left.scope.name === right.scope.name || left.scope.dependencies.includes(right.scope.name) || right.scope.dependencies.includes(left.scope.name);
616
- const siteKey = (site) => `${site.file}#${String(site.start)}`;
617
- const valueSetKey = (site) => {
618
- const keys = pipe(site.values, Array.map((value) => valueKey(value)));
619
- return pipe(Array.sort(keys, Order.String), Array.join("\0"));
620
- };
621
- const duplicateProblems = (relative) => (sites) => {
622
- const unique = Array.dedupeWith(sites, (left, right) => siteKey(left) === siteKey(right));
623
- const groups = Record.values(Array.groupBy(unique, (site) => valueSetKey(site)));
624
- return pipe(groups, Array.filter((group) => group.length > DUPLICATE_THRESHOLD), Array.flatMap((group) => pipe(group, Array.flatMap((site) => {
625
- const related = pipe(group, Array.filter((other) => other !== site && canDerive(site, other)));
626
- if (!Array.isReadonlyArrayNonEmpty(related)) return [];
627
- const others = pipe(related, Array.map((other) => `${relative(other.file)}:${String(other.line)}`), Array.join(", "));
628
- return [{
629
- file: site.file,
630
- line: site.line,
631
- column: site.column,
632
- rule: "duplicate-value-set",
633
- message: `The values ${formatValues(site.values)} are also declared at ${others}. Register one owner with /** @${OWNER_TAG} <concept> */ and derive the others from it.`
634
- }];
635
- }))));
636
- };
637
- // src/telemetry.ts
638
- const RSS_LINE = /^VmRSS:\s+(?<kib>\d+) kB$/mu;
639
- const BYTES_PER_KIB = 1024;
640
- const UNKNOWN_RSS = 0;
641
- const kibibytesIn = (status) => Option.fromNullishOr(RSS_LINE.exec(status)).pipe(Option.flatMap((match) => Option.fromUndefinedOr(match.groups)), Option.flatMap((groups) => Option.fromUndefinedOr(groups["kib"])));
642
- const residentBytesOf = (pid) => Effect.gen(function* residentBytes() {
643
- const status = yield* (yield* RepositoryFiles).readFile(`/proc/${pid}/status`);
644
- return pipe(status, Option.flatMap(kibibytesIn), Option.flatMap(Number$1.parse), Option.map((kib) => kib * BYTES_PER_KIB), Option.getOrElse(() => UNKNOWN_RSS));
645
- });
646
- const childPids = Effect.gen(function* childPids() {
647
- const files = yield* RepositoryFiles;
648
- const pid = String(process.pid);
649
- const children = yield* files.readFile(`/proc/${pid}/task/${pid}/children`);
650
- return pipe(children, Option.map((text) => pipe(String$1.trim(text), String$1.split(" "), Array.filter(String$1.isNonEmpty))), Option.getOrElse(() => []));
651
- });
652
- const annotateMemory = Effect.gen(function* annotateMemory() {
653
- const own = yield* residentBytesOf(String(process.pid));
654
- const pids = yield* childPids;
655
- const children = yield* pipe(pids, Effect.forEach((pid) => residentBytesOf(pid)));
656
- const { heapUsed } = process.memoryUsage();
657
- yield* Effect.annotateCurrentSpan({
658
- "process.memory.rss": own,
659
- "process.memory.heap_used": heapUsed,
660
- "msch.compiler.memory.rss": Number$1.sumAll(children)
661
- });
662
- });
663
- const annotateResources = (api) => Effect.gen(function* annotateCompiler() {
664
- yield* annotateMemory;
665
- const { totals } = api.getTimingInfo();
666
- yield* Effect.annotateCurrentSpan({
667
- "msch.compiler.requests": totals.requestCount,
668
- "msch.compiler.round_trip_ms": totals.roundTripMs,
669
- "msch.compiler.server_ms": totals.serverTimeMs
213
+ });
214
+ const annotateResources = (api) => Effect.gen(function* annotateCompiler() {
215
+ yield* annotateMemory;
216
+ const { totals } = api.getTimingInfo();
217
+ yield* Effect.annotateCurrentSpan({
218
+ "msch.compiler.requests": totals.requestCount,
219
+ "msch.compiler.round_trip_ms": totals.roundTripMs,
220
+ "msch.compiler.server_ms": totals.serverTimeMs
670
221
  });
671
222
  });
672
- // src/project.ts
223
+ // src/entities/project/model/project.ts
673
224
  const CONFIG_PATHSPEC = `:(glob)**/tsconfig.json`;
674
225
  const HIDDEN_PREFIX = ".";
675
226
  const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([
@@ -763,62 +314,39 @@ const mentions$1 = (needle) => ({ api }) => (configPath) => Effect.gen(function*
763
314
  const includesNeedle = String$1.includes(needle);
764
315
  return pipe(texts, Array.some((text) => Option.exists(text, includesNeedle)));
765
316
  });
766
- // src/check.ts
767
- const scanOwners = Effect.fn("scanOwners")(function* scanOwners(workspace, configPaths) {
768
- const ownerConfigs = yield* pipe(configPaths, Effect.filter(mentions$1(`@${OWNER_TAG}`)(workspace.compiler)));
769
- const scans = yield* pipe(ownerConfigs, Effect.forEach((configPath) => withProject(workspace)(configPath)((project) => Effect.sync(() => ownersIn(project)))));
770
- return combineOwnerScans(Array.getSomes(scans));
771
- });
772
- const scopeOf = (project, configPath) => ({
773
- name: Option.getOrElse(project.packageName, () => configPath),
774
- dependencies: project.workspaceDependencies
775
- });
776
- const analyzeProjects = (workspace, owners) => (configPaths) => pipe(configPaths, Effect.forEach((configPath) => withProject(workspace)(configPath)((project) => Effect.sync(() => {
777
- const analysis = analyzeProject(owners)(project);
778
- const scope = scopeOf(project, configPath);
317
+ // src/shared/lib/text-position.ts
318
+ const START$7 = 0;
319
+ const FIRST_COLUMN$3 = 1;
320
+ const positionOf = (source) => (index) => {
321
+ const before = pipe(source, String$1.slice(START$7, index), String$1.split("\n"));
779
322
  return {
780
- problems: analysis.problems,
781
- unowned: pipe(analysis.unowned, Array.map(unownedSiteOf(scope)))
323
+ line: before.length,
324
+ column: pipe(Array.last(before), Option.match({
325
+ onNone: () => FIRST_COLUMN$3,
326
+ onSome: (last) => last.length + FIRST_COLUMN$3
327
+ }))
782
328
  };
783
- }).pipe(Effect.withSpan("analyzeProject")))), Effect.map(Array.getSomes));
784
- const checkRepository = Effect.fn("checkRepository")(function* checkRepository(root) {
785
- const files = yield* RepositoryFiles;
786
- const workspace = {
787
- compiler: yield* typeScriptCompiler,
788
- root,
789
- generated: yield* files.generatedFiles(root)
790
- };
791
- const configPaths = yield* listConfigFiles(root);
792
- const ownerScan = yield* scanOwners(workspace, configPaths);
793
- const analyses = yield* analyzeProjects(workspace, ownerScan.owners)(configPaths);
794
- const relative = (file) => files.relative(root, file);
795
- const unowned = pipe(analyses, Array.flatMap((analysis) => analysis.unowned));
796
- return sortProblems([
797
- ...ownerScan.problems,
798
- ...pipe(analyses, Array.flatMap((analysis) => analysis.problems)),
799
- ...duplicateProblems(relative)(unowned)
800
- ]);
801
- }, Effect.scoped);
802
- // src/import-graph.ts
329
+ };
330
+ // src/features/install-size/model/import-graph.ts
803
331
  const RELATIVE = /^\.\.?(?:\/|$)/u;
804
332
  const SUBPATH_IMPORT = "#";
805
- const WILDCARD = "*";
806
- const SCOPE$1 = "@";
807
- const SEPARATOR$3 = "/";
333
+ const WILDCARD$1 = "*";
334
+ const SCOPE = "@";
335
+ const SEPARATOR$5 = "/";
808
336
  const SOURCE_SUFFIXES = [
809
337
  "",
810
338
  ".ts",
811
339
  ".tsx",
812
340
  "/index.ts"
813
341
  ];
814
- const SCOPED_SEGMENTS = 2;
342
+ const SCOPED_SEGMENTS$1 = 2;
815
343
  const PLAIN_SEGMENTS = 1;
816
344
  const ImportsField = Schema.Struct({ imports: Schema.optional(Schema.Record(Schema.String, Schema.String)) });
817
345
  const decodeImports = Schema.decodeOption(Schema.fromJsonString(ImportsField));
818
346
  const packageNameOf = (specifier) => {
819
- const segments = String$1.split(specifier, SEPARATOR$3);
820
- if (String$1.startsWith(SCOPE$1)(specifier)) return pipe(segments, Array.take(SCOPED_SEGMENTS), Array.join(SEPARATOR$3));
821
- return pipe(segments, Array.take(PLAIN_SEGMENTS), Array.join(SEPARATOR$3));
347
+ const segments = String$1.split(specifier, SEPARATOR$5);
348
+ if (String$1.startsWith(SCOPE)(specifier)) return pipe(segments, Array.take(SCOPED_SEGMENTS$1), Array.join(SEPARATOR$5));
349
+ return pipe(segments, Array.take(PLAIN_SEGMENTS), Array.join(SEPARATOR$5));
822
350
  };
823
351
  const literalText = (specifier) => pipe(Option.liftPredicate(specifier, isStringLiteral), Option.map((literal) => literal.text));
824
352
  const runtimeSpecifierOf = (statement) => {
@@ -836,9 +364,9 @@ const specifiersIn = (api, file, text) => {
836
364
  return Array.getSomes(found);
837
365
  };
838
366
  const subpathTarget = (imports, specifier) => pipe(Record.toEntries(imports), Array.findFirst(([pattern, target]) => {
839
- if (!String$1.endsWith(WILDCARD)(pattern)) return Option.liftPredicate(target, () => pattern === specifier);
840
- const prefix = String$1.replace(WILDCARD, "")(pattern);
841
- return Option.liftPredicate(String$1.replace(WILDCARD, String$1.replace(prefix, "")(specifier))(target), () => String$1.startsWith(prefix)(specifier));
367
+ if (!String$1.endsWith(WILDCARD$1)(pattern)) return Option.liftPredicate(target, () => pattern === specifier);
368
+ const prefix = String$1.replace(WILDCARD$1, "")(pattern);
369
+ return Option.liftPredicate(String$1.replace(WILDCARD$1, String$1.replace(prefix, "")(specifier))(target), () => String$1.startsWith(prefix)(specifier));
842
370
  }));
843
371
  const existingSource = Effect.fn("existingSource")(function* existingSource(base) {
844
372
  const files = yield* RepositoryFiles;
@@ -902,7 +430,7 @@ const packagesByEntry = Effect.fn("packagesByEntry")(function* packagesByEntry(a
902
430
  packages: HashSet.empty()
903
431
  }).pipe(Effect.map((packages) => [entry, packages]))));
904
432
  });
905
- // src/installed-closure.ts
433
+ // src/features/install-size/model/installed-closure.ts
906
434
  const EMPTY = 0;
907
435
  const DependencyMap = Schema.optional(Schema.Record(Schema.String, Schema.String));
908
436
  const PeerMetaEntry = Schema.Struct({ optional: Schema.optional(Schema.Boolean) });
@@ -976,20 +504,7 @@ const installedSize = (directory) => {
976
504
  if (String$1.includes(`/node_modules/`)(directory)) return directorySize(directory);
977
505
  return Effect.succeed(EMPTY);
978
506
  };
979
- // src/text-position.ts
980
- const START$5 = 0;
981
- const FIRST_COLUMN$2 = 1;
982
- const positionOf = (source) => (index) => {
983
- const before = pipe(source, String$1.slice(START$5, index), String$1.split("\n"));
984
- return {
985
- line: before.length,
986
- column: pipe(Array.last(before), Option.match({
987
- onNone: () => FIRST_COLUMN$2,
988
- onSome: (last) => last.length + FIRST_COLUMN$2
989
- }))
990
- };
991
- };
992
- // src/install-size.ts
507
+ // src/features/install-size/model/install-size.ts
993
508
  const INSTALL_SIZE = "install-size";
994
509
  const STACK_DEPENDENCY = "stack-dependency";
995
510
  const STACK_CATALOG = "catalog:stack";
@@ -999,11 +514,11 @@ const LISTED_LARGEST = 5;
999
514
  const SIZE_CONCURRENCY = 32;
1000
515
  const MEGABYTE = 1e6;
1001
516
  const MEGABYTE_DIGITS = 1;
1002
- const START$4 = 0;
517
+ const START$6 = 0;
1003
518
  const SINGLE_ENTRY = 1;
1004
519
  const megabytes = (bytes) => `${(bytes / MEGABYTE).toFixed(MEGABYTE_DIGITS)} MB`;
1005
520
  const usageHint = (dependency, entryCount) => {
1006
- if (!(entryCount > SINGLE_ENTRY && dependency.entries.length > START$4 && dependency.entries.length < entryCount)) return "";
521
+ if (!(entryCount > SINGLE_ENTRY && dependency.entries.length > START$6 && dependency.entries.length < entryCount)) return "";
1007
522
  return ` (imported only from ${Array.join(dependency.entries, ", ")})`;
1008
523
  };
1009
524
  const listed = ({ largest, entryCount }) => pipe(largest, Array.map((dependency) => `${dependency.name} ${megabytes(dependency.size)}${usageHint(dependency, entryCount)}`), Array.join(", "));
@@ -1012,7 +527,7 @@ const budgetProblem = Effect.fn("budgetProblem")(function* budgetProblem(overrun
1012
527
  const { workspace, total } = overrun;
1013
528
  const config = yield* files.readFile(workspace.configFile);
1014
529
  const source = Option.getOrElse(config, () => "");
1015
- const index = Option.getOrElse(String$1.indexOf(BUDGET_KEY)(source), () => START$4);
530
+ const index = Option.getOrElse(String$1.indexOf(BUDGET_KEY)(source), () => START$6);
1016
531
  return {
1017
532
  file: workspace.configFile,
1018
533
  ...positionOf(source)(index),
@@ -1029,7 +544,7 @@ const measure = Effect.fn("measure")(function* measure({ workspace, provided },
1029
544
  const everything = pipe(closures, Array.flatMap(([, packages]) => Array.fromIterable(packages)), HashSet.fromIterable);
1030
545
  const measured = yield* Effect.forEach(everything, (found) => installedSize(found).pipe(Effect.map((size) => [found, size])), { concurrency: SIZE_CONCURRENCY });
1031
546
  const sizes = HashMap.fromIterable(measured);
1032
- const sizeOf = (packages) => Number$1.sumAll(pipe(Array.fromIterable(packages), Array.map((found) => Option.getOrElse(HashMap.get(sizes, found), () => START$4))));
547
+ const sizeOf = (packages) => Number$1.sumAll(pipe(Array.fromIterable(packages), Array.map((found) => Option.getOrElse(HashMap.get(sizes, found), () => START$6))));
1033
548
  return {
1034
549
  closures,
1035
550
  sizeOf,
@@ -1062,11 +577,11 @@ const sizeProblems = Effect.fn("sizeProblems")(function* sizeProblems(published,
1062
577
  })];
1063
578
  });
1064
579
  const stackProblems = (file, source, dependencies) => {
1065
- const section = Option.getOrElse(String$1.indexOf(DEPENDENCIES_KEY)(source), () => START$4);
580
+ const section = Option.getOrElse(String$1.indexOf(DEPENDENCIES_KEY)(source), () => START$6);
1066
581
  const rest = String$1.slice(section)(source);
1067
582
  return pipe(Record.toEntries(dependencies), Array.filter(([, specifier]) => specifier === STACK_CATALOG), Array.map(([name]) => ({
1068
583
  file,
1069
- ...positionOf(source)(section + Option.getOrElse(String$1.indexOf(`"${name}"`)(rest), () => START$4)),
584
+ ...positionOf(source)(section + Option.getOrElse(String$1.indexOf(`"${name}"`)(rest), () => START$6)),
1070
585
  rule: STACK_DEPENDENCY,
1071
586
  message: `${name} comes from the stack catalog, so every project that installs this package already has it. Move it to peerDependencies and keep it in devDependencies, so the installing project shares one copy.`
1072
587
  })));
@@ -1078,7 +593,7 @@ const PublishedManifest = Schema.Struct({
1078
593
  exports: Schema.optional(Schema.Unknown),
1079
594
  bin: Schema.optional(Schema.Unknown)
1080
595
  });
1081
- const problemsOf = Effect.fn("problemsOf")(function* problemsOf(workspace, file, source) {
596
+ const problemsOf$1 = Effect.fn("problemsOf")(function* problemsOf(workspace, file, source) {
1082
597
  const files = yield* RepositoryFiles;
1083
598
  const manifest = Schema.decodeOption(Schema.fromJsonString(PublishedManifest))(source);
1084
599
  if (Option.isNone(manifest)) return [];
@@ -1102,7 +617,7 @@ const workspaceProblems = Effect.fn("workspaceProblems")(function* workspaceProb
1102
617
  const source = yield* files.readFile(file);
1103
618
  return yield* Option.match(source, {
1104
619
  onNone: () => Effect.succeed([]),
1105
- onSome: (text) => problemsOf(workspace, file, text)
620
+ onSome: (text) => problemsOf$1(workspace, file, text)
1106
621
  });
1107
622
  });
1108
623
  /** @internal */
@@ -1111,7 +626,7 @@ const checkPublishedPackages = Effect.fn("checkPublishedPackages")(function* che
1111
626
  const found = yield* pipe(workspaces, Effect.forEach(workspaceProblems));
1112
627
  return Array.flatten(found);
1113
628
  });
1114
- // src/override-findings.ts
629
+ // src/features/overrides/model/override-findings.ts
1115
630
  const describeVersions = (versions) => Option.getOrElse(Option.liftPredicate(Array.join(versions, ","), (joined) => joined !== ""), () => "-");
1116
631
  const describeChanges = (report) => {
1117
632
  const versions = pipe(report.changes, Array.map((change) => `${change.name} ${describeVersions(change.before)} -> ${describeVersions(change.after)}`));
@@ -1136,7 +651,7 @@ const overrideProblem = (located) => (report) => {
1136
651
  });
1137
652
  return Option.none();
1138
653
  };
1139
- // src/override-resolution.ts
654
+ // src/features/overrides/model/override-resolution.ts
1140
655
  const VerdictSchema = Schema.Literals([
1141
656
  "unused",
1142
657
  "keep",
@@ -1178,7 +693,7 @@ const AdvisorySchema = Schema.Struct({
1178
693
  github_advisory_id: Schema.String
1179
694
  });
1180
695
  const AuditReport = Schema.fromJsonString(Schema.Struct({ advisories: Schema.Record(Schema.String, AdvisorySchema) }));
1181
- const SCOPE_PREFIX = "@";
696
+ const SCOPE_PREFIX$1 = "@";
1182
697
  const NAME_START = 0;
1183
698
  const SEPARATOR_LENGTH = 1;
1184
699
  const PEER_CONTEXT_START = "(";
@@ -1202,14 +717,14 @@ const advisoriesIn = (output) => Option.match(Schema.decodeOption(AuditReport)(o
1202
717
  onSome: (report) => sorted(pipe(Record.values(report.advisories), Array.map((advisory) => `${advisory.module_name} ${advisory.github_advisory_id}`)))
1203
718
  });
1204
719
  const separatorOf = (key) => {
1205
- if (!String$1.startsWith(SCOPE_PREFIX)(key)) return String$1.indexOf(SCOPE_PREFIX)(key);
1206
- return pipe(String$1.slice(SEPARATOR_LENGTH)(key), String$1.indexOf(SCOPE_PREFIX), Option.map((index) => index + SEPARATOR_LENGTH));
720
+ if (!String$1.startsWith(SCOPE_PREFIX$1)(key)) return String$1.indexOf(SCOPE_PREFIX$1)(key);
721
+ return pipe(String$1.slice(SEPARATOR_LENGTH)(key), String$1.indexOf(SCOPE_PREFIX$1), Option.map((index) => index + SEPARATOR_LENGTH));
1207
722
  };
1208
723
  const withoutPeerContext = (version) => Option.match(String$1.indexOf(PEER_CONTEXT_START)(version), {
1209
724
  onNone: () => version,
1210
725
  onSome: (start) => String$1.slice(NAME_START, start)(version)
1211
726
  });
1212
- const packageOf = (key) => Option.map(separatorOf(key), (separator) => [String$1.slice(NAME_START, separator)(key), withoutPeerContext(String$1.slice(separator + SEPARATOR_LENGTH)(key))]);
727
+ const packageOf$1 = (key) => Option.map(separatorOf(key), (separator) => [String$1.slice(NAME_START, separator)(key), withoutPeerContext(String$1.slice(separator + SEPARATOR_LENGTH)(key))]);
1213
728
  const keysOf = (node) => {
1214
729
  if (!isMap(node)) return [];
1215
730
  return pipe(node.items, Array.flatMap((pair) => {
@@ -1220,7 +735,7 @@ const keysOf = (node) => {
1220
735
  const lockfileKeysOf = (lockfile, section) => pipe(parseAllDocuments(lockfile), Array.flatMap((document) => keysOf(document.get(section))));
1221
736
  const resolutionOf = (findings) => (lockfile) => {
1222
737
  const snapshots = lockfileKeysOf(lockfile, "snapshots");
1223
- const packages = Array.getSomes(pipe([...lockfileKeysOf(lockfile, "packages"), ...snapshots], Array.map((key) => packageOf(key))));
738
+ const packages = Array.getSomes(pipe([...lockfileKeysOf(lockfile, "packages"), ...snapshots], Array.map((key) => packageOf$1(key))));
1224
739
  const versions = Record.map(Array.groupBy(packages, ([name]) => name), (entries) => sorted(pipe(entries, Array.map(([, version]) => version))));
1225
740
  return {
1226
741
  ...findings,
@@ -1290,12 +805,12 @@ const withBaselineProbe = (manifest) => {
1290
805
  document.setIn([OVERRIDES, BASELINE_PROBE], REMOVED_DEPENDENCY);
1291
806
  return document.toString();
1292
807
  };
1293
- // src/overrides.ts
1294
- const WORKSPACE_FILE = "pnpm-workspace.yaml";
808
+ // src/features/overrides/model/overrides.ts
809
+ const WORKSPACE_FILE$1 = "pnpm-workspace.yaml";
1295
810
  const LOCKFILE$1 = "pnpm-lock.yaml";
1296
811
  const RESOLUTION_FILES = [
1297
812
  "*package.json",
1298
- WORKSPACE_FILE,
813
+ WORKSPACE_FILE$1,
1299
814
  LOCKFILE$1,
1300
815
  ".npmrc",
1301
816
  "patches/*"
@@ -1366,7 +881,7 @@ const resolutionWith = Effect.fn("resolutionWith")(function* resolutionWith(work
1366
881
  const path = yield* Path.Path;
1367
882
  const directory = yield* fs.makeTempDirectoryScoped({ prefix: "msch-overrides-" });
1368
883
  yield* copyFiles(workspace, directory);
1369
- yield* fs.writeFileString(path.join(directory, WORKSPACE_FILE), manifest);
884
+ yield* fs.writeFileString(path.join(directory, WORKSPACE_FILE$1), manifest);
1370
885
  const output = yield* resolveIn(directory, override);
1371
886
  const lockfile = yield* fs.readFileString(path.join(directory, LOCKFILE$1));
1372
887
  yield* Effect.annotateCurrentSpan({ "msch.override": override });
@@ -1385,7 +900,7 @@ const problemsFor = Effect.fn("problemsFor")(function* problemsFor(root, manifes
1385
900
  };
1386
901
  const baseline = yield* resolutionWith(workspace, BASELINE_PROBE, withBaselineProbe(manifest));
1387
902
  const judgeAgainstBaseline = judge(baseline);
1388
- const file = path.join(root, WORKSPACE_FILE);
903
+ const file = path.join(root, WORKSPACE_FILE$1);
1389
904
  const problemOf = (located) => resolutionWith(workspace, located.key, withoutOverride(located.key)(manifest)).pipe(Effect.map((candidate) => overrideProblem({
1390
905
  ...located,
1391
906
  file
@@ -1397,7 +912,7 @@ const problemsFor = Effect.fn("problemsFor")(function* problemsFor(root, manifes
1397
912
  const checkOverrides = Effect.fn("checkOverrides")(function* checkOverrides(root) {
1398
913
  const fs = yield* FileSystem.FileSystem;
1399
914
  const path = yield* Path.Path;
1400
- const manifest = yield* fs.readFileString(path.join(root, WORKSPACE_FILE)).pipe(Effect.option);
915
+ const manifest = yield* fs.readFileString(path.join(root, WORKSPACE_FILE$1)).pipe(Effect.option);
1401
916
  const keys = Option.match(manifest, {
1402
917
  onNone: () => [],
1403
918
  onSome: overrideKeysOf
@@ -1405,14 +920,42 @@ const checkOverrides = Effect.fn("checkOverrides")(function* checkOverrides(root
1405
920
  if (Option.isNone(manifest) || !Array.isReadonlyArrayNonEmpty(keys)) return [];
1406
921
  return yield* problemsFor(root, manifest.value, keys);
1407
922
  });
1408
- // src/colocated-tests.ts
1409
- const RULE$7 = "colocated-test";
1410
- const FIRST$4 = 1;
1411
- const READ_CONCURRENCY$7 = 64;
923
+ // src/features/placement/model/agent-docs-length.ts
924
+ const AGENT_DOC = /(?:^|\/)(?:AGENTS|CLAUDE)\.md$/u;
925
+ const RECOMMENDED_LINES = 200;
926
+ const READ_CONCURRENCY$12 = 16;
927
+ const FIRST$7 = 1;
928
+ const RULE$12 = "agent-docs-length";
929
+ const lineCount = (source) => pipe(String$1.trimEnd(source), String$1.split("\n")).length;
930
+ const problemFor$4 = (file) => (lines) => {
931
+ if (lines <= RECOMMENDED_LINES) return Option.none();
932
+ return Option.some({
933
+ file,
934
+ line: 201,
935
+ column: FIRST$7,
936
+ rule: RULE$12,
937
+ message: `has ${String(lines)} lines. Claude Code recommends under ${String(RECOMMENDED_LINES)} lines per file: longer files cost context and are followed less reliably. Cut what the code already tells, and move rules shared across repositories into skills.`
938
+ });
939
+ };
940
+ /** @internal */
941
+ const checkAgentDocsLength = Effect.fn("checkAgentDocsLength")(function* checkAgentDocsLength(root) {
942
+ const files = yield* RepositoryFiles;
943
+ const listed = yield* files.listedFiles(root);
944
+ const docs = pipe(listed, Array.filter((name) => AGENT_DOC.test(name)));
945
+ const found = yield* Effect.forEach(docs, (name) => {
946
+ const file = files.join(root, name);
947
+ return files.readFile(file).pipe(Effect.map(Option.flatMap((source) => problemFor$4(file)(lineCount(source)))));
948
+ }, { concurrency: READ_CONCURRENCY$12 });
949
+ return Array.getSomes(found);
950
+ });
951
+ // src/features/placement/model/colocated-tests.ts
952
+ const RULE$11 = "colocated-test";
953
+ const FIRST$6 = 1;
954
+ const READ_CONCURRENCY$11 = 64;
1412
955
  const ROOT_SUBPATH = ".";
1413
956
  const NAME_GROUP = "name";
1414
957
  const SPECIFIER_GROUP = "specifier";
1415
- const SCRIPT = /\.[cm]?[jt]sx?$/u;
958
+ const SCRIPT$1 = /\.[cm]?[jt]sx?$/u;
1416
959
  const TEST_FILE = /\.test\.[cm]?[jt]sx?$/u;
1417
960
  const MANIFEST_NAME = /package\.json$/u;
1418
961
  const SEPARATE_TEST_DIRECTORY = /(?:^|\/)(?:__tests__|__mocks__|tests?|specs?)\//u;
@@ -1428,16 +971,16 @@ const Manifest = Schema.Struct({
1428
971
  });
1429
972
  const decodeManifest = Schema.decodeUnknownOption(Schema.fromJsonString(Manifest));
1430
973
  const byLength = Order.mapInput(Order.Number, (directory) => directory.length);
1431
- const problemFor$2 = (test, message) => ({
974
+ const problemFor$3 = (test, message) => ({
1432
975
  file: test.file,
1433
- line: FIRST$4,
1434
- column: FIRST$4,
1435
- rule: RULE$7,
976
+ line: FIRST$6,
977
+ column: FIRST$6,
978
+ rule: RULE$11,
1436
979
  message: `${test.base} ${message}`
1437
980
  });
1438
- const groupsOf = (source, pattern, group) => pipe(Array.fromIterable(String$1.matchAll(pattern)(source)), Array.map((match) => pipe(Option.fromUndefinedOr(match.groups), Option.flatMap((groups) => Option.fromUndefinedOr(groups[group])))), Array.getSomes);
1439
- const namesSibling = (source) => pipe([...groupsOf(source, RELATIVE_REFERENCE, NAME_GROUP), ...groupsOf(source, DIRNAME_REFERENCE, NAME_GROUP)], Array.some((name) => !TEST_FILE.test(name)));
1440
- const ownerOf = (packages, name) => {
981
+ const groupsOf$1 = (source, pattern, group) => pipe(Array.fromIterable(String$1.matchAll(pattern)(source)), Array.map((match) => pipe(Option.fromUndefinedOr(match.groups), Option.flatMap((groups) => Option.fromUndefinedOr(groups[group])))), Array.getSomes);
982
+ const namesSibling = (source) => pipe([...groupsOf$1(source, RELATIVE_REFERENCE, NAME_GROUP), ...groupsOf$1(source, DIRNAME_REFERENCE, NAME_GROUP)], Array.some((name) => !TEST_FILE.test(name)));
983
+ const ownerOf$1 = (packages, name) => {
1441
984
  const owners = pipe(packages, Array.filter((directory) => String$1.startsWith(directory)(name)));
1442
985
  return Array.last(Array.sort(owners, byLength));
1443
986
  };
@@ -1448,7 +991,7 @@ const specifiersBeside = ({ join, dirname, directory }) => (manifest) => pipe(Op
1448
991
  }), Array.filter(({ source }) => dirname(source) === directory), Array.map(({ label }) => String$1.replace(ROOT_SUBPATH, name)(label)))), Option.getOrElse(() => []));
1449
992
  const ownSpecifiers = Effect.fn("ownSpecifiers")(function* ownSpecifiers(context, test) {
1450
993
  const files = yield* RepositoryFiles;
1451
- const owner = ownerOf(context.packages, test.name);
994
+ const owner = ownerOf$1(context.packages, test.name);
1452
995
  if (Option.isNone(owner)) return [];
1453
996
  const text = yield* files.readFile(files.join(context.root, owner.value, MANIFEST_FILE));
1454
997
  const join = (target) => files.join(context.root, owner.value, target);
@@ -1460,7 +1003,7 @@ const ownSpecifiers = Effect.fn("ownSpecifiers")(function* ownSpecifiers(context
1460
1003
  });
1461
1004
  const refersToOwnDirectory = Effect.fn("refersToOwnDirectory")(function* refersToOwnDirectory(context, test, source) {
1462
1005
  if (namesSibling(source)) return true;
1463
- const specifiers = groupsOf(source, MODULE_SPECIFIER, SPECIFIER_GROUP);
1006
+ const specifiers = groupsOf$1(source, MODULE_SPECIFIER, SPECIFIER_GROUP);
1464
1007
  if (Array.isReadonlyArrayEmpty(specifiers)) return false;
1465
1008
  const own = yield* ownSpecifiers(context, test);
1466
1009
  return pipe(specifiers, Array.some((specifier) => pipe(own, Array.contains(specifier))));
@@ -1471,10 +1014,10 @@ const refersIn = Effect.fn("refersIn")(function* refersIn(context, test) {
1471
1014
  return yield* refersToOwnDirectory(context, test, source.value);
1472
1015
  });
1473
1016
  const problemIn$3 = Effect.fn("problemIn")(function* problemIn(context, test) {
1474
- if (SEPARATE_TEST_DIRECTORY.test(test.name)) return Option.some(problemFor$2(test, DIRECTORY_MESSAGE));
1017
+ if (SEPARATE_TEST_DIRECTORY.test(test.name)) return Option.some(problemFor$3(test, DIRECTORY_MESSAGE));
1475
1018
  if (!TEST_FILE.test(test.name)) return Option.none();
1476
1019
  if (yield* refersIn(context, test)) return Option.none();
1477
- return Option.some(problemFor$2(test, SIBLING_MESSAGE));
1020
+ return Option.some(problemFor$3(test, SIBLING_MESSAGE));
1478
1021
  });
1479
1022
  /** @internal */
1480
1023
  const checkColocatedTests = Effect.fn("checkColocatedTests")(function* checkColocatedTests(root) {
@@ -1485,7 +1028,7 @@ const checkColocatedTests = Effect.fn("checkColocatedTests")(function* checkColo
1485
1028
  root,
1486
1029
  packages: pipe(names, Array.filter((name) => files.basename(name) === MANIFEST_FILE), Array.map(String$1.replace(MANIFEST_NAME, "")))
1487
1030
  };
1488
- const tests = pipe(names, Array.filter((name) => SCRIPT.test(name)), Array.map((name) => {
1031
+ const tests = pipe(names, Array.filter((name) => SCRIPT$1.test(name)), Array.map((name) => {
1489
1032
  const file = files.join(root, name);
1490
1033
  return {
1491
1034
  name,
@@ -1494,40 +1037,40 @@ const checkColocatedTests = Effect.fn("checkColocatedTests")(function* checkColo
1494
1037
  directory: files.dirname(file)
1495
1038
  };
1496
1039
  }));
1497
- const found = yield* Effect.forEach(tests, (test) => problemIn$3(context, test), { concurrency: READ_CONCURRENCY$7 });
1040
+ const found = yield* Effect.forEach(tests, (test) => problemIn$3(context, test), { concurrency: READ_CONCURRENCY$11 });
1498
1041
  return Array.getSomes(found);
1499
1042
  });
1500
- // src/nested-docs.ts
1501
- const RULE$6 = "nested-docs";
1043
+ // src/features/placement/model/nested-docs.ts
1044
+ const RULE$10 = "nested-docs";
1502
1045
  const CONFIG_FILE$4 = "vite.config.ts";
1503
- const SEPARATOR$2 = "/";
1504
- const FIRST$3 = 1;
1505
- const READ_CONCURRENCY$6 = 64;
1046
+ const SEPARATOR$4 = "/";
1047
+ const FIRST$5 = 1;
1048
+ const READ_CONCURRENCY$10 = 64;
1506
1049
  const AGENT_DOCS = /^(?:AGENTS|CLAUDE)(?:\.[^/]+)?\.md$/iu;
1507
1050
  const WORKSPACE_AGENT_DOC = "AGENTS.md";
1508
- const README$1 = /^README(?:\.[^/]+)?$/iu;
1051
+ const README = /^README(?:\.[^/]+)?$/iu;
1509
1052
  const RootConfig$1 = Schema.Struct({ msch: Schema.Struct({ workspaceAgentsMd: Schema.Literal(true) }) });
1510
1053
  const taggedError$3 = Schema.TaggedError;
1511
1054
  var RootConfigUnreadable = class extends taggedError$3()("RootConfigUnreadable", { file: Schema.String }) {};
1512
- const isNested = (name) => String$1.includes(SEPARATOR$2)(name);
1513
- const problemFor$1 = (file, message) => ({
1055
+ const isNested = (name) => String$1.includes(SEPARATOR$4)(name);
1056
+ const problemFor$2 = (file, message) => ({
1514
1057
  file,
1515
- line: FIRST$3,
1516
- column: FIRST$3,
1517
- rule: RULE$6,
1058
+ line: FIRST$5,
1059
+ column: FIRST$5,
1060
+ rule: RULE$10,
1518
1061
  message
1519
1062
  });
1520
1063
  const AGENT_DOCS_MESSAGE = "belongs only at the repository root. Move what agents need into the root AGENTS.md and delete this file.";
1521
1064
  const WORKSPACE_AGENT_DOCS_MESSAGE = "belongs only at the repository root or as AGENTS.md directly in a workspace, the directory that holds its package.json. Move what agents need there and delete this file.";
1522
1065
  const README_MESSAGE = "is allowed below the root only in a workspace, the directory that holds its package.json. Move it into the workspace it describes.";
1523
1066
  const agentDocProblem = ({ file, base, directory }, allowed) => {
1524
- if (!allowed.workspaceAgentDocs) return Option.some(problemFor$1(file, `${base} ${AGENT_DOCS_MESSAGE}`));
1067
+ if (!allowed.workspaceAgentDocs) return Option.some(problemFor$2(file, `${base} ${AGENT_DOCS_MESSAGE}`));
1525
1068
  if (base === WORKSPACE_AGENT_DOC && HashSet.has(allowed.workspaces, directory)) return Option.none();
1526
- return Option.some(problemFor$1(file, `${base} ${WORKSPACE_AGENT_DOCS_MESSAGE}`));
1069
+ return Option.some(problemFor$2(file, `${base} ${WORKSPACE_AGENT_DOCS_MESSAGE}`));
1527
1070
  };
1528
1071
  const readmeProblem = ({ file, base, directory }, allowed) => {
1529
- if (!README$1.test(base) || HashSet.has(allowed.workspaces, directory)) return Option.none();
1530
- return Option.some(problemFor$1(file, `${base} ${README_MESSAGE}`));
1072
+ if (!README.test(base) || HashSet.has(allowed.workspaces, directory)) return Option.none();
1073
+ return Option.some(problemFor$2(file, `${base} ${README_MESSAGE}`));
1531
1074
  };
1532
1075
  const problemIn$2 = Effect.fn("problemIn")(function* problemIn(root, allowed, name) {
1533
1076
  const files = yield* RepositoryFiles;
@@ -1550,90 +1093,1089 @@ const allowsWorkspaceAgentDocs = Effect.fn("allowsWorkspaceAgentDocs")(function*
1550
1093
  }).pipe(Effect.option);
1551
1094
  return pipe(config, Option.flatMap(Schema.decodeUnknownOption(RootConfig$1)), Option.isSome);
1552
1095
  });
1553
- /** @internal */
1554
- const checkNestedDocs = Effect.fn("checkNestedDocs")(function* checkNestedDocs(root) {
1555
- const files = yield* RepositoryFiles;
1556
- const names = yield* files.listedFiles(root);
1557
- const nested = pipe(names, Array.filter(isNested));
1558
- const workspaceAgentDocs = yield* allowsWorkspaceAgentDocs(root);
1559
- const allowed = {
1560
- workspaces: pipe(nested, Array.filter((name) => files.basename(name) === MANIFEST_FILE), Array.map((name) => files.dirname(files.join(root, name))), HashSet.fromIterable),
1561
- workspaceAgentDocs
1562
- };
1563
- const found = yield* Effect.forEach(nested, (name) => problemIn$2(root, allowed, name), { concurrency: READ_CONCURRENCY$6 });
1564
- return Array.getSomes(found);
1096
+ /** @internal */
1097
+ const checkNestedDocs = Effect.fn("checkNestedDocs")(function* checkNestedDocs(root) {
1098
+ const files = yield* RepositoryFiles;
1099
+ const names = yield* files.listedFiles(root);
1100
+ const nested = pipe(names, Array.filter(isNested));
1101
+ const workspaceAgentDocs = yield* allowsWorkspaceAgentDocs(root);
1102
+ const allowed = {
1103
+ workspaces: pipe(nested, Array.filter((name) => files.basename(name) === MANIFEST_FILE), Array.map((name) => files.dirname(files.join(root, name))), HashSet.fromIterable),
1104
+ workspaceAgentDocs
1105
+ };
1106
+ const found = yield* Effect.forEach(nested, (name) => problemIn$2(root, allowed, name), { concurrency: READ_CONCURRENCY$10 });
1107
+ return Array.getSomes(found);
1108
+ });
1109
+ // src/features/placement/model/root-readme.ts
1110
+ const RULE$9 = "root-readme";
1111
+ const ROOT_DOC = /^(?:README(?:\.[^/]+)?|AGENTS\.md|CLAUDE\.md)$/iu;
1112
+ const READ_CONCURRENCY$9 = 16;
1113
+ const START$5 = 0;
1114
+ const messageFor = (directory) => `names the workspace ${directory}. The root README, AGENTS.md and CLAUDE.md describe the repository as a whole. Write what belongs to the workspace in ${directory}/README.md, or for agents in ${directory}/AGENTS.md.`;
1115
+ const problemsIn$4 = (file, source) => ({ directory, pattern }) => {
1116
+ const message = messageFor(directory);
1117
+ const at = positionOf(source);
1118
+ return pipe(Array.fromIterable(String$1.matchAll(pattern)(source)), Array.map((found) => ({
1119
+ file,
1120
+ ...at(found.index ?? START$5),
1121
+ rule: RULE$9,
1122
+ message
1123
+ })));
1124
+ };
1125
+ const problemsInReadme = Effect.fn("problemsInReadme")(function* problemsInReadme(file, workspaces) {
1126
+ const text = yield* (yield* RepositoryFiles).readFile(file);
1127
+ return pipe(text, Option.match({
1128
+ onNone: () => [],
1129
+ onSome: (source) => pipe(workspaces, Array.flatMap(problemsIn$4(file, source)))
1130
+ }));
1131
+ });
1132
+ /** @internal */
1133
+ const checkRootReadme = Effect.fn("checkRootReadme")(function* checkRootReadme(root) {
1134
+ const files = yield* RepositoryFiles;
1135
+ const names = yield* files.listedFiles(root);
1136
+ const readmes = pipe(names, Array.filter((name) => ROOT_DOC.test(name)));
1137
+ const workspaces = yield* namedWorkspaces(root);
1138
+ const found = yield* Effect.forEach(readmes, (name) => problemsInReadme(files.join(root, name), workspaces), { concurrency: READ_CONCURRENCY$9 });
1139
+ return Array.flatten(found);
1140
+ });
1141
+ // src/features/placement/model/placement-checks.ts
1142
+ /** @internal */
1143
+ const checkPlacement = Effect.fn("checkPlacement")(function* checkPlacement(root) {
1144
+ const found = yield* Effect.all([
1145
+ checkNestedDocs(root),
1146
+ checkRootReadme(root),
1147
+ checkColocatedTests(root),
1148
+ checkAgentDocsLength(root)
1149
+ ], { concurrency: "unbounded" });
1150
+ return Array.flatten(found);
1151
+ });
1152
+ // src/features/repository-layout/model/crates.ts
1153
+ const RULE$8 = "unverified-crate";
1154
+ const CARGO_FILE = "Cargo.toml";
1155
+ const CONFIG_FILE$3 = "vite.config.ts";
1156
+ const SEPARATOR$3 = "/";
1157
+ const FIRST$4 = 1;
1158
+ const READ_CONCURRENCY$8 = 8;
1159
+ const CrateEntry = Schema.Struct({
1160
+ name: Schema.String,
1161
+ manifest_path: Schema.String
1162
+ });
1163
+ const CrateList = Schema.fromJsonString(Schema.Struct({ packages: Schema.Array(CrateEntry) }));
1164
+ const decodeCrateList = Schema.decodeUnknownEffect(CrateList);
1165
+ const cratesIn = Effect.fn("cratesIn")(function* cratesIn(root) {
1166
+ const output = yield* (yield* ChildProcess.make("cargo", [
1167
+ "metadata",
1168
+ "--no-deps",
1169
+ "--format-version",
1170
+ "1",
1171
+ "--offline"
1172
+ ], {
1173
+ cwd: root,
1174
+ extendEnv: true,
1175
+ stdin: "ignore"
1176
+ })).stdout.pipe(Stream.decodeText(), Stream.mkString);
1177
+ const list = yield* decodeCrateList(output);
1178
+ return pipe(list.packages, Array.map((crate) => ({
1179
+ name: crate.name,
1180
+ manifest: crate.manifest_path
1181
+ })));
1182
+ }, Effect.scoped);
1183
+ const owningWorkspace = (directories) => (directory) => {
1184
+ const owners = pipe(directories, Array.filter((workspace) => directory === workspace || String$1.startsWith(`${workspace}${SEPARATOR$3}`)(directory)));
1185
+ return Array.last(Array.sort(owners, String$1.Order));
1186
+ };
1187
+ const problemFor$1 = (crate, message) => ({
1188
+ file: crate.manifest,
1189
+ line: FIRST$4,
1190
+ column: FIRST$4,
1191
+ rule: RULE$8,
1192
+ message: `crate ${crate.name} ${message}, so vp run verify never checks it.`
1193
+ });
1194
+ const problemIn$1 = Effect.fn("problemIn")(function* problemIn(root, directories, crate) {
1195
+ const files = yield* RepositoryFiles;
1196
+ const workspace = owningWorkspace(directories)(files.relative(root, files.dirname(crate.manifest)));
1197
+ if (Option.isNone(workspace)) return Option.some(problemFor$1(crate, "is outside every workspace package"));
1198
+ if (yield* hasVerifyTask(files.join(root, workspace.value, CONFIG_FILE$3))) return Option.none();
1199
+ return Option.some(problemFor$1(crate, `is in ${workspace.value}, whose ${CONFIG_FILE$3} has no verify task`));
1200
+ });
1201
+ /** @internal */
1202
+ const checkCrates = Effect.fn("checkCrates")(function* checkCrates(root) {
1203
+ const files = yield* RepositoryFiles;
1204
+ if (!(yield* files.exists(files.join(root, CARGO_FILE)))) return [];
1205
+ const directories = yield* workspaceDirectories(root);
1206
+ const crates = yield* cratesIn(root);
1207
+ const found = yield* Effect.forEach(crates, (crate) => problemIn$1(root, directories, crate), { concurrency: READ_CONCURRENCY$8 });
1208
+ return Array.getSomes(found);
1209
+ });
1210
+ // src/features/repository-layout/model/hidden-verify.ts
1211
+ const RULE$7 = "hidden-verify";
1212
+ const CONFIG_FILE$2 = "vite.config.ts";
1213
+ const FIRST$3 = 1;
1214
+ const READ_CONCURRENCY$7 = 8;
1215
+ const problemIn = Effect.fn("problemIn")(function* problemIn(root, directory) {
1216
+ const config = yield* workspaceConfigOf(root, directory);
1217
+ if (Option.isNone(config)) return Option.none();
1218
+ const { file, program } = config.value;
1219
+ if (definesTask(VERIFY_TASK)(program)) return Option.none();
1220
+ const verified = yield* hasVerifyTask(file);
1221
+ return Option.some({
1222
+ file,
1223
+ line: FIRST$3,
1224
+ column: FIRST$3,
1225
+ rule: RULE$7,
1226
+ message: `${directory} gets its verify task from code outside ${CONFIG_FILE$2}. The root verify reads ${CONFIG_FILE$2} without running it, so it never runs this verify. Write run.tasks.verify in ${directory}/${CONFIG_FILE$2}.`
1227
+ }).pipe(Option.filter(() => verified));
1228
+ });
1229
+ /** @internal */
1230
+ const checkHiddenVerify = Effect.fn("checkHiddenVerify")(function* checkHiddenVerify(root) {
1231
+ const directories = yield* workspaceDirectories(root);
1232
+ const found = yield* Effect.forEach(directories, (directory) => problemIn(root, directory), { concurrency: READ_CONCURRENCY$7 });
1233
+ return Array.getSomes(found);
1234
+ });
1235
+ // src/features/repository-layout/model/root-workspace-paths.ts
1236
+ const RULE$6 = "root-workspace-path";
1237
+ const CONFIG_FILE$1 = "vite.config.ts";
1238
+ const PATH_CHARACTER = /[\w.@/-]/u;
1239
+ const NAME_CHARACTER = /[\w.@-]/u;
1240
+ const FIRST$2 = 0;
1241
+ const NEXT$2 = 1;
1242
+ const StringNode = Schema.Union([Schema.Struct({
1243
+ type: Schema.Literal("Literal"),
1244
+ value: Schema.String,
1245
+ start: Schema.Finite
1246
+ }), Schema.Struct({
1247
+ type: Schema.Literal("TemplateElement"),
1248
+ value: Schema.Struct({ cooked: Schema.String }),
1249
+ start: Schema.Finite
1250
+ })]);
1251
+ const decodeStringNode = Schema.decodeUnknownOption(StringNode);
1252
+ const textOf = (node) => {
1253
+ if (node.type === "Literal") return node.value;
1254
+ return node.value.cooked;
1255
+ };
1256
+ const stringsIn = (node) => {
1257
+ return [...pipe(decodeStringNode(node), Option.map((found) => ({
1258
+ text: textOf(found),
1259
+ start: found.start
1260
+ })), Option.toArray), ...pipe(childrenOf$3(node), Array.flatMap(stringsIn))];
1261
+ };
1262
+ const isBoundary = (character, allowed) => character === "" || !allowed.test(character);
1263
+ const mentions = (directory) => (text) => {
1264
+ const parts = String$1.split(text, directory);
1265
+ return pipe(Array.drop(parts, NEXT$2), Array.some((after, index) => {
1266
+ const before = parts[index] ?? "";
1267
+ const previous = String$1.slice(before.length - NEXT$2)(before);
1268
+ const following = String$1.slice(FIRST$2, NEXT$2)(after);
1269
+ return isBoundary(previous, PATH_CHARACTER) && (following === "/" || isBoundary(following, NAME_CHARACTER));
1270
+ }));
1271
+ };
1272
+ const problemsIn$3 = (file, source, directories) => (found) => pipe(directories, Array.filter((directory) => mentions(directory)(found.text)), Array.map((directory) => ({
1273
+ file,
1274
+ ...positionOf(source)(found.start),
1275
+ rule: RULE$6,
1276
+ message: `${directory} is a workspace. The root ${CONFIG_FILE$1} holds what applies to every workspace, so move what only ${directory} needs into ${directory}/${CONFIG_FILE$1}: msch.lint, msch.devDependencies or its verify task.`
1277
+ })));
1278
+ /** @internal */
1279
+ const checkRootWorkspacePaths = Effect.fn("checkRootWorkspacePaths")(function* checkRootWorkspacePaths(root) {
1280
+ const files = yield* RepositoryFiles;
1281
+ const file = files.join(root, CONFIG_FILE$1);
1282
+ const source = yield* files.readFile(file);
1283
+ if (Option.isNone(source)) return [];
1284
+ const directories = yield* workspaceDirectories(root);
1285
+ const parsed = yield* Effect.promise(() => parse(file, source.value, { lang: "ts" }));
1286
+ return pipe(stringsIn(parsed.program), Array.flatMap(problemsIn$3(file, source.value, directories)));
1287
+ });
1288
+ // src/features/repository-layout/model/shared-uncached-tasks.ts
1289
+ const RULE$5 = "shared-uncached-task";
1290
+ const TASKS_PATH = ["run", "tasks"];
1291
+ const READ_CONCURRENCY$6 = 8;
1292
+ const SHARED = 2;
1293
+ const OWN_PROGRAM = /^(?:node|vpx|bun|deno|tsx)$|\//u;
1294
+ const TaskProperty = Schema.Struct({
1295
+ type: Schema.Literal("Property"),
1296
+ computed: Schema.Literal(false),
1297
+ key: KeySchema,
1298
+ value: Schema.Unknown,
1299
+ start: Schema.Finite
1300
+ });
1301
+ const TaskObject = Schema.Struct({
1302
+ type: Schema.Literal("ObjectExpression"),
1303
+ properties: Schema.Array(Schema.Unknown)
1304
+ });
1305
+ const UncachedTask = Schema.Struct({
1306
+ cache: Schema.Literal(false),
1307
+ command: Schema.Union([Schema.String, Schema.NonEmptyArray(Schema.String)])
1308
+ });
1309
+ const decodeTaskProperty = Schema.decodeUnknownOption(TaskProperty);
1310
+ const decodeTaskObject = Schema.decodeUnknownOption(TaskObject);
1311
+ const decodeUncachedTask = Schema.decodeUnknownOption(UncachedTask);
1312
+ const encodeDefinition = Schema.encodeOption(Schema.fromJsonString(Schema.Unknown));
1313
+ const commandText$1 = (command) => Array.join(Array.ensure(command), " && ");
1314
+ const runsOwnProgram = (command) => pipe(String$1.trim(command), String$1.split(/\s+/u), Array.head, Option.exists((program) => OWN_PROGRAM.test(program)));
1315
+ const definitionOf = ({ directory, file, source }) => (task) => Option.gen(function* uncachedDefinition() {
1316
+ const literal = yield* literalOf(task.value);
1317
+ const { command } = yield* decodeUncachedTask(literal);
1318
+ const text = commandText$1(command);
1319
+ if (runsOwnProgram(text)) return yield* Option.none();
1320
+ const definition = yield* encodeDefinition(literal);
1321
+ return {
1322
+ directory,
1323
+ file,
1324
+ position: positionOf(source)(task.start),
1325
+ name: keyName(task.key),
1326
+ command: text,
1327
+ definition
1328
+ };
1329
+ });
1330
+ const definitionsIn = Effect.fn("definitionsIn")(function* definitionsIn(root, directory) {
1331
+ const config = yield* workspaceConfigOf(root, directory);
1332
+ if (Option.isNone(config)) return [];
1333
+ const { file, source, program } = config.value;
1334
+ return pipe(nestedValues(TASKS_PATH)(program), Array.flatMap((tasks) => pipe(decodeTaskObject(tasks), Option.map(({ properties }) => properties), Option.getOrElse(() => []))), Array.flatMap((property) => pipe(decodeTaskProperty(property), Option.flatMap(definitionOf({
1335
+ directory,
1336
+ file,
1337
+ source
1338
+ })), Option.toArray)));
1339
+ });
1340
+ const problemsOf = (definitions) => {
1341
+ const directories = pipe(definitions, Array.map(({ directory }) => directory), Array.dedupe);
1342
+ if (directories.length < SHARED) return [];
1343
+ return pipe(definitions, Array.map(({ file, position, name, command }) => ({
1344
+ file,
1345
+ ...position,
1346
+ rule: RULE$5,
1347
+ message: `The uncached task ${name} (${command}) is written the same way in ${Array.join(directories, ", ")}. Write it once in a shared helper and spread it into each run.tasks, so that a change to it reaches every workspace.`
1348
+ })));
1349
+ };
1350
+ /** @internal */
1351
+ const checkSharedUncachedTasks = Effect.fn("checkSharedUncachedTasks")(function* checkSharedUncachedTasks(root) {
1352
+ const directories = yield* workspaceDirectories(root);
1353
+ const found = yield* Effect.forEach(directories, (directory) => definitionsIn(root, directory), { concurrency: READ_CONCURRENCY$6 });
1354
+ return pipe(Array.flatten(found), Array.groupBy(({ name, definition }) => `${name}\u0000${definition}`), Record.values, Array.flatMap(problemsOf));
1355
+ });
1356
+ // src/features/repository-layout/model/workflow-nodes.ts
1357
+ const MISSING_OFFSET = 0;
1358
+ const isRanged = (node) => isScalar(node) || isMap(node) || isSeq(node);
1359
+ /** @internal */
1360
+ const isText$1 = (node) => isScalar(node) && typeof node.value === "string";
1361
+ const isTextPair = (pair) => isPair(pair) && isText$1(pair.key);
1362
+ const offsetOf = (node) => pipe(Option.liftPredicate(node, isRanged), Option.flatMap((ranged) => Option.fromNullishOr(ranged.range)), Option.map(([start]) => start), Option.getOrElse(() => MISSING_OFFSET));
1363
+ /** @internal */
1364
+ const stringOf = (node) => pipe(Option.liftPredicate(node, isText$1), Option.map((scalar) => ({
1365
+ text: scalar.value,
1366
+ offset: offsetOf(scalar)
1367
+ })));
1368
+ /** @internal */
1369
+ const childOf = (key) => (node) => pipe(Option.liftPredicate(node, isMap), Option.map((map) => map.get(key, true)), Option.getOrUndefined);
1370
+ /** @internal */
1371
+ const workingDirectoryOf = (owner) => {
1372
+ const run = childOf("run")(childOf("defaults")(owner));
1373
+ return stringOf(childOf("working-directory")(run));
1374
+ };
1375
+ /** @internal */
1376
+ const itemsOf = (node) => pipe(Option.liftPredicate(node, isSeq), Option.map((seq) => seq.items), Option.getOrElse(() => []));
1377
+ const pairsOf = (node) => pipe(Option.liftPredicate(node, isMap), Option.map((map) => map.items), Option.getOrElse(() => []));
1378
+ /** @internal */
1379
+ const entriesOf = (node) => pipe(pairsOf(node), Array.filter(isTextPair), Array.map((pair) => [pair.key.value, pair.value]));
1380
+ /** @internal */
1381
+ const scalarsIn = (source) => {
1382
+ const found = [];
1383
+ visit(parseDocument(source), { Scalar: (_key, node) => {
1384
+ found.push(...Option.toArray(stringOf(node)));
1385
+ } });
1386
+ return found;
1387
+ };
1388
+ // src/features/repository-layout/model/workflow-references.ts
1389
+ const ROOT = ".";
1390
+ const LOCAL = "./";
1391
+ const NEGATION = "!";
1392
+ const SEPARATOR$2 = "/";
1393
+ const LINE = "\n";
1394
+ const UNRESOLVED_MARKERS = [
1395
+ "${{",
1396
+ "$",
1397
+ "{"
1398
+ ];
1399
+ const ABSOLUTE_MARKERS = ["/", "~"];
1400
+ const FILE_INPUT_SUFFIX = "-file";
1401
+ const DEPENDENCY_PATH_INPUT = "cache-dependency-path";
1402
+ const FILTER_KEYS = ["paths", "paths-ignore"];
1403
+ const HASH_FILES = /hashFiles\((?<arguments>[^)]*)\)/gu;
1404
+ const QUOTED$1 = /'(?<path>[^']*)'/gu;
1405
+ const SCRIPT = /^[\w.@/-]+\.(?:ts|mts|cts|sh)$/u;
1406
+ const TOKEN_SEPARATOR = /[\s;&|()<>"'`=]+/u;
1407
+ /** @internal */
1408
+ const ACTION_DEFINITIONS = ["action.yml", "action.yaml"];
1409
+ const containsAny = (markers) => (path) => pipe(markers, Array.some((marker) => String$1.includes(marker)(path)));
1410
+ const startsWithAny = (markers) => (path) => pipe(markers, Array.some((marker) => String$1.startsWith(marker)(path)));
1411
+ const isLiteralPath = (path) => String$1.isNonEmpty(path) && !containsAny(UNRESOLVED_MARKERS)(path) && !startsWithAny(ABSOLUTE_MARKERS)(path);
1412
+ const withoutLocal = (path) => {
1413
+ if (String$1.startsWith(LOCAL)(path)) return String$1.slice(2)(path);
1414
+ return path;
1415
+ };
1416
+ const joinPath = (base, path) => {
1417
+ const relative = withoutLocal(String$1.trim(path));
1418
+ if (base === ROOT) return relative;
1419
+ return `${base}${SEPARATOR$2}${relative}`;
1420
+ };
1421
+ const reference = (kind, field, base = ROOT) => ({ text, offset }) => {
1422
+ const path = String$1.trim(text);
1423
+ if (!isLiteralPath(path) || !isLiteralPath(base)) return [];
1424
+ return [{
1425
+ kind,
1426
+ field,
1427
+ path: joinPath(base, path),
1428
+ offset
1429
+ }];
1430
+ };
1431
+ const isPositive = ({ text }) => !String$1.startsWith(NEGATION)(String$1.trim(text));
1432
+ const globsIn = (field, node) => pipe(itemsOf(node), Array.flatMap((item) => Option.toArray(stringOf(item))), Array.filter(isPositive), Array.flatMap(reference("glob", field)));
1433
+ const filtersOf = ([event, filters]) => pipe(FILTER_KEYS, Array.flatMap((key) => globsIn(`on.${event}.${key}`, childOf(key)(filters))));
1434
+ const directoryOf$1 = (located, base) => pipe(located, Option.map(({ text }) => joinPath(ROOT, text)), Option.getOrElse(() => base));
1435
+ const located = (kind, field, base = ROOT) => (found) => pipe(found, Option.toArray, Array.flatMap(reference(kind, field, base)));
1436
+ const localUses = (node) => pipe(stringOf(childOf("uses")(node)), Option.filter(({ text }) => String$1.startsWith(LOCAL)(text)));
1437
+ const scriptsIn = (field, base) => ({ text, offset }) => pipe(String$1.split(text, TOKEN_SEPARATOR), Array.filter((token) => SCRIPT.test(token)), Array.dedupe, Array.flatMap((token) => reference("script", field, base)({
1438
+ text: token,
1439
+ offset
1440
+ })));
1441
+ const isFileInput = ([key]) => String$1.endsWith(FILE_INPUT_SUFFIX)(key) || key === DEPENDENCY_PATH_INPUT;
1442
+ const linesOf = ({ text, offset }) => pipe(String$1.split(text, LINE), Array.map((line) => ({
1443
+ text: line,
1444
+ offset
1445
+ })));
1446
+ const fileInputOf = (field) => ([key, value]) => pipe(stringOf(value), Option.toArray, Array.flatMap(linesOf), Array.flatMap(reference("glob", `${field}.with.${key}`)));
1447
+ const fileInputsIn = (field, step) => pipe(entriesOf(childOf("with")(step)), Array.filter(isFileInput), Array.flatMap(fileInputOf(field)));
1448
+ const stepReferences = (job, base) => (step, index) => {
1449
+ const field = `jobs.${job}.steps[${index}]`;
1450
+ const own = stringOf(childOf("working-directory")(step));
1451
+ const directory = directoryOf$1(own, base);
1452
+ return [
1453
+ ...located("action", `${field}.uses`)(localUses(step)),
1454
+ ...located("directory", `${field}.working-directory`)(own),
1455
+ ...pipe(stringOf(childOf("run")(step)), Option.toArray, Array.flatMap(scriptsIn(`${field}.run`, directory))),
1456
+ ...fileInputsIn(field, step)
1457
+ ];
1458
+ };
1459
+ const jobReferences = (base) => ([job, node]) => {
1460
+ const own = workingDirectoryOf(node);
1461
+ const steps = itemsOf(childOf("steps")(node));
1462
+ const directory = directoryOf$1(own, base);
1463
+ return [
1464
+ ...located("file", `jobs.${job}.uses`)(localUses(node)),
1465
+ ...located("directory", `jobs.${job}.defaults.run.working-directory`)(own),
1466
+ ...pipe(steps, Array.flatMap(stepReferences(job, directory)))
1467
+ ];
1468
+ };
1469
+ const groupsOf = (pattern, group) => ({ text, offset }) => pipe(Array.fromIterable(String$1.matchAll(pattern)(text)), Array.flatMap((match) => pipe(Option.fromNullishOr(match.groups), Option.flatMap((groups) => Option.fromNullishOr(groups[group])), Option.toArray)), Array.map((value) => ({
1470
+ text: value,
1471
+ offset
1472
+ })));
1473
+ const hashFilesIn = (source) => pipe(scalarsIn(source), Array.flatMap(groupsOf(HASH_FILES, "arguments")), Array.flatMap(groupsOf(QUOTED$1, "path")), Array.filter(isPositive), Array.flatMap(reference("glob", "hashFiles")));
1474
+ const jobsOf = (source) => entriesOf(childOf("jobs")(parseDocument(source).contents));
1475
+ /** @internal */
1476
+ const workflowReferences = (source) => {
1477
+ const root = parseDocument(source).contents;
1478
+ const workflowDefault = workingDirectoryOf(root);
1479
+ const base = directoryOf$1(workflowDefault, ROOT);
1480
+ return [
1481
+ ...pipe(entriesOf(childOf("on")(root)), Array.flatMap(filtersOf)),
1482
+ ...located("directory", "defaults.run.working-directory")(workflowDefault),
1483
+ ...pipe(jobsOf(source), Array.flatMap(jobReferences(base))),
1484
+ ...hashFilesIn(source)
1485
+ ];
1486
+ };
1487
+ const pathInputOf = (step) => childOf("path")(childOf("with")(step));
1488
+ const outputPathsOf = (step) => pipe(stringOf(pathInputOf(step)), Option.toArray, Array.flatMap(linesOf), Array.map(({ text }) => joinPath(ROOT, text)), Array.filter(isLiteralPath));
1489
+ /** @internal */
1490
+ const producedPaths = (source) => pipe(jobsOf(source), Array.flatMap(([, job]) => itemsOf(childOf("steps")(job))), Array.flatMap(outputPathsOf));
1491
+ // src/features/repository-layout/model/workflow-paths.ts
1492
+ const RULE$4 = "workflow-path";
1493
+ const WORKFLOW_DIRECTORY = ".github/workflows/";
1494
+ const WORKFLOW_EXTENSIONS = [".yml", ".yaml"];
1495
+ const READ_CONCURRENCY$5 = 8;
1496
+ const WILDCARD = /[*?[]/u;
1497
+ const SEPARATOR$1 = "/";
1498
+ const FIRST$1 = 0;
1499
+ const EXPECTED = {
1500
+ action: "a directory with action.yml",
1501
+ directory: "a directory",
1502
+ file: "a file",
1503
+ glob: "a pattern that matches a tracked file",
1504
+ script: "a file"
1505
+ };
1506
+ const isWorkflow = (file) => String$1.startsWith(WORKFLOW_DIRECTORY)(file) && pipe(WORKFLOW_EXTENSIONS, Array.some((extension) => String$1.endsWith(extension)(file)));
1507
+ const matchesAny = Effect.fn("matchesAny")(function* matchesAny(root, pathspecs) {
1508
+ const matched = yield* (yield* RepositoryFiles).matchingFiles(root, pathspecs);
1509
+ return Array.isReadonlyArrayNonEmpty(matched);
1510
+ });
1511
+ const existsAt = Effect.fn("existsAt")(function* existsAt(root, path) {
1512
+ const files = yield* RepositoryFiles;
1513
+ return yield* files.exists(files.join(root, path));
1514
+ });
1515
+ const matchesGlob = (root, path) => matchesAny(root, [`:(glob)${path}`]);
1516
+ const isDirectoryAt = Effect.fn("isDirectoryAt")(function* isDirectoryAt(root, path) {
1517
+ const files = yield* RepositoryFiles;
1518
+ const directory = yield* files.isDirectory(files.join(root, path));
1519
+ return Option.getOrElse(directory, () => false);
1520
+ });
1521
+ const hasAction = Effect.fn("hasAction")(function* hasAction(root, path) {
1522
+ const found = yield* pipe(ACTION_DEFINITIONS, Effect.forEach((name) => existsAt(root, `${path}${SEPARATOR$1}${name}`)));
1523
+ return pipe(found, Array.some(Boolean));
1524
+ });
1525
+ const suffixAt = (segments) => (index) => `:(glob)**/${pipe(segments, Array.drop(index), Array.join(SEPARATOR$1))}`;
1526
+ const RESOLVERS = {
1527
+ action: hasAction,
1528
+ directory: isDirectoryAt,
1529
+ file: existsAt,
1530
+ glob: matchesGlob,
1531
+ script: Effect.fn("findsScript")(function* findsScript(root, path) {
1532
+ if (yield* existsAt(root, path)) return true;
1533
+ const segments = String$1.split(path, SEPARATOR$1);
1534
+ return yield* matchesAny(root, Array.makeBy(segments.length, suffixAt(segments)));
1535
+ })
1536
+ };
1537
+ const staticPrefix = (path) => {
1538
+ const prefix = Array.headNonEmpty(String$1.split(path, WILDCARD));
1539
+ if (String$1.endsWith(SEPARATOR$1)(prefix)) return String$1.slice(FIRST$1, -1)(prefix);
1540
+ return prefix;
1541
+ };
1542
+ const isIgnored$1 = Effect.fn("isIgnored")(function* isIgnored(root, path) {
1543
+ const prefix = staticPrefix(path);
1544
+ if (String$1.isEmpty(prefix)) return false;
1545
+ const ignored = yield* (yield* RepositoryFiles).ignoredPaths(root, [prefix]);
1546
+ return Array.isReadonlyArrayNonEmpty(ignored);
1547
+ });
1548
+ const overlaps = (path) => (produced) => produced === path || String$1.startsWith(`${path}${SEPARATOR$1}`)(produced) || String$1.startsWith(`${produced}${SEPARATOR$1}`)(path);
1549
+ const isMissing = Effect.fn("isMissing")(function* isMissing(root, produced, found) {
1550
+ const prefix = staticPrefix(found.path);
1551
+ if (pipe(produced, Array.some(overlaps(prefix)))) return false;
1552
+ if (yield* RESOLVERS[found.kind](root, found.path)) return false;
1553
+ return !(yield* isIgnored$1(root, found.path));
1554
+ });
1555
+ const problemOf$2 = (file, source) => (found) => ({
1556
+ file,
1557
+ ...positionOf(source)(found.offset),
1558
+ rule: RULE$4,
1559
+ message: `${found.field} names ${found.path}, which is not ${EXPECTED[found.kind]} in this repository. Point it at a path that exists or remove it.`
1560
+ });
1561
+ const problemsIn$2 = Effect.fn("problemsIn")(function* problemsIn(root, workflow) {
1562
+ const files = yield* RepositoryFiles;
1563
+ const file = files.join(root, workflow);
1564
+ const source = yield* files.readFile(file);
1565
+ if (Option.isNone(source)) return [];
1566
+ const produced = producedPaths(source.value);
1567
+ const missing = yield* Effect.filter(workflowReferences(source.value), (found) => isMissing(root, produced, found));
1568
+ return pipe(missing, Array.map(problemOf$2(file, source.value)));
1569
+ });
1570
+ /** @internal */
1571
+ const checkWorkflowPaths = Effect.fn("checkWorkflowPaths")(function* checkWorkflowPaths(root) {
1572
+ const listed = yield* (yield* RepositoryFiles).listedFiles(root);
1573
+ const found = yield* Effect.forEach(pipe(listed, Array.filter(isWorkflow)), (workflow) => problemsIn$2(root, workflow), { concurrency: READ_CONCURRENCY$5 });
1574
+ return Array.flatten(found);
1575
+ });
1576
+ // src/features/repository-layout/model/workspace-checks.ts
1577
+ /** @internal */
1578
+ const checkWorkspaces = Effect.fn("checkWorkspaces")(function* checkWorkspaces(root) {
1579
+ const found = yield* Effect.all([
1580
+ checkCrates(root),
1581
+ checkHiddenVerify(root),
1582
+ checkRootWorkspacePaths(root),
1583
+ checkSharedUncachedTasks(root),
1584
+ checkWorkflowPaths(root)
1585
+ ], { concurrency: "unbounded" });
1586
+ return Array.flatten(found);
1587
+ });
1588
+ // src/features/scripts/model/shell-scripts.ts
1589
+ const SHELL_FILE = /\.(?:sh|bash|zsh|ksh|fish|command)$/u;
1590
+ const SHELL_SHEBANG = /^#!\S*(?:\/|\s)(?:env\s+)?(?:-\S+\s+)*(?:ba|z|k|da)?sh\b|^#!\S*fish\b/u;
1591
+ const EXTENSION = /\.[^./]+$/u;
1592
+ const SETTINGS_FILE = ".claude/settings.json";
1593
+ const READ_CONCURRENCY$4 = 64;
1594
+ const FIRST = 1;
1595
+ const RULE$3 = "shell-script";
1596
+ const MESSAGE$2 = "is a shell script. Do the work in TypeScript as a Vite+ task in vite.config.ts, a test, or the tool's own hook, and delete this file. Only the SessionStart hook in .claude/settings.json, which installs the toolchain before TypeScript can run, stays a shell script.";
1597
+ const HookSchema = Schema.Struct({
1598
+ command: Schema.optional(Schema.String),
1599
+ args: Schema.optional(Schema.Array(Schema.String))
1600
+ });
1601
+ const MatcherSchema = Schema.Struct({ hooks: Schema.Array(HookSchema) });
1602
+ const HooksSchema = Schema.Struct({ SessionStart: Schema.optional(Schema.Array(MatcherSchema)) });
1603
+ const SettingsSchema = Schema.Struct({ hooks: Schema.optional(HooksSchema) });
1604
+ const decodeSettings = Schema.decodeOption(Schema.fromJsonString(SettingsSchema));
1605
+ const NO_TEXT = [];
1606
+ const commandText = ({ command, args }) => [...Option.toArray(Option.fromUndefinedOr(command)), ...pipe(Option.fromUndefinedOr(args), Option.getOrElse(() => NO_TEXT))];
1607
+ const matcherText = ({ hooks }) => pipe(hooks, Array.flatMap((hook) => commandText(hook)));
1608
+ const sessionStartCommands = (source) => {
1609
+ const matchers = pipe(decodeSettings(source), Option.flatMap(({ hooks }) => Option.fromUndefinedOr(hooks)), Option.flatMap(({ SessionStart }) => Option.fromUndefinedOr(SessionStart)));
1610
+ return pipe(matchers, Option.map(Array.flatMap((matcher) => matcherText(matcher))), Option.getOrElse(() => NO_TEXT));
1611
+ };
1612
+ const baseName = (name) => pipe(String$1.split("/")(name), Array.last, Option.getOrElse(() => name));
1613
+ const hasExtension = (name) => EXTENSION.test(baseName(name));
1614
+ const startsWithShellShebang = (source) => SHELL_SHEBANG.test(source);
1615
+ const problemFor = (file) => ({
1616
+ file,
1617
+ line: FIRST,
1618
+ column: FIRST,
1619
+ rule: RULE$3,
1620
+ message: MESSAGE$2
1621
+ });
1622
+ /** @internal */
1623
+ const checkShellScripts = Effect.fn("checkShellScripts")(function* checkShellScripts(root) {
1624
+ const files = yield* RepositoryFiles;
1625
+ const names = yield* files.listedFiles(root);
1626
+ const settings = yield* files.readFile(files.join(root, SETTINGS_FILE));
1627
+ const commands = pipe(settings, Option.map(sessionStartCommands), Option.getOrElse(() => NO_TEXT));
1628
+ const isSessionStartHook = (name) => pipe(commands, Array.some(String$1.includes(name)));
1629
+ const isShell = (name) => {
1630
+ const file = files.join(root, name);
1631
+ if (SHELL_FILE.test(name)) return files.exists(file);
1632
+ if (hasExtension(name)) return Effect.succeed(false);
1633
+ return files.readFile(file).pipe(Effect.map(Option.exists(startsWithShellShebang)));
1634
+ };
1635
+ const candidates = pipe(names, Array.filter((name) => !isSessionStartHook(name)));
1636
+ const shell = yield* Effect.filter(candidates, isShell, { concurrency: READ_CONCURRENCY$4 });
1637
+ return pipe(shell, Array.map((name) => problemFor(files.join(root, name))));
1638
+ });
1639
+ // src/features/scripts/model/workflows.ts
1640
+ const WORKFLOW_FILE = /^\.github\/workflows\/[^/]+\.ya?ml$/u;
1641
+ const COMMAND_CHAIN = /&&|\|\||;|\|/u;
1642
+ const QUOTED = /\$\{\{.*?\}\}|"(?:[^"\\]|\\.)*"|'[^']*'/gu;
1643
+ const COMMENT = "#";
1644
+ const RUN_KEY = "run";
1645
+ const RULE$2 = "workflow-script";
1646
+ const READ_CONCURRENCY$3 = 16;
1647
+ const START$4 = 0;
1648
+ const ONE_COMMAND = 1;
1649
+ const MESSAGE$1 = "runs more than one command. Keep a step to one command, `vp run <task>` or `vp exec <bin>`, and put the logic in a Vite+ task in TypeScript.";
1650
+ const startOf = (range) => pipe(Option.fromNullishOr(range), Option.map(([start]) => start), Option.getOrElse(() => START$4));
1651
+ const runScriptsOf = (source) => {
1652
+ const found = [];
1653
+ visit(parseDocument(source), { Pair: (_key, pair) => {
1654
+ if (isPair(pair) && isScalar(pair.key) && pair.key.value === RUN_KEY && isScalar(pair.value) && typeof pair.value.value === "string") found.push({
1655
+ text: pair.value.value,
1656
+ start: startOf(pair.value.range)
1657
+ });
1658
+ } });
1659
+ return found;
1660
+ };
1661
+ const isCommand = (line) => String$1.isNonEmpty(line) && !String$1.startsWith(COMMENT)(line);
1662
+ const chainsCommands = (line) => COMMAND_CHAIN.test(String$1.replaceAll(QUOTED, "")(line));
1663
+ const runsMoreThanOneCommand = ({ text }) => {
1664
+ const lines = pipe(String$1.split("\n")(text), Array.map(String$1.trim), Array.filter(isCommand));
1665
+ return lines.length > ONE_COMMAND || pipe(lines, Array.some(chainsCommands));
1666
+ };
1667
+ const problemsIn$1 = (file) => (source) => {
1668
+ const at = positionOf(source);
1669
+ return pipe(runScriptsOf(source), Array.filter(runsMoreThanOneCommand), Array.map(({ start }) => ({
1670
+ file,
1671
+ ...at(start),
1672
+ rule: RULE$2,
1673
+ message: MESSAGE$1
1674
+ })));
1675
+ };
1676
+ /** @internal */
1677
+ const checkWorkflows = Effect.fn("checkWorkflows")(function* checkWorkflows(root) {
1678
+ const files = yield* RepositoryFiles;
1679
+ const names = yield* files.listedFiles(root);
1680
+ const workflows = pipe(names, Array.filter((name) => WORKFLOW_FILE.test(name)));
1681
+ const found = yield* Effect.forEach(workflows, (name) => {
1682
+ const file = files.join(root, name);
1683
+ return files.readFile(file).pipe(Effect.map((text) => pipe(text, Option.map(problemsIn$1(file)), Option.getOrElse(() => []))));
1684
+ }, { concurrency: READ_CONCURRENCY$3 });
1685
+ return Array.flatten(found);
1686
+ });
1687
+ // src/features/scripts/model/script-checks.ts
1688
+ /** @internal */
1689
+ const checkScripts = Effect.fn("checkScripts")(function* checkScripts(root) {
1690
+ const found = yield* Effect.all([checkShellScripts(root), checkWorkflows(root)], { concurrency: "unbounded" });
1691
+ return Array.flatten(found);
1692
+ });
1693
+ // src/features/value-owners/model/slots.ts
1694
+ const ANNOTATED_KINDS = /* @__PURE__ */ new Set([
1695
+ SyntaxKind.Parameter,
1696
+ SyntaxKind.VariableDeclaration,
1697
+ SyntaxKind.PropertySignature,
1698
+ SyntaxKind.PropertyDeclaration
1699
+ ]);
1700
+ const isAnnotated = (declaration) => ANNOTATED_KINDS.has(declaration.kind);
1701
+ const annotationOf = (declaration) => Option.liftPredicate(declaration, isAnnotated).pipe(Option.flatMap((annotated) => Option.fromUndefinedOr(annotated.type)));
1702
+ const argumentSlot = (checker) => (expression) => {
1703
+ const call = expression.parent;
1704
+ if (!isCallExpression(call) && !isNewExpression(call)) return Option.none();
1705
+ const { arguments: listed } = call;
1706
+ const index = (listed ?? []).indexOf(expression);
1707
+ return Option.fromUndefinedOr(checker.getResolvedSignature(call).declaration).pipe(Option.flatMap((handle) => Option.fromUndefinedOr(handle.resolve())), Option.filter(isSignatureDeclaration), Option.flatMap((declaration) => Array.get(declaration.parameters, index)));
1708
+ };
1709
+ const propertySlot = (checker) => (expression) => {
1710
+ const assignment = expression.parent;
1711
+ if (!isPropertyAssignment(assignment) || !isObjectLiteralExpression(assignment.parent)) return Option.none();
1712
+ return Option.fromUndefinedOr(checker.getContextualType(assignment.parent)).pipe(Option.flatMap((objectType) => Option.fromUndefinedOr(objectType.getProperty(assignment.name.getText()))), Option.flatMap((property) => Array.head(declarationsOf(property))));
1713
+ };
1714
+ const variableSlot = (expression) => {
1715
+ const declaration = expression.parent;
1716
+ if (!isVariableDeclaration(declaration) || declaration.initializer !== expression) return Option.none();
1717
+ return Option.some(declaration);
1718
+ };
1719
+ const slotOf = (checker) => (expression) => argumentSlot(checker)(expression).pipe(Option.orElse(() => propertySlot(checker)(expression)), Option.orElse(() => variableSlot(expression)));
1720
+ const contextSymbolsOf = (checker) => (expression) => {
1721
+ const alias = Option.fromUndefinedOr(checker.getContextualType(expression)).pipe(Option.flatMap((contextual) => Option.fromUndefinedOr(contextual.getAliasSymbol())));
1722
+ if (Option.isSome(alias)) return [alias.value];
1723
+ return slotOf(checker)(expression).pipe(Option.flatMap(annotationOf), Option.map((annotation) => referencedSymbols(checker)(annotation)), Option.getOrElse(() => []));
1724
+ };
1725
+ // src/features/value-owners/model/flows.ts
1726
+ const SCOPE_PREFIX = "@";
1727
+ const SCOPED_SEGMENTS = 2;
1728
+ const UNSCOPED_SEGMENTS = 1;
1729
+ const MODULE_PREFIX = /^".*?"\./u;
1730
+ const packageOf = (fileName) => {
1731
+ const afterModules = pipe(fileName, String$1.lastIndexOf(NODE_MODULES_SEGMENT), Option.match({
1732
+ onNone: () => fileName,
1733
+ onSome: (index) => String$1.slice(index + NODE_MODULES_SEGMENT.length)(fileName)
1734
+ }));
1735
+ const segments = String$1.split("/")(afterModules);
1736
+ if (String$1.startsWith(SCOPE_PREFIX)(afterModules)) return pipe(Array.take(segments, SCOPED_SEGMENTS), Array.join("/"));
1737
+ return pipe(Array.take(segments, UNSCOPED_SEGMENTS), Array.join("/"));
1738
+ };
1739
+ const externalDeclarationOf = (context) => (symbol) => Array.findFirst(declarationsOf(symbol), (declaration) => isExternalDeclaration(context.program)(declaration));
1740
+ const aliasTarget = (context) => (type) => Option.fromUndefinedOr(type.getAliasSymbol()).pipe(Option.flatMap((alias) => externalDeclarationOf(context)(alias).pipe(Option.map((declaration) => `${String$1.replace(MODULE_PREFIX, "")(context.checker.getFullyQualifiedName(alias))} from ${packageOf(declaration.getSourceFile().fileName)}`))));
1741
+ const isNamedContainer = (node) => isSignatureDeclaration(node) || isInterfaceDeclaration(node) || isClassDeclaration(node);
1742
+ const slotTarget = (context) => (expression) => slotOf(context.checker)(expression).pipe(Option.filter((slot) => isExternalDeclaration(context.program)(slot)), Option.filter((slot) => Option.isSome(vocabularyOf(context.checker)(context.checker.getTypeAtLocation(slot)))), Option.map((slot) => {
1743
+ const owner = Option.liftPredicate(slot.parent, isNamedContainer).pipe(Option.flatMap((container) => Option.fromUndefinedOr(getNameOfDeclaration(container))), Option.map((name) => ` of ${name.getText()}`), Option.getOrElse(() => ""));
1744
+ return `${Option.fromUndefinedOr(getNameOfDeclaration(slot)).pipe(Option.map((found) => found.getText()), Option.getOrElse(() => "value"))}${owner} from ${packageOf(slot.getSourceFile().fileName)}`;
1745
+ }));
1746
+ const libraryTargetOf = (context) => (expression, contextual) => aliasTarget(context)(contextual).pipe(Option.orElse(() => slotTarget(context)(expression)));
1747
+ const siteWithin = (context) => (node) => Array.findFirst(context.sites, (site) => contains(node)(site.node));
1748
+ const aliasSite = (context) => (type) => Option.fromUndefinedOr(type.getAliasSymbol()).pipe(Option.flatMap((alias) => Array.findFirst(declarationsOf(alias), isTypeAliasDeclaration)), Option.flatMap(siteWithin(context)));
1749
+ const annotationSite = (context) => (expression) => symbolAt(context.checker)(expression).pipe(Option.flatMap((symbol) => Option.fromUndefinedOr(symbol.valueDeclaration)), Option.flatMap((handle) => Option.fromUndefinedOr(handle.resolve())), Option.flatMap(annotationOf), Option.flatMap((annotation) => siteWithin(context)(annotation).pipe(Option.orElse(() => aliasSite(context)(context.checker.getTypeFromTypeNode(annotation))))));
1750
+ const siteBehind = (context) => (expression) => aliasSite(context)(context.checker.getTypeAtLocation(expression)).pipe(Option.orElse(() => annotationSite(context)(expression)));
1751
+ const isFlowSource = (node) => isIdentifier(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node);
1752
+ const flowOf = (context) => (expression) => Option.fromUndefinedOr(context.checker.getContextualType(expression)).pipe(Option.flatMap((contextual) => Option.all([vocabularyOf(context.checker)(contextual), libraryTargetOf(context)(expression, contextual)])), Option.flatMap(([vocabulary, target]) => siteBehind(context)(expression).pipe(Option.filter((site) => isSubsetOf(site.values, vocabulary.values)), Option.map((site) => ({
1753
+ site,
1754
+ target
1755
+ })))));
1756
+ const flowsIn = (context) => (sourceFile) => Array.getSomes(pipe(descendantsOf(sourceFile), Array.filter((node) => isFlowSource(node)), Array.map((node) => flowOf(context)(node))));
1757
+ // src/features/value-owners/model/owners.ts
1758
+ const OWNER_TAG = "msch";
1759
+ const FIRST_OWNER_COUNT = 1;
1760
+ const ownerKeyOf = (declaration) => {
1761
+ if (!isVariableDeclaration(declaration) || !isIdentifier(declaration.name)) return Option.none();
1762
+ return Option.some(`${declaration.getSourceFile().fileName}#${declaration.name.text}`);
1763
+ };
1764
+ const annotationsOf = (node) => pipe(getJSDocTags(node), Array.filter((tag) => tag.tagName.text === OWNER_TAG), Array.map((tag) => ({
1765
+ node,
1766
+ conceptId: String$1.trim(getTextOfJSDocComment(tag.comment) ?? "")
1767
+ })));
1768
+ const ANNOTATABLE_KINDS = /* @__PURE__ */ new Set([
1769
+ SyntaxKind.VariableDeclaration,
1770
+ SyntaxKind.FunctionDeclaration,
1771
+ SyntaxKind.ClassDeclaration,
1772
+ SyntaxKind.InterfaceDeclaration,
1773
+ SyntaxKind.TypeAliasDeclaration,
1774
+ SyntaxKind.EnumDeclaration,
1775
+ SyntaxKind.PropertySignature,
1776
+ SyntaxKind.PropertyAssignment,
1777
+ SyntaxKind.PropertyDeclaration
1778
+ ]);
1779
+ const isAnnotatable = (node) => ANNOTATABLE_KINDS.has(node.kind);
1780
+ const isConstList = (list) => Option.fromUndefinedOr(list.getFirstToken()).pipe(Option.exists((token) => token.kind === SyntaxKind.ConstKeyword));
1781
+ const isModuleStatementList = (list) => isVariableStatement(list.parent) && isSourceFile(list.parent.parent);
1782
+ const isModuleConstList = (node) => isVariableDeclarationList(node) && isModuleStatementList(node) && isConstList(node);
1783
+ const isModuleConst = (node) => isVariableDeclaration(node) && isIdentifier(node.name) && isModuleConstList(node.parent);
1784
+ const objectValuesOf = (checker) => (type) => literalValuesOf(pipe(checker.getPropertiesOfType(type), Array.map((property) => checker.getTypeOfSymbol(property))));
1785
+ const ownerValuesOf = (checker) => (declaration) => {
1786
+ const type = checker.getTypeAtLocation(declaration.name);
1787
+ return finiteValuesOf(checker)(type).pipe(Option.orElse(() => objectValuesOf(checker)(type)));
1788
+ };
1789
+ const annotationProblem = (message) => problemAt({
1790
+ rule: "owner-annotation",
1791
+ message
1792
+ });
1793
+ const scanned = (owners, problems) => ({
1794
+ owners,
1795
+ problems
1796
+ });
1797
+ const ownerOf = (project) => (annotated) => {
1798
+ const { node, conceptId } = annotated;
1799
+ if (!isModuleConst(node)) return scanned([], [annotationProblem(`@${OWNER_TAG} registers an owner only on a module-scope const.`)(node)]);
1800
+ if (conceptId === "") return scanned([], [annotationProblem(`@${OWNER_TAG} needs a concept id.`)(node)]);
1801
+ const values = ownerValuesOf(project.checker)(node);
1802
+ return Option.match(Option.all([values, ownerKeyOf(node)]), {
1803
+ onNone: () => scanned([], [annotationProblem(`The owner of ${conceptId} holds no finite value set.`)(node)]),
1804
+ onSome: ([ownedValues, key]) => scanned([{
1805
+ conceptId,
1806
+ key,
1807
+ name: node.name.getText(),
1808
+ file: node.getSourceFile().fileName,
1809
+ line: lineOf(node),
1810
+ column: columnOf(node),
1811
+ packageName: project.packageName,
1812
+ values: ownedValues
1813
+ }], [])
1814
+ });
1815
+ };
1816
+ const annotatedIn = (sourceFile) => pipe(descendantsOf(sourceFile), Array.filter((node) => isAnnotatable(node)), Array.flatMap((node) => annotationsOf(node)));
1817
+ const ownerProblem = (message) => (owner) => ({
1818
+ file: owner.file,
1819
+ line: owner.line,
1820
+ column: owner.column,
1821
+ rule: "owner-annotation",
1822
+ message
1823
+ });
1824
+ const conflictProblems = (owners) => pipe(owners, Array.flatMap((owner, index) => {
1825
+ const earlier = Array.take(owners, index);
1826
+ const sameConcept = pipe(earlier, Array.filter((other) => other.conceptId === owner.conceptId));
1827
+ const sameSet = pipe(earlier, Array.filter((other) => other.conceptId !== owner.conceptId && sameValues(other.values, owner.values)));
1828
+ return [...pipe(Array.take(sameConcept, FIRST_OWNER_COUNT), Array.map(() => ownerProblem(`The concept ${owner.conceptId} already has an owner.`)(owner))), ...pipe(Array.take(sameSet, FIRST_OWNER_COUNT), Array.map((other) => ownerProblem(`The values ${formatValues(owner.values)} are already owned by ${other.conceptId}.`)(owner)))];
1829
+ }));
1830
+ const ownersIn = (project) => {
1831
+ const results = pipe(project.sourceFiles, Array.flatMap((sourceFile) => pipe(annotatedIn(sourceFile), Array.map((annotated) => ownerOf(project)(annotated)))));
1832
+ return scanned(pipe(results, Array.flatMap((result) => result.owners)), pipe(results, Array.flatMap((result) => result.problems)));
1833
+ };
1834
+ const combineOwnerScans = (scans) => {
1835
+ const owners = Array.dedupeWith(pipe(scans, Array.flatMap((scan) => scan.owners)), (left, right) => left.key === right.key);
1836
+ return {
1837
+ owners,
1838
+ problems: [...pipe(scans, Array.flatMap((scan) => scan.problems)), ...conflictProblems(owners)]
1839
+ };
1840
+ };
1841
+ // src/features/value-owners/model/derivation.ts
1842
+ const contractOf = (node) => {
1843
+ const { parent } = node;
1844
+ if (isSatisfiesExpression(parent) && parent.expression === node) return [parent.type];
1845
+ if (isVariableDeclaration(parent) && parent.initializer === node) return Option.toArray(Option.fromUndefinedOr(parent.type));
1846
+ return [];
1847
+ };
1848
+ const derivedDeclarationsOf = (checker) => (node) => {
1849
+ const scopes = Array.prepend(contractOf(node), node);
1850
+ return new Set(pipe(scopes, Array.flatMap((scope) => referencedSymbols(checker)(scope)), Array.flatMap((symbol) => declarationsOf(symbol)), Array.map((declaration) => declarationKey(locationOf(declaration)))));
1851
+ };
1852
+ // src/features/value-owners/model/shapes.ts
1853
+ const MINIMUM_SHAPE_PROPERTIES = 3;
1854
+ const EXACT = 0;
1855
+ const augmentsAModule = (node) => {
1856
+ const block = node.parent;
1857
+ return isModuleBlock(block) && isModuleDeclaration(block.parent) && isStringLiteral(block.parent.name);
1858
+ };
1859
+ const isPlainInterface = (node) => isInterfaceDeclaration(node) && !isGenericDeclaration(node) && !augmentsAModule(node);
1860
+ const isPlainTypeLiteral = (node) => isTypeAliasDeclaration(node) && !isGenericDeclaration(node) && isTypeLiteralNode(node.type);
1861
+ const isDeclaredShape = (node) => isPlainInterface(node) || isPlainTypeLiteral(node);
1862
+ const declaredShapeOf = (checker) => (node) => Option.liftPredicate(node, isDeclaredShape).pipe(Option.map((declaration) => checker.getTypeAtLocation(declaration.name)));
1863
+ const schemaShapeOf = (checker) => (node) => {
1864
+ if (!isCallExpression(node)) return Option.none();
1865
+ const { arguments: callArguments } = node;
1866
+ if (!pipe(callArguments, Array.some((argument) => isObjectLiteralExpression(argument)))) return Option.none();
1867
+ return schemaTypeOf(checker)(checker.getTypeAtLocation(node)).pipe(Option.filter((type) => isObjectType(checker)(type)));
1868
+ };
1869
+ const shapeSitesIn = (checker) => (sourceFile) => Array.getSomes(pipe(descendantsOf(sourceFile), Array.map((node) => declaredShapeOf(checker)(node).pipe(Option.orElse(() => schemaShapeOf(checker)(node)), Option.map((type) => ({
1870
+ node,
1871
+ type
1872
+ }))))));
1873
+ const openTypeIdsOf = (checker) => ({
1874
+ any: checker.getAnyType().id,
1875
+ unknown: checker.getUnknownType().id
1876
+ });
1877
+ const isIndexedDeclaration = (node) => isTypeDeclaration(node) || isVariableDeclaration(node);
1878
+ const declarationAt = (program) => (location) => Option.fromUndefinedOr(program.getSourceFile(location.file)).pipe(Option.flatMap((sourceFile) => Array.findFirst(descendantsOf(sourceFile), (node) => node.pos === location.pos && node.kind === location.kind && isIndexedDeclaration(node))));
1879
+ const symbolOfDeclaration = (checker) => (declaration) => Option.fromUndefinedOr(checker.getSymbolAtLocation(declaration.name));
1880
+ const shapeTypeOf = (context) => (shape) => {
1881
+ const { checker } = context;
1882
+ return declarationAt(context.program)(shape.declaration).pipe(Option.flatMap((declaration) => symbolOfDeclaration(checker)(declaration).pipe(Option.flatMap((symbol) => {
1883
+ if (shape.form === "declared") return Option.some(checker.getDeclaredTypeOfSymbol(symbol));
1884
+ return schemaTypeOf(checker)(checker.getTypeOfSymbolAtLocation(symbol, declaration));
1885
+ }))));
1886
+ };
1887
+ const hasEveryName = (locals) => (shape) => {
1888
+ const names = new Set(shape.propertyNames);
1889
+ return pipe(locals, Array.every((local) => names.has(local.name)));
1890
+ };
1891
+ const sameProperty = (checker, open) => (localType, library) => {
1892
+ const libraryType = checker.getTypeOfSymbol(library);
1893
+ return libraryType.id !== open.any && libraryType.id !== open.unknown && checker.isTypeAssignableTo(localType, libraryType) && checker.isTypeAssignableTo(libraryType, localType);
1894
+ };
1895
+ const matchOf = (context, open) => (locals, shape) => {
1896
+ const { checker } = context;
1897
+ if (!shapeTypeOf(context)(shape).pipe(Option.exists((shapeType) => pipe(locals, Array.every((local) => Option.fromUndefinedOr(checker.getPropertyOfType(shapeType, local.name)).pipe(Option.exists((library) => sameProperty(checker, open)(local.type, library)))))))) return Option.none();
1898
+ return Option.some({
1899
+ shape,
1900
+ extra: shape.propertyNames.length - locals.length
1901
+ });
1902
+ };
1903
+ const localPropertiesOf = (checker) => (symbols) => pipe(Array.zip(symbols, checker.getTypeOfSymbol(symbols)), Array.map(([symbol, type]) => ({
1904
+ name: symbol.name,
1905
+ type
1906
+ })));
1907
+ const matchOrder = Order.mapInput(Order.Number, (match) => match.extra);
1908
+ const shapeProblem = (site, matches) => {
1909
+ const shown = pipe(Array.take(matches, 3), Array.map((match) => describeLibraryType(match.shape)), Array.join(", "));
1910
+ const advice = Option.match(Array.findFirst(matches, (match) => match.extra === EXACT), {
1911
+ onNone: () => "Derive it from the library type, for example with Pick, instead of copying its properties.",
1912
+ onSome: () => "Use the library type instead of copying it."
1913
+ });
1914
+ return problemAt({
1915
+ rule: "library-shape",
1916
+ message: `This shape copies ${shown}. ${advice}`
1917
+ })(site.node);
1918
+ };
1919
+ const candidatesOf = (context, open) => (site, locals) => {
1920
+ const derived = derivedDeclarationsOf(context.checker)(site.node);
1921
+ const named = pipe(context.shapes, Array.filter(hasEveryName(locals)));
1922
+ if (pipe(named, Array.some((shape) => derived.has(declarationKey(shape.declaration))))) return [];
1923
+ const candidates = pipe(named, Array.map((shape) => matchOf(context, open)(locals, shape)), Array.getSomes);
1924
+ return Array.sort(candidates, matchOrder);
1925
+ };
1926
+ const shapeProblemOf = (context, open) => (site) => {
1927
+ const symbols = context.checker.getPropertiesOfType(site.type);
1928
+ if (symbols.length < MINIMUM_SHAPE_PROPERTIES) return Option.none();
1929
+ const locals = localPropertiesOf(context.checker)(symbols);
1930
+ return Option.liftPredicate(candidatesOf(context, open)(site, locals), Array.isReadonlyArrayNonEmpty).pipe(Option.map((found) => shapeProblem(site, found)));
1931
+ };
1932
+ const shapeProblemsIn = (context) => (sourceFile) => {
1933
+ const sites = shapeSitesIn(context.checker)(sourceFile);
1934
+ if (!Array.isReadonlyArrayNonEmpty(sites)) return [];
1935
+ const open = openTypeIdsOf(context.checker);
1936
+ return Array.getSomes(pipe(sites, Array.map((site) => shapeProblemOf(context, open)(site))));
1937
+ };
1938
+ // src/features/value-owners/model/sites.ts
1939
+ const namedValuesOf = (checker) => (symbol) => {
1940
+ if (pipe(declarationsOf(symbol), Array.some((declaration) => isTypeDeclaration(declaration)))) return finiteValuesOf(checker)(checker.getDeclaredTypeOfSymbol(symbol));
1941
+ return finiteValuesOf(checker)(checker.getTypeOfSymbol(symbol));
1942
+ };
1943
+ const hasFiniteContext = (checker) => (node) => Option.fromUndefinedOr(checker.getContextualType(node)).pipe(Option.flatMap(finiteValuesOf(checker)), Option.isSome);
1944
+ const isNamedValue = (element) => {
1945
+ if (isSpreadElement(element)) return isNamedValue(element.expression);
1946
+ return isIdentifier(element) || isPropertyAccessExpression(element) || isElementAccessExpression(element);
1947
+ };
1948
+ const namesEveryElement = (array) => pipe(array.elements, Array.every((element) => isNamedValue(element)));
1949
+ const expressionValuesOf = (checker) => (node) => {
1950
+ if (hasFiniteContext(checker)(node)) return Option.none();
1951
+ const type = checker.getTypeAtLocation(node);
1952
+ if (isArrayLiteralExpression(node)) return Option.liftPredicate(node, (array) => !namesEveryElement(array)).pipe(Option.flatMap(() => finiteValuesOf(checker)(type)));
1953
+ return schemaTypeOf(checker)(type).pipe(Option.flatMap(literalUnionOf));
1954
+ };
1955
+ const selectsKeys = (checker) => (node, values) => {
1956
+ const { parent } = node;
1957
+ if (!isTypeReferenceNode(parent)) return false;
1958
+ const typeArguments = parent.typeArguments ?? [];
1959
+ return pipe(typeArguments, Array.filter((argument) => argument !== node), Array.some((argument) => isSubsetOf(values, propertyNamesOf(checker)(checker.getTypeFromTypeNode(argument)))));
1960
+ };
1961
+ const unionValuesOf = (checker) => (node) => literalUnionOf(checker.getTypeFromTypeNode(node)).pipe(Option.filter((values) => !selectsKeys(checker)(node, values)));
1962
+ const isExpressionSite = (node) => isArrayLiteralExpression(node) || isCallExpression(node);
1963
+ const expressionSiteValuesOf = (checker) => (node) => Option.liftPredicate(node, isExpressionSite).pipe(Option.flatMap(expressionValuesOf(checker)));
1964
+ const siteValuesOf = (checker) => (node) => {
1965
+ if (isUnionTypeNode(node)) return unionValuesOf(checker)(node);
1966
+ if (isEnumDeclaration(node)) return literalUnionOf(checker.getTypeAtLocation(node.name));
1967
+ return expressionSiteValuesOf(checker)(node);
1968
+ };
1969
+ const derivationScopeOf = (node) => {
1970
+ if (isTypeReferenceNode(node.parent)) return node.parent;
1971
+ return node;
1972
+ };
1973
+ const sourcesOf = (checker) => (node) => pipe(referencedSymbols(checker)(derivationScopeOf(node)), Array.filter((symbol) => Option.isSome(namedValuesOf(checker)(symbol))));
1974
+ const sitesUnder = (checker) => (node) => {
1975
+ const nested = pipe(childrenOf$2(node), Array.flatMap((child) => sitesUnder(checker)(child)));
1976
+ if (Array.isReadonlyArrayNonEmpty(nested)) return nested;
1977
+ return siteValuesOf(checker)(node).pipe(Option.map((values) => ({
1978
+ node,
1979
+ values,
1980
+ sources: sourcesOf(checker)(node)
1981
+ })), Option.toArray);
1982
+ };
1983
+ // src/features/value-owners/model/value-checks.ts
1984
+ const OWNER_SEARCH_DEPTH = 4;
1985
+ const NOTHING_HIDDEN = 0;
1986
+ const directOwners = (context) => (symbol) => {
1987
+ const keys = Array.getSomes(pipe(declarationsOf(symbol), Array.map((declaration) => ownerKeyOf(declaration))));
1988
+ return pipe(context.owners, Array.filter((owner) => keys.includes(owner.key)));
1989
+ };
1990
+ const isFollowable = (declaration) => !declaration.getSourceFile().isDeclarationFile && (isTypeAliasDeclaration(declaration) || isVariableDeclaration(declaration));
1991
+ const ownersBehind = (context) => (symbol, ancestors) => {
1992
+ const direct = directOwners(context)(symbol);
1993
+ if (Array.isReadonlyArrayNonEmpty(direct) || ancestors.length >= OWNER_SEARCH_DEPTH) return direct;
1994
+ const visited = [...ancestors, symbol];
1995
+ return uniqueByReference(pipe(declarationsOf(symbol), Array.filter((declaration) => isFollowable(declaration)), Array.flatMap((declaration) => referencedSymbols(context.checker)(declaration)), Array.filter((referenced) => !visited.includes(referenced)), Array.flatMap((referenced) => ownersBehind(context)(referenced, visited))));
1996
+ };
1997
+ const describeOwners = (owners) => pipe(owners, Array.map((owner) => `${owner.conceptId} (${owner.name})`), Array.join(", "));
1998
+ const verdict = (problems, unowned) => ({
1999
+ problems,
2000
+ unowned
2001
+ });
2002
+ const derivedVerdict = (context) => (site) => {
2003
+ const owners = uniqueByReference(pipe(site.sources, Array.flatMap((source) => ownersBehind(context)(source, []))));
2004
+ const held = pipe(owners, Array.flatMap((owner) => owner.values));
2005
+ const added = pipe(site.values, Array.filter((value) => !isSubsetOf([value], held)));
2006
+ if (!Array.isReadonlyArrayNonEmpty(owners) || !Array.isReadonlyArrayNonEmpty(added)) return verdict([], []);
2007
+ const message = `This set adds ${formatValues(added)} to ${describeOwners(owners)}. Add the values to the owner, or register the wider set as its own concept.`;
2008
+ return verdict([problemAt({
2009
+ rule: "owner-extension",
2010
+ message
2011
+ })(site.node)], []);
2012
+ };
2013
+ const libraryCandidates = (context) => (site) => {
2014
+ const flowing = Array.dedupe(pipe(context.flows, Array.filter((flow) => flow.site.node === site.node), Array.map((flow) => flow.target)));
2015
+ if (Array.isReadonlyArrayNonEmpty(flowing)) return flowing;
2016
+ if (!pipe(site.values, Array.some((value) => typeof value === "string"))) return [];
2017
+ const imported = importedModulesOf(site.node.getSourceFile());
2018
+ return Array.dedupe(pipe(context.vocabularies, Array.filter((library) => imported.includes(library.specifier)), Array.filter((library) => isSubsetOf(site.values, library.vocabulary.values)), Array.map((library) => describeLibraryType(library))));
2019
+ };
2020
+ const listCandidates = (candidates) => {
2021
+ const shown = pipe(Array.take(candidates, 3), Array.join(", "));
2022
+ const hidden = candidates.length - 3;
2023
+ if (hidden > NOTHING_HIDDEN) return `${shown} and ${String(hidden)} more`;
2024
+ return shown;
2025
+ };
2026
+ const originalVerdict = (context) => (site) => {
2027
+ const owners = pipe(context.owners, Array.filter((owner) => isSubsetOf(site.values, owner.values)));
2028
+ if (Array.isReadonlyArrayNonEmpty(owners)) {
2029
+ const message = `The values ${formatValues(site.values)} are owned by ${describeOwners(owners)}. Derive this set from the owner instead of restating it.`;
2030
+ return verdict([problemAt({
2031
+ rule: "owner-value-set",
2032
+ message
2033
+ })(site.node)], []);
2034
+ }
2035
+ const candidates = libraryCandidates(context)(site);
2036
+ if (Array.isReadonlyArrayNonEmpty(candidates)) {
2037
+ const message = `The values ${formatValues(site.values)} restate a dependency type: ${listCandidates(candidates)}. Derive this set from the library type.`;
2038
+ return verdict([problemAt({
2039
+ rule: "library-value-set",
2040
+ message
2041
+ })(site.node)], []);
2042
+ }
2043
+ return verdict([], [site]);
2044
+ };
2045
+ const siteVerdict = (context) => (site) => {
2046
+ if (Array.isReadonlyArrayNonEmpty(site.sources)) return derivedVerdict(context)(site);
2047
+ return originalVerdict(context)(site);
2048
+ };
2049
+ const VALUE_PARENT_KINDS = /* @__PURE__ */ new Set([
2050
+ SyntaxKind.ReturnStatement,
2051
+ SyntaxKind.ArrayLiteralExpression,
2052
+ SyntaxKind.ConditionalExpression,
2053
+ SyntaxKind.ParenthesizedExpression,
2054
+ SyntaxKind.ArrowFunction,
2055
+ SyntaxKind.JsxExpression
2056
+ ]);
2057
+ const isCallArgument = (node, parent) => (isCallExpression(parent) || isNewExpression(parent)) && parent.expression !== node;
2058
+ const isInitializer = (node, parent) => (isPropertyAssignment(parent) || isVariableDeclaration(parent)) && parent.initializer === node;
2059
+ const isRightOperand = (node, parent) => isBinaryExpression(parent) && parent.right === node;
2060
+ const VALUE_SLOTS = [
2061
+ isCallArgument,
2062
+ isInitializer,
2063
+ isRightOperand
2064
+ ];
2065
+ const isValuePosition = (node) => {
2066
+ const { parent } = node;
2067
+ return VALUE_PARENT_KINDS.has(parent.kind) || pipe(VALUE_SLOTS, Array.some((isSlot) => isSlot(node, parent)));
2068
+ };
2069
+ const ownedLiteralProblem = (context) => (literal) => Option.fromUndefinedOr(context.checker.getContextualType(literal)).pipe(Option.filter((contextual) => vocabularyOf(context.checker)(contextual).pipe(Option.exists((vocabulary) => !vocabulary.admitsUnnamedValues))), Option.map(() => pipe(contextSymbolsOf(context.checker)(literal), Array.flatMap((symbol) => ownersBehind(context)(symbol, [])), uniqueByReference, Array.filter((owner) => isSubsetOf([literal.text], pipe(owner.values, Array.map(String)))))), Option.filter((owners) => Array.isReadonlyArrayNonEmpty(owners)), Option.map((owners) => problemAt({
2070
+ rule: "owned-literal",
2071
+ message: `${literal.getText()} is a value of ${describeOwners(owners)}. Write it through the owner's binding instead of as a literal.`
2072
+ })(literal)));
2073
+ const ownedLiteralProblems = (context) => (sourceFile, excluded) => Array.getSomes(pipe(descendantsOf(sourceFile), Array.filter((node) => isStringLiteral(node) || isNumericLiteral(node)), Array.filter((node) => isValuePosition(node)), Array.filter((node) => !pipe(excluded, Array.some((outer) => contains(outer)(node)))), Array.map((node) => ownedLiteralProblem(context)(node))));
2074
+ // src/features/value-owners/model/analysis.ts
2075
+ const isVisibleTo = (project) => (owner) => pipe(project.sourceFiles, Array.some((sourceFile) => sourceFile.fileName === owner.file)) || Option.exists(owner.packageName, (name) => Option.contains(project.packageName, name) || project.workspaceDependencies.includes(name));
2076
+ const ownerDeclarationsIn = (project, owners) => {
2077
+ const keys = new Set(pipe(owners, Array.map((owner) => owner.key)));
2078
+ return pipe(project.sourceFiles, Array.flatMap((sourceFile) => pipe(descendantsOf(sourceFile), Array.filter((node) => isVariableDeclaration(node)), Array.filter((declaration) => Option.exists(ownerKeyOf(declaration), (key) => keys.has(key))))));
2079
+ };
2080
+ const isInside = (outers) => (node) => pipe(outers, Array.some((outer) => contains(outer)(node)));
2081
+ const sitesOutside = (checker) => (project, outers) => pipe(project.sourceFiles, Array.flatMap((sourceFile) => sitesUnder(checker)(sourceFile)), Array.filter((site) => !isInside(outers)(site.node)));
2082
+ const nodesOf = (sites) => pipe(sites, Array.map((site) => site.node));
2083
+ const analyzeProject = (owners) => (project) => {
2084
+ const { checker } = project;
2085
+ const ownerDeclarations = ownerDeclarationsIn(project, owners);
2086
+ const sites = sitesOutside(checker)(project, ownerDeclarations);
2087
+ const flowContext = {
2088
+ checker,
2089
+ program: project.program,
2090
+ sites
2091
+ };
2092
+ const context = {
2093
+ checker,
2094
+ owners: pipe(owners, Array.filter((owner) => isVisibleTo(project)(owner))),
2095
+ vocabularies: project.library.vocabularies,
2096
+ flows: pipe(project.sourceFiles, Array.flatMap((sourceFile) => flowsIn(flowContext)(sourceFile)))
2097
+ };
2098
+ const verdicts = pipe(sites, Array.map((site) => siteVerdict(context)(site)));
2099
+ const excluded = [...ownerDeclarations, ...nodesOf(sites)];
2100
+ const shapeContext = {
2101
+ checker,
2102
+ program: project.program,
2103
+ shapes: project.library.shapes
2104
+ };
2105
+ return {
2106
+ problems: [...pipe(verdicts, Array.flatMap((found) => found.problems)), ...pipe(project.sourceFiles, Array.flatMap((sourceFile) => [...ownedLiteralProblems(context)(sourceFile, excluded), ...shapeProblemsIn(shapeContext)(sourceFile)]))],
2107
+ unowned: pipe(verdicts, Array.flatMap((found) => found.unowned))
2108
+ };
2109
+ };
2110
+ // src/features/value-owners/model/duplicates.ts
2111
+ const DUPLICATE_THRESHOLD = 1;
2112
+ const unownedSiteOf = (scope) => (site) => ({
2113
+ scope,
2114
+ file: site.node.getSourceFile().fileName,
2115
+ start: site.node.getStart(),
2116
+ line: lineOf(site.node),
2117
+ column: columnOf(site.node),
2118
+ values: site.values
2119
+ });
2120
+ const canDerive = (left, right) => left.scope.name === right.scope.name || left.scope.dependencies.includes(right.scope.name) || right.scope.dependencies.includes(left.scope.name);
2121
+ const siteKey = (site) => `${site.file}#${String(site.start)}`;
2122
+ const valueSetKey = (site) => {
2123
+ const keys = pipe(site.values, Array.map((value) => valueKey(value)));
2124
+ return pipe(Array.sort(keys, Order.String), Array.join("\0"));
2125
+ };
2126
+ const duplicateProblems = (relative) => (sites) => {
2127
+ const unique = Array.dedupeWith(sites, (left, right) => siteKey(left) === siteKey(right));
2128
+ const groups = Record.values(Array.groupBy(unique, (site) => valueSetKey(site)));
2129
+ return pipe(groups, Array.filter((group) => group.length > DUPLICATE_THRESHOLD), Array.flatMap((group) => pipe(group, Array.flatMap((site) => {
2130
+ const related = pipe(group, Array.filter((other) => other !== site && canDerive(site, other)));
2131
+ if (!Array.isReadonlyArrayNonEmpty(related)) return [];
2132
+ const others = pipe(related, Array.map((other) => `${relative(other.file)}:${String(other.line)}`), Array.join(", "));
2133
+ return [{
2134
+ file: site.file,
2135
+ line: site.line,
2136
+ column: site.column,
2137
+ rule: "duplicate-value-set",
2138
+ message: `The values ${formatValues(site.values)} are also declared at ${others}. Register one owner with /** @${OWNER_TAG} <concept> */ and derive the others from it.`
2139
+ }];
2140
+ }))));
2141
+ };
2142
+ // src/features/value-owners/model/check.ts
2143
+ const scanOwners = Effect.fn("scanOwners")(function* scanOwners(workspace, configPaths) {
2144
+ const ownerConfigs = yield* pipe(configPaths, Effect.filter(mentions$1(`@${OWNER_TAG}`)(workspace.compiler)));
2145
+ const scans = yield* pipe(ownerConfigs, Effect.forEach((configPath) => withProject(workspace)(configPath)((project) => Effect.sync(() => ownersIn(project)))));
2146
+ return combineOwnerScans(Array.getSomes(scans));
2147
+ });
2148
+ const scopeOf = (project, configPath) => ({
2149
+ name: Option.getOrElse(project.packageName, () => configPath),
2150
+ dependencies: project.workspaceDependencies
1565
2151
  });
1566
- // src/root-readme.ts
1567
- const RULE$5 = "root-readme";
1568
- const SEPARATOR$1 = "/";
1569
- const ALTERNATIVE = "|";
1570
- const SCOPE = /^@[^/]+\//u;
1571
- const README = /^README(?:\.[^/]+)?$/iu;
1572
- const SPECIAL = /[$()*+.?[\\\]^{|}]/gu;
1573
- const READ_CONCURRENCY$5 = 16;
1574
- const START$3 = 0;
1575
- const NamedManifest = Schema.fromJsonString(Schema.Struct({ name: Schema.optional(Schema.String) }));
1576
- const patternOf = (names) => {
1577
- const alternatives = pipe(names, Array.map(String$1.replaceAll(SPECIAL, String.raw`\$&`)));
1578
- return new RegExp(`(?<![\\p{L}\\p{N}_-])(?:${Array.join(alternatives, ALTERNATIVE)})(?![\\p{L}\\p{N}_-])`, "gu");
1579
- };
1580
- const packageNameIn = (text) => pipe(text, Option.flatMap(Schema.decodeOption(NamedManifest)), Option.flatMap((manifest) => Option.fromUndefinedOr(manifest.name)));
1581
- const workspaceIn = Effect.fn("workspaceIn")(function* workspaceIn(root, name) {
1582
- const files = yield* RepositoryFiles;
1583
- const directory = files.dirname(name);
1584
- const text = yield* files.readFile(files.join(root, name));
1585
- const packageName = packageNameIn(text);
1586
- const unscoped = pipe(packageName, Option.map(String$1.replace(SCOPE, "")));
1587
- const names = pipe([
1588
- Option.some(directory),
1589
- Option.some(files.basename(directory)),
1590
- packageName,
1591
- unscoped
1592
- ], Array.getSomes, Array.dedupe);
2152
+ const analyzeProjects = (workspace, owners) => (configPaths) => pipe(configPaths, Effect.forEach((configPath) => withProject(workspace)(configPath)((project) => Effect.sync(() => {
2153
+ const analysis = analyzeProject(owners)(project);
2154
+ const scope = scopeOf(project, configPath);
1593
2155
  return {
1594
- directory,
1595
- pattern: patternOf(names)
2156
+ problems: analysis.problems,
2157
+ unowned: pipe(analysis.unowned, Array.map(unownedSiteOf(scope)))
1596
2158
  };
1597
- });
1598
- const messageFor = (directory) => `names the workspace ${directory}. The root README describes the repository as a whole. Write what belongs to the workspace in ${directory}/README.md.`;
1599
- const problemsIn$2 = (file, source) => ({ directory, pattern }) => {
1600
- const message = messageFor(directory);
1601
- const at = positionOf(source);
1602
- return pipe(Array.fromIterable(String$1.matchAll(pattern)(source)), Array.map((found) => ({
1603
- file,
1604
- ...at(found.index ?? START$3),
1605
- rule: RULE$5,
1606
- message
1607
- })));
1608
- };
1609
- const problemsInReadme = Effect.fn("problemsInReadme")(function* problemsInReadme(file, workspaces) {
1610
- const text = yield* (yield* RepositoryFiles).readFile(file);
1611
- return pipe(text, Option.match({
1612
- onNone: () => [],
1613
- onSome: (source) => pipe(workspaces, Array.flatMap(problemsIn$2(file, source)))
1614
- }));
1615
- });
1616
- /** @internal */
1617
- const checkRootReadme = Effect.fn("checkRootReadme")(function* checkRootReadme(root) {
2159
+ }).pipe(Effect.withSpan("analyzeProject")))), Effect.map(Array.getSomes));
2160
+ const checkRepository = Effect.fn("checkRepository")(function* checkRepository(root) {
1618
2161
  const files = yield* RepositoryFiles;
1619
- const names = yield* files.listedFiles(root);
1620
- const readmes = pipe(names, Array.filter((name) => README.test(name)));
1621
- const manifests = pipe(names, Array.filter((name) => String$1.includes(SEPARATOR$1)(name) && files.basename(name) === "package.json"));
1622
- const workspaces = yield* Effect.forEach(manifests, (name) => workspaceIn(root, name), { concurrency: READ_CONCURRENCY$5 });
1623
- const found = yield* Effect.forEach(readmes, (name) => problemsInReadme(files.join(root, name), workspaces), { concurrency: READ_CONCURRENCY$5 });
1624
- return Array.flatten(found);
1625
- });
1626
- // src/placement-checks.ts
1627
- /** @internal */
1628
- const checkPlacement = Effect.fn("checkPlacement")(function* checkPlacement(root) {
1629
- const found = yield* Effect.all([
1630
- checkNestedDocs(root),
1631
- checkRootReadme(root),
1632
- checkColocatedTests(root)
1633
- ], { concurrency: "unbounded" });
1634
- return Array.flatten(found);
1635
- });
1636
- // src/found-comment.ts
2162
+ const workspace = {
2163
+ compiler: yield* typeScriptCompiler,
2164
+ root,
2165
+ generated: yield* files.generatedFiles(root)
2166
+ };
2167
+ const configPaths = yield* listConfigFiles(root);
2168
+ const ownerScan = yield* scanOwners(workspace, configPaths);
2169
+ const analyses = yield* analyzeProjects(workspace, ownerScan.owners)(configPaths);
2170
+ const relative = (file) => files.relative(root, file);
2171
+ const unowned = pipe(analyses, Array.flatMap((analysis) => analysis.unowned));
2172
+ return sortProblems([
2173
+ ...ownerScan.problems,
2174
+ ...pipe(analyses, Array.flatMap((analysis) => analysis.problems)),
2175
+ ...duplicateProblems(relative)(unowned)
2176
+ ]);
2177
+ }, Effect.scoped);
2178
+ // src/features/comments/model/found-comment.ts
1637
2179
  const taggedError$2 = Schema.TaggedError;
1638
2180
  var CommentsUnreadable = class extends taggedError$2()("CommentsUnreadable", {
1639
2181
  reader: Schema.String,
@@ -1647,8 +2189,8 @@ const trimmed = ({ index, text }) => ({
1647
2189
  index,
1648
2190
  text: String$1.trimEnd(text)
1649
2191
  });
1650
- // src/config-comments.ts
1651
- const NEXT$2 = 1;
2192
+ // src/features/comments/model/config-comments.ts
2193
+ const NEXT$1 = 1;
1652
2194
  const isRecord = (value) => typeof value === "object" && value !== null;
1653
2195
  const childrenOf = (value) => {
1654
2196
  if (Array.isArray(value)) return value;
@@ -1690,7 +2232,7 @@ const sqlComments = (source) => Effect.try({
1690
2232
  },
1691
2233
  catch: unreadable("sql")
1692
2234
  });
1693
- const offsetAt = (lines) => ({ line, character }) => character + pipe(lines, Array.take(line), Array.map((text) => text.length + NEXT$2), Number$1.sumAll);
2235
+ const offsetAt = (lines) => ({ line, character }) => character + pipe(lines, Array.take(line), Array.map((text) => text.length + NEXT$1), Number$1.sumAll);
1694
2236
  const dockerfileComments = (source) => Effect.try({
1695
2237
  try: () => {
1696
2238
  const lines = String$1.split(source, "\n");
@@ -1701,7 +2243,7 @@ const dockerfileComments = (source) => Effect.try({
1701
2243
  },
1702
2244
  catch: unreadable("dockerfile")
1703
2245
  });
1704
- // src/comment-readers.ts
2246
+ // src/features/comments/model/comment-readers.ts
1705
2247
  const GRAMMARS = [
1706
2248
  "bash",
1707
2249
  "c-sharp",
@@ -1723,8 +2265,8 @@ const COMMENT_NODES = [
1723
2265
  "block_comment",
1724
2266
  "multiline_comment"
1725
2267
  ];
1726
- const START$2 = 0;
1727
- const NEXT$1 = 1;
2268
+ const START$3 = 0;
2269
+ const NEXT = 1;
1728
2270
  const NONE$1 = [];
1729
2271
  const grammarFile = (grammar) => fileURLToPath(import.meta.resolve(`@vscode/tree-sitter-wasm/wasm/tree-sitter-${grammar}.wasm`));
1730
2272
  const loadGrammar = (grammar) => Effect.tryPromise({
@@ -1782,11 +2324,11 @@ const markupComment = (source) => (node) => {
1782
2324
  if (!isComment(node) || node.startIndex === null || node.endIndex === null) return NONE$1;
1783
2325
  return [{
1784
2326
  index: node.startIndex,
1785
- text: String$1.slice(node.startIndex, node.endIndex + NEXT$1)(source)
2327
+ text: String$1.slice(node.startIndex, node.endIndex + NEXT)(source)
1786
2328
  }];
1787
2329
  };
1788
2330
  const textComments = (grammars, grammar) => (text) => {
1789
- const shift = shifted(text.startIndex ?? START$2);
2331
+ const shift = shifted(text.startIndex ?? START$3);
1790
2332
  return syntaxComments(grammars, grammar)(text.data).pipe(Effect.map(Array.map(shift)));
1791
2333
  };
1792
2334
  const embeddedComments = (grammars) => (node) => {
@@ -1821,14 +2363,14 @@ const commentsWith = (grammars) => (reader, source) => {
1821
2363
  dockerfile: dockerfileComments
1822
2364
  }[reader](source);
1823
2365
  };
1824
- // src/comments.ts
1825
- const RULE$4 = "comment";
1826
- const CONFIG_FILE$3 = "vite.config.ts";
2366
+ // src/features/comments/model/comments.ts
2367
+ const RULE$1 = "comment";
2368
+ const CONFIG_FILE = "vite.config.ts";
1827
2369
  const VENDORED_PATHSPEC = ":(attr:linguist-vendored)";
1828
- const READ_CONCURRENCY$4 = 64;
1829
- const START$1 = 0;
1830
- const FIRST_LINE$1 = 1;
1831
- const FIRST_COLUMN$1 = 1;
2370
+ const READ_CONCURRENCY$2 = 64;
2371
+ const START$2 = 0;
2372
+ const FIRST_LINE$2 = 1;
2373
+ const FIRST_COLUMN$2 = 1;
1832
2374
  const READERS = [
1833
2375
  [/\.(?:[cm]?jsx?)$/u, "javascript"],
1834
2376
  [/\.(?:[cm]?ts)$/u, "typescript"],
@@ -1883,23 +2425,23 @@ const shebangReader = (source) => {
1883
2425
  const readerOf = (name, source) => pipe(READERS, Array.findFirst(([pattern]) => pattern.test(name)), Option.orElse(() => shebangReader(source)), Option.map(([, reader]) => reader));
1884
2426
  const valueOf = (text) => String$1.replaceAll(DELIMITERS, "")(text);
1885
2427
  const lineBefore = (source, index) => {
1886
- const lines = pipe(source, String$1.slice(START$1, index), String$1.split("\n"));
2428
+ const lines = pipe(source, String$1.slice(START$2, index), String$1.split("\n"));
1887
2429
  return Option.getOrElse(Array.last(lines), () => "");
1888
2430
  };
1889
2431
  const isPinVersion = (source, { index, text }) => PIN.test(lineBefore(source, index)) && VERSION.test(valueOf(text));
1890
- const isShebang = ({ index, text }) => index === START$1 && String$1.startsWith(SHEBANG)(text);
2432
+ const isShebang = ({ index, text }) => index === START$2 && String$1.startsWith(SHEBANG)(text);
1891
2433
  const isAllowed = (source, directives) => (comment) => isShebang(comment) || directives.test(valueOf(comment.text)) || isPinVersion(source, comment);
1892
2434
  const problemOf$1 = (file, source) => ({ index }) => ({
1893
2435
  file,
1894
2436
  ...positionOf(source)(index),
1895
- rule: RULE$4,
2437
+ rule: RULE$1,
1896
2438
  message: MESSAGE
1897
2439
  });
1898
2440
  const unreadableProblem = (file, message) => ({
1899
2441
  file,
1900
- line: FIRST_LINE$1,
1901
- column: FIRST_COLUMN$1,
1902
- rule: RULE$4,
2442
+ line: FIRST_LINE$2,
2443
+ column: FIRST_COLUMN$2,
2444
+ rule: RULE$1,
1903
2445
  message: `msch could not read the comments in this file: ${message}`
1904
2446
  });
1905
2447
  const settingsOf = ({ msch, lint }) => ({
@@ -1911,7 +2453,7 @@ const settingsOf = ({ msch, lint }) => ({
1911
2453
  });
1912
2454
  const rootSettings = Effect.fn("rootSettings")(function* rootSettings(root) {
1913
2455
  const files = yield* RepositoryFiles;
1914
- const file = files.join(root, CONFIG_FILE$3);
2456
+ const file = files.join(root, CONFIG_FILE);
1915
2457
  if (!(yield* files.exists(file))) return NO_SETTINGS;
1916
2458
  const config = yield* Effect.tryPromise({
1917
2459
  try: () => resolveConfigFromFile(file),
@@ -1954,28 +2496,28 @@ const checkComments = Effect.fn("checkComments")(function* checkComments(root) {
1954
2496
  const found = yield* Effect.forEach(scanned, (entry) => files.readFile(entry.file).pipe(Effect.flatMap(Option.match({
1955
2497
  onNone: () => Effect.succeed(NONE),
1956
2498
  onSome: (source) => problemsIn(entry, source)
1957
- }))), { concurrency: READ_CONCURRENCY$4 });
2499
+ }))), { concurrency: READ_CONCURRENCY$2 });
1958
2500
  return Array.flatten(found);
1959
2501
  });
1960
- // src/hidden-unicode.ts
2502
+ // src/features/invisible-characters/model/hidden-unicode.ts
1961
2503
  const HIDDEN = /[\u00AD\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]|[\u{E0000}-\u{E007F}]/gu;
1962
2504
  const NUL = "\0";
1963
- const START = 0;
2505
+ const START$1 = 0;
1964
2506
  const HEX = 16;
1965
2507
  const CODE_POINT_WIDTH = 4;
1966
- const READ_CONCURRENCY$3 = 64;
1967
- const RULE$3 = "hidden-unicode";
1968
- const hexOf = (character) => pipe(String$1.codePointAt(START)(character), Option.getOrElse(() => START), (code) => code.toString(HEX), String$1.toUpperCase, String$1.padStart(CODE_POINT_WIDTH, "0"));
2508
+ const READ_CONCURRENCY$1 = 64;
2509
+ const RULE = "hidden-unicode";
2510
+ const hexOf = (character) => pipe(String$1.codePointAt(START$1)(character), Option.getOrElse(() => START$1), (code) => code.toString(HEX), String$1.toUpperCase, String$1.padStart(CODE_POINT_WIDTH, "0"));
1969
2511
  const problemOf = (file, source) => (found) => {
1970
- const hex = hexOf(found[START]);
2512
+ const hex = hexOf(found[START$1]);
1971
2513
  return {
1972
2514
  file,
1973
- ...positionOf(source)(found.index ?? START),
1974
- rule: RULE$3,
2515
+ ...positionOf(source)(found.index ?? START$1),
2516
+ rule: RULE,
1975
2517
  message: `U+${hex} is invisible in editors and reviews and can change what the text means. Remove it, or write it as the escape \\u${hex}.`
1976
2518
  };
1977
2519
  };
1978
- const problemsIn$1 = (file, source) => {
2520
+ const problemsIn = (file, source) => {
1979
2521
  if (String$1.includes(NUL)(source)) return [];
1980
2522
  return pipe(Array.fromIterable(String$1.matchAll(HIDDEN)(source)), Array.map(problemOf(file, source)));
1981
2523
  };
@@ -1987,16 +2529,43 @@ const checkHiddenUnicode = Effect.fn("checkHiddenUnicode")(function* checkHidden
1987
2529
  const file = files.join(root, name);
1988
2530
  return files.readFile(file).pipe(Effect.map(Option.match({
1989
2531
  onNone: () => [],
1990
- onSome: (source) => problemsIn$1(file, source)
2532
+ onSome: (source) => problemsIn(file, source)
1991
2533
  })));
1992
- }, { concurrency: READ_CONCURRENCY$3 });
2534
+ }, { concurrency: READ_CONCURRENCY$1 });
1993
2535
  return Array.flatten(found);
1994
2536
  });
1995
- // src/python.ts
1996
- const PYTHON_FILE = /(?:\.(?:py|pyi|pyw|pyx|ipynb)|(?:^|\/)(?:pyproject\.toml|uv\.lock|uv\.toml|poetry\.lock|Pipfile|Pipfile\.lock|setup\.cfg|tox\.ini|pytest\.ini|\.python-version|requirements[^/]*\.txt))$/u;
2537
+ // src/shared/lib/scanned-files.ts
1997
2538
  const SCANNED_FILE = /(?:\.(?:[cm]?[jt]sx?|jsonc?|toml|ya?ml|sh|bash|zsh|fish|rs|cs|go|mk)|(?:^|\/)(?:Dockerfile[^/]*|Makefile|justfile|\.tool-versions|[^./][^./]*))$/u;
1998
2539
  const LOCKFILE = /(?:^|\/)(?:[^/]*\.lock|[^/]*-lock\.(?:json|ya?ml))$/u;
1999
2540
  const TOOL_VERSIONS = /(?:^|\/)(?:\.?mise(?:\.[^/]+)?\.toml|\.tool-versions)$/u;
2541
+ const READ_CONCURRENCY = 64;
2542
+ const isScannedText = ({ name }) => SCANNED_FILE.test(name) && !LOCKFILE.test(name);
2543
+ const isToolVersions = ({ name }) => TOOL_VERSIONS.test(name);
2544
+ /** @internal */
2545
+ const listedFiles = Effect.fn("listedFiles")(function* listedFiles(root) {
2546
+ const files = yield* RepositoryFiles;
2547
+ const names = yield* files.listedFiles(root);
2548
+ return pipe(names, Array.map((name) => ({
2549
+ name,
2550
+ file: files.join(root, name)
2551
+ })));
2552
+ });
2553
+ /** @internal */
2554
+ const presentFiles = Effect.fn("presentFiles")(function* presentFiles(listed) {
2555
+ const files = yield* RepositoryFiles;
2556
+ return yield* pipe(listed, Effect.filter(({ file }) => files.exists(file)));
2557
+ });
2558
+ /** @internal */
2559
+ const scanText = Effect.fn("scanText")(function* scanText(listed, problemsIn) {
2560
+ const files = yield* RepositoryFiles;
2561
+ const found = yield* Effect.forEach(listed, (entry) => files.readFile(entry.file).pipe(Effect.map(Option.match({
2562
+ onNone: () => [],
2563
+ onSome: (source) => problemsIn(entry, source)
2564
+ }))), { concurrency: READ_CONCURRENCY });
2565
+ return Array.flatten(found);
2566
+ });
2567
+ // src/features/python/model/python.ts
2568
+ const PYTHON_FILE = /(?:\.(?:py|pyi|pyw|pyx|ipynb)|(?:^|\/)(?:pyproject\.toml|uv\.lock|uv\.toml|poetry\.lock|Pipfile|Pipfile\.lock|setup\.cfg|tox\.ini|pytest\.ini|\.python-version|requirements[^/]*\.txt))$/u;
2000
2569
  const COMMAND_PATTERNS = [
2001
2570
  /(?<![\w./@-])python[\d.]*[ \t]+(?:[-"'$./]|\S+\.py\b)/gu,
2002
2571
  /(?<![\w./@-])pip3?[ \t]+(?:install|uninstall|download|freeze|wheel|compile|sync)\b/gu,
@@ -2007,208 +2576,169 @@ const COMMAND_PATTERNS = [
2007
2576
  /(?:\bcommand["']?\s*[:=]\s*|(?:\bspawn\w*|\bexec\w*|\bexeca|Command::new|ChildProcess\.make|\$)\(\s*)["'`](?:python[\d.]*|pip3?|pipx|uvx?|poetry)["'`]/gu,
2008
2577
  /\buses:\s*["']?(?:actions\/setup-python|astral-sh\/setup-uv|astral-sh\/ruff-action|pypa\/[\w.-]+|snok\/install-poetry|abatilo\/actions-poetry|conda-incubator\/setup-miniconda|mamba-org\/setup-micromamba|pdm-project\/setup-pdm)\b/gu
2009
2578
  ];
2010
- const TOOL_PATTERNS = [/^[ \t]*["']?(?:python|uv|pipx|poetry|ruff|pdm|hatch|pipx:[^"'\s=]+)["']?[ \t]*(?:=|[ \t]+\S)/gmu];
2011
- const READ_CONCURRENCY$2 = 64;
2012
- const FIRST_LINE = 1;
2013
- const FIRST_COLUMN = 1;
2014
- const WHOLE_MATCH = 0;
2015
- const FILE_RULE = "python-file";
2579
+ const TOOL_PATTERNS$1 = [/^[ \t]*["']?(?:python|uv|pipx|poetry|ruff|pdm|hatch|pipx:[^"'\s=]+)["']?[ \t]*(?:=|[ \t]+\S)/gmu];
2580
+ const FIRST_LINE$1 = 1;
2581
+ const FIRST_COLUMN$1 = 1;
2582
+ const WHOLE_MATCH$1 = 0;
2583
+ const FILE_RULE$1 = "python-file";
2016
2584
  const COMMAND_RULE = "python-command";
2017
2585
  const fileProblem = ({ file }) => ({
2018
2586
  file,
2019
- line: FIRST_LINE,
2020
- column: FIRST_COLUMN,
2021
- rule: FILE_RULE,
2587
+ line: FIRST_LINE$1,
2588
+ column: FIRST_COLUMN$1,
2589
+ rule: FILE_RULE$1,
2022
2590
  message: "Python is not used in this repository. Replace this file with TypeScript or Rust."
2023
2591
  });
2024
- const patternsFor = (name) => {
2025
- if (TOOL_VERSIONS.test(name)) return [...COMMAND_PATTERNS, ...TOOL_PATTERNS];
2592
+ const patternsFor = (entry) => {
2593
+ if (isToolVersions(entry)) return [...COMMAND_PATTERNS, ...TOOL_PATTERNS$1];
2026
2594
  return COMMAND_PATTERNS;
2027
2595
  };
2028
2596
  const commandProblem = ({ file }, source) => (found) => ({
2029
2597
  file,
2030
- ...positionOf(source)(found.index ?? WHOLE_MATCH),
2598
+ ...positionOf(source)(found.index ?? WHOLE_MATCH$1),
2031
2599
  rule: COMMAND_RULE,
2032
- message: `Python is not used in this repository. Remove \`${String$1.trim(found[WHOLE_MATCH])}\` and do the work in TypeScript or Rust.`
2600
+ message: `Python is not used in this repository. Remove \`${String$1.trim(found[WHOLE_MATCH$1])}\` and do the work in TypeScript or Rust.`
2033
2601
  });
2034
- const commandProblems = (entry, source) => pipe(patternsFor(entry.name), Array.flatMap((pattern) => Array.fromIterable(String$1.matchAll(pattern)(source))), Array.map(commandProblem(entry, source)));
2602
+ const commandProblems = (entry, source) => pipe(patternsFor(entry), Array.flatMap((pattern) => Array.fromIterable(String$1.matchAll(pattern)(source))), Array.map(commandProblem(entry, source)));
2035
2603
  const isPython = ({ name }) => PYTHON_FILE.test(name);
2036
- const isScanned = (entry) => !isPython(entry) && SCANNED_FILE.test(entry.name) && !LOCKFILE.test(entry.name);
2604
+ const isScanned = (entry) => !isPython(entry) && isScannedText(entry);
2037
2605
  /** @internal */
2038
2606
  const checkPython = Effect.fn("checkPython")(function* checkPython(root) {
2039
- const files = yield* RepositoryFiles;
2040
- const names = yield* files.listedFiles(root);
2041
- const listed = pipe(names, Array.map((name) => ({
2042
- name,
2043
- file: files.join(root, name)
2044
- })));
2045
- const problemsIn = (entry) => files.readFile(entry.file).pipe(Effect.map(Option.match({
2046
- onNone: () => [],
2047
- onSome: (source) => commandProblems(entry, source)
2048
- })));
2049
- const scanned = yield* Effect.forEach(pipe(listed, Array.filter(isScanned)), problemsIn, { concurrency: READ_CONCURRENCY$2 });
2050
- const present = yield* Effect.filter(pipe(listed, Array.filter(isPython)), ({ file }) => files.exists(file));
2051
- return [...pipe(present, Array.map(fileProblem)), ...Array.flatten(scanned)];
2052
- });
2053
- // src/tracked-text.ts
2054
- /** @internal */
2055
- const checkTrackedText = Effect.fn("checkTrackedText")(function* checkTrackedText(root) {
2056
- const found = yield* Effect.all([
2057
- checkHiddenUnicode(root),
2058
- checkPython(root),
2059
- checkComments(root)
2060
- ], { concurrency: "unbounded" });
2061
- return Array.flatten(found);
2607
+ const listed = yield* listedFiles(root);
2608
+ const scanned = yield* scanText(pipe(listed, Array.filter(isScanned)), commandProblems);
2609
+ const present = yield* presentFiles(pipe(listed, Array.filter(isPython)));
2610
+ return [...pipe(present, Array.map(fileProblem)), ...scanned];
2062
2611
  });
2063
- // src/crates.ts
2064
- const RULE$2 = "unverified-crate";
2065
- const CARGO_FILE = "Cargo.toml";
2066
- const CONFIG_FILE$2 = "vite.config.ts";
2612
+ // src/features/unneeded-files/model/unneeded-files.ts
2613
+ const WORKSPACE_FILE = "pnpm-workspace.yaml";
2614
+ const PNPM_DIRECTORY = ".pnpm/";
2067
2615
  const SEPARATOR = "/";
2068
- const FIRST$2 = 1;
2069
- const READ_CONCURRENCY$1 = 8;
2070
- const CrateEntry = Schema.Struct({
2071
- name: Schema.String,
2072
- manifest_path: Schema.String
2616
+ const FOREIGN_LOCKFILE = /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|bun\.lockb?)$/u;
2617
+ const CARGO_MANIFEST_FILE = /(?:^|\/)Cargo\.toml$/u;
2618
+ const CARGO_LOCK_FILE = /(?:^|\/)Cargo\.lock$/u;
2619
+ const PNPM_OUTPUT = /(?:^|\/)\.pnpm\//u;
2620
+ const CARGO_WORKSPACE = /^\[workspace\]/mu;
2621
+ const LEGACY_CARGO_CONFIG = /(?:^|\/)\.cargo\/config$/u;
2622
+ const CARGO_CONFIG_FILE = /(?:^|\/)\.cargo\/config\.toml$/u;
2623
+ const PNPM_CARGO_START = /# >>> pnpm-managed cargo sources >>>/u;
2624
+ const PNPM_CARGO_BLOCK = /# >>> pnpm-managed cargo sources >>>[\s\S]*?# <<< pnpm-managed cargo sources <<<\n?/gu;
2625
+ const SETUP_PATTERNS = [
2626
+ /(?<![\w./@-])rustup[ \t]+(?:toolchain[ \t]+install|install|update|default|override[ \t]+set|target[ \t]+add|component[ \t]+add)\b/gu,
2627
+ /(?<![\w./@-])cargo[ \t]+(?:vendor|fetch)\b/gu,
2628
+ /\buses:\s*["']?(?:dtolnay\/rust-toolchain|actions-rust-lang\/setup-rust-toolchain|actions-rs\/toolchain|moonrepo\/setup-rust)\b/gu
2629
+ ];
2630
+ const TOOL_PATTERNS = [/^[ \t]*["']?(?:rust|rustup)["']?[ \t]*(?:=|[ \t]+\S)/gmu];
2631
+ const START = 0;
2632
+ const LAST_SEGMENT = 1;
2633
+ const FIRST_LINE = 1;
2634
+ const FIRST_COLUMN = 1;
2635
+ const WHOLE_MATCH = 0;
2636
+ const FILE_RULE = "unneeded-file";
2637
+ const SETUP_RULE = "unneeded-setup";
2638
+ const CARGO_RULE = "cargo-outside-pnpm";
2639
+ const CargoSettings = Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) });
2640
+ const WorkspaceFile = Schema.Struct({ cargo: Schema.optionalKey(CargoSettings) });
2641
+ const decodeWorkspaceFile = Schema.decodeUnknownOption(WorkspaceFile);
2642
+ const cargoEnabled = (text) => pipe(decodeWorkspaceFile(parse$1(text)), Option.flatMap(({ cargo }) => Option.fromUndefinedOr(cargo)), Option.flatMap(({ enabled }) => Option.fromUndefinedOr(enabled)), Option.getOrElse(() => false));
2643
+ const problemAtStart = (rule, message) => ({ file }) => ({
2644
+ file,
2645
+ line: FIRST_LINE,
2646
+ column: FIRST_COLUMN,
2647
+ rule,
2648
+ message
2073
2649
  });
2074
- const CrateList = Schema.fromJsonString(Schema.Struct({ packages: Schema.Array(CrateEntry) }));
2075
- const decodeCrateList = Schema.decodeUnknownEffect(CrateList);
2076
- const cratesIn = Effect.fn("cratesIn")(function* cratesIn(root) {
2077
- const output = yield* (yield* ChildProcess.make("cargo", [
2078
- "metadata",
2079
- "--no-deps",
2080
- "--format-version",
2081
- "1",
2082
- "--offline"
2083
- ], {
2084
- cwd: root,
2085
- extendEnv: true,
2086
- stdin: "ignore"
2087
- })).stdout.pipe(Stream.decodeText(), Stream.mkString);
2088
- const list = yield* decodeCrateList(output);
2089
- return pipe(list.packages, Array.map((crate) => ({
2090
- name: crate.name,
2091
- manifest: crate.manifest_path
2650
+ const foreignLockfile = problemAtStart(FILE_RULE, "pnpm-lock.yaml is this repository's lockfile, and pnpm never reads this one. Delete it.");
2651
+ const nestedCargoLock = problemAtStart(FILE_RULE, "Cargo reads only the Cargo.lock beside the workspace's Cargo.toml, and pnpm install writes that one. Delete this one.");
2652
+ const legacyCargoConfig = problemAtStart(FILE_RULE, "pnpm install writes .cargo/config.toml, and Cargo warns when .cargo/config sits beside it. Move its settings into .cargo/config.toml and delete it.");
2653
+ const pnpmOutput = problemAtStart(FILE_RULE, "pnpm install writes .pnpm/ from Cargo.lock and rust-toolchain.toml. Add this .pnpm directory to .gitignore and keep it out of the repository.");
2654
+ const pnpmCargoConfig = problemAtStart(FILE_RULE, "pnpm install writes this .cargo/config.toml, and it holds nothing else. Add /.cargo/config.toml to .gitignore and keep it out of the repository.");
2655
+ const generatedCargoConfig = (entry, source) => {
2656
+ if (!CARGO_CONFIG_FILE.test(entry.name) || !PNPM_CARGO_START.test(source)) return [];
2657
+ if (String$1.isNonEmpty(String$1.trim(String$1.replaceAll(PNPM_CARGO_BLOCK, "")(source)))) return [];
2658
+ return [pnpmCargoConfig(entry)];
2659
+ };
2660
+ const cargoOutsidePnpm = problemAtStart(CARGO_RULE, `pnpm does not manage these crates. Set \`cargo: { enabled: true }\` in ${WORKSPACE_FILE} so pnpm install fetches the crates and the Rust toolchain.`);
2661
+ const setupProblem = ({ file }, source) => (found) => ({
2662
+ file,
2663
+ ...positionOf(source)(found.index ?? WHOLE_MATCH),
2664
+ rule: SETUP_RULE,
2665
+ message: `pnpm install already installs the toolchain in rust-toolchain.toml and vendors the crates in Cargo.lock. Remove \`${String$1.trim(found[WHOLE_MATCH])}\`.`
2666
+ });
2667
+ const setupPatternsFor = (entry) => {
2668
+ if (isToolVersions(entry)) return [...SETUP_PATTERNS, ...TOOL_PATTERNS];
2669
+ return SETUP_PATTERNS;
2670
+ };
2671
+ const setupProblems = (entry, source) => pipe(setupPatternsFor(entry), Array.flatMap((pattern) => Array.fromIterable(String$1.matchAll(pattern)(source))), Array.map(setupProblem(entry, source)), Array.appendAll(generatedCargoConfig(entry, source)));
2672
+ const matches = (pattern) => ({ name }) => pattern.test(name);
2673
+ const isCargoManifest = matches(CARGO_MANIFEST_FILE);
2674
+ const isForeignLockfile = matches(FOREIGN_LOCKFILE);
2675
+ const isLegacyCargoConfig = matches(LEGACY_CARGO_CONFIG);
2676
+ const isPnpmOutput = matches(PNPM_OUTPUT);
2677
+ const directoryOf = (name) => pipe(String$1.split(name, SEPARATOR), Array.dropRight(LAST_SEGMENT), Array.join(SEPARATOR));
2678
+ const ancestorsOf = (directory) => {
2679
+ const parts = String$1.split(directory, SEPARATOR);
2680
+ return pipe(Array.makeBy(parts.length, (depth) => Array.join(Array.take(parts, depth), SEPARATOR)), Array.filter((ancestor) => ancestor !== directory));
2681
+ };
2682
+ const readsCargoLock = (manifests, workspaces) => ({ name }) => {
2683
+ const directory = directoryOf(name);
2684
+ const insideWorkspace = pipe(ancestorsOf(directory), Array.some((ancestor) => Array.contains(workspaces, ancestor)));
2685
+ return Array.contains(manifests, directory) && !insideWorkspace;
2686
+ };
2687
+ const isWorkspaceManifest = (source) => Option.exists(source, (text) => CARGO_WORKSPACE.test(text));
2688
+ const directoriesOf = (entries) => pipe(entries, Array.map(({ name }) => directoryOf(name)));
2689
+ const cargoWorkspaces = Effect.fn("cargoWorkspaces")(function* cargoWorkspaces(manifests) {
2690
+ const files = yield* RepositoryFiles;
2691
+ const roots = yield* pipe(manifests, Effect.filter(({ file }) => files.readFile(file).pipe(Effect.map(isWorkspaceManifest))));
2692
+ return directoriesOf(roots);
2693
+ });
2694
+ const pnpmDirectoryOf = ({ name }) => pipe(name, String$1.indexOf(PNPM_DIRECTORY), Option.getOrElse(() => START), (end) => String$1.slice(START, end)(name));
2695
+ const pnpmOutputs = (present) => pipe(present, Array.filter(isPnpmOutput), Array.dedupeWith((left, right) => pnpmDirectoryOf(left) === pnpmDirectoryOf(right)), Array.map(pnpmOutput));
2696
+ const byDepth = Order.mapInput(Order.Number, ({ name }) => String$1.split(name, "/").length);
2697
+ const cargoProblems = (present, enabled) => {
2698
+ if (!enabled) return Effect.succeed(pipe(present, Array.filter(isCargoManifest), Array.match({
2699
+ onEmpty: () => [],
2700
+ onNonEmpty: (manifests) => [cargoOutsidePnpm(Array.min(manifests, byDepth))]
2092
2701
  })));
2093
- }, Effect.scoped);
2094
- const owningWorkspace = (directories) => (directory) => {
2095
- const owners = pipe(directories, Array.filter((workspace) => directory === workspace || String$1.startsWith(`${workspace}${SEPARATOR}`)(directory)));
2096
- return Array.last(Array.sort(owners, String$1.Order));
2702
+ return Effect.gen(function* enabledCargoProblems() {
2703
+ const manifests = pipe(present, Array.filter(isCargoManifest));
2704
+ const workspaces = yield* cargoWorkspaces(manifests);
2705
+ const reads = readsCargoLock(directoriesOf(manifests), workspaces);
2706
+ const setup = yield* scanText(pipe(present, Array.filter(isScannedText)), setupProblems);
2707
+ return [
2708
+ ...pipe(present, Array.filter((entry) => CARGO_LOCK_FILE.test(entry.name) && !reads(entry)), Array.map(nestedCargoLock)),
2709
+ ...pipe(present, Array.filter(isLegacyCargoConfig), Array.map(legacyCargoConfig)),
2710
+ ...pnpmOutputs(present),
2711
+ ...setup
2712
+ ];
2713
+ });
2097
2714
  };
2098
- const problemFor = (crate, message) => ({
2099
- file: crate.manifest,
2100
- line: FIRST$2,
2101
- column: FIRST$2,
2102
- rule: RULE$2,
2103
- message: `crate ${crate.name} ${message}, so vp run verify never checks it.`
2104
- });
2105
- const problemIn$1 = Effect.fn("problemIn")(function* problemIn(root, directories, crate) {
2106
- const files = yield* RepositoryFiles;
2107
- const workspace = owningWorkspace(directories)(files.relative(root, files.dirname(crate.manifest)));
2108
- if (Option.isNone(workspace)) return Option.some(problemFor(crate, "is outside every workspace package"));
2109
- if (yield* hasVerifyTask(files.join(root, workspace.value, CONFIG_FILE$2))) return Option.none();
2110
- return Option.some(problemFor(crate, `is in ${workspace.value}, whose ${CONFIG_FILE$2} has no verify task`));
2111
- });
2112
- /** @internal */
2113
- const checkCrates = Effect.fn("checkCrates")(function* checkCrates(root) {
2114
- const files = yield* RepositoryFiles;
2115
- if (!(yield* files.exists(files.join(root, CARGO_FILE)))) return [];
2116
- const directories = yield* workspaceDirectories(root);
2117
- const crates = yield* cratesIn(root);
2118
- const found = yield* Effect.forEach(crates, (crate) => problemIn$1(root, directories, crate), { concurrency: READ_CONCURRENCY$1 });
2119
- return Array.getSomes(found);
2120
- });
2121
- // src/hidden-verify.ts
2122
- const RULE$1 = "hidden-verify";
2123
- const CONFIG_FILE$1 = "vite.config.ts";
2124
- const FIRST$1 = 1;
2125
- const READ_CONCURRENCY = 8;
2126
- const problemIn = Effect.fn("problemIn")(function* problemIn(root, directory) {
2127
- const files = yield* RepositoryFiles;
2128
- const file = files.join(root, directory, CONFIG_FILE$1);
2129
- const text = yield* files.readFile(file);
2130
- if (Option.isNone(text)) return Option.none();
2131
- const program = yield* programOf(file, text.value);
2132
- if (definesTask(VERIFY_TASK)(program)) return Option.none();
2133
- const verified = yield* hasVerifyTask(file);
2134
- return Option.some({
2135
- file,
2136
- line: FIRST$1,
2137
- column: FIRST$1,
2138
- rule: RULE$1,
2139
- message: `${directory} gets its verify task from code outside ${CONFIG_FILE$1}. The root verify reads ${CONFIG_FILE$1} without running it, so it never runs this verify. Write run.tasks.verify in ${directory}/${CONFIG_FILE$1}.`
2140
- }).pipe(Option.filter(() => verified));
2141
- });
2142
- /** @internal */
2143
- const checkHiddenVerify = Effect.fn("checkHiddenVerify")(function* checkHiddenVerify(root) {
2144
- const directories = yield* workspaceDirectories(root);
2145
- const found = yield* Effect.forEach(directories, (directory) => problemIn(root, directory), { concurrency: READ_CONCURRENCY });
2146
- return Array.getSomes(found);
2715
+ const unneededIn = Effect.fn("unneededIn")(function* unneededIn(root, workspace) {
2716
+ const listed = yield* listedFiles(root);
2717
+ const present = yield* presentFiles(listed);
2718
+ const lockfiles = pipe(present, Array.filter(isForeignLockfile), Array.map(foreignLockfile));
2719
+ if (!pipe(present, Array.some(isCargoManifest))) return lockfiles;
2720
+ const cargo = yield* cargoProblems(present, cargoEnabled(workspace));
2721
+ return [...lockfiles, ...cargo];
2147
2722
  });
2148
- // src/root-workspace-paths.ts
2149
- const RULE = "root-workspace-path";
2150
- const CONFIG_FILE = "vite.config.ts";
2151
- const PATH_CHARACTER = /[\w.@/-]/u;
2152
- const NAME_CHARACTER = /[\w.@-]/u;
2153
- const FIRST = 0;
2154
- const NEXT = 1;
2155
- const StringNode = Schema.Union([Schema.Struct({
2156
- type: Schema.Literal("Literal"),
2157
- value: Schema.String,
2158
- start: Schema.Finite
2159
- }), Schema.Struct({
2160
- type: Schema.Literal("TemplateElement"),
2161
- value: Schema.Struct({ cooked: Schema.String }),
2162
- start: Schema.Finite
2163
- })]);
2164
- const decodeStringNode = Schema.decodeUnknownOption(StringNode);
2165
- const textOf = (node) => {
2166
- if (node.type === "Literal") return node.value;
2167
- return node.value.cooked;
2168
- };
2169
- const stringsIn = (node) => {
2170
- return [...pipe(decodeStringNode(node), Option.map((found) => ({
2171
- text: textOf(found),
2172
- start: found.start
2173
- })), Option.toArray), ...pipe(childrenOf$3(node), Array.flatMap(stringsIn))];
2174
- };
2175
- const isBoundary = (character, allowed) => character === "" || !allowed.test(character);
2176
- const mentions = (directory) => (text) => {
2177
- const parts = String$1.split(text, directory);
2178
- return pipe(Array.drop(parts, NEXT), Array.some((after, index) => {
2179
- const before = parts[index] ?? "";
2180
- const previous = String$1.slice(before.length - NEXT)(before);
2181
- const following = String$1.slice(FIRST, NEXT)(after);
2182
- return isBoundary(previous, PATH_CHARACTER) && (following === "/" || isBoundary(following, NAME_CHARACTER));
2183
- }));
2184
- };
2185
- const problemsIn = (file, source, directories) => (found) => pipe(directories, Array.filter((directory) => mentions(directory)(found.text)), Array.map((directory) => ({
2186
- file,
2187
- ...positionOf(source)(found.start),
2188
- rule: RULE,
2189
- message: `${directory} is a workspace. The root ${CONFIG_FILE} holds what applies to every workspace, so move what only ${directory} needs into ${directory}/${CONFIG_FILE}: msch.lint, msch.devDependencies or its verify task.`
2190
- })));
2191
2723
  /** @internal */
2192
- const checkRootWorkspacePaths = Effect.fn("checkRootWorkspacePaths")(function* checkRootWorkspacePaths(root) {
2724
+ const checkUnneededFiles = Effect.fn("checkUnneededFiles")(function* checkUnneededFiles(root) {
2193
2725
  const files = yield* RepositoryFiles;
2194
- const file = files.join(root, CONFIG_FILE);
2195
- const source = yield* files.readFile(file);
2196
- if (Option.isNone(source)) return [];
2197
- const directories = yield* workspaceDirectories(root);
2198
- const parsed = yield* Effect.promise(() => parse(file, source.value, { lang: "ts" }));
2199
- return pipe(stringsIn(parsed.program), Array.flatMap(problemsIn(file, source.value, directories)));
2726
+ const workspace = yield* files.readFile(files.join(root, WORKSPACE_FILE));
2727
+ if (Option.isNone(workspace)) return [];
2728
+ return yield* unneededIn(root, workspace.value);
2200
2729
  });
2201
- // src/workspace-checks.ts
2730
+ // src/app/tracked-text.ts
2202
2731
  /** @internal */
2203
- const checkWorkspaces = Effect.fn("checkWorkspaces")(function* checkWorkspaces(root) {
2732
+ const checkTrackedText = Effect.fn("checkTrackedText")(function* checkTrackedText(root) {
2204
2733
  const found = yield* Effect.all([
2205
- checkCrates(root),
2206
- checkHiddenVerify(root),
2207
- checkRootWorkspacePaths(root)
2734
+ checkHiddenUnicode(root),
2735
+ checkPython(root),
2736
+ checkUnneededFiles(root),
2737
+ checkComments(root)
2208
2738
  ], { concurrency: "unbounded" });
2209
2739
  return Array.flatten(found);
2210
2740
  });
2211
- // src/all-checks.ts
2741
+ // src/app/all-checks.ts
2212
2742
  /** @internal */
2213
2743
  const checkAll = Effect.fn("checkAll")(function* checkAll(root) {
2214
2744
  const found = yield* Effect.all([
@@ -2216,12 +2746,13 @@ const checkAll = Effect.fn("checkAll")(function* checkAll(root) {
2216
2746
  checkOverrides(root),
2217
2747
  checkTrackedText(root),
2218
2748
  checkPlacement(root),
2749
+ checkScripts(root),
2219
2750
  checkPublishedPackages(root),
2220
2751
  checkWorkspaces(root)
2221
2752
  ], { concurrency: "unbounded" });
2222
2753
  return Array.flatten(found);
2223
2754
  });
2224
- // src/output.ts
2755
+ // src/app/output.ts
2225
2756
  const taggedError = Schema.TaggedError;
2226
2757
  var ProblemsFound = class extends taggedError()("ProblemsFound", { count: Schema.Finite }) {};
2227
2758
  /** @internal */
@@ -2229,7 +2760,7 @@ const writeStdout = Effect.fn("writeStdout")(function* writeStdout(text) {
2229
2760
  const stdio = yield* Stdio.Stdio;
2230
2761
  yield* Stream.make(text).pipe(Stream.run(stdio.stdout()), Effect.orDie);
2231
2762
  });
2232
- // src/runtime.ts
2763
+ // src/app/runtime.ts
2233
2764
  const reportFailure = (cause) => Effect.gen(function* report() {
2234
2765
  const stdio = yield* Stdio.Stdio;
2235
2766
  if (Cause.findErrorOption(cause).pipe(Option.exists(Schema.is(ProblemsFound)))) return;
@@ -2242,7 +2773,7 @@ const runCli = (program) => {
2242
2773
  const main = Layer.build(services).pipe(Effect.flatMap((context) => Effect.provideContext(program.pipe(Effect.tapCause(reportFailure)), context)), Effect.scoped);
2243
2774
  runMain(main, { disableErrorReporting: true });
2244
2775
  };
2245
- // src/cli.ts
2776
+ // src/app/cli.ts
2246
2777
  const NO_PROBLEMS = 0;
2247
2778
  const reportText = (root, problems) => Effect.gen(function* report() {
2248
2779
  const files = yield* RepositoryFiles;