@stateward/core 1.1.0 → 1.2.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/rollout.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { ruleIds } from "./severity.js";
4
+ import { renamedRule } from "./renamed.js";
4
5
  export const ROLLOUT_FILE = "stateward.rollout.json";
5
6
  const ROLLOUT_VERSION = 1;
6
7
  /**
@@ -58,7 +59,8 @@ function parseEnabled(text, file, known) {
58
59
  const seen = new Set();
59
60
  const kept = [];
60
61
  for (const listed of enabled) {
61
- const id = listed;
62
+ // A renamed rule is read under its new id; the next write saves that one.
63
+ const id = known.has(listed) ? listed : (renamedRule(listed) ?? listed);
62
64
  if (!known.has(id)) {
63
65
  throw broken(file, `lists "${id}", which is not a rule of your packs`, `remove "${id}" from its "enabled" list; the other rules stay on`);
64
66
  }
package/dist/testing.js CHANGED
@@ -86,14 +86,18 @@ const MIN_EXAMPLE_INDENT = 4;
86
86
  function withoutNames(line) {
87
87
  return line.replace(/`[^`]*`/g, "");
88
88
  }
89
- /** A hint is one line, or one line and an indented code example of up to four lines. */
90
- function hintProblems(hint) {
91
- const [first = "", ...example] = hint.split(/\r?\n/);
92
- const problems = lineProblems("fix hint", first, undefined);
93
- const words = withoutNames(first);
94
- if (words.length > MAX_HINT_LENGTH) {
95
- problems.push(`fix hint words are ${String(words.length)} characters without its names; at most ${String(MAX_HINT_LENGTH)}`);
96
- }
89
+ /** The words of one line of a fix, its names left out, must fit the fix line's limit. */
90
+ function wordsProblems(label, line) {
91
+ const words = withoutNames(line);
92
+ return words.length > MAX_HINT_LENGTH
93
+ ? [
94
+ `${label} words are ${String(words.length)} characters without its names; at most ${String(MAX_HINT_LENGTH)}`,
95
+ ]
96
+ : [];
97
+ }
98
+ /** A code example: up to four lines, each indented 4 spaces and at most 100 characters. */
99
+ function exampleProblems(example) {
100
+ const problems = [];
97
101
  if (example.length > MAX_EXAMPLE_LINES) {
98
102
  problems.push(`fix hint example has ${String(example.length)} lines; at most ${String(MAX_EXAMPLE_LINES)}`);
99
103
  }
@@ -107,6 +111,42 @@ function hintProblems(hint) {
107
111
  }
108
112
  return problems;
109
113
  }
114
+ /**
115
+ * A hint is one line, or one line and an indented code example of up to four lines (M2). With
116
+ * several ways to fix (M22) it is `one of`, then one `- ` line per way, each starting with its
117
+ * action in lowercase and every one after the first with `or`, each with its own example.
118
+ */
119
+ function hintProblems(hint) {
120
+ const [first = "", ...rest] = hint.split(/\r?\n/);
121
+ const problems = lineProblems("fix hint", first, undefined);
122
+ problems.push(...wordsProblems("fix hint", first));
123
+ if (!rest.some((line) => line.startsWith("- ")))
124
+ return [...problems, ...exampleProblems(rest)];
125
+ if (first !== "one of")
126
+ problems.push('a fix hint with ways to fix must start with "one of"');
127
+ const ways = [];
128
+ for (const line of rest) {
129
+ const last = ways.at(-1);
130
+ if (line.startsWith("- "))
131
+ ways.push({ line, example: [] });
132
+ else if (last === undefined)
133
+ problems.push(`fix hint line "${line}" must follow a way to fix`);
134
+ else
135
+ last.example.push(line);
136
+ }
137
+ if (ways.length < 2)
138
+ problems.push('a fix hint with "one of" needs two ways to fix or more');
139
+ ways.forEach((way, index) => {
140
+ const text = way.line.slice(2);
141
+ problems.push(...wordsProblems("fix hint way", text), ...exampleProblems(way.example));
142
+ if (!/^[a-z]/.test(text))
143
+ problems.push(`fix hint way "${text}" must start in lowercase`);
144
+ if (index > 0 && !/^or\b/.test(text)) {
145
+ problems.push(`fix hint way "${text}" must start with "or"`);
146
+ }
147
+ });
148
+ return problems;
149
+ }
110
150
  function lineProblems(label, text, maxLength) {
111
151
  const problems = [];
112
152
  if (text.trim().length === 0)
package/dist/types.d.ts CHANGED
@@ -379,7 +379,9 @@ export type TypeQueries = {
379
379
  * `"not-object"` for a primitive, a union, an array, a tuple or an array-like (a number index and a numeric `length`, such as
380
380
  * `RegExpMatchArray`): the rules that ask do not apply.
381
381
  * `"generic"` when the keys depend on a type parameter (`Record<K, string>`, `{ [P in K]: n }`):
382
- * the properties are not known until `K` is, so the type has no key list to judge.
382
+ * the properties are not known until `K` is, so the type has no key list to judge. Also when a
383
+ * mapped type takes its keys from a type that does not resolve (`keyof typeof NAMES` from a
384
+ * package that is not installed): TypeScript then gives it an index signature for every key.
383
385
  */
384
386
  propertyKeysOf(node: ts.Node): {
385
387
  required: readonly string[];
@@ -430,16 +432,73 @@ export type TypeQueries = {
430
432
  */
431
433
  uniqueSymbolKeyFiles(node: ts.Node): readonly string[];
432
434
  /**
433
- * The guarantees a type states: the string literals of its optional `__guarantee` property
434
- * (`Context<T> & { readonly __guarantee?: "required-context" }`), sorted. The type is the one
435
- * of an expression or type node, or the declared type of a symbol (a variable's type, a type
436
- * alias's type), resolved through aliases, generics and re-exports. A type parameter is widened
437
- * to its constraint; `null` and `undefined` members are left out, and every other member of a
438
- * union must state a guarantee for it to count. Empty for a type that states none, or whose
439
- * `__guarantee` is required or not a string literal (that is a brand, not a guarantee). The
435
+ * The guarantees a type states: one name per optional `"__guarantee:<name>"` property
436
+ * (`Context<T> & { readonly "__guarantee:required-context"?: true }`), and the string literals of
437
+ * an optional `__guarantee` property (the 1.1.0 form, `{ readonly __guarantee?: "owned" }`),
438
+ * sorted. Traits combine by intersection: `Owned<Opaque<string, "Id">>` gives both. The type is
439
+ * the one of an expression or type node, or the declared type of a symbol (a variable's type, a
440
+ * type alias's type), resolved through aliases, generics and re-exports. A type parameter is
441
+ * widened to its constraint; `null` and `undefined` members are left out, and every other member
442
+ * of a union must state a guarantee for it to count. A required marker property, or a 1.1.0
443
+ * `__guarantee` that is not string literals, states none (that is a brand, not a guarantee). The
440
444
  * names mean nothing to core; each plugin reads its own.
441
445
  */
442
446
  guaranteesOf(target: ts.Node | SymbolRef): readonly string[];
447
+ /**
448
+ * The guarantees of the type the surrounding code expects for an expression (as
449
+ * `contextualTypeTextOf`), read as `guaranteesOf` reads a type: `{ … }` returned from a function
450
+ * typed `OrderId`, or passed to a parameter of that type. Empty when nothing is expected.
451
+ */
452
+ contextualGuaranteesOf(node: ts.Expression): readonly string[];
453
+ /**
454
+ * The values a trait's marker property holds, sorted: `"OrderId"` for
455
+ * `Opaque<string, "OrderId">`, `true` for `Pending<boolean>`, `"saving"` for
456
+ * `Pending<Status, "saving">`. Read from the type of the node, of the symbol's declaration, or,
457
+ * with `contextual`, of the type the surrounding code expects for the expression. Undefined when
458
+ * the type does not state the trait; `"not-finite"` when the property's type is not literals.
459
+ */
460
+ guaranteeValuesOf(target: ts.Node | SymbolRef, name: string, contextual?: boolean): readonly Literal[] | "not-finite" | undefined;
461
+ /**
462
+ * How a value is disposed when its type is a standard `Disposable` or `AsyncDisposable`: it has
463
+ * a `[Symbol.dispose]` (`"sync"`) or `[Symbol.asyncDispose]` (`"async"`) method, declared in
464
+ * `file`. Undefined for any other type, and for `any`.
465
+ */
466
+ disposeOf(node: ts.Node): {
467
+ readonly kind: "sync" | "async";
468
+ readonly file: string;
469
+ } | undefined;
470
+ /**
471
+ * The type alias the surrounding code expects for an expression (`OrderId` for an argument of
472
+ * `save(id: OrderId)`; `OrderId | undefined` gives `OrderId`), as a symbol whose declaration
473
+ * `declarationOf` finds. Undefined when nothing is expected, the type is not one alias, or the
474
+ * alias is generic.
475
+ */
476
+ contextualAliasOf(node: ts.Expression): SymbolRef | undefined;
477
+ /**
478
+ * The property a name destructured from an object reads: `cacheEntryRemoved` of the
479
+ * parameter's type for `{ cacheEntryRemoved }`, as a symbol whose declaration `declarationOf`
480
+ * finds. Undefined for a rest element, an array pattern, a computed key, or a type with no such
481
+ * property.
482
+ */
483
+ bindingPropertyOf(element: ts.BindingElement): SymbolRef | undefined;
484
+ /**
485
+ * Whether any file of the program (the project's or a package's) writes the marker property of
486
+ * a trait, `"__guarantee:<name>"`: a rule skips work for a trait nobody states.
487
+ */
488
+ declaresTrait(name: string): boolean;
489
+ /**
490
+ * Whether a file of the project declares a member named `[Symbol.dispose]` or
491
+ * `[Symbol.asyncDispose]` (a class, an interface, a type or an object literal), read from the
492
+ * syntax once per program: only such a member states the release trait by its type.
493
+ */
494
+ declaresDispose(): boolean;
495
+ /**
496
+ * The other names the project's files give a binding, by the name they rename: `onSnapshot` →
497
+ * `listen` for `import { onSnapshot as listen }`, `export { onSnapshot as listen }`,
498
+ * `const listen = onSnapshot` (or `= db.onSnapshot`) and `const { onSnapshot: listen } = db`.
499
+ * Read from the syntax once per program.
500
+ */
501
+ renamedBindings(): ReadonlyMap<string, ReadonlySet<string>>;
443
502
  /**
444
503
  * The type alias a value's type is an instance of, found from its declaration: after awaiting a
445
504
  * `Promise`, every member of the type must be written in the same alias (`Result<T, E>` and
@@ -454,11 +513,13 @@ export type TypeQueries = {
454
513
  /**
455
514
  * The type alias that names the type of an expression as written (`TouchpointStatus` for
456
515
  * `touchpointStatus()` declared to return it; a type parameter widened to its constraint), or
457
- * undefined when the type has no alias or the alias takes type arguments.
516
+ * undefined when the type has no alias or the alias takes type arguments. `declaration` is the
517
+ * alias's declaration.
458
518
  */
459
519
  typeAliasOf(node: ts.Node): {
460
520
  readonly name: string;
461
521
  readonly file: string;
522
+ readonly declaration: ts.TypeAliasDeclaration;
462
523
  } | undefined;
463
524
  /**
464
525
  * Where `fromFile` would import the type alias `name` declared in `file` from, written as
@@ -646,6 +707,15 @@ export type TypeQueries = {
646
707
  * takes one, the call does not resolve, or the parameter is a rest parameter.
647
708
  */
648
709
  signalParameterOf(call: ts.CallExpression): SignalParameter | undefined;
710
+ /**
711
+ * Whether TypeScript reports that the end of a function can be reached although the function
712
+ * must return a value: TS2366 (the return type does not include `undefined`), TS2355 (a
713
+ * declared type that is not `void`, `any` or `undefined`), TS2534 (a function returning
714
+ * `never`) or TS7030 (`noImplicitReturns`: not all code paths return a value). Only the errors
715
+ * TypeScript reports on the function itself (its name, signature or return type) count, not
716
+ * those in its body. Asks for the type errors of the function's file, once per file.
717
+ */
718
+ reportsReachableEnd(fn: ts.FunctionLikeDeclaration): boolean;
649
719
  };
650
720
  export type ReportProblem = {
651
721
  message: string;
@@ -660,6 +730,12 @@ export type ReportProblem = {
660
730
  * finding's kind (`option.severities`) still wins over it.
661
731
  */
662
732
  severity?: "info" | "warning";
733
+ /**
734
+ * The finding is against a guarantee the code states (`Pending<T>`, `Owned<T>`): proven strictly,
735
+ * so it is an error while the rule is on, even for a heuristic rule whose shape-based findings
736
+ * are warnings. A severity the config gives this finding's kind still wins over it.
737
+ */
738
+ stated?: true;
663
739
  related?: readonly {
664
740
  node: ts.Node;
665
741
  message: string;
@@ -681,6 +757,21 @@ export type ReportProblem = {
681
757
  export type FunctionFacts = {
682
758
  readonly throws?: readonly string[];
683
759
  readonly rejects?: readonly string[];
760
+ /** What the call returns must be released (the release trait): how it is released. */
761
+ readonly returns?: ReleaseFact;
762
+ /**
763
+ * The promise never rejects: the function's result, or the property itself for a promise
764
+ * property (RTK Query's `cacheEntryRemoved`). An `await` of it is not a way out.
765
+ */
766
+ readonly neverRejects?: true;
767
+ };
768
+ /**
769
+ * How a value with the release trait is released, as a `facts` line says it: `"release"`, call the
770
+ * returned function (`onSnapshot`'s unsubscribe); `{ release: "unsubscribe" }`, call that method
771
+ * on the returned value (RxJS's `Subscription`).
772
+ */
773
+ export type ReleaseFact = "release" | {
774
+ readonly release: string;
684
775
  };
685
776
  export type PackageFactsConfig = Readonly<Record<string, Readonly<Record<string, FunctionFacts>>>>;
686
777
  /** Where a library fact comes from, in order of trust. */
@@ -699,6 +790,14 @@ export type LibraryUse = {
699
790
  readonly unknown: readonly string[];
700
791
  }[];
701
792
  };
793
+ /**
794
+ * The noun for the places a guarantee covers, both forms written out ("switch", "switches"): a
795
+ * plural is never made by adding "s".
796
+ */
797
+ export type CoveredNoun = {
798
+ readonly one: string;
799
+ readonly many: string;
800
+ };
702
801
  /** A place a stated guarantee covers: a reader of a required context, a writer of owned state. */
703
802
  export type CoveredPlace = {
704
803
  /** How the place is named in a list: `<Profile>`, `useTheme()`. */
@@ -709,11 +808,31 @@ export type CoveredPlace = {
709
808
  * A guarantee stated in the project's code, as the plugin that proves it reads it
710
809
  * (`EditorContributions.guarantees`): for `stateward guarantees` and the editor's hover and code
711
810
  * lens. Whether it is proven is not said here: core counts the findings of `ruleId` that name the
712
- * declaration (a related note at `location`), so the list and the check never disagree.
811
+ * declaration (a related note at `location`) or lie in a place it covers, so the list and the
812
+ * check never disagree.
813
+ */
814
+ /**
815
+ * Where a trait is stated: a standard type that already says it (`Disposable`), the project's
816
+ * marker type (`Owned<T>`), the config's `facts` line for a package, or the facts a plugin ships
817
+ * for it (stateward's facts).
713
818
  */
819
+ export type TraitSource = {
820
+ readonly kind: "type";
821
+ readonly name: string;
822
+ } | {
823
+ readonly kind: "marker";
824
+ } | {
825
+ readonly kind: "config";
826
+ readonly package: string;
827
+ } | {
828
+ readonly kind: "shipped";
829
+ readonly package: string;
830
+ };
714
831
  export type StatedGuarantee = {
715
- /** The guarantee's name, as `__guarantee` writes it: `required-context`. */
832
+ /** The guarantee's name, as its marker property writes it: `required-context`. */
716
833
  readonly guarantee: string;
834
+ /** Where the trait is stated; a marker when not given. */
835
+ readonly source?: TraitSource;
717
836
  /** The marker type as the declaration's type names it: `RequiredContext`. */
718
837
  readonly marker: string;
719
838
  /** The declaration that states it: `ThemeContext`. */
@@ -727,8 +846,8 @@ export type StatedGuarantee = {
727
846
  readonly ruleId: string;
728
847
  /** What it promises, after "Guaranteed: ": "every reader is rendered under its Provider". */
729
848
  readonly promise: string;
730
- /** What `covered` holds, as a plural noun: "readers", "writers". */
731
- readonly covers: string;
849
+ /** What `covered` holds, as a noun in both forms: `{ one: "switch", many: "switches" }`. */
850
+ readonly covers: CoveredNoun;
732
851
  /** The places the proof covers, in file and offset order; empty when nothing uses it. */
733
852
  readonly covered: readonly CoveredPlace[];
734
853
  };
@@ -736,6 +855,11 @@ export type FileContext<O extends Options = Options> = {
736
855
  readonly file: string;
737
856
  /** The config's facts about packages (`facts`); `{}` when it gives none. */
738
857
  readonly facts: PackageFactsConfig;
858
+ /**
859
+ * The facts the loaded plugins ship for common packages (`Plugin.facts`), joined in plugin
860
+ * order. The config's own `facts` line for a function wins over a shipped one.
861
+ */
862
+ readonly shippedFacts: PackageFactsConfig;
739
863
  /** The rule's options: the config's values with the defaults filled in; `{}` when it declares none. */
740
864
  readonly options: O;
741
865
  readonly sourceFile: ts.SourceFile;
@@ -774,6 +898,13 @@ export type FileRule<S extends OptionSpecs = OptionSpecs, G extends string = str
774
898
  kind: "file";
775
899
  meta: RuleMeta<S, G>;
776
900
  check(ctx: FileContext<OptionsOf<S>>): void;
901
+ /**
902
+ * What the plugin's editor contributions read of this file (`EditorContributions.guarantees`,
903
+ * `hover`), as JSON: run after `check` on the same file, cached with its findings, and handed
904
+ * out by `projectSummaries` like a project rule's. It decides no finding: the findings are
905
+ * `check`'s alone, so the editor's fast pass stays complete without it.
906
+ */
907
+ summarize?(ctx: FileContext<OptionsOf<S>>): Json | undefined;
777
908
  };
778
909
  export type ProjectRule<Summary extends Json = Json, S extends OptionSpecs = OptionSpecs, G extends string = string> = {
779
910
  kind: "project";
@@ -910,6 +1041,12 @@ export type Plugin = {
910
1041
  description: string;
911
1042
  rules: Readonly<Record<string, PluginRule>>;
912
1043
  editor?: EditorContributions;
1044
+ /**
1045
+ * Facts about common packages that the plugin ships (stateward's facts), in the config's
1046
+ * `facts` shape: `{ rxjs: { "Observable.subscribe": { returns: { release: "unsubscribe" } } } }`.
1047
+ * Every rule reads them as `FileContext.shippedFacts`; the config's facts win over them.
1048
+ */
1049
+ facts?: PackageFactsConfig;
913
1050
  };
914
1051
  /** A plugin that keeps its literal name and rule keys, as `definePlugin` returns it. */
915
1052
  export type PluginOf<N extends string, R extends Readonly<Record<string, PluginRule>>> = {
@@ -917,6 +1054,7 @@ export type PluginOf<N extends string, R extends Readonly<Record<string, PluginR
917
1054
  description: string;
918
1055
  rules: R;
919
1056
  editor?: EditorContributions;
1057
+ facts?: PackageFactsConfig;
920
1058
  };
921
1059
  /** Every rule id ("<plugin>/<rule key>") a plugin type offers; any string pair for a wide `Plugin`. */
922
1060
  export type RuleIdOf<P extends Plugin> = P extends Plugin ? `${P["name"]}/${Extract<keyof P["rules"], string>}` : never;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stateward/core",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "The engine of stateward (exclusive states and predictable code paths for TypeScript) and the API for writing your own rules and packs.",
5
5
  "license": "MIT",
6
6
  "repository": {