tslaws 0.10.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.
Files changed (122) hide show
  1. package/README.md +7 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +25 -5
  5. package/dist/bundled.js +2 -2
  6. package/dist/bundlerPlugins.d.ts +2 -0
  7. package/dist/bundlerPlugins.js +7 -0
  8. package/dist/certificates.d.ts +139 -0
  9. package/dist/certificates.js +433 -0
  10. package/dist/chc.d.ts +85 -0
  11. package/dist/chc.js +298 -0
  12. package/dist/check.d.ts +13 -1
  13. package/dist/check.js +211 -27
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +175 -34
  16. package/dist/compile.d.ts +15 -5
  17. package/dist/compile.js +198 -69
  18. package/dist/coverage.d.ts +38 -1
  19. package/dist/coverage.js +94 -12
  20. package/dist/e2eApi.js +3 -1
  21. package/dist/generators.js +12 -2
  22. package/dist/github.d.ts +49 -5
  23. package/dist/github.js +107 -24
  24. package/dist/githubCli.d.ts +28 -0
  25. package/dist/githubCli.js +1039 -211
  26. package/dist/hints.js +2 -1
  27. package/dist/init.js +42 -0
  28. package/dist/isolate.d.ts +28 -0
  29. package/dist/isolate.js +262 -0
  30. package/dist/isolatedCheck.d.ts +1 -0
  31. package/dist/isolatedCheck.js +16 -0
  32. package/dist/lawHost.d.ts +50 -0
  33. package/dist/lawHost.js +199 -0
  34. package/dist/lawRuntime.d.ts +39 -0
  35. package/dist/lawRuntime.js +242 -0
  36. package/dist/lock.d.ts +49 -9
  37. package/dist/lock.js +132 -21
  38. package/dist/mcp.js +28 -7
  39. package/dist/mutate.d.ts +4 -0
  40. package/dist/mutate.js +7 -1
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +4 -0
  43. package/dist/pluginHooks.d.ts +16 -0
  44. package/dist/pluginHooks.js +48 -0
  45. package/dist/pluginHost.d.ts +5 -0
  46. package/dist/pluginHost.js +43 -0
  47. package/dist/pluginWorker.d.ts +1 -0
  48. package/dist/pluginWorker.js +40 -0
  49. package/dist/plural.d.ts +2 -0
  50. package/dist/plural.js +4 -0
  51. package/dist/pool.d.ts +80 -7
  52. package/dist/pool.js +222 -11
  53. package/dist/projects.d.ts +43 -1
  54. package/dist/projects.js +283 -11
  55. package/dist/promote.d.ts +56 -2
  56. package/dist/promote.js +429 -13
  57. package/dist/property.js +5 -1
  58. package/dist/propertyWorker.js +7 -0
  59. package/dist/proposals.d.ts +52 -4
  60. package/dist/proposals.js +484 -21
  61. package/dist/reporters.js +5 -1
  62. package/dist/runtimeEnv.d.ts +13 -5
  63. package/dist/runtimeEnv.js +48 -10
  64. package/dist/sandbox.d.ts +98 -0
  65. package/dist/sandbox.js +673 -0
  66. package/dist/sandboxGuard.d.ts +56 -0
  67. package/dist/sandboxGuard.js +249 -0
  68. package/dist/seal.d.ts +9 -0
  69. package/dist/seal.js +426 -0
  70. package/dist/security/cli.d.ts +6 -0
  71. package/dist/security/cli.js +39 -0
  72. package/dist/security/cwe.d.ts +14 -0
  73. package/dist/security/cwe.js +40 -0
  74. package/dist/security/deps/cache.d.ts +28 -0
  75. package/dist/security/deps/cache.js +107 -0
  76. package/dist/security/deps/config.d.ts +16 -0
  77. package/dist/security/deps/config.js +43 -0
  78. package/dist/security/deps/imports.d.ts +4 -0
  79. package/dist/security/deps/imports.js +33 -0
  80. package/dist/security/deps/lockfiles.d.ts +23 -0
  81. package/dist/security/deps/lockfiles.js +153 -0
  82. package/dist/security/deps/osv.d.ts +66 -0
  83. package/dist/security/deps/osv.js +137 -0
  84. package/dist/security/deps/run.d.ts +54 -0
  85. package/dist/security/deps/run.js +135 -0
  86. package/dist/security/deps/severity.d.ts +26 -0
  87. package/dist/security/deps/severity.js +78 -0
  88. package/dist/security/generators.d.ts +9 -0
  89. package/dist/security/generators.js +36 -0
  90. package/dist/security/index.d.ts +27 -0
  91. package/dist/security/index.js +18 -0
  92. package/dist/security/integers.d.ts +31 -0
  93. package/dist/security/integers.js +105 -0
  94. package/dist/security/law.d.ts +54 -0
  95. package/dist/security/law.js +54 -0
  96. package/dist/security/pathTraversal.d.ts +29 -0
  97. package/dist/security/pathTraversal.js +146 -0
  98. package/dist/security/prototypePollution.d.ts +30 -0
  99. package/dist/security/prototypePollution.js +142 -0
  100. package/dist/security/redirect.d.ts +21 -0
  101. package/dist/security/redirect.js +154 -0
  102. package/dist/security/redos.d.ts +21 -0
  103. package/dist/security/redos.js +93 -0
  104. package/dist/security/validation.d.ts +25 -0
  105. package/dist/security/validation.js +89 -0
  106. package/dist/security/xss.d.ts +21 -0
  107. package/dist/security/xss.js +90 -0
  108. package/dist/settings.d.ts +20 -0
  109. package/dist/settings.js +32 -0
  110. package/dist/smt.d.ts +29 -1
  111. package/dist/smt.js +239 -107
  112. package/dist/smtWorker.d.ts +1 -0
  113. package/dist/smtWorker.js +26 -0
  114. package/dist/solvers.d.ts +9 -0
  115. package/dist/solvers.js +11 -5
  116. package/dist/symbolic.d.ts +54 -1
  117. package/dist/symbolic.js +239 -13
  118. package/dist/tsconfigResolve.d.ts +28 -0
  119. package/dist/tsconfigResolve.js +141 -0
  120. package/dist/types.d.ts +28 -0
  121. package/hooks/claude-hook.mjs +2 -0
  122. package/package.json +18 -6
