@shivaedev/quality 0.41.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +12 -8
  3. package/biome/plugins/effect-test-bodies.grit +1 -1
  4. package/dist/appTestConfig.js +1 -1
  5. package/dist/appTestConfig.js.map +1 -1
  6. package/dist/biome/withoutEntryPointImports.d.ts +4 -0
  7. package/dist/biome/withoutEntryPointImports.d.ts.map +1 -0
  8. package/dist/biome/withoutEntryPointImports.js +46 -0
  9. package/dist/biome/withoutEntryPointImports.js.map +1 -0
  10. package/dist/imports/pnpmWorkspacePatterns.d.ts +1 -0
  11. package/dist/imports/pnpmWorkspacePatterns.d.ts.map +1 -1
  12. package/dist/imports/pnpmWorkspacePatterns.js +28 -22
  13. package/dist/imports/pnpmWorkspacePatterns.js.map +1 -1
  14. package/dist/imports/runtime.d.ts +6 -0
  15. package/dist/imports/runtime.d.ts.map +1 -1
  16. package/dist/imports/runtime.js +54 -8
  17. package/dist/imports/runtime.js.map +1 -1
  18. package/dist/manifests/entryPoints.d.ts +15 -0
  19. package/dist/manifests/entryPoints.d.ts.map +1 -0
  20. package/dist/manifests/entryPoints.js +60 -0
  21. package/dist/manifests/entryPoints.js.map +1 -0
  22. package/dist/rules/biome.d.ts.map +1 -1
  23. package/dist/rules/biome.js +4 -2
  24. package/dist/rules/biome.js.map +1 -1
  25. package/dist/rules/builtIn.d.ts +1 -1
  26. package/dist/rules/builtIn.d.ts.map +1 -1
  27. package/dist/rules/builtIn.js +2 -0
  28. package/dist/rules/builtIn.js.map +1 -1
  29. package/dist/rules/imports/fences.d.ts +1 -1
  30. package/dist/rules/imports/manifest.d.ts.map +1 -1
  31. package/dist/rules/imports/manifest.js +27 -14
  32. package/dist/rules/imports/manifest.js.map +1 -1
  33. package/dist/rules/imports/runtime.d.ts.map +1 -1
  34. package/dist/rules/imports/runtime.js +10 -4
  35. package/dist/rules/imports/runtime.js.map +1 -1
  36. package/dist/rules/manifestsApplication.d.ts +2 -0
  37. package/dist/rules/manifestsApplication.d.ts.map +1 -0
  38. package/dist/rules/manifestsApplication.js +99 -0
  39. package/dist/rules/manifestsApplication.js.map +1 -0
  40. package/dist/rules/manifestsExportsShape.d.ts.map +1 -1
  41. package/dist/rules/manifestsExportsShape.js +5 -2
  42. package/dist/rules/manifestsExportsShape.js.map +1 -1
  43. package/dist/rules/stories/engineOf.js +1 -1
  44. package/dist/rules/stories/engineOf.js.map +1 -1
  45. package/dist/rules/test-names/colocated.d.ts.map +1 -1
  46. package/dist/rules/test-names/colocated.js +10 -6
  47. package/dist/rules/test-names/colocated.js.map +1 -1
  48. package/package.json +1 -1
  49. package/src/appTestConfig.ts +1 -1
  50. package/src/biome/withoutEntryPointImports.ts +52 -0
  51. package/src/imports/pnpmWorkspacePatterns.ts +29 -22
  52. package/src/imports/runtime.ts +69 -9
  53. package/src/manifests/entryPoints.ts +87 -0
  54. package/src/rules/biome.ts +4 -2
  55. package/src/rules/builtIn.ts +2 -0
  56. package/src/rules/imports/manifest.ts +42 -14
  57. package/src/rules/imports/runtime.ts +10 -4
  58. package/src/rules/manifestsApplication.ts +117 -0
  59. package/src/rules/manifestsExportsShape.ts +6 -2
  60. package/src/rules/stories/engineOf.ts +1 -1
  61. package/src/rules/test-names/colocated.ts +13 -6
  62. package/tsconfig/package.json +2 -0
@@ -1,4 +1,6 @@
1
- const KEY = /^(?:packages|"packages"|'packages')\s*:/u;
1
+ function keyPattern(key: string): RegExp {
2
+ return new RegExp(`^(?:${key}|"${key}"|'${key}')\\s*:`, "u");
3
+ }
2
4
 
3
5
  const ITEM = "-";
4
6
 
@@ -25,20 +27,20 @@ function withoutComment(line: string): string {
25
27
  return line.trimEnd();
26
28
  }
27
29
 
