tslaws 0.9.0 → 1.0.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/README.md +8 -2
- package/bin/tslaws.js +8 -2
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +36 -7
- package/dist/bundled.js +2 -2
- package/dist/bundlerPlugins.d.ts +2 -0
- package/dist/bundlerPlugins.js +7 -0
- package/dist/certificates.d.ts +139 -0
- package/dist/certificates.js +433 -0
- package/dist/chc.d.ts +85 -0
- package/dist/chc.js +298 -0
- package/dist/check.d.ts +13 -1
- package/dist/check.js +215 -28
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +324 -41
- package/dist/compile.d.ts +17 -1
- package/dist/compile.js +244 -25
- package/dist/coverage.d.ts +55 -3
- package/dist/coverage.js +231 -12
- package/dist/e2eApi.js +3 -1
- package/dist/generators.js +12 -2
- package/dist/github.d.ts +49 -5
- package/dist/github.js +107 -24
- package/dist/githubCli.d.ts +28 -0
- package/dist/githubCli.js +1039 -211
- package/dist/hints.js +2 -1
- package/dist/init.js +42 -0
- package/dist/isolate.d.ts +28 -0
- package/dist/isolate.js +262 -0
- package/dist/isolatedCheck.d.ts +1 -0
- package/dist/isolatedCheck.js +16 -0
- package/dist/lawHost.d.ts +50 -0
- package/dist/lawHost.js +199 -0
- package/dist/lawRuntime.d.ts +39 -0
- package/dist/lawRuntime.js +242 -0
- package/dist/lock.d.ts +49 -9
- package/dist/lock.js +132 -21
- package/dist/mcp.js +28 -7
- package/dist/mutate.d.ts +4 -0
- package/dist/mutate.js +7 -1
- package/dist/plan.d.ts +1 -0
- package/dist/plan.js +4 -0
- package/dist/pluginHooks.d.ts +16 -0
- package/dist/pluginHooks.js +48 -0
- package/dist/pluginHost.d.ts +5 -0
- package/dist/pluginHost.js +43 -0
- package/dist/pluginWorker.d.ts +1 -0
- package/dist/pluginWorker.js +40 -0
- package/dist/plural.d.ts +2 -0
- package/dist/plural.js +4 -0
- package/dist/pool.d.ts +80 -7
- package/dist/pool.js +222 -11
- package/dist/projects.d.ts +70 -0
- package/dist/projects.js +457 -0
- package/dist/promote.d.ts +56 -2
- package/dist/promote.js +429 -13
- package/dist/property.js +13 -2
- package/dist/propertyWorker.js +11 -1
- package/dist/proposals.d.ts +52 -4
- package/dist/proposals.js +484 -21
- package/dist/reporters.js +5 -1
- package/dist/runtimeEnv.d.ts +32 -0
- package/dist/runtimeEnv.js +146 -0
- package/dist/sandbox.d.ts +98 -0
- package/dist/sandbox.js +673 -0
- package/dist/sandboxGuard.d.ts +56 -0
- package/dist/sandboxGuard.js +249 -0
- package/dist/seal.d.ts +9 -0
- package/dist/seal.js +426 -0
- package/dist/security/cli.d.ts +6 -0
- package/dist/security/cli.js +39 -0
- package/dist/security/cwe.d.ts +14 -0
- package/dist/security/cwe.js +40 -0
- package/dist/security/deps/cache.d.ts +28 -0
- package/dist/security/deps/cache.js +107 -0
- package/dist/security/deps/config.d.ts +16 -0
- package/dist/security/deps/config.js +43 -0
- package/dist/security/deps/imports.d.ts +4 -0
- package/dist/security/deps/imports.js +33 -0
- package/dist/security/deps/lockfiles.d.ts +23 -0
- package/dist/security/deps/lockfiles.js +153 -0
- package/dist/security/deps/osv.d.ts +66 -0
- package/dist/security/deps/osv.js +137 -0
- package/dist/security/deps/run.d.ts +54 -0
- package/dist/security/deps/run.js +135 -0
- package/dist/security/deps/severity.d.ts +26 -0
- package/dist/security/deps/severity.js +78 -0
- package/dist/security/generators.d.ts +9 -0
- package/dist/security/generators.js +36 -0
- package/dist/security/index.d.ts +27 -0
- package/dist/security/index.js +18 -0
- package/dist/security/integers.d.ts +31 -0
- package/dist/security/integers.js +105 -0
- package/dist/security/law.d.ts +54 -0
- package/dist/security/law.js +54 -0
- package/dist/security/pathTraversal.d.ts +29 -0
- package/dist/security/pathTraversal.js +146 -0
- package/dist/security/prototypePollution.d.ts +30 -0
- package/dist/security/prototypePollution.js +142 -0
- package/dist/security/redirect.d.ts +21 -0
- package/dist/security/redirect.js +154 -0
- package/dist/security/redos.d.ts +21 -0
- package/dist/security/redos.js +93 -0
- package/dist/security/validation.d.ts +25 -0
- package/dist/security/validation.js +89 -0
- package/dist/security/xss.d.ts +21 -0
- package/dist/security/xss.js +90 -0
- package/dist/settings.d.ts +20 -0
- package/dist/settings.js +32 -0
- package/dist/smt.d.ts +29 -1
- package/dist/smt.js +239 -107
- package/dist/smtWorker.d.ts +1 -0
- package/dist/smtWorker.js +26 -0
- package/dist/solvers.d.ts +9 -0
- package/dist/solvers.js +11 -5
- package/dist/symbolic.d.ts +54 -1
- package/dist/symbolic.js +239 -13
- package/dist/tsconfigResolve.d.ts +28 -0
- package/dist/tsconfigResolve.js +141 -0
- package/dist/types.d.ts +28 -0
- package/env.d.ts +17 -0
- package/hooks/claude-hook.mjs +2 -0
- package/package.json +22 -6
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type ts from 'typescript';
|
|
2
|
+
import type { ResolutionOptions } from './tsconfigResolve.ts';
|
|
3
|
+
/** What a project registers: its root and the resolution options of its tsconfig (none when it has none or opts out). */
|
|
4
|
+
export interface LawRuntime {
|
|
5
|
+
cwd: string;
|
|
6
|
+
options?: ResolutionOptions;
|
|
7
|
+
/**
|
|
8
|
+
* Where the project's compiled files are. Under `.tslaws/out`, but deeper when the output mirrors a tree above the
|
|
9
|
+
* project (sources outside it were compiled too): files then sit at the same depth as in the source tree.
|
|
10
|
+
*/
|
|
11
|
+
outDir?: string;
|
|
12
|
+
/** The project's `bundlerPlugins` (absolute module paths): they load the source formats Node cannot (see pluginHost.ts). */
|
|
13
|
+
bundlerPlugins?: string[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* How a file Node cannot load as written becomes something it can: TypeScript source (esbuild) and a project format (the
|
|
17
|
+
* `bundlerPlugins`). Both start a helper (a child process, a thread), which a sandboxed law process may not do, so
|
|
18
|
+
* there the parent transforms the reviewed files up front and the process looks the result up (see lawHost.ts).
|
|
19
|
+
*/
|
|
20
|
+
export interface Transforms {
|
|
21
|
+
source(file: string, extension: string): string;
|
|
22
|
+
plugin(file: string, cwd: string, plugins: readonly string[], format: 'cjs' | 'esm'): string;
|
|
23
|
+
}
|
|
24
|
+
/** The TypeScript source of `file` as CommonJS, the way a law loads it. */
|
|
25
|
+
export declare function transformSource(file: string, extension: string): string;
|
|
26
|
+
/** Replaces how this thread transforms files; used by the sandboxed law process, which cannot run the real ones. */
|
|
27
|
+
export declare function useTransforms(next: Transforms): void;
|
|
28
|
+
/** The runtime a project registered, as the last build left it. */
|
|
29
|
+
export declare function runtimeOf(cwd: string): LawRuntime | undefined;
|
|
30
|
+
/** Loads what the resolver needs, while no law is running. A law process calls it once its project is installed. */
|
|
31
|
+
export declare function loadResolver(): void;
|
|
32
|
+
/** The file the build leaves beside the output, so a property worker can put the same resolution in place. */
|
|
33
|
+
export declare const runtimeFile = "tslaws-runtime.json";
|
|
34
|
+
/** The options for a program over the declarations in `outDir`: `base` plus the project's resolution. */
|
|
35
|
+
export declare function withResolution(outDir: string, base: ts.CompilerOptions): ts.CompilerOptions;
|
|
36
|
+
/** The directory holding the project's compiled files, as the last build left it. */
|
|
37
|
+
export declare function compiledDirOf(cwd: string): string;
|
|
38
|
+
/** Registers a project's resolution for compiled laws and, on first use, puts the hooks in. */
|
|
39
|
+
export declare function installLawRuntime(runtime: LawRuntime): void;
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// Node resolution for compiled laws. The compiler leaves `require('@app/x')` as written, so Node must find what the type
|
|
2
|
+
// checker found: tsconfig `paths`, and packages whose `exports` or `types` point at TypeScript source. Two hooks, put in
|
|
3
|
+
// once per process (and once per property worker): a resolver that asks TypeScript when Node cannot resolve a name, and
|
|
4
|
+
// a loader for `.ts` files that no compiler wrote out (a workspace package's source).
|
|
5
|
+
import { existsSync as fsExists, readFileSync, statSync } from 'node:fs';
|
|
6
|
+
import Module, { createRequire } from 'node:module';
|
|
7
|
+
import { dirname, extname, join, relative, resolve, sep } from 'node:path';
|
|
8
|
+
import { installPluginHooks, pluginExtensionNeeded } from "./pluginHooks.js";
|
|
9
|
+
import { transformPluginFile } from "./pluginHost.js";
|
|
10
|
+
import { transformSync } from 'esbuild';
|
|
11
|
+
import { importMetaDefines } from "./runtimeEnv.js";
|
|
12
|
+
import { nearestTsconfig, readResolutionOf, resolutionCompilerOptions } from "./tsconfigResolve.js";
|
|
13
|
+
/** Whether `path` exists. A path the sandbox may not read is answered with no, as a missing one is. */
|
|
14
|
+
function existsSync(path) {
|
|
15
|
+
try {
|
|
16
|
+
return fsExists(path);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** The TypeScript source of `file` as CommonJS, the way a law loads it. */
|
|
23
|
+
export function transformSource(file, extension) {
|
|
24
|
+
return transformSync(readFileSync(file, 'utf8'), {
|
|
25
|
+
loader: extension === '.tsx' ? 'tsx' : 'ts',
|
|
26
|
+
format: 'cjs',
|
|
27
|
+
target: 'es2022',
|
|
28
|
+
sourcefile: file,
|
|
29
|
+
sourcemap: 'inline',
|
|
30
|
+
define: importMetaDefines(file),
|
|
31
|
+
}).code;
|
|
32
|
+
}
|
|
33
|
+
let transforms = { source: transformSource, plugin: transformPluginFile };
|
|
34
|
+
/** Replaces how this thread transforms files; used by the sandboxed law process, which cannot run the real ones. */
|
|
35
|
+
export function useTransforms(next) {
|
|
36
|
+
transforms = next;
|
|
37
|
+
}
|
|
38
|
+
/** The runtime a project registered, as the last build left it. */
|
|
39
|
+
export function runtimeOf(cwd) {
|
|
40
|
+
return projects.get(outDirOf(cwd));
|
|
41
|
+
}
|
|
42
|
+
const projects = new Map();
|
|
43
|
+
const byConfig = new Map();
|
|
44
|
+
// Compiled laws are CommonJS (see `build` in compile.ts), and these hooks are the CommonJS loader's own (`_resolveFilename`,
|
|
45
|
+
// `_extensions`), so `createRequire` is unavoidable: it loads TypeScript lazily, inside the synchronous resolver hook.
|
|
46
|
+
const load = createRequire(import.meta.url);
|
|
47
|
+
let hooked = false;
|
|
48
|
+
/**
|
|
49
|
+
* TypeScript, which the resolver asks when Node cannot find a module. It needs Node modules a law may not load, and the
|
|
50
|
+
* guard refuses a module that a law's code is waiting on, so a law process loads it before the first law runs (`loadResolver`).
|
|
51
|
+
*/
|
|
52
|
+
let typescriptModule;
|
|
53
|
+
const typescriptOf = () => (typescriptModule ??= load('typescript'));
|
|
54
|
+
/** Loads what the resolver needs, while no law is running. A law process calls it once its project is installed. */
|
|
55
|
+
export function loadResolver() {
|
|
56
|
+
typescriptOf();
|
|
57
|
+
}
|
|
58
|
+
const outDirOf = (cwd) => join(cwd, '.tslaws', 'out');
|
|
59
|
+
/** The file the build leaves beside the output, so a property worker can put the same resolution in place. */
|
|
60
|
+
export const runtimeFile = 'tslaws-runtime.json';
|
|
61
|
+
const compiledRoot = (project) => project.outDir ?? outDirOf(project.cwd);
|
|
62
|
+
/** The options for a program over the declarations in `outDir`: `base` plus the project's resolution. */
|
|
63
|
+
export function withResolution(outDir, base) {
|
|
64
|
+
const project = [...projects.values()].find((p) => compiledRoot(p) === outDir);
|
|
65
|
+
return { ...resolutionCompilerOptions(project?.options), ...base };
|
|
66
|
+
}
|
|
67
|
+
/** The directory holding the project's compiled files, as the last build left it. */
|
|
68
|
+
export function compiledDirOf(cwd) {
|
|
69
|
+
const project = projects.get(outDirOf(cwd));
|
|
70
|
+
return project === undefined ? outDirOf(cwd) : compiledRoot(project);
|
|
71
|
+
}
|
|
72
|
+
/** Registers a project's resolution for compiled laws and, on first use, puts the hooks in. */
|
|
73
|
+
export function installLawRuntime(runtime) {
|
|
74
|
+
projects.set(outDirOf(runtime.cwd), runtime);
|
|
75
|
+
if (hooked)
|
|
76
|
+
return;
|
|
77
|
+
hooked = true;
|
|
78
|
+
installPluginHooks({ ownerOf, beside, transform: (...args) => transforms.plugin(...args) });
|
|
79
|
+
const internals = Module;
|
|
80
|
+
const original = internals._resolveFilename;
|
|
81
|
+
internals._resolveFilename = function (request, parent, ...rest) {
|
|
82
|
+
const bare = !/^(\.{0,2}[\\/]|\w:|node:)/.test(request) && !Module.isBuiltin(request);
|
|
83
|
+
// An alias that shares its name with an installed package must run what the type checker saw, not the package.
|
|
84
|
+
const mapped = bare && namedInPaths(request, parent) ? resolveThroughTypeScript(request, parent) : undefined;
|
|
85
|
+
if (mapped !== undefined)
|
|
86
|
+
return mapped;
|
|
87
|
+
try {
|
|
88
|
+
return original.call(this, request, parent, ...rest);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
const found = bare ? resolveThroughTypeScript(request, parent) : beside(request, parent);
|
|
92
|
+
if (found === undefined)
|
|
93
|
+
throw error;
|
|
94
|
+
return found;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
// Node loads an unknown extension as JavaScript. A project format (`.tsrx`) goes through its `bundlerPlugins` instead.
|
|
98
|
+
const plain = internals._extensions['.js'];
|
|
99
|
+
internals._extensions['.js'] = function (module, file) {
|
|
100
|
+
const extension = extname(file).toLowerCase();
|
|
101
|
+
if (!pluginExtensionNeeded(extension))
|
|
102
|
+
return plain.call(this, module, file);
|
|
103
|
+
const owner = ownerOf(file);
|
|
104
|
+
module._compile(transforms.plugin(file, owner?.cwd ?? process.cwd(), owner?.bundlerPlugins ?? [], 'cjs'), file);
|
|
105
|
+
};
|
|
106
|
+
for (const extension of ['.ts', '.tsx', '.mts', '.cts'])
|
|
107
|
+
internals._extensions[extension] = (module, file) => {
|
|
108
|
+
module._compile(transforms.source(file, extension), file);
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/** The project a file belongs to: the one with the deepest directory holding it, else the most recently registered. */
|
|
112
|
+
function ownerOf(file) {
|
|
113
|
+
const all = [...projects.values()];
|
|
114
|
+
const holding = all.filter((p) => file.startsWith(p.cwd + sep)).sort((a, b) => b.cwd.length - a.cwd.length);
|
|
115
|
+
return holding[0] ?? all.at(-1);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* A relative import of a file the compiler does not write out (a template, a stylesheet) names the file beside the
|
|
119
|
+
* source, not beside the compiled output.
|
|
120
|
+
*/
|
|
121
|
+
function beside(request, parent) {
|
|
122
|
+
const from = parent?.filename;
|
|
123
|
+
if (from === undefined || !request.startsWith('.'))
|
|
124
|
+
return undefined;
|
|
125
|
+
const owner = [...projects].find(([top]) => from.startsWith(top + sep))?.[1];
|
|
126
|
+
if (owner === undefined)
|
|
127
|
+
return undefined;
|
|
128
|
+
const file = resolve(owner.cwd, relative(compiledRoot(owner), dirname(from)), request);
|
|
129
|
+
return existsSync(file) && statSync(file).isFile() ? file : undefined;
|
|
130
|
+
}
|
|
131
|
+
/** The options for a file that is not a compiled law: those of the nearest tsconfig, as the package would resolve. */
|
|
132
|
+
function optionsAround(file) {
|
|
133
|
+
const config = nearestTsconfig(dirname(file));
|
|
134
|
+
if (config === undefined)
|
|
135
|
+
return undefined;
|
|
136
|
+
let options = byConfig.get(config);
|
|
137
|
+
if (options === undefined) {
|
|
138
|
+
options = readResolutionOf(config, false);
|
|
139
|
+
byConfig.set(config, options);
|
|
140
|
+
}
|
|
141
|
+
return options;
|
|
142
|
+
}
|
|
143
|
+
/** Whether a `paths` entry other than the catch-all `*` (`baseUrl`'s fallback) names the request. */
|
|
144
|
+
function namedInPaths(request, parent) {
|
|
145
|
+
const from = parent?.filename;
|
|
146
|
+
if (from === undefined)
|
|
147
|
+
return false;
|
|
148
|
+
const owner = [...projects].find(([top]) => from.startsWith(top + sep))?.[1];
|
|
149
|
+
const options = owner === undefined ? optionsAround(from) : owner.options;
|
|
150
|
+
return Object.keys((options?.paths ?? {})).some((pattern) => {
|
|
151
|
+
if (pattern === '*')
|
|
152
|
+
return false;
|
|
153
|
+
const star = pattern.indexOf('*');
|
|
154
|
+
if (star < 0)
|
|
155
|
+
return pattern === request;
|
|
156
|
+
const [head, tail] = [pattern.slice(0, star), pattern.slice(star + 1)];
|
|
157
|
+
return request.length >= head.length + tail.length && request.startsWith(head) && request.endsWith(tail);
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* `sys` for a sandboxed process: the permission model answers a probe outside the readable trees (the directories above the
|
|
162
|
+
* project, which module resolution looks through) with an error, where it needs "no such file".
|
|
163
|
+
*/
|
|
164
|
+
function readableSys(sys) {
|
|
165
|
+
const safe = (call, otherwise) => (...args) => {
|
|
166
|
+
try {
|
|
167
|
+
return call(...args);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return otherwise;
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
return {
|
|
174
|
+
fileExists: safe(sys.fileExists, false),
|
|
175
|
+
// `sys` answers "no" for a directory the process may not read. TypeScript then skips the files under it, and a file the
|
|
176
|
+
// process may read (one granted by name, outside the project) sits in one: such a directory is taken to exist.
|
|
177
|
+
directoryExists: (path) => {
|
|
178
|
+
try {
|
|
179
|
+
return statSync(path).isDirectory();
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
return error.code === 'ERR_ACCESS_DENIED';
|
|
183
|
+
}
|
|
184
|
+
},
|
|
185
|
+
readFile: safe(sys.readFile, undefined),
|
|
186
|
+
// A path it may not resolve is taken as it is: resolving walks the directories above, which the process may not read.
|
|
187
|
+
realpath: (path) => {
|
|
188
|
+
try {
|
|
189
|
+
return sys.realpath?.(path) ?? path;
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
return path;
|
|
193
|
+
}
|
|
194
|
+
},
|
|
195
|
+
getCurrentDirectory: () => sys.getCurrentDirectory(),
|
|
196
|
+
getDirectories: safe(sys.getDirectories, []),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
function resolveThroughTypeScript(request, parent) {
|
|
200
|
+
const from = parent?.filename;
|
|
201
|
+
if (from === undefined)
|
|
202
|
+
return undefined;
|
|
203
|
+
const owner = [...projects].find(([top]) => from.startsWith(top + sep))?.[1];
|
|
204
|
+
// A compiled law resolves as its source does; the source is what imports are relative to.
|
|
205
|
+
const containing = owner === undefined ? from : join(owner.cwd, relative(compiledRoot(owner), from)).replace(/\.js$/, '.ts');
|
|
206
|
+
const options = owner === undefined ? optionsAround(from) : owner.options;
|
|
207
|
+
if (options === undefined)
|
|
208
|
+
return undefined;
|
|
209
|
+
const typescript = typescriptOf();
|
|
210
|
+
const compilerOptions = {
|
|
211
|
+
...resolutionCompilerOptions(options),
|
|
212
|
+
module: typescript.ModuleKind.ESNext,
|
|
213
|
+
moduleResolution: typescript.ModuleResolutionKind.Bundler,
|
|
214
|
+
};
|
|
215
|
+
// `require` first, since that is how the code loads; a package may only offer an `import` entry.
|
|
216
|
+
const modes = [typescript.ModuleKind.CommonJS, typescript.ModuleKind.ESNext];
|
|
217
|
+
for (const mode of modes) {
|
|
218
|
+
const found = typescript.resolveModuleName(request, containing, compilerOptions, readableSys(typescript.sys), undefined, undefined, mode).resolvedModule;
|
|
219
|
+
const file = found === undefined ? undefined : runnableFile(found.resolvedFileName, owner);
|
|
220
|
+
if (file !== undefined)
|
|
221
|
+
return file;
|
|
222
|
+
}
|
|
223
|
+
return undefined;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* The file Node can run for the file the type checker found: for a source file of the project, or one outside it that
|
|
227
|
+
* the compiler also wrote out, the compiled output at the same place in the tree; the `.js` beside a `.d.ts`; else the
|
|
228
|
+
* file itself (TypeScript source loads through the hook above).
|
|
229
|
+
*/
|
|
230
|
+
function runnableFile(found, owner) {
|
|
231
|
+
const declaration = /\.d\.([cm]?)ts$/.exec(found);
|
|
232
|
+
if (declaration !== null) {
|
|
233
|
+
const js = found.replace(/\.d\.[cm]?ts$/, `.${declaration[1] ?? ''}js`);
|
|
234
|
+
return existsSync(js) ? js : undefined;
|
|
235
|
+
}
|
|
236
|
+
if (owner !== undefined && /\.[cm]?tsx?$/.test(found) && !/[\\/]node_modules[\\/]/.test(found)) {
|
|
237
|
+
const compiled = resolve(compiledRoot(owner), relative(owner.cwd, found)).replace(/\.[cm]?tsx?$/, '.js');
|
|
238
|
+
if (existsSync(compiled))
|
|
239
|
+
return compiled;
|
|
240
|
+
}
|
|
241
|
+
return existsSync(found) ? found : undefined;
|
|
242
|
+
}
|
package/dist/lock.d.ts
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type CertificateRecord } from './certificates.ts';
|
|
2
|
+
import type { LawResult, ManifestLaw } from './types.ts';
|
|
2
3
|
export type LockEntries = Record<string, string>;
|
|
4
|
+
/**
|
|
5
|
+
* The lock format this tslaws writes. 2 hashes each law with the code it depends on and the settings it ran under (see
|
|
6
|
+
* seal.ts); a lock without a version, or with a lower one, hashed the law's own text only and must be accepted again.
|
|
7
|
+
*/
|
|
8
|
+
export declare const lockFormat = 2;
|
|
3
9
|
export interface Lock {
|
|
10
|
+
/** The format the lock file was written in: 0 when it names none. Set by `readLock`; `writeLockValue` always writes the current one. */
|
|
11
|
+
version?: number;
|
|
4
12
|
laws: LockEntries;
|
|
5
13
|
/** `file::name` of the functions a person exempted from coverage. */
|
|
6
14
|
exempt: string[];
|
|
@@ -9,24 +17,48 @@ export interface Lock {
|
|
|
9
17
|
* (the default) has no such section and keeps the format it always had.
|
|
10
18
|
*/
|
|
11
19
|
levels?: Record<string, string>;
|
|
20
|
+
/**
|
|
21
|
+
* Only in a lock accepted after `tslaws check --certify`: for each law a checker accepted a proof of, the hashes of the
|
|
22
|
+
* proof and of the checker's verdict. A record counts only while its `law` is the law's hash in `laws`.
|
|
23
|
+
*/
|
|
24
|
+
certificates?: Record<string, CertificateRecord>;
|
|
12
25
|
}
|
|
13
26
|
export declare function lawKey(file: string, name: string): string;
|
|
27
|
+
/** The hash of a law: its own text, whether it is `proved`, and its seal (the code it depends on and the run settings). */
|
|
14
28
|
export declare function lawHash(law: ManifestLaw): string;
|
|
15
29
|
export declare function readLock(path: string): Lock | undefined;
|
|
16
|
-
|
|
30
|
+
/** The records that still describe their law: the law is in the lock with the hash the record was made for. */
|
|
31
|
+
export declare function currentCertificates(laws: LockEntries, records: Record<string, CertificateRecord> | undefined): Record<string, CertificateRecord>;
|
|
32
|
+
/** Whether the lock records a certificate for the law as the lock holds it. */
|
|
33
|
+
export declare function isCertified(lock: Lock | undefined, key: string): boolean;
|
|
34
|
+
/** The lock that records exactly these laws: one entry each, the levels of their files, the certificates still current. */
|
|
35
|
+
export declare function lockOf(laws: ManifestLaw[], exempt?: string[], levels?: Record<string, string>, certificates?: Record<string, CertificateRecord>): Lock;
|
|
36
|
+
export declare function writeLock(path: string, laws: ManifestLaw[], exempt?: string[], levels?: Record<string, string>, certificates?: Record<string, CertificateRecord>): void;
|
|
37
|
+
export declare const fileOfKey: (key: string) => string;
|
|
38
|
+
/** The laws files, as the lock names them, of a run that named files. */
|
|
39
|
+
export declare function scopeOf(files: readonly string[]): ReadonlySet<string>;
|
|
40
|
+
/**
|
|
41
|
+
* The lock after a run that covered only the files in `scope` was accepted: `next` replaces what the lock holds for
|
|
42
|
+
* those files, and every entry of a file outside the scope (law, level, certificate) stays as it was. Exemptions are
|
|
43
|
+
* only added: a run of some files cannot tell whether an exemption in the rest still stands.
|
|
44
|
+
*/
|
|
45
|
+
export declare function mergeScoped(lock: Lock | undefined, scope: ReadonlySet<string>, next: Lock): Lock;
|
|
17
46
|
export interface LockViolation {
|
|
18
47
|
key: string;
|
|
19
48
|
reason: 'changed' | 'added' | 'removed' | 'level';
|
|
20
49
|
}
|
|
21
50
|
/**
|
|
22
|
-
* `levels` is
|
|
23
|
-
*
|
|
24
|
-
* locked at all, is a violation until a person accepts again
|
|
51
|
+
* `levels` is what to compare of the levels: `locked` is the lock's levels section and `now` the level each laws file
|
|
52
|
+
* resolves to now, which only a project with `levels: "imports"` has. A law whose file's level is not the locked one, or
|
|
53
|
+
* is not locked at all, is a violation until a person accepts again, and so is every law of a lock that records levels
|
|
54
|
+
* when the project no longer resolves any (`levels` went back to names). Leave `levels` out when neither side has any.
|
|
55
|
+
* `scope` is the laws files of a run that named files: only a law locked in one of them can be removed; the locked laws
|
|
56
|
+
* of other files are not part of the run.
|
|
25
57
|
*/
|
|
26
58
|
export declare function compareLock(lock: LockEntries | undefined, laws: ManifestLaw[], levels?: {
|
|
27
59
|
locked: Record<string, string> | undefined;
|
|
28
|
-
now: Record<string, string
|
|
29
|
-
}): LockViolation[];
|
|
60
|
+
now: Record<string, string> | undefined;
|
|
61
|
+
}, scope?: ReadonlySet<string>): LockViolation[];
|
|
30
62
|
/**
|
|
31
63
|
* One difference between the lock and the project: a law added, changed, removed or moved to another level, or a
|
|
32
64
|
* coverage exemption added or removed. `fingerprint` names the exact content a person accepts, so an approval given for
|
|
@@ -40,13 +72,21 @@ export interface LockChange {
|
|
|
40
72
|
}
|
|
41
73
|
/**
|
|
42
74
|
* Every change a person would record by accepting the project as it is now. `levels` is the level of each laws file
|
|
43
|
-
* now, or undefined when the lock
|
|
75
|
+
* now, or undefined when the project resolves none (levels from names); a lock that still records levels then changes.
|
|
44
76
|
*/
|
|
45
77
|
export declare function lockChanges(lock: Lock | undefined, laws: ManifestLaw[], exempt: string[], levels?: Record<string, string>): LockChange[];
|
|
46
78
|
/**
|
|
47
79
|
* The lock after accepting only the changes whose fingerprints are in `accepted`; every other entry keeps what the lock
|
|
48
80
|
* had. Levels are recorded per laws file, so a file's level is taken from now once every law change in it is accepted.
|
|
49
81
|
*/
|
|
50
|
-
export declare function acceptChanges(lock: Lock | undefined, laws: ManifestLaw[], exempt: string[], levels: Record<string, string> | undefined, accepted: ReadonlySet<string>): Lock;
|
|
82
|
+
export declare function acceptChanges(lock: Lock | undefined, laws: ManifestLaw[], exempt: string[], levels: Record<string, string> | undefined, accepted: ReadonlySet<string>, certificates?: Record<string, CertificateRecord>): Lock;
|
|
83
|
+
/** `proved` or `bounded` when the law's proof held, whether the result says so or is the proposal of a law the lock lacks. */
|
|
84
|
+
export declare function proofStatus(result: LawResult): 'proved' | 'bounded' | undefined;
|
|
85
|
+
/**
|
|
86
|
+
* The certificates a run vouches for: one for each law this run proved and certified, made from this run's proof and
|
|
87
|
+
* only while the law is the one the lock holds. Nothing is carried over from an older lock, since a certificate for the
|
|
88
|
+
* same law text can be for a problem that the code it calls has since changed.
|
|
89
|
+
*/
|
|
90
|
+
export declare function certificatesFromRun(lock: Lock, laws: ManifestLaw[], results: LawResult[]): Record<string, CertificateRecord>;
|
|
51
91
|
/** Writes a lock value in the same canonical form as `writeLock`. */
|
|
52
92
|
export declare function writeLockValue(path: string, lock: Lock): void;
|
package/dist/lock.js
CHANGED
|
@@ -2,40 +2,115 @@
|
|
|
2
2
|
// addition or removal fails the check until a person runs `tslaws accept`.
|
|
3
3
|
import { createHash } from 'node:crypto';
|
|
4
4
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { recordOf } from "./certificates.js";
|
|
6
|
+
/**
|
|
7
|
+
* The lock format this tslaws writes. 2 hashes each law with the code it depends on and the settings it ran under (see
|
|
8
|
+
* seal.ts); a lock without a version, or with a lower one, hashed the law's own text only and must be accepted again.
|
|
9
|
+
*/
|
|
10
|
+
export const lockFormat = 2;
|
|
5
11
|
export function lawKey(file, name) {
|
|
6
12
|
return `${file.replaceAll('\\', '/')}::${name}`;
|
|
7
13
|
}
|
|
14
|
+
/** The hash of a law: its own text, whether it is `proved`, and its seal (the code it depends on and the run settings). */
|
|
8
15
|
export function lawHash(law) {
|
|
9
16
|
const normalized = `${law.proved ? 'proved ' : ''}${law.text.replace(/\s+/g, ' ')}`;
|
|
10
|
-
return createHash('sha256')
|
|
17
|
+
return createHash('sha256')
|
|
18
|
+
.update(normalized)
|
|
19
|
+
.update('|')
|
|
20
|
+
.update(law.seal ?? '')
|
|
21
|
+
.digest('hex');
|
|
11
22
|
}
|
|
12
23
|
export function readLock(path) {
|
|
13
24
|
if (!existsSync(path))
|
|
14
25
|
return undefined;
|
|
15
26
|
const lock = JSON.parse(readFileSync(path, 'utf8'));
|
|
16
|
-
return {
|
|
27
|
+
return {
|
|
28
|
+
version: typeof lock.version === 'number' ? Math.min(lockFormat, Math.max(0, lock.version)) : 0,
|
|
29
|
+
laws: lock.laws,
|
|
30
|
+
exempt: lock.exempt ?? [],
|
|
31
|
+
...(lock.levels === undefined ? {} : { levels: lock.levels }),
|
|
32
|
+
...(lock.certificates === undefined ? {} : { certificates: lock.certificates }),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** The records that still describe their law: the law is in the lock with the hash the record was made for. */
|
|
36
|
+
export function currentCertificates(laws, records) {
|
|
37
|
+
const kept = {};
|
|
38
|
+
for (const key of Object.keys(records ?? {}).sort())
|
|
39
|
+
if (laws[key] !== undefined && records[key].law === laws[key])
|
|
40
|
+
kept[key] = records[key];
|
|
41
|
+
return kept;
|
|
17
42
|
}
|
|
18
|
-
|
|
43
|
+
/** Whether the lock records a certificate for the law as the lock holds it. */
|
|
44
|
+
export function isCertified(lock, key) {
|
|
45
|
+
return lock?.laws[key] !== undefined && lock.certificates?.[key]?.law === lock.laws[key];
|
|
46
|
+
}
|
|
47
|
+
/** The `certificates` part of a lock body: nothing when no record is current, so an uncertified lock keeps its format. */
|
|
48
|
+
function certificatesBody(laws, records) {
|
|
49
|
+
const current = currentCertificates(laws, records);
|
|
50
|
+
return Object.keys(current).length === 0 ? {} : { certificates: current };
|
|
51
|
+
}
|
|
52
|
+
/** The lock that records exactly these laws: one entry each, the levels of their files, the certificates still current. */
|
|
53
|
+
export function lockOf(laws, exempt = [], levels, certificates) {
|
|
19
54
|
const entries = {};
|
|
20
55
|
for (const law of [...laws].sort((a, b) => lawKey(a.file, a.name).localeCompare(lawKey(b.file, b.name))))
|
|
21
56
|
entries[lawKey(law.file, law.name)] = lawHash(law);
|
|
22
57
|
const recorded = {};
|
|
23
58
|
for (const file of Object.keys(levels ?? {}).sort())
|
|
24
59
|
recorded[file.replaceAll('\\', '/')] = levels[file];
|
|
25
|
-
|
|
26
|
-
version: 1,
|
|
60
|
+
return {
|
|
27
61
|
laws: entries,
|
|
28
|
-
exempt: [...exempt]
|
|
62
|
+
exempt: [...exempt],
|
|
29
63
|
...(levels === undefined ? {} : { levels: recorded }),
|
|
64
|
+
...certificatesBody(entries, certificates),
|
|
30
65
|
};
|
|
31
|
-
|
|
66
|
+
}
|
|
67
|
+
export function writeLock(path, laws, exempt = [], levels, certificates) {
|
|
68
|
+
writeLockValue(path, lockOf(laws, exempt, levels, certificates));
|
|
69
|
+
}
|
|
70
|
+
export const fileOfKey = (key) => key.slice(0, key.lastIndexOf('::'));
|
|
71
|
+
/** The laws files, as the lock names them, of a run that named files. */
|
|
72
|
+
export function scopeOf(files) {
|
|
73
|
+
return new Set(files.map((f) => f.replaceAll('\\', '/')));
|
|
32
74
|
}
|
|
33
75
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
76
|
+
* The lock after a run that covered only the files in `scope` was accepted: `next` replaces what the lock holds for
|
|
77
|
+
* those files, and every entry of a file outside the scope (law, level, certificate) stays as it was. Exemptions are
|
|
78
|
+
* only added: a run of some files cannot tell whether an exemption in the rest still stands.
|
|
37
79
|
*/
|
|
38
|
-
export function
|
|
80
|
+
export function mergeScoped(lock, scope, next) {
|
|
81
|
+
if (lock === undefined)
|
|
82
|
+
return next;
|
|
83
|
+
const outside = (key) => !scope.has(fileOfKey(key));
|
|
84
|
+
const laws = { ...next.laws };
|
|
85
|
+
for (const [key, hash] of Object.entries(lock.laws))
|
|
86
|
+
if (outside(key))
|
|
87
|
+
laws[key] = hash;
|
|
88
|
+
const certificates = { ...next.certificates };
|
|
89
|
+
for (const [key, record] of Object.entries(lock.certificates ?? {}))
|
|
90
|
+
if (outside(key))
|
|
91
|
+
certificates[key] = record;
|
|
92
|
+
const levels = next.levels === undefined && lock.levels === undefined
|
|
93
|
+
? undefined
|
|
94
|
+
: {
|
|
95
|
+
...Object.fromEntries(Object.entries(lock.levels ?? {}).filter(([file]) => !scope.has(file))),
|
|
96
|
+
...next.levels,
|
|
97
|
+
};
|
|
98
|
+
return {
|
|
99
|
+
laws,
|
|
100
|
+
exempt: [...new Set([...lock.exempt, ...next.exempt])],
|
|
101
|
+
...(levels === undefined ? {} : { levels }),
|
|
102
|
+
...(Object.keys(certificates).length === 0 ? {} : { certificates }),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* `levels` is what to compare of the levels: `locked` is the lock's levels section and `now` the level each laws file
|
|
107
|
+
* resolves to now, which only a project with `levels: "imports"` has. A law whose file's level is not the locked one, or
|
|
108
|
+
* is not locked at all, is a violation until a person accepts again, and so is every law of a lock that records levels
|
|
109
|
+
* when the project no longer resolves any (`levels` went back to names). Leave `levels` out when neither side has any.
|
|
110
|
+
* `scope` is the laws files of a run that named files: only a law locked in one of them can be removed; the locked laws
|
|
111
|
+
* of other files are not part of the run.
|
|
112
|
+
*/
|
|
113
|
+
export function compareLock(lock, laws, levels, scope) {
|
|
39
114
|
const violations = [];
|
|
40
115
|
const seen = new Set();
|
|
41
116
|
for (const law of laws) {
|
|
@@ -48,23 +123,23 @@ export function compareLock(lock, laws, levels) {
|
|
|
48
123
|
violations.push({ key, reason: 'changed' });
|
|
49
124
|
else if (levels !== undefined) {
|
|
50
125
|
const file = law.file.replaceAll('\\', '/');
|
|
51
|
-
if (levels.locked?.[file] !== levels.now[file])
|
|
126
|
+
if (levels.locked?.[file] !== levels.now?.[file] || (levels.locked !== undefined && levels.now === undefined))
|
|
52
127
|
violations.push({ key, reason: 'level' });
|
|
53
128
|
}
|
|
54
129
|
}
|
|
55
130
|
for (const key of Object.keys(lock ?? {}))
|
|
56
|
-
if (!seen.has(key))
|
|
131
|
+
if (!seen.has(key) && (scope === undefined || scope.has(fileOfKey(key))))
|
|
57
132
|
violations.push({ key, reason: 'removed' });
|
|
58
133
|
return violations;
|
|
59
134
|
}
|
|
60
135
|
const fingerprintOf = (...parts) => createHash('sha256').update(parts.join('\u0000')).digest('hex').slice(0, 16);
|
|
61
136
|
/**
|
|
62
137
|
* Every change a person would record by accepting the project as it is now. `levels` is the level of each laws file
|
|
63
|
-
* now, or undefined when the lock
|
|
138
|
+
* now, or undefined when the project resolves none (levels from names); a lock that still records levels then changes.
|
|
64
139
|
*/
|
|
65
140
|
export function lockChanges(lock, laws, exempt, levels) {
|
|
66
141
|
const byKey = new Map(laws.map((law) => [lawKey(law.file, law.name), law]));
|
|
67
|
-
const compared = compareLock(lock?.laws, laws, levels === undefined ? undefined : { locked: lock?.levels, now: levels });
|
|
142
|
+
const compared = compareLock(lock?.laws, laws, levels === undefined && lock?.levels === undefined ? undefined : { locked: lock?.levels, now: levels });
|
|
68
143
|
const changes = compared.map((violation) => {
|
|
69
144
|
const law = byKey.get(violation.key);
|
|
70
145
|
const hash = law === undefined ? 'removed' : lawHash(law);
|
|
@@ -88,7 +163,7 @@ export function lockChanges(lock, laws, exempt, levels) {
|
|
|
88
163
|
* The lock after accepting only the changes whose fingerprints are in `accepted`; every other entry keeps what the lock
|
|
89
164
|
* had. Levels are recorded per laws file, so a file's level is taken from now once every law change in it is accepted.
|
|
90
165
|
*/
|
|
91
|
-
export function acceptChanges(lock, laws, exempt, levels, accepted) {
|
|
166
|
+
export function acceptChanges(lock, laws, exempt, levels, accepted, certificates) {
|
|
92
167
|
const changes = lockChanges(lock, laws, exempt, levels);
|
|
93
168
|
const taken = changes.filter((c) => accepted.has(c.fingerprint));
|
|
94
169
|
const byKey = new Map(laws.map((law) => [lawKey(law.file, law.name), law]));
|
|
@@ -109,10 +184,15 @@ export function acceptChanges(lock, laws, exempt, levels, accepted) {
|
|
|
109
184
|
entries[change.key] = lawHash(law);
|
|
110
185
|
}
|
|
111
186
|
let recorded;
|
|
112
|
-
|
|
187
|
+
const fileOf = (key) => key.slice(0, key.lastIndexOf('::'));
|
|
188
|
+
const open = new Set(changes.filter((c) => c.kind === 'law' && !accepted.has(c.fingerprint)).map((c) => fileOf(c.key)));
|
|
189
|
+
if (levels === undefined && lock?.levels !== undefined) {
|
|
190
|
+
// Levels went back to names: the recorded level of a file goes once every change in it is accepted, not before.
|
|
191
|
+
const kept = Object.entries(lock.levels).filter(([file]) => open.has(file));
|
|
192
|
+
recorded = kept.length === 0 ? undefined : Object.fromEntries(kept);
|
|
193
|
+
}
|
|
194
|
+
else if (levels !== undefined) {
|
|
113
195
|
recorded = { ...lock?.levels };
|
|
114
|
-
const fileOf = (key) => key.slice(0, key.lastIndexOf('::'));
|
|
115
|
-
const open = new Set(changes.filter((c) => c.kind === 'law' && !accepted.has(c.fingerprint)).map((c) => fileOf(c.key)));
|
|
116
196
|
for (const [file, level] of Object.entries(levels))
|
|
117
197
|
if (!open.has(file))
|
|
118
198
|
recorded[file] = level;
|
|
@@ -120,7 +200,37 @@ export function acceptChanges(lock, laws, exempt, levels, accepted) {
|
|
|
120
200
|
if (!(file in levels) && !Object.keys(entries).some((key) => fileOf(key) === file))
|
|
121
201
|
delete recorded[file];
|
|
122
202
|
}
|
|
123
|
-
return {
|
|
203
|
+
return {
|
|
204
|
+
laws: entries,
|
|
205
|
+
exempt: [...exemptions],
|
|
206
|
+
...(recorded === undefined ? {} : { levels: recorded }),
|
|
207
|
+
...certificatesBody(entries, certificates),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
/** `proved` or `bounded` when the law's proof held, whether the result says so or is the proposal of a law the lock lacks. */
|
|
211
|
+
export function proofStatus(result) {
|
|
212
|
+
const status = result.status === 'tampered' ? result.proposal?.status : result.status;
|
|
213
|
+
return status === 'proved' || status === 'bounded' ? status : undefined;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The certificates a run vouches for: one for each law this run proved and certified, made from this run's proof and
|
|
217
|
+
* only while the law is the one the lock holds. Nothing is carried over from an older lock, since a certificate for the
|
|
218
|
+
* same law text can be for a problem that the code it calls has since changed.
|
|
219
|
+
*/
|
|
220
|
+
export function certificatesFromRun(lock, laws, results) {
|
|
221
|
+
const current = new Map(laws.map((law) => [lawKey(law.file, law.name), lawHash(law)]));
|
|
222
|
+
const records = {};
|
|
223
|
+
for (const result of results) {
|
|
224
|
+
const key = lawKey(result.file, result.name);
|
|
225
|
+
const hash = current.get(key);
|
|
226
|
+
const certificate = proofStatus(result) === undefined ? undefined : (result.proposal?.certificate ?? result.certificate);
|
|
227
|
+
if (certificate === undefined || hash === undefined || lock.laws[key] !== hash)
|
|
228
|
+
continue;
|
|
229
|
+
const record = recordOf(hash, certificate);
|
|
230
|
+
if (record !== undefined)
|
|
231
|
+
records[key] = record;
|
|
232
|
+
}
|
|
233
|
+
return records;
|
|
124
234
|
}
|
|
125
235
|
/** Writes a lock value in the same canonical form as `writeLock`. */
|
|
126
236
|
export function writeLockValue(path, lock) {
|
|
@@ -128,7 +238,7 @@ export function writeLockValue(path, lock) {
|
|
|
128
238
|
for (const key of Object.keys(lock.laws).sort((a, b) => a.localeCompare(b)))
|
|
129
239
|
laws[key] = lock.laws[key];
|
|
130
240
|
const body = {
|
|
131
|
-
version:
|
|
241
|
+
version: lockFormat,
|
|
132
242
|
laws,
|
|
133
243
|
exempt: [...lock.exempt].sort(),
|
|
134
244
|
...(lock.levels === undefined
|
|
@@ -138,6 +248,7 @@ export function writeLockValue(path, lock) {
|
|
|
138
248
|
.sort()
|
|
139
249
|
.map((f) => [f, lock.levels[f]])),
|
|
140
250
|
}),
|
|
251
|
+
...certificatesBody(laws, lock.certificates),
|
|
141
252
|
};
|
|
142
253
|
writeFileSync(path, JSON.stringify(body, null, 2) + '\n');
|
|
143
254
|
}
|