@forwardimpact/libcoaligned 0.1.10 → 0.1.12
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/LICENSE +21 -201
- package/README.md +46 -9
- package/bin/coaligned.js +7 -1
- package/package.json +8 -6
- package/src/index.js +1 -0
- package/src/invariant-kit.js +468 -0
- package/src/invariants.js +23 -9
package/LICENSE
CHANGED
|
@@ -1,201 +1,21 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
-
exercising permissions granted by this License.
|
|
25
|
-
|
|
26
|
-
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
-
including but not limited to software source code, documentation
|
|
28
|
-
source, and configuration files.
|
|
29
|
-
|
|
30
|
-
"Object" form shall mean any form resulting from mechanical
|
|
31
|
-
transformation or translation of a Source form, including but
|
|
32
|
-
not limited to compiled object code, generated documentation,
|
|
33
|
-
and conversions to other media types.
|
|
34
|
-
|
|
35
|
-
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
-
Object form, made available under the License, as indicated by a
|
|
37
|
-
copyright notice that is included in or attached to the work
|
|
38
|
-
(an example is provided in the Appendix below).
|
|
39
|
-
|
|
40
|
-
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
-
form, that is based on (or derived from) the Work and for which the
|
|
42
|
-
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
-
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
-
of this License, Derivative Works shall not include works that remain
|
|
45
|
-
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
-
the Work and Derivative Works thereof.
|
|
47
|
-
|
|
48
|
-
"Contribution" shall mean any work of authorship, including
|
|
49
|
-
the original version of the Work and any modifications or additions
|
|
50
|
-
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
-
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
-
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
-
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
-
means any form of electronic, verbal, or written communication sent
|
|
55
|
-
to the Licensor or its representatives, including but not limited to
|
|
56
|
-
communication on electronic mailing lists, source code control systems,
|
|
57
|
-
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
-
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
-
excluding communication that is conspicuously marked or otherwise
|
|
60
|
-
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
-
|
|
62
|
-
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
-
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
-
subsequently incorporated within the Work.
|
|
65
|
-
|
|
66
|
-
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
-
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
-
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
-
Work and such Derivative Works in Source or Object form.
|
|
72
|
-
|
|
73
|
-
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
-
(except as stated in this section) patent license to make, have made,
|
|
77
|
-
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
-
where such license applies only to those patent claims licensable
|
|
79
|
-
by such Contributor that are necessarily infringed by their
|
|
80
|
-
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
-
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
-
institute patent litigation against any entity (including a
|
|
83
|
-
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
-
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
-
or contributory patent infringement, then any patent licenses
|
|
86
|
-
granted to You under this License for that Work shall terminate
|
|
87
|
-
as of the date such litigation is filed.
|
|
88
|
-
|
|
89
|
-
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
-
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
-
modifications, and in Source or Object form, provided that You
|
|
92
|
-
meet the following conditions:
|
|
93
|
-
|
|
94
|
-
(a) You must give any other recipients of the Work or
|
|
95
|
-
Derivative Works a copy of this License; and
|
|
96
|
-
|
|
97
|
-
(b) You must cause any modified files to carry prominent notices
|
|
98
|
-
stating that You changed the files; and
|
|
99
|
-
|
|
100
|
-
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
-
that You distribute, all copyright, patent, trademark, and
|
|
102
|
-
attribution notices from the Source form of the Work,
|
|
103
|
-
excluding those notices that do not pertain to any part of
|
|
104
|
-
the Derivative Works; and
|
|
105
|
-
|
|
106
|
-
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
-
distribution, then any Derivative Works that You distribute must
|
|
108
|
-
include a readable copy of the attribution notices contained
|
|
109
|
-
within such NOTICE file, excluding those notices that do not
|
|
110
|
-
pertain to any part of the Derivative Works, in at least one
|
|
111
|
-
of the following places: within a NOTICE text file distributed
|
|
112
|
-
as part of the Derivative Works; within the Source form or
|
|
113
|
-
documentation, if provided along with the Derivative Works; or,
|
|
114
|
-
within a display generated by the Derivative Works, if and
|
|
115
|
-
wherever such third-party notices normally appear. The contents
|
|
116
|
-
of the NOTICE file are for informational purposes only and
|
|
117
|
-
do not modify the License. You may add Your own attribution
|
|
118
|
-
notices within Derivative Works that You distribute, alongside
|
|
119
|
-
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
-
that such additional attribution notices cannot be construed
|
|
121
|
-
as modifying the License.
|
|
122
|
-
|
|
123
|
-
You may add Your own copyright statement to Your modifications and
|
|
124
|
-
may provide additional or different license terms and conditions
|
|
125
|
-
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
-
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
-
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
-
the conditions stated in this License.
|
|
129
|
-
|
|
130
|
-
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
-
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
-
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
-
this License, without any additional terms or conditions.
|
|
134
|
-
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
-
the terms of any separate license agreement you may have executed
|
|
136
|
-
with Licensor regarding such Contributions.
|
|
137
|
-
|
|
138
|
-
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
-
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
-
except as required for reasonable and customary use in describing the
|
|
141
|
-
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
-
|
|
143
|
-
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
-
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
-
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
-
implied, including, without limitation, any warranties or conditions
|
|
148
|
-
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
-
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
-
appropriateness of using or redistributing the Work and assume any
|
|
151
|
-
risks associated with Your exercise of permissions under this License.
|
|
152
|
-
|
|
153
|
-
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
-
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
-
unless required by applicable law (such as deliberate and grossly
|
|
156
|
-
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
-
liable to You for damages, including any direct, indirect, special,
|
|
158
|
-
incidental, or consequential damages of any character arising as a
|
|
159
|
-
result of this License or out of the use or inability to use the
|
|
160
|
-
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
-
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
-
other commercial damages or losses), even if such Contributor
|
|
163
|
-
has been advised of the possibility of such damages.
|
|
164
|
-
|
|
165
|
-
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
-
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
-
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
-
or other liability obligations and/or rights consistent with this
|
|
169
|
-
License. However, in accepting such obligations, You may act only
|
|
170
|
-
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
-
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
-
defend, and hold each Contributor harmless for any liability
|
|
173
|
-
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
-
of your accepting any such warranty or additional liability.
|
|
175
|
-
|
|
176
|
-
END OF TERMS AND CONDITIONS
|
|
177
|
-
|
|
178
|
-
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
-
|
|
180
|
-
To apply the Apache License to your work, attach the following
|
|
181
|
-
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
-
replaced with your own identifying information. (Don't include
|
|
183
|
-
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
-
comment syntax for the file format. We also recommend that a
|
|
185
|
-
file or class name and description of purpose be included on the
|
|
186
|
-
same "printed page" as the copyright notice for easier
|
|
187
|
-
identification within third-party archives.
|
|
188
|
-
|
|
189
|
-
Copyright 2026 Dick Olsson
|
|
190
|
-
|
|
191
|
-
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
-
you may not use this file except in compliance with the License.
|
|
193
|
-
You may obtain a copy of the License at
|
|
194
|
-
|
|
195
|
-
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
-
|
|
197
|
-
Unless required by applicable law or agreed to in writing, software
|
|
198
|
-
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
-
See the License for the specific language governing permissions and
|
|
201
|
-
limitations under the License.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2019 Zachary Rice
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -41,19 +41,56 @@ A rule module's default export is:
|
|
|
41
41
|
```js
|
|
42
42
|
export default {
|
|
43
43
|
name: "ambient-deps",
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
44
|
+
// `build` (and `seed`) receive the injected build kit; the module never
|
|
45
|
+
// imports the engine (it loads into consuming repos via npx, where the
|
|
46
|
+
// package is not resolvable from `.coaligned/`). Return plain subjects per
|
|
47
|
+
// scope, plus optional shared ctx the rules read.
|
|
48
|
+
build: (kit) => ({
|
|
49
|
+
subjects: { "src-file": kit.scanAst({ dirs, match, extract }) },
|
|
50
|
+
ctx: { deny: kit.config("ambient-deps.deny.yml", {}) },
|
|
49
51
|
}),
|
|
50
|
-
// Declarative rules over those subjects
|
|
51
|
-
|
|
52
|
+
// Declarative rules over those subjects: either a static array, or a
|
|
53
|
+
// `(ruleKit) => array` factory that builds them from the rule helpers.
|
|
54
|
+
rules: ({ parseError, failAll }) => [
|
|
55
|
+
parseError("src-file"),
|
|
56
|
+
{ id, scope, severity, when, check, message, hint },
|
|
57
|
+
],
|
|
52
58
|
// Optional: text for `coaligned invariants --seed <name>` — e.g. a
|
|
53
|
-
// regenerated grandfather deny-list.
|
|
54
|
-
seed:
|
|
59
|
+
// regenerated grandfather deny-list. Also receives the build kit.
|
|
60
|
+
seed: (kit) => "…",
|
|
55
61
|
};
|
|
56
62
|
```
|
|
57
63
|
|
|
64
|
+
### The build kit
|
|
65
|
+
|
|
66
|
+
The engine binds a kit per run to the repo `root`, the module's own `dir`
|
|
67
|
+
(for co-located config), and the `runtime` bag (fs and ripgrep route through
|
|
68
|
+
it, so the engine carries no ambient dependencies). The module declares only
|
|
69
|
+
policy; the kit owns the mechanism:
|
|
70
|
+
|
|
71
|
+
- `scan({ dirs, match, skip?, under?, read? })` — collect files as
|
|
72
|
+
`{ path, rel, text? }`; `under` restricts to the per-package `src`/`test`
|
|
73
|
+
shape.
|
|
74
|
+
- `scanAst({ dirs, match, extract, locations?, … })` — read + parse each file
|
|
75
|
+
and merge `extract(ast)`; a parse failure becomes `{ path, rel, parseError }`.
|
|
76
|
+
- `parse(src, path, opts?)`, `walk(ast, visit)` — the lower-level AST seam.
|
|
77
|
+
- `grep({ pattern | patterns, paths?, globs?, caseSensitive?, onlyMatching?,
|
|
78
|
+
dedupe? })` — ripgrep matches as `{ path, lineNo, text, reason? }`, with
|
|
79
|
+
per-entry `exclude` and built-in de-duplication.
|
|
80
|
+
- `restatementDrift({ entries, equal })` — the shared "single source restated
|
|
81
|
+
across consumers" scan + compare (service URLs, scalar values).
|
|
82
|
+
- `readText`, `readJson`, `config(name, fallback?)` (co-located JSON/YAML),
|
|
83
|
+
`listDir(path, { dirsOnly? })`.
|
|
84
|
+
- `lineAt(text, offset)`, `glob(pattern)`.
|
|
85
|
+
|
|
86
|
+
### The rule kit
|
|
87
|
+
|
|
88
|
+
When `rules` is a function it receives the rule helpers:
|
|
89
|
+
|
|
90
|
+
- `parseError(scope, { id?, hint? })` — fails any subject carrying a
|
|
91
|
+
`parseError` (paired with `scanAst`).
|
|
92
|
+
- `failAll(scope, { id, message, hint?, when? })` — fails every subject in
|
|
93
|
+
scope (the build step already decided each is a violation).
|
|
94
|
+
|
|
58
95
|
Findings render in the same ESLint-style format as the other subcommands
|
|
59
96
|
(`--json` for machine output); any finding fails the run.
|
package/bin/coaligned.js
CHANGED
|
@@ -2,12 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
import "@forwardimpact/libpreflight/node22";
|
|
4
4
|
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
|
|
5
7
|
import { createDefaultRuntime } from "@forwardimpact/libutil/runtime";
|
|
6
8
|
import { createCli } from "@forwardimpact/libcli";
|
|
7
9
|
import { emitFindingsJson, emitFindingsText } from "@forwardimpact/libutil";
|
|
8
10
|
import {
|
|
9
11
|
checkInstructions,
|
|
10
12
|
checkJtbd,
|
|
13
|
+
createBuildKit,
|
|
11
14
|
findInvariantsRoot,
|
|
12
15
|
INVARIANTS_DIR,
|
|
13
16
|
loadRuleModules,
|
|
@@ -134,7 +137,10 @@ async function invariantsHandler(ctx) {
|
|
|
134
137
|
cli.error(`rule module "${mod.name}" has no seed output`);
|
|
135
138
|
return 1;
|
|
136
139
|
}
|
|
137
|
-
|
|
140
|
+
const dir = resolve(root, INVARIANTS_DIR);
|
|
141
|
+
rt.proc.stdout.write(
|
|
142
|
+
await mod.seed(createBuildKit({ root, dir, runtime: rt })),
|
|
143
|
+
);
|
|
138
144
|
return 0;
|
|
139
145
|
}
|
|
140
146
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@forwardimpact/libcoaligned",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.12",
|
|
4
4
|
"description": "Co-Aligned architecture checks — enforce instruction-layer length caps, JTBD invariants, and the repo's own declarative invariant rule modules.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"coaligned",
|
|
@@ -21,11 +21,11 @@
|
|
|
21
21
|
"jobs": [
|
|
22
22
|
{
|
|
23
23
|
"user": "Platform Builders",
|
|
24
|
-
"goal": "
|
|
25
|
-
"trigger": "
|
|
26
|
-
"bigHire": "
|
|
24
|
+
"goal": "Run a Predictable Platform",
|
|
25
|
+
"trigger": "A service fails on a customer machine and the cause is a missing precondition, an unsupervised process, missing telemetry, or stale instructions.",
|
|
26
|
+
"bigHire": "check preconditions before anything heavy runs, supervise long-running processes, emit structured telemetry, and keep instruction files honest.",
|
|
27
27
|
"littleHire": "verify a docs change before commit and trust the layered architecture has not drifted.",
|
|
28
|
-
"competesWith": "
|
|
28
|
+
"competesWith": "failing deep in execution instead of at startup; ad-hoc process management; console.log debugging; instruction files nobody validates"
|
|
29
29
|
}
|
|
30
30
|
],
|
|
31
31
|
"type": "module",
|
|
@@ -49,7 +49,9 @@
|
|
|
49
49
|
"@forwardimpact/libcli": "^0.1.9",
|
|
50
50
|
"@forwardimpact/libpreflight": "^0.1.0",
|
|
51
51
|
"@forwardimpact/libutil": "*",
|
|
52
|
-
"
|
|
52
|
+
"acorn": "^8.17.0",
|
|
53
|
+
"prettier": "^3.8.4",
|
|
54
|
+
"yaml": "^2.9.0"
|
|
53
55
|
},
|
|
54
56
|
"devDependencies": {
|
|
55
57
|
"@forwardimpact/libmock": "^0.1.0"
|
package/src/index.js
CHANGED
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
// The invariant authoring kit: the mechanism an invariant rule module needs to
|
|
2
|
+
// turn the repository into subjects and findings, so the module itself carries
|
|
3
|
+
// only policy. The engine injects a *build kit* into every module's `build`
|
|
4
|
+
// (and `seed`), and a *rule kit* into a module's `rules` when it is written as
|
|
5
|
+
// a function. Modules never import this file — the host (invariants.js) binds a
|
|
6
|
+
// kit per run and passes it in, the same way the rest of the monorepo threads
|
|
7
|
+
// the `runtime` bag instead of importing ambient collaborators.
|
|
8
|
+
//
|
|
9
|
+
// Filesystem and subprocess access route through the injected `runtime`
|
|
10
|
+
// (`runtime.fsSync`, `runtime.subprocess`) so this module — which lives under
|
|
11
|
+
// libraries/<pkg>/src — stays clean under the repo's own ambient-deps invariant.
|
|
12
|
+
|
|
13
|
+
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
14
|
+
|
|
15
|
+
import { parse as acornParse } from "acorn";
|
|
16
|
+
import { parse as parseYaml } from "yaml";
|
|
17
|
+
|
|
18
|
+
// -- AST -----------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Parse an ES module, wrapping acorn's error with the offending path.
|
|
22
|
+
*
|
|
23
|
+
* @param {string} source - Module source text.
|
|
24
|
+
* @param {string} filePath - Path used in parse-error messages.
|
|
25
|
+
* @param {{ locations?: boolean }} [options]
|
|
26
|
+
* @returns {object} The acorn AST.
|
|
27
|
+
*/
|
|
28
|
+
export function parse(source, filePath, { locations = false } = {}) {
|
|
29
|
+
try {
|
|
30
|
+
return acornParse(source, {
|
|
31
|
+
ecmaVersion: "latest",
|
|
32
|
+
sourceType: "module",
|
|
33
|
+
locations,
|
|
34
|
+
allowAwaitOutsideFunction: true,
|
|
35
|
+
});
|
|
36
|
+
} catch (err) {
|
|
37
|
+
throw new Error(`failed to parse ${filePath}: ${err.message}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Depth-first visit of every typed node in an acorn AST.
|
|
43
|
+
*
|
|
44
|
+
* @param {object|object[]} node - AST node (or array of nodes).
|
|
45
|
+
* @param {(node: object) => void} visit - Called once per typed node.
|
|
46
|
+
*/
|
|
47
|
+
export function walk(node, visit) {
|
|
48
|
+
if (!node || typeof node !== "object") return;
|
|
49
|
+
if (Array.isArray(node)) {
|
|
50
|
+
for (const child of node) walk(child, visit);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (typeof node.type !== "string") return;
|
|
54
|
+
visit(node);
|
|
55
|
+
for (const key of Object.keys(node)) {
|
|
56
|
+
if (key === "loc" || key === "start" || key === "end") continue;
|
|
57
|
+
walk(node[key], visit);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// -- Small pure utilities ------------------------------------------------
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The 1-based line number a character offset falls on.
|
|
65
|
+
*
|
|
66
|
+
* @param {string} text - The source text.
|
|
67
|
+
* @param {number} offset - A character offset into `text`.
|
|
68
|
+
* @returns {number} The 1-based line number.
|
|
69
|
+
*/
|
|
70
|
+
export function lineAt(text, offset) {
|
|
71
|
+
let line = 1;
|
|
72
|
+
for (let i = 0; i < offset && i < text.length; i++) {
|
|
73
|
+
if (text.charCodeAt(i) === 10) line++;
|
|
74
|
+
}
|
|
75
|
+
return line;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Compile a minimal path glob to a `RegExp`. `**` matches any path segments;
|
|
80
|
+
* `*` matches a non-slash run.
|
|
81
|
+
*
|
|
82
|
+
* @param {string} pattern - The glob.
|
|
83
|
+
* @returns {RegExp} An anchored regular expression.
|
|
84
|
+
*/
|
|
85
|
+
export function glob(pattern) {
|
|
86
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
87
|
+
return new RegExp(
|
|
88
|
+
`^${escaped
|
|
89
|
+
.replace(/\*\*/g, "DOUBLESTAR")
|
|
90
|
+
.replace(/\*/g, "[^/]*")
|
|
91
|
+
.replace(/DOUBLESTAR/g, ".*")}$`,
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// -- Filesystem walking (over runtime.fsSync) ----------------------------
|
|
96
|
+
|
|
97
|
+
function collectFiles(fsSync, dir, skip, match) {
|
|
98
|
+
const out = [];
|
|
99
|
+
if (!fsSync.existsSync(dir)) return out;
|
|
100
|
+
for (const entry of fsSync.readdirSync(dir)) {
|
|
101
|
+
if (skip.has(entry)) continue;
|
|
102
|
+
const full = join(dir, entry);
|
|
103
|
+
if (fsSync.statSync(full).isDirectory()) {
|
|
104
|
+
out.push(...collectFiles(fsSync, full, skip, match));
|
|
105
|
+
} else if (match(entry)) {
|
|
106
|
+
out.push(full);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function readTextOrNull(fsSync, abs) {
|
|
113
|
+
try {
|
|
114
|
+
return fsSync.readFileSync(abs, "utf8");
|
|
115
|
+
} catch {
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// -- ripgrep (over runtime.subprocess.runSync) ---------------------------
|
|
121
|
+
|
|
122
|
+
function normalizePatterns(pattern, patterns) {
|
|
123
|
+
const list = patterns ?? (pattern === undefined ? [] : [pattern]);
|
|
124
|
+
return list.map((p) => (typeof p === "string" ? { pattern: p } : p));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function parseRgLine(raw) {
|
|
128
|
+
const i = raw.indexOf(":");
|
|
129
|
+
const j = raw.indexOf(":", i + 1);
|
|
130
|
+
return {
|
|
131
|
+
rel: raw.slice(0, i),
|
|
132
|
+
lineNo: Number.parseInt(raw.slice(i + 1, j), 10),
|
|
133
|
+
text: raw.slice(j + 1),
|
|
134
|
+
raw,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Keep the first row per key. `dedupe` is `false`, `true` (key on the raw
|
|
139
|
+
// line), or a key function over the row.
|
|
140
|
+
function dedupeRows(rows, dedupe) {
|
|
141
|
+
if (!dedupe) return rows;
|
|
142
|
+
const keyOf = typeof dedupe === "function" ? dedupe : (m) => m.raw;
|
|
143
|
+
const seen = new Set();
|
|
144
|
+
return rows.filter((r) => {
|
|
145
|
+
const k = keyOf(r);
|
|
146
|
+
if (seen.has(k)) return false;
|
|
147
|
+
seen.add(k);
|
|
148
|
+
return true;
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// A grep row carries `rel`/`raw` for dedupe; the subject keeps only the
|
|
153
|
+
// reportable fields (plus `reason` when the matching entry supplied one).
|
|
154
|
+
function toGrepSubject({ path, lineNo, text, reason }) {
|
|
155
|
+
const subject = { path, lineNo, text };
|
|
156
|
+
if (reason !== undefined) subject.reason = reason;
|
|
157
|
+
return subject;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// -- The build kit -------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Build the kit injected into a rule module's `build` and `seed`. Every
|
|
164
|
+
* collaborator is bound to `root` (the repository root), `dir` (the module's
|
|
165
|
+
* own directory, for co-located config), and `runtime` (the ambient bag).
|
|
166
|
+
*
|
|
167
|
+
* @param {{ root: string, dir: string, runtime: import('@forwardimpact/libutil/runtime').Runtime }} options
|
|
168
|
+
* @returns {object} The build kit.
|
|
169
|
+
*/
|
|
170
|
+
export function createBuildKit({ root, dir, runtime }) {
|
|
171
|
+
const { fsSync, subprocess } = runtime;
|
|
172
|
+
const abs = (p) => (isAbsolute(p) ? p : resolve(root, p));
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Collect files under one or more directories as subjects.
|
|
176
|
+
*
|
|
177
|
+
* @param {object} options
|
|
178
|
+
* @param {string[]} options.dirs - Root directories, relative to the repo.
|
|
179
|
+
* @param {(name: string) => boolean} options.match - File-name predicate.
|
|
180
|
+
* @param {Iterable<string>} [options.skip] - Directory names to prune.
|
|
181
|
+
* @param {string} [options.under] - Restrict to `<dir>/<child>/<under>/**`,
|
|
182
|
+
* the per-package `src`/`test` shape.
|
|
183
|
+
* @param {boolean} [options.read] - Attach file `text` (default true).
|
|
184
|
+
* @returns {Array<{ path: string, rel: string, text?: string }>}
|
|
185
|
+
*/
|
|
186
|
+
function scan({ dirs, match, skip = [], under, read = true }) {
|
|
187
|
+
const skipSet = new Set(skip);
|
|
188
|
+
const files = [];
|
|
189
|
+
for (const d of dirs) {
|
|
190
|
+
const base = resolve(root, d);
|
|
191
|
+
const roots = under
|
|
192
|
+
? (fsSync.existsSync(base) ? fsSync.readdirSync(base) : []).map((n) =>
|
|
193
|
+
join(base, n, under),
|
|
194
|
+
)
|
|
195
|
+
: [base];
|
|
196
|
+
for (const r of roots)
|
|
197
|
+
files.push(...collectFiles(fsSync, r, skipSet, match));
|
|
198
|
+
}
|
|
199
|
+
return files.map((path) => {
|
|
200
|
+
const subject = { path, rel: relative(root, path) };
|
|
201
|
+
if (read) subject.text = readTextOrNull(fsSync, path) ?? "";
|
|
202
|
+
return subject;
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Like `scan`, but parse each file and merge `extract(ast)` into the subject.
|
|
208
|
+
* A file that fails to parse becomes `{ path, rel, parseError }` instead, so
|
|
209
|
+
* the module pairs it with the rule kit's `parseError(scope, …)`.
|
|
210
|
+
*
|
|
211
|
+
* @param {object} options - `scan` options plus the two below.
|
|
212
|
+
* @param {(ast: object) => object} options.extract - Subject fields from the AST.
|
|
213
|
+
* @param {boolean} [options.locations] - Pass `locations` to the parser.
|
|
214
|
+
* @returns {Array<object>}
|
|
215
|
+
*/
|
|
216
|
+
function scanAst({ extract, locations = false, ...scanOpts }) {
|
|
217
|
+
return scan({ ...scanOpts, read: true }).map(({ path, rel, text }) => {
|
|
218
|
+
try {
|
|
219
|
+
return { path, rel, ...extract(parse(text, rel, { locations })) };
|
|
220
|
+
} catch (err) {
|
|
221
|
+
return { path, rel, parseError: err.message };
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function assertRg() {
|
|
227
|
+
if (subprocess.runSync("rg", ["--version"]).exitCode !== 0) {
|
|
228
|
+
throw new Error("ripgrep (rg) is required by the invariant rule modules");
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function rgOnce({ pattern, paths, globs, caseSensitive, onlyMatching }) {
|
|
233
|
+
const args = [
|
|
234
|
+
"--hidden",
|
|
235
|
+
"--no-messages",
|
|
236
|
+
"--line-number",
|
|
237
|
+
"--color",
|
|
238
|
+
"never",
|
|
239
|
+
];
|
|
240
|
+
if (!caseSensitive) args.push("-i");
|
|
241
|
+
if (onlyMatching) args.push("--only-matching");
|
|
242
|
+
for (const g of globs) args.push("--glob", g);
|
|
243
|
+
args.push("-e", pattern, ...paths);
|
|
244
|
+
const { stdout, exitCode } = subprocess.runSync("rg", args, { cwd: root });
|
|
245
|
+
if (exitCode === 2)
|
|
246
|
+
throw new Error(`ripgrep failed for pattern: ${pattern}`);
|
|
247
|
+
return (stdout || "").split("\n").filter(Boolean).map(parseRgLine);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Scan the repo with ripgrep and return matches as subjects. Accepts one
|
|
252
|
+
* `pattern` or a list of `patterns` (strings, or `{ pattern, reason?, globs?,
|
|
253
|
+
* caseSensitive?, onlyMatching?, exclude? }`); per-entry options override the
|
|
254
|
+
* call defaults, and a per-entry `exclude` RegExp drops matches whose raw
|
|
255
|
+
* line it tests true (a false-positive filter). `dedupe` is `false`, `true`
|
|
256
|
+
* (key on the raw line), or a key function over `{ path, rel, lineNo, text,
|
|
257
|
+
* raw, reason }`.
|
|
258
|
+
*
|
|
259
|
+
* Each subject is `{ path, lineNo, text }`, plus `reason` when the matching
|
|
260
|
+
* entry carries one. The repo-relative `rel` and full `raw` line are
|
|
261
|
+
* available to the `dedupe` key function but are not part of the subject.
|
|
262
|
+
*
|
|
263
|
+
* @param {object} options
|
|
264
|
+
* @returns {Array<{ path: string, lineNo: number, text: string, reason?: string }>}
|
|
265
|
+
*/
|
|
266
|
+
function grep({
|
|
267
|
+
pattern,
|
|
268
|
+
patterns,
|
|
269
|
+
paths = ["."],
|
|
270
|
+
globs = [],
|
|
271
|
+
caseSensitive = false,
|
|
272
|
+
onlyMatching = false,
|
|
273
|
+
dedupe = false,
|
|
274
|
+
}) {
|
|
275
|
+
assertRg();
|
|
276
|
+
const rows = [];
|
|
277
|
+
for (const entry of normalizePatterns(pattern, patterns)) {
|
|
278
|
+
const matches = rgOnce({
|
|
279
|
+
pattern: entry.pattern,
|
|
280
|
+
paths,
|
|
281
|
+
globs: [...globs, ...(entry.globs ?? [])],
|
|
282
|
+
caseSensitive: entry.caseSensitive ?? caseSensitive,
|
|
283
|
+
onlyMatching: entry.onlyMatching ?? onlyMatching,
|
|
284
|
+
});
|
|
285
|
+
for (const m of matches) {
|
|
286
|
+
if (entry.exclude && entry.exclude.test(m.raw)) continue;
|
|
287
|
+
rows.push({ ...m, path: resolve(root, m.rel), reason: entry.reason });
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return dedupeRows(rows, dedupe).map(toGrepSubject);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Read a repo file's text (path relative to the repo root, or absolute).
|
|
295
|
+
*
|
|
296
|
+
* @param {string} path
|
|
297
|
+
* @returns {string|null} The text, or `null` when missing.
|
|
298
|
+
*/
|
|
299
|
+
function readText(path) {
|
|
300
|
+
return readTextOrNull(fsSync, abs(path));
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Read and parse a repo JSON file, returning `null` when missing or invalid.
|
|
305
|
+
*
|
|
306
|
+
* @param {string} path - Relative to the repo root, or absolute.
|
|
307
|
+
* @returns {object|null}
|
|
308
|
+
*/
|
|
309
|
+
function readJson(path) {
|
|
310
|
+
const text = readTextOrNull(fsSync, abs(path));
|
|
311
|
+
if (text == null) return null;
|
|
312
|
+
try {
|
|
313
|
+
return JSON.parse(text);
|
|
314
|
+
} catch {
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Read a config file co-located with the rule module (`<dir>/<name>`),
|
|
321
|
+
* parsed by extension (`.json` / `.yml` / `.yaml`). Returns `fallback` when
|
|
322
|
+
* the file is missing, empty, or unparseable.
|
|
323
|
+
*
|
|
324
|
+
* @param {string} name - File name beside the module.
|
|
325
|
+
* @param {*} [fallback] - Value when absent or unreadable (default `null`).
|
|
326
|
+
* @returns {*}
|
|
327
|
+
*/
|
|
328
|
+
function config(name, fallback = null) {
|
|
329
|
+
const text = readTextOrNull(fsSync, join(dir, name));
|
|
330
|
+
if (text == null || text.trim() === "") return fallback;
|
|
331
|
+
try {
|
|
332
|
+
const parsed = name.endsWith(".json")
|
|
333
|
+
? JSON.parse(text)
|
|
334
|
+
: parseYaml(text);
|
|
335
|
+
return parsed ?? fallback;
|
|
336
|
+
} catch {
|
|
337
|
+
return fallback;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* The shared "single source restated across consumers" check. For every
|
|
343
|
+
* registry `entry` (`{ key, expected, consumers: [{ path, pattern }] }`),
|
|
344
|
+
* scan each consumer file line by line for `pattern` and emit one subject
|
|
345
|
+
* per match: the restated value (capture group 1, else the whole match,
|
|
346
|
+
* trimmed) paired with the entry's `expected` value and an `ok` verdict from
|
|
347
|
+
* `equal(restated, expected, key)`. The module supplies the domain pieces
|
|
348
|
+
* (how `expected` is computed, what `equal` means); the kit owns the scan.
|
|
349
|
+
*
|
|
350
|
+
* Native line-by-line matching, not ripgrep: the surfaces carry URLs and
|
|
351
|
+
* other colon-bearing values that ripgrep's single-file output corrupts, and
|
|
352
|
+
* look-around is sometimes needed.
|
|
353
|
+
*
|
|
354
|
+
* @param {object} options
|
|
355
|
+
* @param {Array<{ key: string, expected: *, consumers: Array<{ path: string, pattern: RegExp|string }> }>} options.entries
|
|
356
|
+
* @param {(restated: string, expected: *, key: string) => boolean} options.equal
|
|
357
|
+
* @returns {Array<{ key: string, path: string, lineNo: number, restated: string, expected: *, ok: boolean }>}
|
|
358
|
+
*/
|
|
359
|
+
function restatementDrift({ entries, equal }) {
|
|
360
|
+
const subjects = [];
|
|
361
|
+
for (const { key, expected, consumers } of entries) {
|
|
362
|
+
for (const consumer of consumers) {
|
|
363
|
+
const text = readTextOrNull(fsSync, abs(consumer.path));
|
|
364
|
+
if (text == null) continue;
|
|
365
|
+
const re =
|
|
366
|
+
typeof consumer.pattern === "string"
|
|
367
|
+
? new RegExp(consumer.pattern)
|
|
368
|
+
: consumer.pattern;
|
|
369
|
+
text.split("\n").forEach((line, i) => {
|
|
370
|
+
const m = line.match(re);
|
|
371
|
+
if (!m) return;
|
|
372
|
+
const restated = (m[1] ?? m[0]).trim();
|
|
373
|
+
subjects.push({
|
|
374
|
+
key,
|
|
375
|
+
path: consumer.path,
|
|
376
|
+
lineNo: i + 1,
|
|
377
|
+
restated,
|
|
378
|
+
expected,
|
|
379
|
+
ok: equal(restated, expected, key),
|
|
380
|
+
});
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return subjects;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* List the entries of a repo directory by name, returning `[]` when missing.
|
|
389
|
+
*
|
|
390
|
+
* @param {string} path - Relative to the repo root, or absolute.
|
|
391
|
+
* @param {{ dirsOnly?: boolean, filesOnly?: boolean }} [options]
|
|
392
|
+
* @returns {string[]}
|
|
393
|
+
*/
|
|
394
|
+
function listDir(path, { dirsOnly = false, filesOnly = false } = {}) {
|
|
395
|
+
let entries;
|
|
396
|
+
try {
|
|
397
|
+
entries = fsSync.readdirSync(abs(path), { withFileTypes: true });
|
|
398
|
+
} catch {
|
|
399
|
+
return [];
|
|
400
|
+
}
|
|
401
|
+
return entries
|
|
402
|
+
.filter((e) =>
|
|
403
|
+
dirsOnly ? e.isDirectory() : filesOnly ? e.isFile() : true,
|
|
404
|
+
)
|
|
405
|
+
.map((e) => e.name);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
return {
|
|
409
|
+
root,
|
|
410
|
+
dir,
|
|
411
|
+
runtime,
|
|
412
|
+
scan,
|
|
413
|
+
scanAst,
|
|
414
|
+
parse,
|
|
415
|
+
walk,
|
|
416
|
+
grep,
|
|
417
|
+
restatementDrift,
|
|
418
|
+
readText,
|
|
419
|
+
readJson,
|
|
420
|
+
config,
|
|
421
|
+
listDir,
|
|
422
|
+
lineAt,
|
|
423
|
+
glob,
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// -- The rule kit --------------------------------------------------------
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Helpers a rule module receives when it exports `rules` as a function. They
|
|
431
|
+
* build the two recurring rule shapes so the module declares only policy.
|
|
432
|
+
*/
|
|
433
|
+
export const RULE_KIT = {
|
|
434
|
+
/**
|
|
435
|
+
* The standard parse-error rule: fails any subject carrying a `parseError`
|
|
436
|
+
* string (as produced by the build kit's `scanAst`).
|
|
437
|
+
*
|
|
438
|
+
* @param {string} scope - The subject scope to guard.
|
|
439
|
+
* @param {{ id?: string, hint?: string }} [options]
|
|
440
|
+
* @returns {object} A rule for the rules engine.
|
|
441
|
+
*/
|
|
442
|
+
parseError(scope, { id = `${scope}.parse-error`, hint } = {}) {
|
|
443
|
+
return {
|
|
444
|
+
id,
|
|
445
|
+
scope,
|
|
446
|
+
severity: "fail",
|
|
447
|
+
check: (s) => (s.parseError ? { msg: s.parseError } : null),
|
|
448
|
+
message: (_s, r) => r.msg,
|
|
449
|
+
hint: hint ?? "fix the syntax error so the file can be parsed",
|
|
450
|
+
};
|
|
451
|
+
},
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* A rule that fails every subject in `scope` (optionally gated by `when`).
|
|
455
|
+
* The build step has already decided each subject is a violation; the rule
|
|
456
|
+
* only renders it.
|
|
457
|
+
*
|
|
458
|
+
* @param {string} scope
|
|
459
|
+
* @param {{ id: string, message: (s: object, r: object, c: object) => string, hint?: string, when?: (s: object, c: object) => boolean }} options
|
|
460
|
+
* @returns {object} A rule for the rules engine.
|
|
461
|
+
*/
|
|
462
|
+
failAll(scope, { id, message, hint, when }) {
|
|
463
|
+
const rule = { id, scope, severity: "fail", check: () => ({}), message };
|
|
464
|
+
if (hint !== undefined) rule.hint = hint;
|
|
465
|
+
if (when !== undefined) rule.when = when;
|
|
466
|
+
return rule;
|
|
467
|
+
},
|
|
468
|
+
};
|
package/src/invariants.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { resolve } from "node:path";
|
|
2
2
|
import { pathToFileURL } from "node:url";
|
|
3
3
|
import { runRules } from "@forwardimpact/libutil";
|
|
4
|
+
import { createBuildKit, RULE_KIT } from "./invariant-kit.js";
|
|
4
5
|
|
|
5
6
|
// The conventional rules location, relative to the project root.
|
|
6
7
|
export const INVARIANTS_DIR = ".coaligned/invariants";
|
|
@@ -45,14 +46,20 @@ function assertModuleShape(mod, fileName) {
|
|
|
45
46
|
mod &&
|
|
46
47
|
typeof mod.name === "string" &&
|
|
47
48
|
typeof mod.build === "function" &&
|
|
48
|
-
Array.isArray(mod.rules);
|
|
49
|
+
(Array.isArray(mod.rules) || typeof mod.rules === "function");
|
|
49
50
|
if (!ok) {
|
|
50
51
|
throw new Error(
|
|
51
|
-
`${fileName}: default export must be { name, build, rules }`,
|
|
52
|
+
`${fileName}: default export must be { name, build, rules } (rules is an array or a (ruleKit) => array)`,
|
|
52
53
|
);
|
|
53
54
|
}
|
|
54
55
|
}
|
|
55
56
|
|
|
57
|
+
// A module's rules are either a static array or a `(ruleKit) => array` factory
|
|
58
|
+
// that builds them from the shared rule helpers.
|
|
59
|
+
function resolveRules(mod) {
|
|
60
|
+
return typeof mod.rules === "function" ? mod.rules(RULE_KIT) : mod.rules;
|
|
61
|
+
}
|
|
62
|
+
|
|
56
63
|
/**
|
|
57
64
|
* Discover and import every rule module under `rulesDir` (sorted by file
|
|
58
65
|
* name for a stable run order).
|
|
@@ -89,20 +96,26 @@ export async function loadRuleModules({
|
|
|
89
96
|
}
|
|
90
97
|
|
|
91
98
|
/**
|
|
92
|
-
* Run already-loaded rule modules: build each module's
|
|
93
|
-
* its rule catalogue through the shared rules engine.
|
|
99
|
+
* Run already-loaded rule modules: inject the build kit, build each module's
|
|
100
|
+
* subjects, then apply its rule catalogue through the shared rules engine.
|
|
94
101
|
*
|
|
95
102
|
* @param {object[]} modules - Rule-module default exports.
|
|
96
|
-
* @param {{ root: string, runtime: import('@forwardimpact/libutil/runtime').Runtime }} options
|
|
103
|
+
* @param {{ root: string, runtime: import('@forwardimpact/libutil/runtime').Runtime, dir?: string }} options
|
|
104
|
+
* `dir` is the modules' directory (for co-located config); defaults to
|
|
105
|
+
* `<root>/.coaligned/invariants`.
|
|
97
106
|
* @returns {Promise<object[]>} Structured findings; empty when conformant.
|
|
98
107
|
*/
|
|
99
|
-
export async function runRuleModules(
|
|
108
|
+
export async function runRuleModules(
|
|
109
|
+
modules,
|
|
110
|
+
{ root, runtime, dir = resolve(root, INVARIANTS_DIR) },
|
|
111
|
+
) {
|
|
100
112
|
const findings = [];
|
|
101
113
|
for (const mod of modules) {
|
|
102
|
-
const
|
|
114
|
+
const kit = createBuildKit({ root, dir, runtime });
|
|
115
|
+
const { subjects, ctx = {} } = await mod.build(kit);
|
|
103
116
|
findings.push(
|
|
104
117
|
...runRules(
|
|
105
|
-
mod
|
|
118
|
+
resolveRules(mod),
|
|
106
119
|
{ ...ctx, subjects },
|
|
107
120
|
{ resolveScope: (key, c) => c.subjects[key] ?? [] },
|
|
108
121
|
),
|
|
@@ -125,6 +138,7 @@ export async function checkInvariants({
|
|
|
125
138
|
runtime,
|
|
126
139
|
}) {
|
|
127
140
|
if (!runtime) throw new Error("runtime is required");
|
|
141
|
+
const dir = resolve(root, rulesDir);
|
|
128
142
|
const modules = await loadRuleModules({ root, rulesDir, runtime });
|
|
129
|
-
return runRuleModules(modules, { root, runtime });
|
|
143
|
+
return runRuleModules(modules, { root, runtime, dir });
|
|
130
144
|
}
|