28
- function scalar(raw: string): string {
30
+ function scalar(raw: string, key: string): string {
29
31
  const value = raw.trim();
30
32
  if (value.startsWith('"') && value.endsWith('"') && value.length > 1) {
31
33
  try {
32
34
  return String(JSON.parse(value));
33
35
  } catch (error) {
34
- throw failure(`cannot read "${value}" in packages`, error);
36
+ throw failure(`cannot read "${value}" in ${key}`, error);
35
37
  }
36
38
  }
37
39
  if (value.startsWith("'") && value.endsWith("'") && value.length > 1) {
38
40
  return value.slice(1, -1).replaceAll("''", "'");
39
41
  }
40
42
  if (value === "" || value.includes(": ") || value.endsWith(":") || ["[", "{", "'", '"'].some((opening) => value.startsWith(opening))) {
41
- throw failure(`cannot read "${value}" in packages`);
43
+ throw failure(`cannot read "${value}" in ${key}`);
42
44
  }
43
45
  return value;
44
46
  }
@@ -51,20 +53,20 @@ interface FlowScan {
51
53
  quote: string | undefined;
52
54
  }
53
55
 
54
- function flowScalar(raw: string): string {
56
+ function flowScalar(raw: string, key: string): string {
55
57
  const value = raw.trim();
56
58
  const quoted = value.startsWith('"') || value.startsWith("'");
57
59
  if (!quoted && FLOW_INDICATOR.test(value)) {
58
- throw failure(`cannot read "${value}" in packages; quote a pattern that holds { } [ ] or ,`);
60
+ throw failure(`cannot read "${value}" in ${key}; quote a pattern that holds { } [ ] or ,`);
59
61
  }
60
- return scalar(value);
62
+ return scalar(value, key);
61
63
  }
62
64
 
63
- function closed(scan: FlowScan, rest: string): readonly string[] {
65
+ function closed(scan: FlowScan, rest: string, key: string): readonly string[] {
64
66
  if (rest.trim() !== "") {
65
- throw failure(`cannot read "${rest.trim()}" after the packages list`);
67
+ throw failure(`cannot read "${rest.trim()}" after the ${key} list`);
66
68
  }
67
- return [...scan.entries, scan.current].filter((entry) => entry.trim() !== "").map(flowScalar);
69
+ return [...scan.entries, scan.current].filter((entry) => entry.trim() !== "").map((entry) => flowScalar(entry, key));
68
70
  }
69
71
 
70
72
  function scanned(scan: FlowScan, char: string): "close" | undefined {
@@ -83,20 +85,20 @@ function scanned(scan: FlowScan, char: string): "close" | undefined {
83
85
  return undefined;
84
86
  }
85
87
 
86
- function flowList(lines: readonly string[]): readonly string[] {
88
+ function flowList(lines: readonly string[], key: string): readonly string[] {
87
89
  const scan: FlowScan = { current: "", entries: [], quote: undefined };
88
90
  for (const [number, line] of lines.map(withoutComment).entries()) {
89
91
  for (let index = number === 0 ? 1 : 0; index < line.length; index += 1) {
90
92
  if (scanned(scan, line[index] ?? "") === "close") {
91
- return closed(scan, line.slice(index + 1));
93
+ return closed(scan, line.slice(index + 1), key);
92
94
  }
93
95
  }
94
96
  scan.current += " ";
95
97
  }
96
- throw failure("the packages list never closes");
98
+ throw failure(`the ${key} list never closes`);
97
99
  }
98
100
 
99
- function blockList(lines: readonly string[]): readonly string[] {
101
+ function blockList(lines: readonly string[], key: string): readonly string[] {
100
102
  const patterns: string[] = [];
101
103
  for (const line of lines.map(withoutComment)) {
102
104
  const trimmed = line.trim();
@@ -108,27 +110,32 @@ function blockList(lines: readonly string[]): readonly string[] {
108
110
  break;
109
111
  }
110
112
  if (!item) {
111
- throw failure(`cannot read "${trimmed}" in packages`);
113
+ throw failure(`cannot read "${trimmed}" in ${key}`);
112
114
  }
113
- patterns.push(scalar(trimmed.slice(ITEM.length)));
115
+ patterns.push(scalar(trimmed.slice(ITEM.length), key));
114
116
  }
115
117
  return patterns;
116
118
  }
117
119
 
118
- export function pnpmWorkspacePatterns(text: string): readonly string[] {
120
+ export function pnpmWorkspaceList(text: string, key: string): readonly string[] {
121
+ const pattern = keyPattern(key);
119
122
  const lines = text.split(LINE_BREAK);
120
- const start = lines.findIndex((line) => KEY.test(line));
123
+ const start = lines.findIndex((line) => pattern.test(line));
121
124
  if (start === -1) {
122
125
  return [];
123
126
  }
124
127
  const rest = withoutComment(lines[start] ?? "")
125
- .replace(KEY, "")
128
+ .replace(pattern, "")
126
129
  .trim();
127
130
  if (rest.startsWith("[")) {
128
- return flowList([rest, ...lines.slice(start + 1)]);
131
+ return flowList([rest, ...lines.slice(start + 1)], key);
129
132
  }
130
133
  if (rest !== "") {
131
- throw failure(`cannot read "${rest}" in packages`);
134
+ throw failure(`cannot read "${rest}" in ${key}`);
132
135
  }
133
- return blockList(lines.slice(start + 1));
136
+ return blockList(lines.slice(start + 1), key);
137
+ }
138
+
139
+ export function pnpmWorkspacePatterns(text: string): readonly string[] {
140
+ return pnpmWorkspaceList(text, "packages");
134
141
  }
@@ -6,27 +6,43 @@ import { packageOf, type WorkspacePackage } from "./workspace.ts";
6
6
 
7
7
  export type Runtime = "client" | "server" | "shared";
8
8
 
9
+ export type DeclaredRuntime = "client" | "server";
10
+
9
11
  function executablePath(value: unknown): boolean {
10
12
  return typeof value === "string" && value.trim().length > 0;
11
13
  }
12
14
 
13
- function hasExecutable(root: string, directory: string): boolean {
15
+ function readManifest(root: string, directory: string): object | undefined {
14
16
  const path = join(root, directory, "package.json");
15
17
  try {
16
18
  const manifest: unknown = JSON.parse(readFileSync(path, "utf8"));
17
19
  if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) {
18
20
  throw new Error("the manifest must be an object");
19
21
  }
20
- const bin: unknown = Reflect.get(manifest, "bin");
21
- return executablePath(bin) || (typeof bin === "object" && bin !== null && !Array.isArray(bin) && Object.values(bin).some(executablePath));
22
+ return manifest;
22
23
  } catch (cause) {
23
24
  if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
24
- return false;
25
+ return undefined;
25
26
  }
26
27
  throw new Error(`cannot read runtime policy at ${path}`, { cause });
27
28
  }
28
29
  }
29
30
 
31
+ function hasExecutable(manifest: object | undefined): boolean {
32
+ const bin: unknown = manifest === undefined ? undefined : Reflect.get(manifest, "bin");
33
+ return executablePath(bin) || (typeof bin === "object" && bin !== null && !Array.isArray(bin) && Object.values(bin).some(executablePath));
34
+ }
35
+
36
+ function declaredValue(manifest: object | undefined): unknown {
37
+ const quality: unknown = manifest === undefined ? undefined : Reflect.get(manifest, "quality");
38
+ return typeof quality === "object" && quality !== null ? Reflect.get(quality, "runtime") : undefined;
39
+ }
40
+
41
+ function declaredRuntime(manifest: object | undefined): DeclaredRuntime | undefined {
42
+ const value = declaredValue(manifest);
43
+ return value === "client" || value === "server" ? value : undefined;
44
+ }
45
+
30
46
  function directoryExists(path: string): boolean {
31
47
  try {
32
48
  return statSync(path).isDirectory();
@@ -38,19 +54,63 @@ function directoryExists(path: string): boolean {
38
54
  }
39
55
  }
40
56
 
57
+ type Owner = Pick<WorkspacePackage, "directory">;
58
+
59
+ function runtimeFoldersOf(root: string, owner: Owner): readonly string[] {
60
+ return ["client", "server"].filter((folder) => directoryExists(join(root, owner.directory, "src", folder)));
61
+ }
62
+
63
+ export interface RuntimeDeclarationProblem {
64
+ readonly directory: string;
65
+ readonly message: string;
66
+ }
67
+
68
+ export function runtimeDeclarationProblems(inputs: RuleInputs, packages: readonly WorkspacePackage[]): readonly RuntimeDeclarationProblem[] {
69
+ return [...packages, { directory: ".", name: "." }].flatMap((owner) => {
70
+ const value = declaredValue(readManifest(inputs.root, owner.directory));
71
+ if (value === undefined) {
72
+ return [];
73
+ }
74
+ if (value !== "client" && value !== "server") {
75
+ return [
76
+ {
77
+ directory: owner.directory,
78
+ message: `"quality.runtime" is ${JSON.stringify(value)}. Declare "client" or "server" for a package whose code runs in one runtime, or remove the field and use src/client/ and src/server/.`,
79
+ },
80
+ ];
81
+ }
82
+ const folders = runtimeFoldersOf(inputs.root, owner);
83
+ return folders.length === 0
84
+ ? []
85
+ : [
86
+ {
87
+ directory: owner.directory,
88
+ message: `"quality.runtime" declares the whole package ${value} code, but it also has ${folders.map((folder) => `src/${folder}/`).join(" and ")}. Keep one convention: remove the declaration and classify code by runtime folders, or move the code out of the runtime folders.`,
89
+ },
90
+ ];
91
+ });
92
+ }
93
+
41
94
  export function runtimeOf(inputs: RuleInputs, packages: readonly WorkspacePackage[]): (path: string) => Runtime | undefined {
42
95
  const owners = [...packages, { directory: ".", name: "." }];
43
- const adopted = new Set(
44
- owners
45
- .filter((owner) => ["client", "server"].some((folder) => directoryExists(join(inputs.root, owner.directory, "src", folder))))
46
- .map((owner) => owner.directory),
96
+ const manifests = new Map(owners.map((owner) => [owner.directory, readManifest(inputs.root, owner.directory)]));
97
+ const adopted = new Set(owners.filter((owner) => runtimeFoldersOf(inputs.root, owner).length > 0).map((owner) => owner.directory));
98
+ const declared = new Map(
99
+ owners.flatMap((owner) => {
100
+ const runtime = declaredRuntime(manifests.get(owner.directory));
101
+ return runtime === undefined || adopted.has(owner.directory) ? [] : [[owner.directory, runtime] as const];
102
+ }),
47
103
  );
48
- const executable = new Set(owners.filter((owner) => hasExecutable(inputs.root, owner.directory)).map((owner) => owner.directory));
104
+ const executable = new Set(owners.filter((owner) => hasExecutable(manifests.get(owner.directory))).map((owner) => owner.directory));
49
105
  return (path) => {
50
106
  const owner = packageOf(packages, path)?.directory ?? ".";
51
107
  if (isTooling(owner, path)) {
52
108
  return "server";
53
109
  }
110
+ const whole = declared.get(owner);
111
+ if (whole !== undefined) {
112
+ return whole;
113
+ }
54
114
  if (!adopted.has(owner)) {
55
115
  return executable.has(owner) ? "server" : undefined;
56
116
  }
@@ -0,0 +1,87 @@
1
+ import { posix } from "node:path";
2
+ import type { RuleInputs } from "#rule.ts";
3
+
4
+ export const SHIPPED_FIELDS = ["dependencies", "peerDependencies", "optionalDependencies"] as const;
5
+
6
+ export const DEPENDENCY_FIELDS = [...SHIPPED_FIELDS, "devDependencies"] as const;
7
+
8
+ export const PLATFORM = "@shivaedev/platform";
9
+
10
+ const ENTRY_POINTS = [
11
+ { name: PLATFORM, testOnly: false },
12
+ { name: "@shivaedev/test-story", testOnly: true },
13
+ ] as const;
14
+
15
+ export interface EntryPoint {
16
+ readonly declared: "development" | "shipped" | undefined;
17
+ readonly name: string;
18
+ readonly provides: ReadonlySet<string>;
19
+ readonly testOnly: boolean;
20
+ }
21
+
22
+ export function dependencyNames(manifest: unknown, field: string): readonly string[] {
23
+ const value: unknown = typeof manifest === "object" && manifest !== null ? Reflect.get(manifest, field) : undefined;
24
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? Object.keys(value) : [];
25
+ }
26
+
27
+ function parsed(text: string | undefined): unknown {
28
+ if (text === undefined) {
29
+ return undefined;
30
+ }
31
+ try {
32
+ return JSON.parse(text);
33
+ } catch {
34
+ return undefined;
35
+ }
36
+ }
37
+
38
+ async function installedManifest(inputs: Pick<RuleInputs, "readText">, directory: string, name: string, workspace: ReadonlyMap<string, string>) {
39
+ const candidates = [
40
+ ...(workspace.has(name) ? [posix.join(workspace.get(name) ?? ".", "package.json")] : []),
41
+ posix.join(directory, "node_modules", name, "package.json"),
42
+ posix.join("node_modules", name, "package.json"),
43
+ ];
44
+ for (const candidate of candidates) {
45
+ const manifest = parsed(await inputs.readText(candidate));
46
+ if (manifest !== undefined) {
47
+ return manifest;
48
+ }
49
+ }
50
+ return undefined;
51
+ }
52
+
53
+ function declaration(manifest: unknown, name: string): EntryPoint["declared"] {
54
+ if (SHIPPED_FIELDS.some((field) => dependencyNames(manifest, field).includes(name))) {
55
+ return "shipped";
56
+ }
57
+ return dependencyNames(manifest, "devDependencies").includes(name) ? "development" : undefined;
58
+ }
59
+
60
+ export function entryPointsOf(
61
+ inputs: Pick<RuleInputs, "readText">,
62
+ directory: string,
63
+ manifest: unknown,
64
+ workspace: ReadonlyMap<string, string>,
65
+ ): Promise<readonly EntryPoint[]> {
66
+ return Promise.all(
67
+ ENTRY_POINTS.map(async ({ name, testOnly }) => ({
68
+ declared: declaration(manifest, name),
69
+ name,
70
+ provides: new Set(dependencyNames(await installedManifest(inputs, directory, name, workspace), "dependencies")),
71
+ testOnly,
72
+ })),
73
+ );
74
+ }
75
+
76
+ export function isApplication(manifest: unknown): boolean {
77
+ return DEPENDENCY_FIELDS.some((field) => dependencyNames(manifest, field).includes(PLATFORM));
78
+ }
79
+
80
+ export function provider(entryPoints: readonly EntryPoint[], target: string, development: boolean, declaredOnly: boolean) {
81
+ return entryPoints.find(
82
+ (entry) =>
83
+ entry.provides.has(target)
84
+ && (development || !entry.testOnly)
85
+ && (declaredOnly ? entry.declared === "shipped" || (entry.declared === "development" && development) : entry.declared === undefined),
86
+ );
87
+ }
@@ -1,4 +1,5 @@
1
1
  import { biomeReport, type Diagnostic, FAILING } from "#biome/report.ts";
2
+ import { withoutEntryPointImports } from "#biome/withoutEntryPointImports.ts";
2
3
  import { defineRule, type Finding, type Rule, type RuleInputs } from "#rule.ts";
3
4
  import { itemsOf, member, parseJsonc, textOf } from "#rules/suppressions/biome/json.ts";
4
5
 
@@ -43,10 +44,11 @@ async function presetFinding(readText: RuleInputs["readText"]): Promise<readonly
43
44
  const bridge = defineRule({
44
45
  check: async ({ exceptions, readText, root }) => {
45
46
  const [preset, report] = await Promise.all([presetFinding(readText), biomeReport(root, ["check"], exceptions)]);
46
- return [...preset, ...report.diagnostics.filter((diagnostic) => FAILING.has(diagnostic.severity)).map(findingOf)];
47
+ const failing = report.diagnostics.filter((diagnostic) => FAILING.has(diagnostic.severity));
48
+ return [...preset, ...(await withoutEntryPointImports(readText, failing)).map(findingOf)];
47
49
  },
48
50
  description:
49
- "Biome's lint, format and assist findings under the shared preset. `quality fix` applies Biome's lint fixes, unsafe ones included, its assist actions and formatting.",
51
+ "Biome's lint, format and assist findings under the shared preset, except undeclared-dependency findings for a piece that an application's entry point brings. `quality fix` applies Biome's lint fixes, unsafe ones included, its assist actions and formatting.",
50
52
  id: "biome",
51
53
  registrable: false,
52
54
  });
@@ -34,6 +34,7 @@ import { noInline } from "#rules/suppressions/noInline.ts";
34
34
  import { testsColocated } from "#rules/test-names/colocated.ts";
35
35
  import { testsFollow } from "#rules/test-names/follow.ts";
36
36
  import { biome } from "./biome.ts";
37
+ import { manifestsApplication } from "./manifestsApplication.ts";
37
38
  import { manifestsExportsShape } from "./manifestsExportsShape.ts";
38
39
  import { manifestsSorted } from "./manifestsSorted.ts";
39
40
  import { manifestsSourceFirst } from "./manifestsSourceFirst.ts";
@@ -68,6 +69,7 @@ export const builtInRules = [
68
69
  manifestsSorted,
69
70
  manifestsSourceFirst,
70
71
  manifestsExportsShape,
72
+ manifestsApplication,
71
73
  namedAfterExport,
72
74
  folderNames,
73
75
  distinctCase,
@@ -3,6 +3,7 @@ import { type ImportGraph, importGraph } from "#imports/graph.ts";
3
3
  import { isTooling } from "#imports/isTooling.ts";
4
4
  import { builtinName } from "#imports/resolve.ts";
5
5
  import { packageOf, type WorkspacePackage } from "#imports/workspace.ts";
6
+ import { type EntryPoint, entryPointsOf, isApplication, provider, SHIPPED_FIELDS } from "#manifests/entryPoints.ts";
6
7
  import { isTestCode } from "#naming/testName.ts";
7
8
  import { defineRule, type RuleInputs } from "#rule.ts";
8
9
  import { bundleInputs } from "./bundleInputs.ts";
@@ -21,7 +22,10 @@ function packageName(specifier: string): string {
21
22
  }
22
23
 
23
24
  interface ManifestDependencies {
25
+ readonly application: boolean;
24
26
  readonly development: ReadonlySet<string>;
27
+ readonly entryPoints: readonly EntryPoint[];
28
+ readonly private: boolean;
25
29
  readonly privateFiles: ReadonlySet<string>;
26
30
  readonly runtime: ReadonlySet<string>;
27
31
  readonly shipped: ReadonlySet<string>;
@@ -38,7 +42,12 @@ function names(manifest: object, field: string): readonly string[] {
38
42
  return Object.keys(value);
39
43
  }
40
44
 
41
- async function manifestDependencies(inputs: RuleInputs, owner: WorkspacePackage, graph: ImportGraph): Promise<ManifestDependencies> {
45
+ async function manifestDependencies(
46
+ inputs: RuleInputs,
47
+ owner: WorkspacePackage,
48
+ graph: ImportGraph,
49
+ workspace: ReadonlyMap<string, string>,
50
+ ): Promise<ManifestDependencies> {
42
51
  const path = posix.join(owner.directory, "package.json");
43
52
  try {
44
53
  const text = await inputs.readText(path);
@@ -51,8 +60,11 @@ async function manifestDependencies(inputs: RuleInputs, owner: WorkspacePackage,
51
60
  }
52
61
  return {
53
62
  ...bundleInputs(graph, owner, manifest, (candidate) => developmentFile(owner, candidate)),
63
+ application: isApplication(manifest),
54
64
  development: new Set(names(manifest, "devDependencies")),
55
- shipped: new Set(["dependencies", "peerDependencies", "optionalDependencies"].flatMap((field) => names(manifest, field))),
65
+ entryPoints: await entryPointsOf(inputs, owner.directory, manifest, workspace),
66
+ private: Reflect.get(manifest, "private") === true,
67
+ shipped: new Set(SHIPPED_FIELDS.flatMap((field) => names(manifest, field))),
56
68
  };
57
69
  } catch (cause) {
58
70
  throw new Error(`cannot read dependency policy at ${path}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
@@ -70,12 +82,35 @@ function developmentImport(policy: ManifestDependencies | undefined, owner: Work
70
82
  return developmentFile(owner, path) || policy?.privateFiles.has(path);
71
83
  }
72
84
 
85
+ function declares(policy: ManifestDependencies, target: string, development: boolean): boolean {
86
+ return (
87
+ policy.shipped.has(target)
88
+ || (development && policy.development.has(target))
89
+ || (policy.application && provider(policy.entryPoints, target, development, true) !== undefined)
90
+ );
91
+ }
92
+
93
+ function undeclared(owner: WorkspacePackage, policy: ManifestDependencies | undefined, target: string, development: boolean): string {
94
+ const missing = policy?.private === true ? provider(policy.entryPoints, target, development, false) : undefined;
95
+ const entryPoint =
96
+ missing === undefined
97
+ ? ""
98
+ : ` An application can instead add "${missing.name}" to ${missing.testOnly ? "devDependencies" : "dependencies"}, which brings it.`;
99
+ const scope = development
100
+ ? " Tooling, test code and export-blocked bundle inputs may also use devDependencies."
101
+ : " devDependencies are only available to tests, test support, tooling and export-blocked bundle inputs unreachable from runtime code.";
102
+ return `Imports workspace package "${target}" without declaring it in ${posix.join(owner.directory, "package.json")}. Add it to dependencies, peerDependencies or optionalDependencies, or remove the import.${entryPoint}${scope}`;
103
+ }
104
+
73
105
  export const importsManifest = defineRule({
74
106
  check: async (inputs) => {
75
107
  const graph = await importGraph(inputs);
76
108
  const root: WorkspacePackage | undefined = (await inputs.readText("package.json")) === undefined ? undefined : { directory: ".", name: "." };
77
109
  const owners = [...graph.packages, ...(root === undefined ? [] : [root])];
78
- const policies = new Map(await Promise.all(owners.map(async (owner) => [owner, await manifestDependencies(inputs, owner, graph)] as const)));
110
+ const workspace = new Map(graph.packages.map((owner) => [owner.name, owner.directory]));
111
+ const policies = new Map(
112
+ await Promise.all(owners.map(async (owner) => [owner, await manifestDependencies(inputs, owner, graph, workspace)] as const)),
113
+ );
79
114
  const runtime = new Set([...policies.values()].flatMap((policy) => [...policy.runtime]));
80
115
  const named = new Map(graph.packages.map((owner) => [owner.name, owner]));
81
116
  const requests = [...graph.edges, ...graph.unresolved.filter((request) => request.missing === undefined)];
@@ -88,21 +123,14 @@ export const importsManifest = defineRule({
88
123
  return [];
89
124
  }
90
125
  const policy = policies.get(owner);
91
- const development = developmentImport(policy, owner, request.from, runtime);
92
- if (policy?.shipped.has(target.name) || (development && policy?.development.has(target.name))) {
126
+ const development = developmentImport(policy, owner, request.from, runtime) === true;
127
+ if (policy !== undefined && declares(policy, target.name, development)) {
93
128
  return [];
94
129
  }
95
- return [
96
- {
97
- file: request.from,
98
- line: request.line,
99
- message: `Imports workspace package "${target.name}" without declaring it in ${posix.join(owner.directory, "package.json")}. Add it to dependencies, peerDependencies or optionalDependencies, or remove the import.${development ? " Tooling, test code and export-blocked bundle inputs may also use devDependencies." : " devDependencies are only available to tests, test support, tooling and export-blocked bundle inputs unreachable from runtime code."}`,
100
- subject: target.name,
101
- },
102
- ];
130
+ return [{ file: request.from, line: request.line, message: undeclared(owner, policy, target.name, development), subject: target.name }];
103
131
  });
104
132
  },
105
133
  description:
106
- "Workspace imports follow the importing package's manifest; devDependencies are available only outside runtime code, including export-blocked bundle inputs.",
134
+ "Workspace imports follow the importing package's manifest; devDependencies are available only outside runtime code, including export-blocked bundle inputs, and an application also reaches the dependencies of the entry points it declares: @shivaedev/platform for any code and @shivaedev/test-story for test code.",
107
135
  id: "imports/manifest",
108
136
  });
@@ -1,6 +1,6 @@
1
1
  import { importGraph } from "#imports/graph.ts";
2
2
  import { builtinName } from "#imports/resolve.ts";
3
- import { type Runtime, runtimeOf } from "#imports/runtime.ts";
3
+ import { type Runtime, runtimeDeclarationProblems, runtimeOf } from "#imports/runtime.ts";
4
4
  import { isTestCode } from "#naming/testName.ts";
5
5
  import { defineRule } from "#rule.ts";
6
6
 
@@ -34,14 +34,20 @@ export const importsRuntime = defineRule({
34
34
  },
35
35
  ];
36
36
  });
37
+ const declarations = runtimeDeclarationProblems(inputs, graph.packages).map(({ directory, message }) => ({
38
+ file: directory === "." ? "package.json" : `${directory}/package.json`,
39
+ line: 1,
40
+ message,
41
+ subject: "quality.runtime",
42
+ }));
37
43
  const shared = inputs.sources.filter((file) => !isTestCode(file.path) && runtime(file.path) === "shared");
38
44
  if (shared.length === 0) {
39
- return imports;
45
+ return [...imports, ...declarations];
40
46
  }
41
47
  const { browserGlobals } = await import("#imports/browserGlobals.ts");
42
- return [...imports, ...shared.flatMap(browserGlobals)];
48
+ return [...imports, ...declarations, ...shared.flatMap(browserGlobals)];
43
49
  },
44
50
  description:
45
- "Runtime folders define client, server and shared code. Executable packages without runtime folders and package-root tooling are server code.",
51
+ "Runtime folders define client, server and shared code. A manifest's quality.runtime declares a single-runtime package whole; executable packages without runtime folders and package-root tooling are server code.",
46
52
  id: "imports/runtime",
47
53
  });
@@ -0,0 +1,117 @@
1
+ import { dirname, posix, relative, resolve, sep } from "node:path";
2
+ import { pnpmWorkspaceList } from "#imports/pnpmWorkspacePatterns.ts";
3
+ import { workspacePackages } from "#imports/workspace.ts";
4
+ import { DEPENDENCY_FIELDS, dependencyNames, entryPointsOf, isApplication, PLATFORM } from "#manifests/entryPoints.ts";
5
+ import { defineRule, type Finding, type RuleInputs } from "#rule.ts";
6
+
7
+ const HOISTED = "@shivaedev/*";
8
+
9
+ const HOIST_KEY = "publicHoistPattern";
10
+
11
+ const HOIST_LINE = `${HOIST_KEY}: ["${HOISTED}"]`;
12
+
13
+ const PROBE = "@shivaedev/probe";
14
+
15
+ function hoists(pattern: string): boolean {
16
+ const source = pattern.replaceAll(/[.+?^${}()|[\]\\]/gu, "\\$&").replaceAll("*", ".*");
17
+ return new RegExp(`^${source}$`, "u").test(PROBE);
18
+ }
19
+
20
+ function parsed(text: string | undefined): unknown {
21
+ if (text === undefined) {
22
+ return undefined;
23
+ }
24
+ try {
25
+ return JSON.parse(text);
26
+ } catch {
27
+ return undefined;
28
+ }
29
+ }
30
+
31
+ function ancestors(root: string, directory: string): readonly string[] {
32
+ const start = resolve(root, directory);
33
+ const parent = dirname(start);
34
+ return parent === start ? [start] : [start, ...ancestors(root, relative(root, parent))];
35
+ }
36
+
37
+ async function nearestWorkspace(inputs: Pick<RuleInputs, "readText" | "root">, directory: string) {
38
+ for (const candidate of ancestors(inputs.root, directory)) {
39
+ const path = posix.join(relative(inputs.root, candidate).split(sep).join("/") || ".", "pnpm-workspace.yaml");
40
+ const text = await inputs.readText(path);
41
+ if (text !== undefined) {
42
+ return { path, text };
43
+ }
44
+ }
45
+ return undefined;
46
+ }
47
+
48
+ async function hoistFindings(inputs: Pick<RuleInputs, "readText" | "root">, manifestPath: string, directory: string): Promise<readonly Finding[]> {
49
+ const workspace = await nearestWorkspace(inputs, directory);
50
+ const target = workspace?.path ?? posix.join(directory, "pnpm-workspace.yaml");
51
+ const repair = `Add \`${HOIST_LINE}\` to ${target} so the pieces platform brings resolve by their own names.`;
52
+ if (workspace === undefined) {
53
+ return [{ file: manifestPath, message: `Depends on "${PLATFORM}" without a pnpm-workspace.yaml. ${repair}`, subject: HOIST_KEY }];
54
+ }
55
+ let patterns: readonly string[];
56
+ try {
57
+ patterns = pnpmWorkspaceList(workspace.text, HOIST_KEY);
58
+ } catch (cause) {
59
+ return [{ file: workspace.path, message: `${cause instanceof Error ? cause.message : String(cause)}. Write ${HOIST_LINE}.`, subject: HOIST_KEY }];
60
+ }
61
+ const included = patterns.some((pattern) => !pattern.startsWith("!") && hoists(pattern));
62
+ const excluded = patterns.some((pattern) => pattern.startsWith("!") && hoists(pattern.slice(1)));
63
+ if (included && !excluded) {
64
+ return [];
65
+ }
66
+ return [
67
+ { file: manifestPath, message: `Depends on "${PLATFORM}", but ${workspace.path} does not hoist ${HOISTED}. ${repair}`, subject: HOIST_KEY },
68
+ ];
69
+ }
70
+
71
+ async function duplicateFindings(
72
+ inputs: Pick<RuleInputs, "readText">,
73
+ manifestPath: string,
74
+ directory: string,
75
+ manifest: unknown,
76
+ workspace: ReadonlyMap<string, string>,
77
+ ): Promise<readonly Finding[]> {
78
+ const entryPoints = (await entryPointsOf(inputs, directory, manifest, workspace)).filter((entry) => entry.declared !== undefined);
79
+ return DEPENDENCY_FIELDS.flatMap((field) =>
80
+ dependencyNames(manifest, field).flatMap((name) => {
81
+ const entry = entryPoints.find((candidate) => candidate.provides.has(name));
82
+ return entry === undefined
83
+ ? []
84
+ : [
85
+ {
86
+ file: manifestPath,
87
+ message: `Lists "${name}" in ${field} beside "${entry.name}", which already brings it. Remove "${name}" from ${field} and keep importing it by its own name.`,
88
+ subject: name,
89
+ },
90
+ ];
91
+ }),
92
+ );
93
+ }
94
+
95
+ export const manifestsApplication = defineRule({
96
+ check: async (inputs) => {
97
+ const packages = await workspacePackages(inputs);
98
+ const workspace = new Map(packages.map((owner) => [owner.name, owner.directory]));
99
+ const directories = [".", ...packages.map((owner) => owner.directory)];
100
+ const findings = await Promise.all(
101
+ directories.map(async (directory) => {
102
+ const manifestPath = posix.join(directory, "package.json");
103
+ const manifest = parsed(await inputs.readText(manifestPath));
104
+ if (!isApplication(manifest)) {
105
+ return [];
106
+ }
107
+ return [
108
+ ...(await hoistFindings(inputs, manifestPath, directory)),
109
+ ...(await duplicateFindings(inputs, manifestPath, directory, manifest, workspace)),
110
+ ];
111
+ }),
112
+ );
113
+ return findings.flat();
114
+ },
115
+ description: `An application, a package that depends on ${PLATFORM}, hoists ${HOISTED} in its nearest pnpm-workspace.yaml and lists no package beside the entry point that already brings it.`,
116
+ id: "manifests/application",
117
+ });
@@ -45,8 +45,11 @@ function findingsIn(file: string, exports: unknown): readonly Finding[] {
45
45
  }
46
46
  const entries = Object.entries(exports);
47
47
  const patterns = entries.filter(([key, value]) => key.includes("*") && value !== null);
48
+ const exportsModules = entries.some(([key, value]) => value !== null && !exactAsset(key, value));
48
49
  const count =
49
- patterns.length === 1 ? [] : [finding(file, "exports", `The exports field needs exactly one non-null wildcard; found ${patterns.length}.`)];
50
+ patterns.length === 1 || (patterns.length === 0 && !exportsModules)
51
+ ? []
52
+ : [finding(file, "exports", `The exports field needs exactly one non-null wildcard; found ${patterns.length}.`)];
50
53
  return [
51
54
  ...count,
52
55
  ...entries.flatMap(([key, value]) =>
@@ -73,7 +76,8 @@ export const manifestsExportsShape = defineRule({
73
76
  );
74
77
  return findings.flat();
75
78
  },
76
- description: "Workspace packages export modules through one file-preserving wildcard, with optional root, exact non-code assets and null blocks.",
79
+ description:
80
+ "Workspace packages export modules through one file-preserving wildcard, with optional root, exact non-code assets and null blocks; a package without modules exports only exact assets.",
77
81
  id: "manifests/exports-shape",
78
82
  registrable: false,
79
83
  });
@@ -50,7 +50,7 @@ const ENGINES: ReadonlyArray<readonly [string, readonly string[]]> = [
50
50
  ],
51
51
  ],
52
52
  ["the DOM", ["@happy-dom/", "@playwright/test", "@testing-library/", "happy-dom", "jsdom", "playwright", "react-dom"]],
53
- ["a story engine", ["@shivaedev/effect-test-sql", "@shivaedev/local-postgres", "@shivaedev/test-story"]],
53
+ ["a story engine", ["@shivaedev/test-sql", "@shivaedev/local-postgres", "@shivaedev/test-story"]],
54
54
  ];
55
55
 
56
56
  function names(prefix: string, specifier: string): boolean {