package/dist/promote.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import ts from 'typescript';
1
2
  export interface ParsedLaw {
2
3
  name: string;
3
4
  /** The declaration as written, from `export` to its end. */
@@ -5,10 +6,27 @@ export interface ParsedLaw {
5
6
  start: number;
6
7
  end: number;
7
8
  }
9
+ /** A top-level statement that is neither an import nor a law (a helper const, function, type, interface, class, enum or namespace). */
10
+ export interface ParsedDeclaration {
11
+ /** The names the statement declares: one for most, several for `const a = 1, b = 2` or a destructuring. */
12
+ names: string[];
13
+ /** The statement as written, with the comments directly above it (a JSDoc block, `//` lines) and no blank line between. */
14
+ text: string;
15
+ start: number;
16
+ end: number;
17
+ /** Every identifier the statement mentions, apart from property names after a `.`. A superset of what it really references. */
18
+ references: string[];
19
+ }
8
20
  export interface ParsedLawFile {
9
21
  /** Whole import statements, in order. */
10
22
  imports: string[];
11
23
  laws: ParsedLaw[];
24
+ /** Where the last import statement ends, or 0 when there is none. */
25
+ importEnd: number;
26
+ /** The named top-level statements that are not imports or laws, in source order. */
27
+ declarations: ParsedDeclaration[];
28
+ /** The text with the imports and laws overwritten by spaces (line breaks kept): what is left to the helpers and anything else. */
29
+ rest: string;
12
30
  }
13
31
  /**
14
32
  * `foo.proposed.laws.ts` -> `foo.laws.ts`, `foo.browser.proposed.laws.ts` -> `foo.browser.laws.ts` and
@@ -21,13 +39,45 @@ export declare function acceptedPathFor(proposed: string): string | undefined;
21
39
  * brackets: a law ends at its closing `}` or at a `;` at depth 0.
22
40
  */
23
41
  export declare function parseLawFile(text: string): ParsedLawFile;
42
+ /** The identifiers in `text`, found with the scanner so it also reads a law (`export law ...`, which is not standard TypeScript). */
43
+ export declare function identifiersIn(text: string): Set<string>;
44
+ /** The code of `text` printed from its syntax tree without comments: layout is normalised, string and template contents are not. */
45
+ export declare function sameCode(a: string, b: string): boolean;
46
+ /** A `const` statement: not `let`, `var`, `using` or `await using` (the last two carry the Const flag too and call a dispose method). */
47
+ export declare function isPlainConst(statement: ts.VariableStatement): boolean;
48
+ /**
49
+ * Why a helper may not be proposed or copied, or undefined when it may. A helper is a function, type or interface
50
+ * declaration, or a `const` whose initialiser has no side effects (a literal, a function, an object or array of those,
51
+ * `as const`): a helper becomes part of the accepted tree, and a `const` initialiser runs when the file loads.
52
+ */
53
+ export declare function helperProblem(text: string): string | undefined;
54
+ /** Throws unless every one of `declarations` passes `helperProblem`. */
55
+ export declare function assertHelpersSafe(declarations: ParsedDeclaration[]): void;
56
+ /** Throws unless each of `imports` is exactly one import statement, so a scanning slip cannot pass other code off as an import. */
57
+ export declare function assertImportStatements(imports: string[]): void;
24
58
  /** Joins the import statements, dropping repeats by whitespace-insensitive text. */
25
59
  export declare function dedupeImports(existing: string[], added: string[]): string[];
26
60
  /**
27
61
  * The accepted file after promoting `laws` (with the proposed file's imports) into it. `existing` is the current text
28
- * of the accepted file, or undefined when it does not exist yet. Throws when a law name is already taken there.
62
+ * of the accepted file, or undefined when it does not exist yet. `declarations` are all the helper declarations of the
63
+ * proposed file: the ones the laws use, directly or through each other, are copied too. A declaration already in the
64
+ * accepted file with the same code (layout and comments aside) is not copied again; one of the same name with different text is
65
+ * an error. Throws when a law name is already taken there, and, as a safety net, when the result would use a name the
66
+ * proposed file declares but the accepted file does not.
29
67
  */
30
- export declare function buildAccepted(existing: string | undefined, imports: string[], laws: ParsedLaw[]): string;
68
+ export declare function buildAccepted(existing: string | undefined, imports: string[], laws: ParsedLaw[], declarations?: ParsedDeclaration[]): string;
69
+ /** What a promote would write, with the code it adds beside the laws. */
70
+ export interface AcceptedPlan {
71
+ text: string;
72
+ /** The import statements the accepted file does not have yet. */
73
+ imports: string[];
74
+ /** The helper declarations copied into the accepted file. */
75
+ declarations: ParsedDeclaration[];
76
+ }
77
+ /** `buildAccepted`, with the imports and helpers it adds, so a person can read them before anything is written. */
78
+ export declare function planAccepted(existing: string | undefined, imports: string[], laws: ParsedLaw[], declarations?: ParsedDeclaration[]): AcceptedPlan;
79
+ /** `block` placed after the last declaration of `text`, else after its last import, else before its first law, else at the end. */
80
+ export declare function withDeclarations(text: string, block: string): string;
31
81
  /** The proposed file without the promoted laws, or undefined when no law is left (the file is deleted). */
32
82
  export declare function buildRemaining(text: string, promoted: string[]): string | undefined;
33
83
  export interface PromoteHost {
@@ -36,6 +86,8 @@ export interface PromoteHost {
36
86
  checkFile: (file: string) => Promise<Map<string, string>>;
37
87
  ask: (question: string) => Promise<string>;
38
88
  out: (text: string) => void;
89
+ /** Add the imports and helpers without asking (`--yes`); they are still printed. */
90
+ yes?: boolean;
39
91
  }
40
92
  /** Walks the proposed files, asks per law, and rewrites the accepted and proposed files. Returns the number promoted. */
41
93
  export declare function promoteFiles(host: PromoteHost, proposedFiles: string[]): Promise<number>;
@@ -52,6 +104,8 @@ export interface PromoteProposalHost {
52
104
  checkFile: (file: string) => Promise<Map<string, string>>;
53
105
  ask: (question: string) => Promise<string>;
54
106
  out: (text: string) => void;
107
+ /** Add the imports and helpers without asking (`--yes`); they are still printed. */
108
+ yes?: boolean;
55
109
  }
56
110
  export interface PromoteProposalResult {
57
111
  /** Project-relative path the laws went to; undefined when the person declined or nothing was moved. */
package/dist/promote.js CHANGED
@@ -5,7 +5,7 @@ import ts from 'typescript';
5
5
  import { ignoredDirs, namesLawsFile } from "./lawFiles.js";
6
6
  import { directProjectImports } from "./lawKinds.js";
7
7
  import { acceptedLawName, isProposedLawFile } from "./lawNames.js";
8
- import { existingProposal, importsForTarget, ProposalError } from "./proposals.js";
8
+ import { assertImportsAllowed, existingProposal, importsForTarget, ProposalError } from "./proposals.js";
9
9
  /**
10
10
  * `foo.proposed.laws.ts` -> `foo.laws.ts`, `foo.browser.proposed.laws.ts` -> `foo.browser.laws.ts` and
11
11
  * `foo.e2e.proposed.laws.ts` -> `foo.e2e.laws.ts`, so a proposal lands in a file of its own kind; undefined for any other name.
@@ -21,6 +21,7 @@ export function acceptedPathFor(proposed) {
21
21
  export function parseLawFile(text) {
22
22
  const scanner = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.Standard, text);
23
23
  const imports = [];
24
+ const importRanges = [];
24
25
  const laws = [];
25
26
  const templates = []; // depth at which each open template substitution started
26
27
  let depth = 0;
@@ -29,8 +30,10 @@ export function parseLawFile(text) {
29
30
  const finish = (end) => {
30
31
  if (statement === undefined)
31
32
  return;
32
- if (statement.kind === 'import')
33
+ if (statement.kind === 'import') {
33
34
  imports.push(text.slice(statement.start, end));
35
+ importRanges.push({ start: statement.start, end });
36
+ }
34
37
  else
35
38
  laws.push({ name: statement.name, text: text.slice(statement.start, end), start: statement.start, end });
36
39
  statement = undefined;
@@ -50,7 +53,12 @@ export function parseLawFile(text) {
50
53
  }
51
54
  else if (depth === 0 && statement === undefined) {
52
55
  if (kind === ts.SyntaxKind.ImportKeyword) {
53
- statement = { kind: 'import', start: tokenStart, name: '', sawString: false };
56
+ // `import(...)` and `import.meta` are expressions inside some other statement, not an import statement.
57
+ const after = scanner.getTokenEnd();
58
+ const peek = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.Standard, text, undefined, after, text.length - after);
59
+ const next = peek.scan();
60
+ if (next !== ts.SyntaxKind.OpenParenToken && next !== ts.SyntaxKind.DotToken)
61
+ statement = { kind: 'import', start: tokenStart, name: '', sawString: false };
54
62
  }
55
63
  else if (kind === ts.SyntaxKind.ExportKeyword) {
56
64
  const rest = scanner.getTokenEnd();
@@ -116,7 +124,106 @@ export function parseLawFile(text) {
116
124
  if (!laws.some((l) => call.start >= l.start && call.start < l.end))
117
125
  laws.push(call);
118
126
  laws.sort((a, b) => a.start - b.start);
119
- return { imports, laws };
127
+ return {
128
+ imports,
129
+ laws,
130
+ importEnd: importRanges[importRanges.length - 1]?.end ?? 0,
131
+ declarations: declarationsOf(text, [...importRanges, ...laws]),
132
+ rest: blank(text, [...importRanges, ...laws]),
133
+ };
134
+ }
135
+ /** `text` with the given ranges overwritten by spaces (line breaks kept), so positions stay the same. */
136
+ function blank(text, ranges) {
137
+ let out = text;
138
+ for (const { start, end } of ranges)
139
+ out = out.slice(0, start) + out.slice(start, end).replace(/[^\r\n]/g, ' ') + out.slice(end);
140
+ return out;
141
+ }
142
+ /** The names a statement declares; empty for statements that declare none (expressions, `export { x }`, `export default`). */
143
+ function declaredNames(statement) {
144
+ if (ts.isVariableStatement(statement)) {
145
+ const names = [];
146
+ const walk = (name) => {
147
+ if (ts.isIdentifier(name))
148
+ names.push(name.text);
149
+ else
150
+ for (const element of name.elements)
151
+ if (!ts.isOmittedExpression(element))
152
+ walk(element.name);
153
+ };
154
+ for (const declaration of statement.declarationList.declarations)
155
+ walk(declaration.name);
156
+ return names;
157
+ }
158
+ if (ts.isFunctionDeclaration(statement) ||
159
+ ts.isClassDeclaration(statement) ||
160
+ ts.isInterfaceDeclaration(statement) ||
161
+ ts.isTypeAliasDeclaration(statement) ||
162
+ ts.isEnumDeclaration(statement) ||
163
+ ts.isModuleDeclaration(statement))
164
+ return statement.name !== undefined && ts.isIdentifier(statement.name) ? [statement.name.text] : [];
165
+ return [];
166
+ }
167
+ /** Where the comments directly above a statement start: only a run with no blank line between its comments and the statement. */
168
+ function commentStart(text, statement, source) {
169
+ const start = statement.getStart(source);
170
+ const ranges = ts.getLeadingCommentRanges(text, statement.getFullStart()) ?? [];
171
+ let from = start;
172
+ for (const range of [...ranges].reverse()) {
173
+ if ((text.slice(range.end, from).match(/\n/g) ?? []).length > 1)
174
+ break;
175
+ from = range.pos;
176
+ }
177
+ return from;
178
+ }
179
+ /** The identifiers in `text`, found with the scanner so it also reads a law (`export law ...`, which is not standard TypeScript). */
180
+ export function identifiersIn(text) {
181
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.Standard, text);
182
+ const found = new Set();
183
+ const templates = [];
184
+ let depth = 0;
185
+ let previous = ts.SyntaxKind.Unknown;
186
+ let kind = scanner.scan();
187
+ while (kind !== ts.SyntaxKind.EndOfFileToken) {
188
+ if (kind === ts.SyntaxKind.CloseBraceToken && templates.length > 0 && templates[templates.length - 1] === depth) {
189
+ templates.pop();
190
+ kind = scanner.reScanTemplateToken(false);
191
+ if (kind === ts.SyntaxKind.TemplateMiddle)
192
+ templates.push(depth);
193
+ }
194
+ else if (kind === ts.SyntaxKind.TemplateHead) {
195
+ templates.push(depth);
196
+ }
197
+ else if (kind === ts.SyntaxKind.OpenBraceToken) {
198
+ depth += 1;
199
+ }
200
+ else if (kind === ts.SyntaxKind.CloseBraceToken) {
201
+ depth = Math.max(0, depth - 1);
202
+ }
203
+ else if ((kind === ts.SyntaxKind.Identifier || kind > ts.SyntaxKind.LastReservedWord) &&
204
+ previous !== ts.SyntaxKind.DotToken &&
205
+ previous !== ts.SyntaxKind.QuestionDotToken) {
206
+ found.add(scanner.getTokenValue());
207
+ }
208
+ previous = kind;
209
+ kind = scanner.scan();
210
+ }
211
+ return found;
212
+ }
213
+ /** The named statements left once imports and laws are blanked out, each with the comments directly above it. */
214
+ function declarationsOf(text, taken) {
215
+ const rest = blank(text, taken);
216
+ const source = ts.createSourceFile('laws.ts', rest, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
217
+ const found = [];
218
+ for (const statement of source.statements) {
219
+ const names = declaredNames(statement);
220
+ if (names.length === 0)
221
+ continue;
222
+ const start = commentStart(rest, statement, source);
223
+ const written = text.slice(start, statement.end);
224
+ found.push({ names, text: written, start, end: statement.end, references: [...identifiersIn(written)] });
225
+ }
226
+ return found;
120
227
  }
121
228
  /** The call-style laws: top-level `law('name', ...)` and `law.proved('name', ...)` statements, found in the syntax tree. */
122
229
  function callLaws(text) {
@@ -144,6 +251,199 @@ function callLaws(text) {
144
251
  return found;
145
252
  }
146
253
  const squash = (s) => s.replace(/\s+/g, ' ').trim();
254
+ /** The code of `text` printed from its syntax tree without comments: layout is normalised, string and template contents are not. */
255
+ export function sameCode(a, b) {
256
+ const printer = ts.createPrinter({ removeComments: true });
257
+ const print = (text) => {
258
+ const source = ts.createSourceFile('helper.ts', text, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
259
+ return source.statements
260
+ .map((statement) => printer.printNode(ts.EmitHint.Unspecified, statement, source))
261
+ .join('\n');
262
+ };
263
+ return print(a) === print(b);
264
+ }
265
+ /** The local names the import statements bind (`import a, { b as c, type d } from 'x'` binds a, c and d). */
266
+ function importedNames(imports) {
267
+ const names = new Set();
268
+ const source = ts.createSourceFile('imports.ts', imports.join('\n'), ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
269
+ for (const statement of source.statements) {
270
+ if (ts.isImportEqualsDeclaration(statement))
271
+ names.add(statement.name.text);
272
+ if (!ts.isImportDeclaration(statement) || statement.importClause === undefined)
273
+ continue;
274
+ const { name, namedBindings } = statement.importClause;
275
+ if (name !== undefined)
276
+ names.add(name.text);
277
+ if (namedBindings === undefined)
278
+ continue;
279
+ if (ts.isNamespaceImport(namedBindings))
280
+ names.add(namedBindings.name.text);
281
+ else
282
+ for (const element of namedBindings.elements)
283
+ names.add(element.name.text);
284
+ }
285
+ return names;
286
+ }
287
+ const isAssignmentOperator = (kind) => kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;
288
+ /** Whether `node` is a BigInt: mixing one with a number, dividing by zero or a unary plus throws, so a BigInt is only allowed bare or negated. */
289
+ function isBigInt(node) {
290
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node))
291
+ return isBigInt(node.expression);
292
+ if (ts.isPrefixUnaryExpression(node))
293
+ return isBigInt(node.operand);
294
+ return ts.isBigIntLiteral(node);
295
+ }
296
+ /** Whether `node` is a constant that cannot throw: literals joined by operators that read no property, call nothing and cannot fail on their operands. */
297
+ function isLiteralValue(node) {
298
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node))
299
+ return isLiteralValue(node.expression);
300
+ if (ts.isPrefixUnaryExpression(node))
301
+ return (node.operator !== ts.SyntaxKind.PlusPlusToken &&
302
+ node.operator !== ts.SyntaxKind.MinusMinusToken &&
303
+ !(node.operator === ts.SyntaxKind.PlusToken && isBigInt(node.operand)) &&
304
+ isLiteralValue(node.operand));
305
+ if (ts.isBinaryExpression(node))
306
+ return (!isAssignmentOperator(node.operatorToken.kind) &&
307
+ node.operatorToken.kind !== ts.SyntaxKind.CommaToken &&
308
+ // `in` and `instanceof` throw on a primitive right-hand side.
309
+ node.operatorToken.kind !== ts.SyntaxKind.InKeyword &&
310
+ node.operatorToken.kind !== ts.SyntaxKind.InstanceOfKeyword &&
311
+ !isBigInt(node.left) &&
312
+ !isBigInt(node.right) &&
313
+ isLiteralValue(node.left) &&
314
+ isLiteralValue(node.right));
315
+ return (ts.isStringLiteral(node) ||
316
+ ts.isNumericLiteral(node) ||
317
+ ts.isBigIntLiteral(node) ||
318
+ ts.isNoSubstitutionTemplateLiteral(node) ||
319
+ ts.isRegularExpressionLiteral(node) ||
320
+ node.kind === ts.SyntaxKind.TrueKeyword ||
321
+ node.kind === ts.SyntaxKind.FalseKeyword ||
322
+ node.kind === ts.SyntaxKind.NullKeyword);
323
+ }
324
+ /** A `const` statement: not `let`, `var`, `using` or `await using` (the last two carry the Const flag too and call a dispose method). */
325
+ export function isPlainConst(statement) {
326
+ return (statement.declarationList.flags & ts.NodeFlags.BlockScoped) === ts.NodeFlags.Const;
327
+ }
328
+ /** Why `expression` may not run when a file loads (it can have a side effect), or undefined when it may. */
329
+ function initialiserProblem(expression, source) {
330
+ const bad = (what, node) => `${what} \`${node.getText(source).replace(/\s+/g, ' ').slice(0, 40)}\``;
331
+ const visit = (node) => {
332
+ if (ts.isParenthesizedExpression(node) ||
333
+ ts.isAsExpression(node) ||
334
+ ts.isSatisfiesExpression(node) ||
335
+ ts.isNonNullExpression(node) ||
336
+ ts.isTypeAssertionExpression(node))
337
+ return visit(node.expression);
338
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isIdentifier(node) || isLiteralValue(node))
339
+ return undefined;
340
+ if (ts.isTemplateExpression(node)) {
341
+ const span = node.templateSpans.find((s) => !isLiteralValue(s.expression));
342
+ return span === undefined ? undefined : bad('a substitution', span.expression);
343
+ }
344
+ if (ts.isArrayLiteralExpression(node)) {
345
+ for (const element of node.elements) {
346
+ if (ts.isSpreadElement(element))
347
+ return bad('a spread', element);
348
+ const problem = visit(element);
349
+ if (problem !== undefined)
350
+ return problem;
351
+ }
352
+ return undefined;
353
+ }
354
+ if (ts.isObjectLiteralExpression(node)) {
355
+ for (const property of node.properties) {
356
+ if (ts.isShorthandPropertyAssignment(property))
357
+ continue;
358
+ if (!ts.isPropertyAssignment(property) && !ts.isMethodDeclaration(property))
359
+ return bad(ts.isSpreadAssignment(property) ? 'a spread' : 'an accessor', property);
360
+ // A computed key is evaluated when the object is built, methods included; `[Symbol.dispose]` is the hook `using` calls.
361
+ if (ts.isComputedPropertyName(property.name) && !isLiteralValue(property.name.expression))
362
+ return bad(/^Symbol\s*\.\s*(?:async)?dispose$/i.test(property.name.expression.getText(source))
363
+ ? 'a dispose method'
364
+ : 'a computed key', property.name);
365
+ if (ts.isMethodDeclaration(property))
366
+ continue;
367
+ const problem = visit(property.initializer);
368
+ if (problem !== undefined)
369
+ return problem;
370
+ }
371
+ return undefined;
372
+ }
373
+ if (ts.isCallExpression(node))
374
+ return bad(node.expression.kind === ts.SyntaxKind.ImportKeyword ? 'an import()' : 'a call', node);
375
+ if (ts.isNewExpression(node))
376
+ return bad('a new expression', node);
377
+ if (ts.isTaggedTemplateExpression(node))
378
+ return bad('a tagged template', node);
379
+ if (ts.isAwaitExpression(node))
380
+ return bad('an await', node);
381
+ if (ts.isDeleteExpression(node))
382
+ return bad('a delete', node);
383
+ if (ts.isPostfixUnaryExpression(node) ||
384
+ (ts.isPrefixUnaryExpression(node) &&
385
+ (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken)))
386
+ return bad('an update', node);
387
+ if (ts.isBinaryExpression(node) && isAssignmentOperator(node.operatorToken.kind))
388
+ return bad('an assignment', node);
389
+ return bad('an expression that may run code', node);
390
+ };
391
+ return visit(expression);
392
+ }
393
+ /**
394
+ * Why a helper may not be proposed or copied, or undefined when it may. A helper is a function, type or interface
395
+ * declaration, or a `const` whose initialiser has no side effects (a literal, a function, an object or array of those,
396
+ * `as const`): a helper becomes part of the accepted tree, and a `const` initialiser runs when the file loads.
397
+ */
398
+ export function helperProblem(text) {
399
+ const source = ts.createSourceFile('helper.ts', text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
400
+ for (const statement of source.statements) {
401
+ if (ts.isEmptyStatement(statement))
402
+ continue;
403
+ if (ts.isFunctionDeclaration(statement) ||
404
+ ts.isTypeAliasDeclaration(statement) ||
405
+ ts.isInterfaceDeclaration(statement))
406
+ continue;
407
+ if (ts.isVariableStatement(statement) && isPlainConst(statement)) {
408
+ for (const declaration of statement.declarationList.declarations) {
409
+ if (!ts.isIdentifier(declaration.name))
410
+ return `a destructuring \`${declaration.name.getText(source).slice(0, 40)}\` reads properties, which can run code`;
411
+ if (declaration.initializer === undefined)
412
+ continue;
413
+ const problem = initialiserProblem(declaration.initializer, source);
414
+ if (problem !== undefined)
415
+ return `const '${declaration.name.text}' is initialised with ${problem}, which would run when the file loads`;
416
+ }
417
+ continue;
418
+ }
419
+ if (ts.isClassDeclaration(statement))
420
+ return 'a class is not an allowed helper';
421
+ if (ts.isEnumDeclaration(statement))
422
+ return 'an enum is not an allowed helper';
423
+ if (ts.isModuleDeclaration(statement))
424
+ return 'a namespace is not an allowed helper';
425
+ return 'only function, type, interface and const declarations are allowed helpers';
426
+ }
427
+ return undefined;
428
+ }
429
+ const helperRule = 'Helpers may only be function, type and interface declarations, and const with a side-effect-free initialiser (a literal, a function, an object or array literal of those, as const)';
430
+ /** Throws unless every one of `declarations` passes `helperProblem`. */
431
+ export function assertHelpersSafe(declarations) {
432
+ for (const declaration of declarations) {
433
+ const problem = helperProblem(declaration.text);
434
+ if (problem !== undefined)
435
+ throw new Error(`helper '${declaration.names.join(', ')}' is refused: ${problem}. ${helperRule}`);
436
+ }
437
+ }
438
+ /** Throws unless each of `imports` is exactly one import statement, so a scanning slip cannot pass other code off as an import. */
439
+ export function assertImportStatements(imports) {
440
+ for (const text of imports) {
441
+ const source = ts.createSourceFile('import.ts', text, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
442
+ const [only, ...more] = source.statements;
443
+ if (only === undefined || more.length > 0 || !(ts.isImportDeclaration(only) || ts.isImportEqualsDeclaration(only)))
444
+ throw new Error(`\`${text.replace(/\s+/g, ' ').slice(0, 40)}\` is not an import statement`);
445
+ }
446
+ }
147
447
  /** Joins the import statements, dropping repeats by whitespace-insensitive text. */
148
448
  export function dedupeImports(existing, added) {
149
449
  const seen = new Set(existing.map(squash));
@@ -156,11 +456,40 @@ export function dedupeImports(existing, added) {
156
456
  }
157
457
  return out;
158
458
  }
459
+ /**
460
+ * The declarations the promoted `laws` need: every one of `declarations` whose name a law mentions, and so on for the
461
+ * names those declarations mention, in source order. A declaration is taken with all others of the same name
462
+ * (overloads, merged interfaces). One that no promoted law reaches stays behind.
463
+ */
464
+ function neededDeclarations(laws, declarations) {
465
+ const byName = new Map();
466
+ for (const declaration of declarations)
467
+ for (const name of declaration.names)
468
+ byName.set(name, [...(byName.get(name) ?? []), declaration]);
469
+ const needed = new Set();
470
+ const queue = laws.flatMap((l) => [...identifiersIn(l.text)]);
471
+ for (let name = queue.pop(); name !== undefined; name = queue.pop())
472
+ for (const declaration of byName.get(name) ?? []) {
473
+ if (needed.has(declaration))
474
+ continue;
475
+ needed.add(declaration);
476
+ queue.push(...declaration.references);
477
+ }
478
+ return declarations.filter((d) => needed.has(d));
479
+ }
159
480
  /**
160
481
  * The accepted file after promoting `laws` (with the proposed file's imports) into it. `existing` is the current text
161
- * of the accepted file, or undefined when it does not exist yet. Throws when a law name is already taken there.
482
+ * of the accepted file, or undefined when it does not exist yet. `declarations` are all the helper declarations of the
483
+ * proposed file: the ones the laws use, directly or through each other, are copied too. A declaration already in the
484
+ * accepted file with the same code (layout and comments aside) is not copied again; one of the same name with different text is
485
+ * an error. Throws when a law name is already taken there, and, as a safety net, when the result would use a name the
486
+ * proposed file declares but the accepted file does not.
162
487
  */
163
- export function buildAccepted(existing, imports, laws) {
488
+ export function buildAccepted(existing, imports, laws, declarations = []) {
489
+ return planAccepted(existing, imports, laws, declarations).text;
490
+ }
491
+ /** `buildAccepted`, with the imports and helpers it adds, so a person can read them before anything is written. */
492
+ export function planAccepted(existing, imports, laws, declarations = []) {
164
493
  const base = existing ?? '';
165
494
  const parsed = parseLawFile(base);
166
495
  const taken = new Set(parsed.laws.map((l) => l.name));
@@ -168,6 +497,7 @@ export function buildAccepted(existing, imports, laws) {
168
497
  if (taken.has(law.name))
169
498
  throw new Error(`law '${law.name}' already exists in the accepted file`);
170
499
  const missing = dedupeImports(parsed.imports, imports).slice(parsed.imports.length);
500
+ assertImportStatements(missing);
171
501
  let text = base;
172
502
  if (missing.length > 0) {
173
503
  // New imports go after the last existing import, or at the top.
@@ -180,9 +510,49 @@ export function buildAccepted(existing, imports, laws) {
180
510
  ? `${block}\n${base === '' ? '' : `${base.startsWith('\n') ? '' : '\n'}`}${base}`
181
511
  : `${base.slice(0, lastEnd)}\n${block}${base.slice(lastEnd)}`;
182
512
  }
513
+ const copied = copiedDeclarations(text, laws, declarations);
514
+ assertHelpersSafe(copied);
515
+ if (copied.length > 0)
516
+ text = withDeclarations(text, copied.map((d) => d.text.trim()).join('\n\n'));
183
517
  const body = laws.map((l) => l.text.trimEnd()).join('\n\n');
184
518
  const trimmed = text.trimEnd();
185
- return `${trimmed === '' ? '' : `${trimmed}\n\n`}${body}\n`;
519
+ const result = `${trimmed === '' ? '' : `${trimmed}\n\n`}${body}\n`;
520
+ assertNothingLost(result, laws, copied, declarations);
521
+ return { text: result, imports: missing, declarations: copied };
522
+ }
523
+ /** The needed declarations that `accepted` does not have yet; throws when it has a different one under the same name. */
524
+ function copiedDeclarations(accepted, laws, declarations) {
525
+ const { declarations: have, imports } = parseLawFile(accepted);
526
+ const imported = importedNames(imports);
527
+ return neededDeclarations(laws, declarations).filter((declaration) => {
528
+ const bound = declaration.names.find((n) => imported.has(n));
529
+ if (bound !== undefined)
530
+ throw new Error(`'${bound}' is imported in the accepted file but declared as a helper in the proposed file; rename one`);
531
+ const same = have.filter((h) => h.names.some((n) => declaration.names.includes(n)));
532
+ if (same.length === 0)
533
+ return true;
534
+ if (same.some((h) => sameCode(h.text, declaration.text)))
535
+ return false;
536
+ throw new Error(`'${declaration.names.find((n) => same.some((h) => h.names.includes(n)))}' is declared differently in the accepted file; make the two the same or rename one`);
537
+ });
538
+ }
539
+ /** `block` placed after the last declaration of `text`, else after its last import, else before its first law, else at the end. */
540
+ export function withDeclarations(text, block) {
541
+ const parsed = parseLawFile(text);
542
+ const lastDeclaration = parsed.declarations[parsed.declarations.length - 1];
543
+ const at = lastDeclaration?.end ?? (parsed.importEnd > 0 ? parsed.importEnd : (parsed.laws[0]?.start ?? text.length));
544
+ const before = text.slice(0, at).trimEnd();
545
+ const after = text.slice(at).trimStart();
546
+ return `${before === '' ? '' : `${before}\n\n`}${block}${after === '' ? '' : `\n\n${after}`}`;
547
+ }
548
+ /** Throws when the result mentions a name the proposed file declares and the result does not declare or import. */
549
+ function assertNothingLost(result, laws, copied, declarations) {
550
+ const proposed = new Set(declarations.flatMap((d) => d.names));
551
+ const present = new Set(parseLawFile(result).declarations.flatMap((d) => d.names));
552
+ for (const part of [...laws, ...copied])
553
+ for (const name of identifiersIn(part.text))
554
+ if (proposed.has(name) && !present.has(name))
555
+ throw new Error(`'${name}' is declared in the proposed file but would be missing from the accepted file`);
186
556
  }
187
557
  /** The proposed file without the promoted laws, or undefined when no law is left (the file is deleted). */
188
558
  export function buildRemaining(text, promoted) {
@@ -201,6 +571,42 @@ export function buildRemaining(text, promoted) {
201
571
  }
202
572
  return out;
203
573
  }
574
+ /**
575
+ * Throws unless every file the code a promote adds names by a relative or absolute path is reviewed code: inside the
576
+ * project, outside `.tslaws/`, `node_modules` and `.git`, and not git-ignored. `dir` is the project-relative directory of
577
+ * the file the code lands in, which is where its specifiers are read from. Checks the new imports, the copied helpers and
578
+ * the promoted laws, so a `require` or `import()` in either is covered.
579
+ */
580
+ function assertPlanImportsAllowed(cwd, dir, plan, laws) {
581
+ const pieces = [plan.imports.join('\n'), ...plan.declarations.map((d) => d.text), ...laws.map((l) => l.text)];
582
+ for (const piece of pieces)
583
+ assertImportsAllowed(cwd, piece, dir === '.' ? '' : dir);
584
+ }
585
+ /**
586
+ * Prints the imports and helper declarations a promote adds, in full, before anything is written, and asks the person
587
+ * to confirm: both are code that becomes part of the trusted tree. `yes` skips the question. Returns whether to go on;
588
+ * true when nothing is added.
589
+ */
590
+ async function confirmAdditions(host, target, plan) {
591
+ if (plan.imports.length === 0 && plan.declarations.length === 0)
592
+ return true;
593
+ let shown = `\nThis also adds code to ${target}, which becomes part of the trusted tree:\n`;
594
+ if (plan.imports.length > 0)
595
+ shown += `\nimports (${plan.imports.length}):\n${plan.imports.map((i) => i.trim()).join('\n')}\n`;
596
+ if (plan.declarations.length > 0)
597
+ shown += `\nhelpers (${plan.declarations.length}):\n${plan.declarations.map((d) => d.text.trim()).join('\n\n')}\n`;
598
+ host.out(shown);
599
+ if (host.yes === true) {
600
+ host.out('adding it (--yes)\n');
601
+ return true;
602
+ }
603
+ const what = plan.imports.length > 0 && plan.declarations.length > 0
604
+ ? 'import and helper'
605
+ : plan.imports.length > 0
606
+ ? 'import'
607
+ : 'helper';
608
+ return (await host.ask(`add this ${what} code to ${target}? [y/N] `)).trim().toLowerCase() === 'y';
609
+ }
204
610
  /** Walks the proposed files, asks per law, and rewrites the accepted and proposed files. Returns the number promoted. */
205
611
  export async function promoteFiles(host, proposedFiles) {
206
612
  let promoted = 0;
@@ -228,15 +634,20 @@ export async function promoteFiles(host, proposedFiles) {
228
634
  if (chosen.length === 0)
229
635
  continue;
230
636
  const existing = existsSync(acceptedPath) ? readFileSync(acceptedPath, 'utf8') : undefined;
231
- let built;
637
+ let plan;
232
638
  try {
233
- built = buildAccepted(existing, parsed.imports, chosen);
639
+ plan = planAccepted(existing, parsed.imports, chosen, parsed.declarations);
640
+ assertPlanImportsAllowed(host.cwd, posix.dirname(accepted), plan, chosen);
234
641
  }
235
642
  catch (error) {
236
643
  host.out(`${accepted}: ${error instanceof Error ? error.message : String(error)}; nothing promoted from ${file}\n`);
237
644
  continue;
238
645
  }
239
- writeFileSync(acceptedPath, built);
646
+ if (!(await confirmAdditions(host, accepted, plan))) {
647
+ host.out(`nothing promoted from ${file}\n`);
648
+ continue;
649
+ }
650
+ writeFileSync(acceptedPath, plan.text);
240
651
  const remaining = buildRemaining(text, chosen.map((l) => l.name));
241
652
  if (remaining === undefined)
242
653
  rmSync(proposedPath);
@@ -326,16 +737,21 @@ export async function promoteProposal(host, file, to) {
326
737
  const existing = existsSync(targetPath) ? readFileSync(targetPath, 'utf8') : undefined;
327
738
  const toDir = posix.dirname(target);
328
739
  const moved = parseLawFile(importsForTarget(text, toDir === '.' ? '' : toDir));
329
- let built;
740
+ let plan;
330
741
  try {
331
- built = buildAccepted(existing, moved.imports, moved.laws);
742
+ plan = planAccepted(existing, moved.imports, moved.laws, moved.declarations);
743
+ assertPlanImportsAllowed(host.cwd, toDir, plan, moved.laws);
332
744
  }
333
745
  catch (error) {
334
746
  host.out(`${target}: ${error instanceof Error ? error.message : String(error)}; nothing moved\n`);
335
747
  return {};
336
748
  }
749
+ if (!(await confirmAdditions(host, target, plan))) {
750
+ host.out('nothing moved\n');
751
+ return {};
752
+ }
337
753
  mkdirSync(dirname(targetPath), { recursive: true });
338
- writeFileSync(targetPath, built);
754
+ writeFileSync(targetPath, plan.text);
339
755
  rmSync(abs);
340
756
  host.out(`${plural(parsed.laws.length)} moved to ${target}; ${rel} removed\n` +
341
757
  'The lock is unchanged: until a person runs `tslaws accept`, `tslaws check` fails these laws as not in the lock.\n');
package/dist/property.js CHANGED
@@ -5,7 +5,7 @@ import ts from 'typescript';
5
5
  import { GeneratorFactory } from "./generators.js";
6
6
  import { lawEnv } from "./coverage.js";
7
7
  import { arbitraryOf, UnsupportedType } from "./plan.js";
8
- import { WorkerPool } from "./pool.js";
8
+ import { budget, WorkerPool } from "./pool.js";
9
9
  export { isDiscard, jsPath, runLaw, runProperty, summarise } from "./propertyRun.js";
10
10
  /** Every declaration file the compiler emitted: the laws' own do not import the code they are about. */
11
11
  export function declarationFiles(outDir) {
@@ -111,6 +111,10 @@ export function warmWorkers(n) {
111
111
  }
112
112
  /** Runs the property test of `law` in a pooled worker, giving up on it after `options.propertyTimeoutMs`. */
113
113
  export async function runLawGuarded(outDir, law, options, plans) {
114
+ // The worker task is a slot of the budget (the law's own, when it runs under one).
115
+ return budget.run(() => runInWorker(outDir, law, options, plans));
116
+ }
117
+ async function runInWorker(outDir, law, options, plans) {
114
118
  const current = await workers.acquire();
115
119
  return new Promise((resolve, reject) => {
116
120
  const timer = setTimeout(() => {