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
@@ -1,10 +1,15 @@
1
+ import { readFileSync } from 'node:fs';
1
2
  import { createRequire } from 'node:module';
3
+ import { join } from 'node:path';
2
4
  import { parentPort } from 'node:worker_threads';
5
+ import { installLawRuntime, runtimeFile } from "./lawRuntime.js";
3
6
  import { arbitraryOf } from "./plan.js";
4
7
  import { jsPath, runLaw, summarise } from "./propertyRun.js";
5
8
  import { installLoaderHooks, setImportMetaEnv } from "./runtimeEnv.js";
6
9
  // Property tests run here so that a law over code that never terminates costs a timeout, not the whole check.
7
10
  // The main process read the types and sends the generators as plans, so a worker never loads the TypeScript compiler.
11
+ // Compiled laws are CommonJS (see `build` in compile.ts), loaded with `require` so that a recompiled law can be dropped
12
+ // from `require.cache` and loaded again; an `import()` of it could not be forgotten.
8
13
  const require = createRequire(import.meta.url);
9
14
  installLoaderHooks();
10
15
  parentPort.on('message', async (request) => {
@@ -12,6 +17,8 @@ parentPort.on('message', async (request) => {
12
17
  const { outDir, law, plans, options, env } = request;
13
18
  setImportMetaEnv(env);
14
19
  const generators = plans.map(arbitraryOf);
20
+ // The build left the project's module resolution beside the output (aliases from its tsconfig, TypeScript sources).
21
+ installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
15
22
  // The worker outlives a check, and the code may have been recompiled since the last one.
16
23
  for (const loaded of Object.keys(require.cache))
17
24
  if (loaded.startsWith(outDir))
@@ -20,20 +20,67 @@ export declare function existingProposal(cwd: string, file: string): {
20
20
  export declare function toStoredImports(text: string): string;
21
21
  /** Re-expresses the relative imports of a stored proposal for a file in the project-relative directory `toDir`. */
22
22
  export declare function importsForTarget(text: string, toDir: string): string;
23
- /** The proposed file with the proposal's laws appended (same-named laws replaced) and its imports added once. */
23
+ /**
24
+ * Throws unless `text` loads code only through a static import or re-export, or an `import()` or `require()` whose one
25
+ * argument is a plain string literal: those are the loads `assertImportsAllowed` can read. A call with another argument,
26
+ * and any other reference to `require`, `module`, `createRequire`, `process.mainModule` or `import.meta`, could load a
27
+ * file the check never saw, so it is refused. This is the first layer of defence, not a sandbox: a computed index is
28
+ * allowed only when the type checker says its type is a number, and a string that spells a name of the loader or of
29
+ * the prototype chain is refused wherever it stands.
30
+ */
31
+ export declare function assertStaticLoading(text: string): void;
32
+ /**
33
+ * Throws unless every file the module specifiers of `text` name (an import, a re-export, `require` or `import()`)
34
+ * is code a person has reviewed: inside the project, not under `.tslaws/` (the proposals area), `node_modules` or
35
+ * `.git`, and not git-ignored. Specifiers are read relative to the project-relative directory `fromDir`, where the file
36
+ * stands. A package name is not a path and is left alone, unless the project's `paths` or `baseUrl` maps it to a file outside `node_modules`, which is checked as a path. Any specifier with `%`, `?`, `#` or a control character is
37
+ * refused (percent escapes, queries, fragments and package `imports` aliases make the file the runtime loads differ
38
+ * from the text). A path specifier is resolved as the runtime does, as a URL against the importing directory, then
39
+ * made canonical on the real file system; the reserved names are compared without regard to case. Git must answer: when
40
+ * git is missing, the project is not in a repository or the check fails, the import is refused. A project that sits
41
+ * inside an ignored directory of a larger repository has no usable ignore rules, so each file is not asked. Each path
42
+ * is also resolved with the TypeScript module resolution of the project's compiler options, and the file that gives
43
+ * (through `package.json` `main`, an index file, `rootDirs` and so on) is checked as well; a directory that resolves to
44
+ * no file is refused. Loading by any means but a static import or a string-literal `import()` or `require()` is refused.
45
+ */
46
+ export declare function assertImportsAllowed(cwd: string, text: string, fromDir: string): void;
47
+ /**
48
+ * The imports and helper declarations of `source` as they would be stored, after the same checks `addProposal` makes.
49
+ * `packages` lists the package specifiers the source loads (anything that is not a relative path), which are code
50
+ * outside the project that no person has reviewed.
51
+ */
52
+ export declare function previewProposal(source: string, cwd: string): {
53
+ imports: string[];
54
+ packages: string[];
55
+ helpers: {
56
+ names: string[];
57
+ text: string;
58
+ }[];
59
+ };
60
+ interface Helper {
61
+ names: string[];
62
+ text: string;
63
+ }
64
+ /**
65
+ * The proposed file with the proposal's laws appended (same-named laws replaced), its imports added once and its
66
+ * helpers placed after the declarations already there (a helper of the same name with other code replaces the old one,
67
+ * and throws when that would drop a name its statement bound together with it; an identical one is kept as it is).
68
+ */
24
69
  export declare function mergeProposal(current: string, imports: string[], laws: {
25
70
  name: string;
26
71
  text: string;
27
- }[]): string;
72
+ }[], helpers?: Helper[]): string;
28
73
  export interface Written {
29
74
  /** Project-relative path of the proposal. */
30
75
  file: string;
31
76
  /** The names of the laws the source declared. */
32
77
  laws: string[];
78
+ /** The names of the helpers the source declared. */
79
+ helpers: string[];
33
80
  }
34
81
  /**
35
- * Adds laws to a proposal (appended; a law of the same name is replaced). `source` holds only imports and `export law`
36
- * declarations; with `only`, it must declare that law. Writes inside `.tslaws/proposals/` and nowhere else.
82
+ * Adds laws to a proposal (appended; a law of the same name is replaced). `source` holds imports, `export law`
83
+ * declarations and the helpers they need (see `parts`); with `only`, it must declare that law. Writes inside `.tslaws/proposals/` and nowhere else.
37
84
  */
38
85
  export declare function addProposal(cwd: string, file: string, source: string, only?: string): Written;
39
86
  /**
@@ -41,3 +88,4 @@ export declare function addProposal(cwd: string, file: string, source: string, o
41
88
  * Returns whether the file changed. Does nothing for a path that is not a plain file in the directory.
42
89
  */
43
90
  export declare function normaliseProposal(cwd: string, file: string): boolean;
91
+ export {};
package/dist/proposals.js CHANGED
@@ -6,11 +6,15 @@
6
6
  // author at the project root expects. They are stored relative to the file (`../../src/cart`), so the stored file is
7
7
  // ordinary TypeScript that resolves, type-checks and runs where it is. `../` and package imports are left alone.
8
8
  // `promote` rewrites the stored form again for the directory the law moves to.
9
- import { constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, writeSync, closeSync, appendFileSync, writeFileSync, } from 'node:fs';
10
- import { join, posix } from 'node:path';
9
+ import { constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, statSync, writeSync, closeSync, appendFileSync, writeFileSync, } from 'node:fs';
10
+ import { spawnSync } from 'node:child_process';
11
+ import { builtinModules, createRequire } from 'node:module';
12
+ import { basename, dirname, isAbsolute, join, posix, relative, sep } from 'node:path';
13
+ import { fileURLToPath, pathToFileURL } from 'node:url';
11
14
  import { moduleSpecifiers } from "./lawKinds.js";
12
- import { proposalsDir } from "./lawFiles.js";
13
- import { parseLawFile } from "./promote.js";
15
+ import { ignoredDirs, proposalsDir } from "./lawFiles.js";
16
+ import ts from 'typescript';
17
+ import { assertHelpersSafe, assertImportStatements, isPlainConst, parseLawFile, sameCode, withDeclarations, } from "./promote.js";
14
18
  /** A refusal with a message for the person or agent that asked. */
15
19
  export class ProposalError extends Error {
16
20
  }
@@ -107,24 +111,483 @@ export function importsForTarget(text, toDir) {
107
111
  return dotted(posix.relative(toDir === '' ? '.' : toDir, posix.join(proposalsDir, specifier)));
108
112
  });
109
113
  }
110
- /** The proposal's own text after `parseLawFile`: only imports and law declarations are allowed in one. */
111
- function parts(source) {
114
+ /**
115
+ * Whether git ignores `path` (absolute, or relative to `cwd`): `ignored`, `kept`, or `unknown` when git is missing,
116
+ * `cwd` is not in a repository or the check fails for any other reason. Callers treat `unknown` as a refusal.
117
+ */
118
+ function gitIgnoreState(cwd, path) {
119
+ const result = spawnSync('git', ['check-ignore', '-q', '--', path], {
120
+ cwd,
121
+ stdio: 'ignore',
122
+ windowsHide: true,
123
+ timeout: 15_000,
124
+ });
125
+ if (result.error !== undefined || result.status === null)
126
+ return 'unknown';
127
+ if (result.status === 0)
128
+ return 'ignored';
129
+ return result.status === 1 ? 'kept' : 'unknown';
130
+ }
131
+ const sourceSuffixes = [
132
+ '',
133
+ '.ts',
134
+ '.tsx',
135
+ '.mts',
136
+ '.cts',
137
+ '.js',
138
+ '.jsx',
139
+ '.mjs',
140
+ '.cjs',
141
+ '.json',
142
+ '/index.ts',
143
+ '/index.js',
144
+ ];
145
+ /** The files a relative specifier may name: the path itself, the same with an extension or `index`, and `.js` read as `.ts`. */
146
+ function specifierCandidates(target) {
147
+ const swapped = target.replace(/\.([cm]?)js$/, '.$1ts');
148
+ const all = [...new Set([target, swapped].flatMap((base) => sourceSuffixes.map((suffix) => base + suffix)))];
149
+ const found = all.filter((candidate) => existsSync(candidate));
150
+ return found.length > 0 ? [target, ...found] : [target];
151
+ }
152
+ /**
153
+ * The canonical path of `path`: links followed and the file system's own spelling of every part (long names and case
154
+ * on Windows and macOS), as far as it exists; the parts that do not exist yet are appended to the nearest existing parent.
155
+ */
156
+ function realish(path) {
157
+ const rest = [];
158
+ let probe = path;
159
+ while (!existsSync(probe) && dirname(probe) !== probe) {
160
+ rest.unshift(basename(probe));
161
+ probe = dirname(probe);
162
+ }
163
+ return join(realpathSync.native(probe), ...rest);
164
+ }
165
+ /** Names that reach the module loader or a way to run or load code the check cannot read. */
166
+ const loaderNames = new Set([
167
+ 'require',
168
+ 'module',
169
+ 'createRequire',
170
+ 'eval',
171
+ 'Function',
172
+ 'globalThis',
173
+ 'global',
174
+ 'process',
175
+ 'Reflect',
176
+ 'Proxy',
177
+ 'exports',
178
+ // Spelled in parts so that the check for CommonJS globals in the built package does not mistake the names for use.
179
+ `__${'filename'}`,
180
+ `__${'dirname'}`,
181
+ ]);
182
+ /** Properties that reach the loader or the prototype chain (and so `Function`), by `.name`, `['name']` or destructuring. */
183
+ const loaderProperties = new Set([
184
+ 'mainModule',
185
+ 'createRequire',
186
+ 'getBuiltinModule',
187
+ 'constructor',
188
+ '__proto__',
189
+ 'prototype',
190
+ 'getPrototypeOf',
191
+ 'setPrototypeOf',
192
+ 'getOwnPropertyDescriptor',
193
+ 'getOwnPropertyDescriptors',
194
+ 'getOwnPropertyNames',
195
+ 'defineProperty',
196
+ 'defineProperties',
197
+ ]);
198
+ /** Strings that may not appear anywhere in a proposal, because they can name the loader or the prototype chain at run time. */
199
+ const reflected = new Set([...loaderNames, ...loaderProperties]);
200
+ /** The only Node built-in modules a proposal may import, by bare name or with the `node:` prefix. */
201
+ const allowedBuiltins = new Set(['path', 'url', 'util', 'assert']);
202
+ const isBuiltin = (specifier) => specifier.startsWith('node:') || builtinModules.includes(specifier);
203
+ /**
204
+ * The proposal as plain TypeScript, so that a type checker can read it: each `law` header becomes a function (the
205
+ * `proved` marker dropped) and an arrow law `law f(x) => e;` becomes `function f(x) { return (e); }`. A header it cannot
206
+ * read is left as written, which makes the types in that law unknown and so refused where a type is needed.
207
+ */
208
+ function lowerLaws(text) {
209
+ let lowered = text;
210
+ const header = /^(export\s+(?:default\s+)?(?:async\s+)?)law\s+(?:proved\s+)?([A-Za-z_$][\w$]*)\s*\(/;
211
+ for (const law of [...parseLawFile(text).laws].sort((a, b) => b.start - a.start)) {
212
+ const match = header.exec(law.text);
213
+ if (match === null)
214
+ continue;
215
+ const params = match[0].length;
216
+ let rewritten = `${match[1]}function ${match[2]}(${law.text.slice(params)}`;
217
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.Standard, law.text, undefined, params);
218
+ let depth = 1;
219
+ let token = scanner.scan();
220
+ while (token !== ts.SyntaxKind.EndOfFileToken && depth > 0) {
221
+ if (token === ts.SyntaxKind.OpenParenToken)
222
+ depth++;
223
+ else if (token === ts.SyntaxKind.CloseParenToken)
224
+ depth--;
225
+ if (depth > 0)
226
+ token = scanner.scan();
227
+ }
228
+ if (depth === 0) {
229
+ const after = scanner.scan();
230
+ if (after === ts.SyntaxKind.EqualsGreaterThanToken) {
231
+ const body = law.text.slice(scanner.getTokenEnd()).trim().replace(/;$/, '');
232
+ const head = law.text.slice(params, scanner.getTokenStart()).trimEnd();
233
+ rewritten = `${match[1]}function ${match[2]}(${head} { return (${body}); }`;
234
+ }
235
+ }
236
+ lowered = lowered.slice(0, law.start) + rewritten + lowered.slice(law.end);
237
+ }
238
+ return `${lowered}\ntype int = number;\n`;
239
+ }
240
+ const libraryFiles = new Map();
241
+ const virtualFile = join(process.cwd(), '__tslaws_proposal__.ts').replaceAll(sep, '/');
242
+ /** A type checker over `source` alone: no import is followed (an imported name has an unknown type) and no project file is read. */
243
+ function checkerFor(source) {
244
+ const options = {
245
+ target: ts.ScriptTarget.ES2022,
246
+ module: ts.ModuleKind.ESNext,
247
+ strict: true,
248
+ noResolve: true,
249
+ types: [],
250
+ noEmit: true,
251
+ skipLibCheck: true,
252
+ };
253
+ const host = ts.createCompilerHost(options, true);
254
+ host.getSourceFile = (name, languageVersion) => {
255
+ if (name.replaceAll(sep, '/') === virtualFile)
256
+ return source;
257
+ const key = `${name}|${languageVersion}`;
258
+ if (!libraryFiles.has(key)) {
259
+ const content = ts.sys.readFile(name);
260
+ libraryFiles.set(key, content === undefined ? undefined : ts.createSourceFile(name, content, languageVersion));
261
+ }
262
+ return libraryFiles.get(key);
263
+ };
264
+ return ts.createProgram([virtualFile], options, host).getTypeChecker();
265
+ }
266
+ /** Whether every member of the type is a number or a numeric literal (so not `any`, `unknown`, a string or a union with one). */
267
+ function isNumberType(type) {
268
+ if (type.isUnion())
269
+ return type.types.every(isNumberType);
270
+ return (type.flags & (ts.TypeFlags.Number | ts.TypeFlags.NumberLiteral)) !== 0;
271
+ }
272
+ /**
273
+ * Throws unless `text` loads code only through a static import or re-export, or an `import()` or `require()` whose one
274
+ * argument is a plain string literal: those are the loads `assertImportsAllowed` can read. A call with another argument,
275
+ * and any other reference to `require`, `module`, `createRequire`, `process.mainModule` or `import.meta`, could load a
276
+ * file the check never saw, so it is refused. This is the first layer of defence, not a sandbox: a computed index is
277
+ * allowed only when the type checker says its type is a number, and a string that spells a name of the loader or of
278
+ * the prototype chain is refused wherever it stands.
279
+ */
280
+ export function assertStaticLoading(text) {
281
+ let checker;
282
+ const refuse = (node, why) => {
283
+ const shown = node.getText().replace(/\s+/g, ' ');
284
+ throw new ProposalError(`\`${shown.length > 40 ? `${shown.slice(0, 40)}…` : shown}\` ${why}; code may be loaded only by a static import or an import() or require() of a string literal, so that the files it names can be reviewed`);
285
+ };
286
+ const isLiteral = (node) => node !== undefined && ts.isStringLiteralLike(node);
287
+ const namedBy = (parent, node) => (ts.isPropertyAccessExpression(parent) ||
288
+ ts.isPropertyAssignment(parent) ||
289
+ ts.isPropertyDeclaration(parent) ||
290
+ ts.isPropertySignature(parent) ||
291
+ ts.isMethodDeclaration(parent) ||
292
+ ts.isMethodSignature(parent) ||
293
+ ts.isGetAccessorDeclaration(parent) ||
294
+ ts.isSetAccessorDeclaration(parent) ||
295
+ ts.isEnumMember(parent)) &&
296
+ parent.name === node;
297
+ // An object literal that is the target of a destructuring assignment, directly or nested in another pattern.
298
+ const isAssignmentTarget = (literal) => {
299
+ let child = literal;
300
+ let parent = literal.parent;
301
+ while (ts.isParenthesizedExpression(parent) ||
302
+ ts.isArrayLiteralExpression(parent) ||
303
+ ts.isObjectLiteralExpression(parent) ||
304
+ ts.isPropertyAssignment(parent) ||
305
+ ts.isShorthandPropertyAssignment(parent) ||
306
+ ts.isSpreadElement(parent) ||
307
+ ts.isSpreadAssignment(parent)) {
308
+ child = parent;
309
+ parent = parent.parent;
310
+ }
311
+ if (ts.isBinaryExpression(parent))
312
+ return parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && parent.left === child;
313
+ return (ts.isForOfStatement(parent) || ts.isForInStatement(parent)) && parent.initializer === child;
314
+ };
315
+ // `arguments` is the module wrapper's own arguments object (require, module and so on) outside any non-arrow function.
316
+ const hasOwnArguments = (node) => ts.isFunctionDeclaration(node) ||
317
+ ts.isFunctionExpression(node) ||
318
+ ts.isMethodDeclaration(node) ||
319
+ ts.isConstructorDeclaration(node) ||
320
+ ts.isGetAccessorDeclaration(node) ||
321
+ ts.isSetAccessorDeclaration(node);
322
+ // The name of a module in an import or export declaration or `import x = require(...)`: `assertImportsAllowed` judges those.
323
+ const isSpecifier = (node) => (ts.isImportDeclaration(node.parent) || ts.isExportDeclaration(node.parent)) && node.parent.moduleSpecifier === node
324
+ ? true
325
+ : ts.isExternalModuleReference(node.parent) ||
326
+ (ts.isCallExpression(node.parent) &&
327
+ (node.parent.expression.kind === ts.SyntaxKind.ImportKeyword ||
328
+ (ts.isIdentifier(node.parent.expression) && node.parent.expression.text === 'require')));
329
+ // `typed` is set on the pass over the lowered text, where each law is a function and so has typed parameters.
330
+ const walk = (file, typed) => {
331
+ let functionDepth = 0;
332
+ const visit = (node) => {
333
+ if (hasOwnArguments(node)) {
334
+ functionDepth++;
335
+ ts.forEachChild(node, visit);
336
+ functionDepth--;
337
+ return;
338
+ }
339
+ if (ts.isCallExpression(node) &&
340
+ (node.expression.kind === ts.SyntaxKind.ImportKeyword ||
341
+ (ts.isIdentifier(node.expression) && node.expression.text === 'require'))) {
342
+ if (node.arguments.length !== 1 || !isLiteral(node.arguments[0]))
343
+ refuse(node, 'loads code by a name that is not a single string literal');
344
+ return;
345
+ }
346
+ if (ts.isStringLiteralLike(node) && reflected.has(node.text) && !isSpecifier(node))
347
+ refuse(node, 'spells a name of the module loader or the prototype chain');
348
+ else if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword)
349
+ refuse(node, 'reads import.meta, which can build a loader');
350
+ else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
351
+ if (!isLiteral(node.moduleReference.expression))
352
+ refuse(node, 'loads code by a name that is not a string literal');
353
+ }
354
+ else if (ts.isPropertyAccessExpression(node) && loaderProperties.has(node.name.text))
355
+ refuse(node, 'reaches the module loader');
356
+ else if (ts.isElementAccessExpression(node)) {
357
+ const index = node.argumentExpression;
358
+ if (typed && !ts.isStringLiteralLike(index) && !ts.isNumericLiteral(index)) {
359
+ checker ??= checkerFor(file);
360
+ if (!isNumberType(checker.getTypeAtLocation(index)))
361
+ refuse(node, 'indexes by a name that is not known to be a number, which can reach the module loader');
362
+ }
363
+ }
364
+ else if (ts.isBindingElement(node)) {
365
+ const key = node.propertyName ?? node.name;
366
+ if (ts.isComputedPropertyName(key))
367
+ refuse(node, 'destructures by a computed name, which can reach the module loader');
368
+ if ((ts.isIdentifier(key) || ts.isStringLiteralLike(key)) && loaderProperties.has(key.text))
369
+ refuse(node, 'reaches the module loader');
370
+ }
371
+ else if (ts.isPropertyAssignment(node) &&
372
+ ts.isComputedPropertyName(node.name) &&
373
+ ts.isObjectLiteralExpression(node.parent) &&
374
+ isAssignmentTarget(node.parent))
375
+ refuse(node, 'destructures by a computed name, which can reach the module loader');
376
+ else if (ts.isIdentifier(node) && loaderNames.has(node.text) && !namedBy(node.parent, node))
377
+ refuse(node, 'refers to the module loader or a way to run code the check cannot read');
378
+ else if (ts.isIdentifier(node) && node.text === 'arguments' && functionDepth === 0 && !namedBy(node.parent, node))
379
+ refuse(node, 'reads the module-level arguments object, which holds require and module');
380
+ ts.forEachChild(node, visit);
381
+ };
382
+ visit(file);
383
+ };
384
+ walk(ts.createSourceFile('proposal.ts', text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS), false);
385
+ // The lowered text is parsed as the virtual file, so the checker is asked about the nodes it was built from.
386
+ walk(ts.createSourceFile(virtualFile, lowerLaws(text), ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS), true);
387
+ }
388
+ /** The compiler options the project's `tsconfig.json` gives (or bundler-style defaults), widened to find .js and .json files. */
389
+ function resolutionOptions(root) {
390
+ const widened = { allowJs: true, resolveJsonModule: true };
391
+ try {
392
+ const configPath = ts.findConfigFile(root, ts.sys.fileExists);
393
+ if (configPath !== undefined) {
394
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
395
+ if (read.error === undefined) {
396
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(configPath));
397
+ return { ...parsed.options, ...widened };
398
+ }
399
+ }
400
+ }
401
+ catch {
402
+ // An unreadable tsconfig falls back to the defaults below.
403
+ }
404
+ return { moduleResolution: ts.ModuleResolutionKind.Bundler, module: ts.ModuleKind.ESNext, ...widened };
405
+ }
406
+ const isDirectory = (path) => {
407
+ try {
408
+ return statSync(path).isDirectory();
409
+ }
410
+ catch {
411
+ return false;
412
+ }
413
+ };
414
+ /**
415
+ * Throws unless every file the module specifiers of `text` name (an import, a re-export, `require` or `import()`)
416
+ * is code a person has reviewed: inside the project, not under `.tslaws/` (the proposals area), `node_modules` or
417
+ * `.git`, and not git-ignored. Specifiers are read relative to the project-relative directory `fromDir`, where the file
418
+ * stands. A package name is not a path and is left alone, unless the project's `paths` or `baseUrl` maps it to a file outside `node_modules`, which is checked as a path. Any specifier with `%`, `?`, `#` or a control character is
419
+ * refused (percent escapes, queries, fragments and package `imports` aliases make the file the runtime loads differ
420
+ * from the text). A path specifier is resolved as the runtime does, as a URL against the importing directory, then
421
+ * made canonical on the real file system; the reserved names are compared without regard to case. Git must answer: when
422
+ * git is missing, the project is not in a repository or the check fails, the import is refused. A project that sits
423
+ * inside an ignored directory of a larger repository has no usable ignore rules, so each file is not asked. Each path
424
+ * is also resolved with the TypeScript module resolution of the project's compiler options, and the file that gives
425
+ * (through `package.json` `main`, an index file, `rootDirs` and so on) is checked as well; a directory that resolves to
426
+ * no file is refused. Loading by any means but a static import or a string-literal `import()` or `require()` is refused.
427
+ */
428
+ export function assertImportsAllowed(cwd, text, fromDir) {
429
+ assertStaticLoading(text);
430
+ const all = [...new Set(moduleSpecifiers(text, 'proposal.ts').map((s) => s.value))];
431
+ const refuse = (specifier, why) => {
432
+ throw new ProposalError(`import '${specifier}' ${why}; an import must name code that is inside the project, outside .tslaws/, node_modules and .git, and not git-ignored, so that a person has reviewed it`);
433
+ };
434
+ for (const specifier of all)
435
+ if (isBuiltin(specifier) && !allowedBuiltins.has(specifier.replace(/^node:/, '')))
436
+ refuse(specifier, 'is a Node built-in module other than path, url, util and assert, which are the only ones allowed');
437
+ for (const specifier of all)
438
+ if (/[%?#]/.test(specifier) || [...specifier].some((c) => c.charCodeAt(0) < 0x20 || c === '\u007f'))
439
+ refuse(specifier, 'has a %, ?, # or control character, which can make the loaded file differ from its text');
440
+ const specifiers = all.filter((v) => v.startsWith('.') ||
441
+ v.startsWith('/') ||
442
+ v.startsWith('file:') ||
443
+ /^[A-Za-z]:[\\/]/.test(v) ||
444
+ v.startsWith('\\'));
445
+ // A bare name the project's `paths` or `baseUrl` maps to a file of its own is code in the project, not a package.
446
+ const bare = all.filter((v) => !specifiers.includes(v) && !isBuiltin(v));
447
+ if (specifiers.length === 0 && bare.length === 0)
448
+ return;
449
+ const root = realpathSync.native(cwd);
450
+ const reserved = new Set([...ignoredDirs].map((name) => name.toLowerCase()));
451
+ let rootIgnored;
452
+ let options;
453
+ const ignored = (specifier, path) => {
454
+ const state = gitIgnoreState(root, path);
455
+ if (state === 'unknown')
456
+ refuse(specifier, 'could not be checked against git ignore rules (git is missing, this is not a repository or the check failed)');
457
+ return state === 'ignored';
458
+ };
459
+ // The checks on one file a specifier leads to: inside the project, outside reserved directories, not git-ignored.
460
+ const guardFile = (specifier, candidate) => {
461
+ const rel = relative(root, realish(candidate)).replaceAll('\\', '/');
462
+ if (rel === '..' || rel.startsWith('../') || isAbsolute(rel))
463
+ refuse(specifier, 'resolves outside the project');
464
+ const name = rel.split('/').find((part) => reserved.has(part.toLowerCase()));
465
+ if (name !== undefined)
466
+ refuse(specifier, `resolves into ${name}/ (${rel})`);
467
+ rootIgnored ??= ignored(specifier, root);
468
+ if (!rootIgnored && ignored(specifier, rel))
469
+ refuse(specifier, `resolves to ${rel}, which git ignores`);
470
+ };
471
+ for (const specifier of bare) {
472
+ const compilerOptions = (options ??= resolutionOptions(root));
473
+ // Without `paths` or `baseUrl` nothing maps a bare name to a project file: it is a package.
474
+ if (compilerOptions.paths === undefined && compilerOptions.baseUrl === undefined)
475
+ break;
476
+ const containing = join(root, fromDir, 'proposal.ts');
477
+ const found = ts.resolveModuleName(specifier, containing, compilerOptions, ts.sys).resolvedModule;
478
+ if (found !== undefined && !found.isExternalLibraryImport)
479
+ guardFile(specifier, found.resolvedFileName);
480
+ }
481
+ for (const specifier of specifiers) {
482
+ if (specifier.startsWith('file:'))
483
+ refuse(specifier, 'is a file URL');
484
+ // Resolve as the runtime does: a URL against the directory of the importing file.
485
+ let url;
486
+ try {
487
+ url = new URL(specifier, pathToFileURL(join(root, fromDir) + sep));
488
+ }
489
+ catch {
490
+ return refuse(specifier, 'is not a path');
491
+ }
492
+ if (url.protocol !== 'file:' || url.host !== '')
493
+ refuse(specifier, 'is not a path inside the project');
494
+ const target = fileURLToPath(url);
495
+ // The file TypeScript's resolution gives (package.json main, index files, rootDirs, .js read as .ts), by the
496
+ // specifier as written and by the path it names, so that a redirect the textual candidates miss is checked too.
497
+ const compilerOptions = (options ??= resolutionOptions(root));
498
+ const containing = join(root, fromDir, 'proposal.ts');
499
+ const resolved = [specifier, target].flatMap((name) => {
500
+ const found = ts.resolveModuleName(name, containing, compilerOptions, ts.sys).resolvedModule;
501
+ return found === undefined ? [] : [found.resolvedFileName];
502
+ });
503
+ // The file Node's own resolution loads (it can differ from TypeScript's, as with `exports` conditions or a .json
504
+ // file); a specifier Node cannot resolve is left to the checks above.
505
+ try {
506
+ resolved.push(createRequire(containing).resolve(specifier));
507
+ }
508
+ catch {
509
+ // Unresolvable by Node: nothing more to check.
510
+ }
511
+ if (resolved.length === 0 && isDirectory(target))
512
+ refuse(specifier, 'names a directory that resolves to no file (no package.json main and no index file)');
513
+ for (const candidate of new Set([...specifierCandidates(target), ...resolved]))
514
+ guardFile(specifier, candidate);
515
+ }
516
+ }
517
+ /** Whether a top-level statement may stand in a proposal beside the laws: a `const`, function, type or interface. */
518
+ function isHelper(statement) {
519
+ if (ts.isVariableStatement(statement))
520
+ return isPlainConst(statement);
521
+ return (ts.isFunctionDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement));
522
+ }
523
+ /**
524
+ * The proposal's own text after `parseLawFile`: imports, law declarations and the helpers the laws need (top-level
525
+ * `const`, function, type and interface declarations, with their comments). Any other top-level statement, such as a
526
+ * bare call, a loop, `export default` or `let`, runs on its own or changes shared state, so it is refused.
527
+ */
528
+ function parts(source, cwd) {
112
529
  const parsed = parseLawFile(source);
113
- let rest = source;
114
- for (const part of [...parsed.laws, ...parsed.imports.map((text) => ({ text }))])
115
- rest = rest.replace(part.text, '');
116
- if (rest.trim() !== '')
117
- throw new ProposalError('a proposal may contain only imports and law declarations');
530
+ const file = ts.createSourceFile('proposal.ts', parsed.rest, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
531
+ for (const statement of file.statements)
532
+ if (!isHelper(statement) && !ts.isEmptyStatement(statement)) {
533
+ const shown = parsed.rest.slice(statement.getStart(file), statement.end).replace(/\s+/g, ' ');
534
+ throw new ProposalError(`a proposal may contain only imports, law declarations and top-level const, function, type and interface declarations; found \`${shown.length > 40 ? `${shown.slice(0, 40)}…` : shown}\``);
535
+ }
536
+ try {
537
+ assertImportStatements(parsed.imports);
538
+ assertHelpersSafe(parsed.declarations);
539
+ // The source is stored in the proposals directory, so its specifiers are read from there.
540
+ assertImportsAllowed(cwd, source, proposalsDir);
541
+ }
542
+ catch (error) {
543
+ throw new ProposalError(error instanceof Error ? error.message : String(error));
544
+ }
118
545
  return parsed;
119
546
  }
120
- /** The proposed file with the proposal's laws appended (same-named laws replaced) and its imports added once. */
121
- export function mergeProposal(current, imports, laws) {
547
+ /**
548
+ * The imports and helper declarations of `source` as they would be stored, after the same checks `addProposal` makes.
549
+ * `packages` lists the package specifiers the source loads (anything that is not a relative path), which are code
550
+ * outside the project that no person has reviewed.
551
+ */
552
+ export function previewProposal(source, cwd) {
553
+ const parsed = parts(toStoredImports(source), cwd);
554
+ const packages = moduleSpecifiers(source, 'proposal.ts')
555
+ .map((s) => s.value)
556
+ .filter((v) => !v.startsWith('.'));
557
+ return {
558
+ imports: parsed.imports.map((i) => i.trim()),
559
+ packages: [...new Set(packages)],
560
+ helpers: parsed.declarations.map((d) => ({ names: d.names, text: d.text.trim() })),
561
+ };
562
+ }
563
+ /**
564
+ * The proposed file with the proposal's laws appended (same-named laws replaced), its imports added once and its
565
+ * helpers placed after the declarations already there (a helper of the same name with other code replaces the old one,
566
+ * and throws when that would drop a name its statement bound together with it; an identical one is kept as it is).
567
+ */
568
+ export function mergeProposal(current, imports, laws, helpers = []) {
122
569
  const parsed = parseLawFile(current);
570
+ const added = helpers.filter((helper) => !parsed.declarations.some((d) => d.names.some((n) => helper.names.includes(n)) && sameCode(d.text, helper.text)));
571
+ const replaced = parsed.declarations.filter((d) => added.some((h) => h.names.some((n) => d.names.includes(n))));
572
+ for (const declaration of replaced) {
573
+ // One statement may bind several names (`const a = 1, b = 2`); dropping it must not take a name nobody redeclares.
574
+ const lost = declaration.names.find((n) => !added.some((h) => h.names.includes(n)));
575
+ if (lost !== undefined)
576
+ throw new ProposalError(`'${lost}' is declared together with ${declaration.names
577
+ .filter((n) => n !== lost)
578
+ .map((n) => `'${n}'`)
579
+ .join(', ')} in the proposal; send the whole declaration again, or rename the helper`);
580
+ }
581
+ const drops = [...parsed.laws.filter((law) => laws.some((l) => l.name === law.name)), ...replaced].sort((a, b) => b.start - a.start);
123
582
  let text = current;
124
- for (const law of [...parsed.laws].reverse()) {
125
- if (laws.some((l) => l.name === law.name))
126
- text = text.slice(0, law.start) + text.slice(law.end);
583
+ for (const { start, end } of drops) {
584
+ let to = end;
585
+ while (text[to] === '\r' || text[to] === '\n')
586
+ to += 1;
587
+ text = text.slice(0, start) + text.slice(to);
127
588
  }
589
+ if (added.length > 0)
590
+ text = withDeclarations(text, added.map((h) => h.text.trim()).join('\n\n'));
128
591
  const have = new Set(parseLawFile(text).imports.map((i) => i.replace(/\s+/g, ' ').trim()));
129
592
  const missing = imports.filter((i) => !have.has(i.replace(/\s+/g, ' ').trim()));
130
593
  const head = missing.length > 0 ? `${missing.join('\n')}\n` : '';
@@ -161,21 +624,21 @@ function ignoreProposals(cwd) {
161
624
  writeFileSync(ignore, '.tslaws/proposals\n');
162
625
  }
163
626
  /**
164
- * Adds laws to a proposal (appended; a law of the same name is replaced). `source` holds only imports and `export law`
165
- * declarations; with `only`, it must declare that law. Writes inside `.tslaws/proposals/` and nowhere else.
627
+ * Adds laws to a proposal (appended; a law of the same name is replaced). `source` holds imports, `export law`
628
+ * declarations and the helpers they need (see `parts`); with `only`, it must declare that law. Writes inside `.tslaws/proposals/` and nowhere else.
166
629
  */
167
630
  export function addProposal(cwd, file, source, only) {
168
631
  const { rel, abs } = writablePath(cwd, file);
169
632
  const stored = toStoredImports(source);
170
- const parsed = parts(stored);
633
+ const parsed = parts(stored, cwd);
171
634
  if (parsed.laws.length === 0)
172
635
  throw new ProposalError('source must declare at least one law (`export law name(...) ...`)');
173
636
  if (only !== undefined && !parsed.laws.some((l) => l.name === only))
174
637
  throw new ProposalError(`source must contain \`export law ${only}\`…`);
175
638
  const current = existsSync(abs) ? readFileSync(abs, 'utf8') : '';
176
- write(abs, mergeProposal(current, parsed.imports, parsed.laws));
639
+ write(abs, mergeProposal(current, parsed.imports, parsed.laws, parsed.declarations));
177
640
  ignoreProposals(cwd);
178
- return { file: rel, laws: parsed.laws.map((l) => l.name) };
641
+ return { file: rel, laws: parsed.laws.map((l) => l.name), helpers: parsed.declarations.flatMap((d) => d.names) };
179
642
  }
180
643
  /**
181
644
  * Stores the root-relative imports of a proposal someone placed in the directory by hand, so it resolves where it is.