tslaws 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/coverage.js CHANGED
@@ -7,13 +7,16 @@
7
7
  import { parseGithubConfig } from "./github.js";
8
8
  import { parseSecurityConfig } from "./security/deps/config.js";
9
9
  import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
10
- import { dirname, isAbsolute, join, posix, relative, resolve } from 'node:path';
10
+ import { dirname, extname, isAbsolute, join, posix, relative, resolve } from 'node:path';
11
11
  import ts from 'typescript';
12
12
  import { parseE2eConfig } from "./e2e.js";
13
13
  import { globMatcher } from "./globs.js";
14
14
  import { customLawFile } from "./lawFiles.js";
15
+ import { pluginExtensionNeeded } from "./pluginHooks.js";
16
+ import { transformPluginFile } from "./pluginHost.js";
15
17
  import { certifyProblem } from "./certificates.js";
16
18
  import { importMetaEnvOf, parseEnvConfig } from "./runtimeEnv.js";
19
+ import { resolveRelativeJs } from "./symbolic.js";
17
20
  import { solversProblem } from "./solvers.js";
18
21
  const settingKeys = ['runs', 'propertyTimeoutMs', 'proofTimeoutMs', 'bound'];
19
22
  const configKeys = [
@@ -24,6 +27,7 @@ const configKeys = [
24
27
  'certify',
25
28
  'compilerOptions',
26
29
  'tsconfig',
30
+ 'browser',
27
31
  'e2e',
28
32
  'bundlerPlugins',
29
33
  'sandboxReads',
@@ -93,6 +97,37 @@ function checkFile(raw, source) {
93
97
  (!Array.isArray(laws) ||
94
98
  laws.some((entry) => typeof entry !== 'string' || entry.replace(/^!/, '') === '' || entry.startsWith('/'))))
95
99
  fail(`"laws" must be an array of project-relative globs, got ${JSON.stringify(laws)}`);
100
+ if (object.browser !== undefined) {
101
+ if (!isPlain(object.browser))
102
+ return fail('"browser" must be an object');
103
+ const b = object.browser;
104
+ const allowed = ['isolation', 'headless', 'viewport', 'colorScheme', 'inBrowser', 'traceOnFailure'];
105
+ for (const key of Object.keys(b))
106
+ if (!allowed.includes(key))
107
+ fail(`"browser.${key}" is not supported; supported options are ${allowed.join(', ')}`);
108
+ if (b.isolation !== undefined && b.isolation !== 'page' && b.isolation !== 'iframe')
109
+ fail('"browser.isolation" must be "page" or "iframe"');
110
+ if (b.headless !== undefined && typeof b.headless !== 'boolean')
111
+ fail('"browser.headless" must be true or false');
112
+ if (b.inBrowser !== undefined && typeof b.inBrowser !== 'boolean')
113
+ fail('"browser.inBrowser" must be true or false');
114
+ if (b.traceOnFailure !== undefined && typeof b.traceOnFailure !== 'boolean')
115
+ fail('"browser.traceOnFailure" must be true or false');
116
+ if (b.colorScheme !== undefined &&
117
+ b.colorScheme !== 'light' &&
118
+ b.colorScheme !== 'dark' &&
119
+ b.colorScheme !== 'no-preference')
120
+ fail('"browser.colorScheme" must be "light", "dark" or "no-preference"');
121
+ if (b.viewport !== undefined) {
122
+ if (!isPlain(b.viewport))
123
+ return fail('"browser.viewport" must be { width, height } with positive numbers');
124
+ if (typeof b.viewport.width !== 'number' ||
125
+ typeof b.viewport.height !== 'number' ||
126
+ b.viewport.width < 1 ||
127
+ b.viewport.height < 1)
128
+ fail('"browser.viewport" must be { width, height } with positive numbers');
129
+ }
130
+ }
96
131
  if (object.security !== undefined)
97
132
  parseSecurityConfig(object.security);
98
133
  return object;
@@ -263,11 +298,40 @@ function loadMerged(file, cwd, root, chain, loaded) {
263
298
  delete base.standalone;
264
299
  return deepMerge(base, own);
265
300
  }
301
+ const configCache = new Map();
266
302
  /** The settings of tslaws.json in `cwd`, with every `extends` followed; `{}` when there is no file. */
267
303
  export function readConfig(cwd) {
304
+ const key = resolve(cwd);
268
305
  const path = join(cwd, 'tslaws.json');
269
- if (!existsSync(path))
270
- return {};
306
+ const cached = configCache.get(key);
307
+ if (cached !== undefined) {
308
+ if (cached.files.length === 0) {
309
+ if (!existsSync(path))
310
+ return cached.config;
311
+ }
312
+ else {
313
+ let valid = true;
314
+ for (const [file, prev] of cached.files) {
315
+ try {
316
+ if (readFileSync(file, 'utf8') !== prev) {
317
+ valid = false;
318
+ break;
319
+ }
320
+ }
321
+ catch {
322
+ valid = false;
323
+ break;
324
+ }
325
+ }
326
+ if (valid)
327
+ return cached.config;
328
+ }
329
+ }
330
+ if (!existsSync(path)) {
331
+ const empty = {};
332
+ configCache.set(key, { files: [], config: empty });
333
+ return empty;
334
+ }
271
335
  const loaded = [];
272
336
  const merged = loadMerged(path, cwd, extendsRoot(cwd), [], loaded);
273
337
  let config;
@@ -282,6 +346,15 @@ export function readConfig(cwd) {
282
346
  const files = loaded.map((file) => relative(cwd, file).replaceAll('\\', '/')).join(', ');
283
347
  throw new Error(`${error.message} (merged from ${files})`);
284
348
  }
349
+ try {
350
+ const files = loaded.map((file) => [file, readFileSync(file, 'utf8')]);
351
+ if (configCache.size > 512)
352
+ configCache.clear();
353
+ configCache.set(key, { files, config });
354
+ }
355
+ catch {
356
+ // Skip caching if a file vanished mid-read.
357
+ }
285
358
  return config;
286
359
  }
287
360
  /** The `import.meta.env` of the project's laws: `process.env`, the defaults and the `env` of tslaws.json. */
@@ -340,15 +413,73 @@ function relativeRequire(expression) {
340
413
  return call.arguments[0].text;
341
414
  return undefined;
342
415
  }
343
- function parseModule(jsFile, modules) {
416
+ function resolveImport(jsFile, specifier, pluginCtx) {
417
+ const resolved = resolveRelativeJs(jsFile, specifier);
418
+ try {
419
+ if (existsSync(resolved) && statSync(resolved).isFile())
420
+ return resolved;
421
+ }
422
+ catch {
423
+ // Fall through to plugin resolution.
424
+ }
425
+ if (pluginCtx !== undefined && pluginCtx.plugins.length > 0) {
426
+ const base = resolve(dirname(jsFile), specifier);
427
+ const rel = relative(pluginCtx.outDir, base);
428
+ if (!rel.startsWith('..') && !isAbsolute(rel)) {
429
+ const src = resolve(pluginCtx.cwd, rel);
430
+ try {
431
+ if (pluginExtensionNeeded(extname(src)) && existsSync(src) && statSync(src).isFile())
432
+ return base;
433
+ }
434
+ catch {
435
+ // Ignore unreadable paths.
436
+ }
437
+ }
438
+ }
439
+ return resolved;
440
+ }
441
+ function exportedTargetName(left) {
442
+ if (!ts.isPropertyAccessExpression(left) || !ts.isIdentifier(left.expression))
443
+ return undefined;
444
+ if (left.expression.text === 'exports')
445
+ return left.name.text;
446
+ if (left.expression.text === 'module' && left.name.text === 'exports')
447
+ return 'default';
448
+ return undefined;
449
+ }
450
+ function parseModule(jsFile, modules, pluginCtx) {
344
451
  const known = modules.get(jsFile);
345
452
  if (known !== undefined)
346
453
  return known;
347
- if (!existsSync(jsFile))
454
+ let text;
455
+ if (existsSync(jsFile) && statSync(jsFile).isFile()) {
456
+ text = readFileSync(jsFile, 'utf8');
457
+ }
458
+ else if (pluginCtx !== undefined && pluginCtx.plugins.length > 0 && pluginExtensionNeeded(extname(jsFile))) {
459
+ const rel = relative(pluginCtx.outDir, jsFile);
460
+ if (rel.startsWith('..') || isAbsolute(rel))
461
+ return undefined;
462
+ const src = resolve(pluginCtx.cwd, rel);
463
+ if (!existsSync(src) || !statSync(src).isFile())
464
+ return undefined;
465
+ try {
466
+ text = transformPluginFile(src, pluginCtx.cwd, pluginCtx.plugins, 'cjs');
467
+ }
468
+ catch {
469
+ return undefined;
470
+ }
471
+ }
472
+ else {
348
473
  return undefined;
349
- const text = readFileSync(jsFile, 'utf8');
474
+ }
350
475
  const source = ts.createSourceFile(jsFile, text, ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);
351
- const module = { nodes: new Map(), imports: new Map() };
476
+ const module = {
477
+ nodes: new Map(),
478
+ imports: new Map(),
479
+ reexports: new Map(),
480
+ localExports: new Map(),
481
+ stars: [],
482
+ };
352
483
  modules.set(jsFile, module);
353
484
  const exempt = (statement) => (ts.getLeadingCommentRanges(text, statement.getFullStart()) ?? []).some((r) => text.slice(r.pos, r.end).includes('@tslaws-exempt'));
354
485
  for (const statement of source.statements) {
@@ -366,8 +497,98 @@ function parseModule(jsFile, modules) {
366
497
  const specifier = relativeRequire(init);
367
498
  if (specifier === undefined)
368
499
  continue;
369
- const base = resolve(dirname(jsFile), specifier);
370
- module.imports.set(declaration.name.text, /\.[cm]?js$/.test(base) ? base : `${base}.js`);
500
+ module.imports.set(declaration.name.text, resolveImport(jsFile, specifier, pluginCtx));
501
+ }
502
+ }
503
+ }
504
+ const recordGetter = (exportedName, returned) => {
505
+ if (returned === undefined)
506
+ return;
507
+ if (ts.isPropertyAccessExpression(returned) && ts.isIdentifier(returned.expression)) {
508
+ const target = module.imports.get(returned.expression.text);
509
+ if (target !== undefined)
510
+ module.reexports.set(exportedName, { file: target, name: returned.name.text });
511
+ }
512
+ else if (ts.isIdentifier(returned) && exportedName !== returned.text) {
513
+ module.localExports.set(exportedName, returned.text);
514
+ }
515
+ };
516
+ for (const statement of source.statements) {
517
+ if (!ts.isExpressionStatement(statement))
518
+ continue;
519
+ if (ts.isBinaryExpression(statement.expression) &&
520
+ statement.expression.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
521
+ const name = exportedTargetName(statement.expression.left);
522
+ if (name !== undefined) {
523
+ const rhs = statement.expression.right;
524
+ if (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs) || ts.isClassExpression(rhs))
525
+ module.nodes.set(name, { name, body: rhs, exempt: exempt(statement) });
526
+ else
527
+ recordGetter(name, rhs);
528
+ }
529
+ continue;
530
+ }
531
+ if (!ts.isCallExpression(statement.expression))
532
+ continue;
533
+ const call = statement.expression;
534
+ const callee = call.expression;
535
+ const calleeName = ts.isIdentifier(callee)
536
+ ? callee.text
537
+ : ts.isPropertyAccessExpression(callee)
538
+ ? callee.name.text
539
+ : '';
540
+ if (calleeName === '__exportStar' && call.arguments.length >= 1) {
541
+ const specifier = relativeRequire(call.arguments[0]);
542
+ if (specifier !== undefined)
543
+ module.stars.push(resolveImport(jsFile, specifier, pluginCtx));
544
+ }
545
+ else if (calleeName === '__reExport' && call.arguments.length >= 2) {
546
+ const specifier = relativeRequire(call.arguments[1]);
547
+ if (specifier !== undefined)
548
+ module.stars.push(resolveImport(jsFile, specifier, pluginCtx));
549
+ }
550
+ else if (calleeName === '__export' &&
551
+ call.arguments.length === 2 &&
552
+ ts.isObjectLiteralExpression(call.arguments[1])) {
553
+ for (const prop of call.arguments[1].properties) {
554
+ if (!ts.isPropertyAssignment(prop))
555
+ continue;
556
+ const exportedName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : undefined;
557
+ if (exportedName === undefined)
558
+ continue;
559
+ const getter = prop.initializer;
560
+ if (!ts.isArrowFunction(getter) && !ts.isFunctionExpression(getter))
561
+ continue;
562
+ const returned = ts.isBlock(getter.body)
563
+ ? getter.body.statements.length === 1 && ts.isReturnStatement(getter.body.statements[0])
564
+ ? getter.body.statements[0].expression
565
+ : undefined
566
+ : getter.body;
567
+ recordGetter(exportedName, returned);
568
+ }
569
+ }
570
+ else if (ts.isPropertyAccessExpression(callee) &&
571
+ ts.isIdentifier(callee.expression) &&
572
+ callee.expression.text === 'Object' &&
573
+ callee.name.text === 'defineProperty' &&
574
+ call.arguments.length === 3 &&
575
+ ts.isIdentifier(call.arguments[0]) &&
576
+ call.arguments[0].text === 'exports' &&
577
+ ts.isStringLiteral(call.arguments[1]) &&
578
+ ts.isObjectLiteralExpression(call.arguments[2])) {
579
+ const exportedName = call.arguments[1].text;
580
+ const getter = call.arguments[2].properties.find((p) => ts.isPropertyAssignment(p) &&
581
+ ts.isIdentifier(p.name) &&
582
+ p.name.text === 'get' &&
583
+ (ts.isFunctionExpression(p.initializer) || ts.isArrowFunction(p.initializer)));
584
+ if (getter !== undefined) {
585
+ const fn = getter.initializer;
586
+ const returned = ts.isBlock(fn.body)
587
+ ? fn.body.statements.length === 1 && ts.isReturnStatement(fn.body.statements[0])
588
+ ? fn.body.statements[0].expression
589
+ : undefined
590
+ : fn.body;
591
+ recordGetter(exportedName, returned);
371
592
  }
372
593
  }
373
594
  }
@@ -405,6 +626,8 @@ const sourceOf = (outDir, cwd, js) => {
405
626
  return candidates.find((c) => existsSync(join(cwd, c))) ?? candidates[0];
406
627
  };
407
628
  export function analyzeCoverage(input) {
629
+ const plugins = (readConfig(input.cwd).bundlerPlugins ?? []).map((p) => resolve(input.cwd, p));
630
+ const pluginCtx = plugins.length > 0 ? { cwd: input.cwd, outDir: input.outDir, plugins } : undefined;
408
631
  const modules = new Map();
409
632
  const key = (js, name) => `${js}::${name}`;
410
633
  const edges = (js, node) => {
@@ -416,7 +639,7 @@ export function analyzeCoverage(input) {
416
639
  if (ts.isPropertyAccessExpression(n) && ts.isIdentifier(n.expression)) {
417
640
  const target = module.imports.get(n.expression.text);
418
641
  if (target !== undefined) {
419
- parseModule(target, modules);
642
+ parseModule(target, modules, pluginCtx);
420
643
  out.push(key(target, n.name.text));
421
644
  }
422
645
  }
@@ -430,7 +653,7 @@ export function analyzeCoverage(input) {
430
653
  const queue = [];
431
654
  const lawJs = input.lawFiles.map((f) => jsOf(input.outDir, f));
432
655
  for (const js of lawJs) {
433
- const module = parseModule(js, modules);
656
+ const module = parseModule(js, modules, pluginCtx);
434
657
  if (module === undefined)
435
658
  continue;
436
659
  for (const node of module.nodes.values())
@@ -442,12 +665,35 @@ export function analyzeCoverage(input) {
442
665
  continue;
443
666
  reached.add(current);
444
667
  const [js, name] = current.split('::');
445
- const module = parseModule(js, modules);
446
- const node = module?.nodes.get(name);
668
+ const module = parseModule(js, modules, pluginCtx);
669
+ if (module === undefined)
670
+ continue;
671
+ const node = module.nodes.get(name);
447
672
  if (node !== undefined)
448
673
  for (const next of edges(js, node))
449
674
  if (!reached.has(next))
450
675
  queue.push(next);
676
+ const local = module.localExports.get(name);
677
+ if (local !== undefined) {
678
+ const localNode = module.nodes.get(local);
679
+ if (localNode !== undefined)
680
+ for (const next of edges(js, localNode))
681
+ if (!reached.has(next))
682
+ queue.push(next);
683
+ }
684
+ const reexport = module.reexports.get(name);
685
+ if (reexport !== undefined) {
686
+ parseModule(reexport.file, modules, pluginCtx);
687
+ const next = key(reexport.file, reexport.name);
688
+ if (!reached.has(next))
689
+ queue.push(next);
690
+ }
691
+ for (const star of module.stars) {
692
+ parseModule(star, modules, pluginCtx);
693
+ const next = key(star, name);
694
+ if (!reached.has(next))
695
+ queue.push(next);
696
+ }
451
697
  }
452
698
  // The modules in scope: the cover globs, or every project module the laws import.
453
699
  const scope = new Set();
@@ -455,13 +701,18 @@ export function analyzeCoverage(input) {
455
701
  for (const f of input.coverFiles)
456
702
  scope.add(jsOf(input.outDir, f));
457
703
  else {
704
+ const visited = new Set();
458
705
  const visit = (js) => {
459
- const module = parseModule(js, modules);
706
+ if (visited.has(js))
707
+ return;
708
+ visited.add(js);
709
+ const module = parseModule(js, modules, pluginCtx);
460
710
  if (module === undefined)
461
711
  return;
462
- for (const target of module.imports.values()) {
463
- if (!scope.has(target) && !lawJs.includes(target)) {
464
- scope.add(target);
712
+ for (const target of [...module.imports.values(), ...module.stars]) {
713
+ if (!lawJs.includes(target)) {
714
+ if (!pluginExtensionNeeded(extname(target)))
715
+ scope.add(target);
465
716
  visit(target);
466
717
  }
467
718
  }
@@ -472,7 +723,7 @@ export function analyzeCoverage(input) {
472
723
  const uncovered = [];
473
724
  const exempt = [];
474
725
  for (const js of scope) {
475
- const module = parseModule(js, modules);
726
+ const module = parseModule(js, modules, pluginCtx);
476
727
  if (module === undefined)
477
728
  continue;
478
729
  const file = sourceOf(input.outDir, input.cwd, js);
package/dist/derived.d.ts CHANGED
@@ -4,5 +4,7 @@ import type { ManifestLaw } from './types.ts';
4
4
  export interface DerivedStore {
5
5
  law(law: ManifestLaw, compute: () => LawTypes): LawTypes;
6
6
  coverage(compute: () => CoverageReport): CoverageReport;
7
+ /** Writes any new entries to disk once, instead of rewriting derived.json on every law. */
8
+ flush(): void;
7
9
  }
8
10
  export declare function derivedStore(cwd: string, key: string | undefined): DerivedStore;
package/dist/derived.js CHANGED
@@ -5,7 +5,7 @@ import { join } from 'node:path';
5
5
  import { arbitraryOf } from "./plan.js";
6
6
  export function derivedStore(cwd, key) {
7
7
  if (key === undefined)
8
- return { law: (_law, compute) => compute(), coverage: (compute) => compute() };
8
+ return { law: (_law, compute) => compute(), coverage: (compute) => compute(), flush: () => undefined };
9
9
  const path = join(cwd, '.tslaws', 'derived.json');
10
10
  let stored = { key, laws: {} };
11
11
  try {
@@ -16,7 +16,11 @@ export function derivedStore(cwd, key) {
16
16
  catch {
17
17
  // Nothing kept yet.
18
18
  }
19
- const save = () => {
19
+ let dirty = false;
20
+ const flush = () => {
21
+ if (!dirty)
22
+ return;
23
+ dirty = false;
20
24
  try {
21
25
  mkdirSync(join(cwd, '.tslaws'), { recursive: true });
22
26
  writeFileSync(path, JSON.stringify(stored));
@@ -37,7 +41,7 @@ export function derivedStore(cwd, key) {
37
41
  };
38
42
  const types = compute();
39
43
  stored.laws[id] = { plans: types.plans, shapes: types.shapes.map((shape) => shape ?? null) };
40
- save();
44
+ dirty = true;
41
45
  return types;
42
46
  },
43
47
  coverage(compute) {
@@ -45,8 +49,9 @@ export function derivedStore(cwd, key) {
45
49
  return stored.coverage;
46
50
  const report = compute();
47
51
  stored.coverage = report;
48
- save();
52
+ dirty = true;
49
53
  return report;
50
54
  },
55
+ flush,
51
56
  };
52
57
  }
@@ -2,6 +2,10 @@ import type * as fc from 'fast-check';
2
2
  import ts from 'typescript';
3
3
  import { type Plan } from './plan.ts';
4
4
  export { toWire, UnsupportedType, wireKey } from './plan.ts';
5
+ /** Extracts `[min, max]` literal bounds from `intRange<Lo, Hi>`. */
6
+ export declare function readIntRangeBounds(checker: ts.TypeChecker, type: ts.Type): [number, number] | undefined;
7
+ /** Extracts the element type `T` from `nonEmpty<T>`. */
8
+ export declare function readNonEmptyElement(checker: ts.TypeChecker, type: ts.Type): ts.Type | undefined;
5
9
  export declare class GeneratorFactory {
6
10
  private readonly checker;
7
11
  private readonly active;
@@ -10,7 +14,7 @@ export declare class GeneratorFactory {
10
14
  of(type: ts.Type): fc.Arbitrary<unknown>;
11
15
  plan(type: ts.Type, depth?: number): Plan;
12
16
  private structural;
13
- /** A type with a registered generator keeps its name in the plan, so a registration made later still applies. */
17
+ /** A type with a registered generator or built-in refinement type (`int`, `nat`, `posInt`, `nonZeroInt`, `intRange`, `uint8`/`16`/`32`, `int32`, `nonEmpty`, `nonEmptyString`, `asciiString`, `finite`). */
14
18
  private registered;
15
19
  private union;
16
20
  private template;
@@ -3,6 +3,37 @@ import { arbitraryRegistry } from "./api.js";
3
3
  import { registerSecurityGenerators, securityTypeNames } from "./security/generators.js";
4
4
  import { arbitraryOf, UnsupportedType } from "./plan.js";
5
5
  export { toWire, UnsupportedType, wireKey } from "./plan.js";
6
+ /** Extracts `[min, max]` literal bounds from `intRange<Lo, Hi>`. */
7
+ export function readIntRangeBounds(checker, type) {
8
+ const args = type.aliasTypeArguments;
9
+ if (args !== undefined && args.length === 2 && args[0].isNumberLiteral() && args[1].isNumberLiteral()) {
10
+ const lo = args[0].value;
11
+ const hi = args[1].value;
12
+ if (Number.isSafeInteger(lo) && Number.isSafeInteger(hi) && lo <= hi)
13
+ return [lo, hi];
14
+ }
15
+ const minProp = type.getProperty('__tslawsMin');
16
+ const maxProp = type.getProperty('__tslawsMax');
17
+ if (minProp === undefined || maxProp === undefined)
18
+ return undefined;
19
+ const minType = checker.getTypeOfSymbol(minProp);
20
+ const maxType = checker.getTypeOfSymbol(maxProp);
21
+ if (minType.isNumberLiteral() && maxType.isNumberLiteral() && minType.value <= maxType.value)
22
+ return [minType.value, maxType.value];
23
+ return undefined;
24
+ }
25
+ /** Extracts the element type `T` from `nonEmpty<T>`. */
26
+ export function readNonEmptyElement(checker, type) {
27
+ if (type.aliasTypeArguments !== undefined && type.aliasTypeArguments.length === 1)
28
+ return type.aliasTypeArguments[0];
29
+ if (type.flags & ts.TypeFlags.Intersection) {
30
+ for (const part of type.types) {
31
+ if (checker.isArrayType(part))
32
+ return checker.getTypeArguments(part)[0];
33
+ }
34
+ }
35
+ return undefined;
36
+ }
6
37
  /** Whether a type is declared in tslaws' own security module, not by a project that reuses the name. */
7
38
  function declaredBySecurity(symbol) {
8
39
  return (symbol.declarations ?? []).some((d) => /\/tslaws\/(dist|src)\/security\//.test(d.getSourceFile().fileName));
@@ -70,19 +101,34 @@ export class GeneratorFactory {
70
101
  return { k: 'object' };
71
102
  throw new UnsupportedType(`no generator for type ${this.checker.typeToString(type)}`);
72
103
  }
73
- /** A type with a registered generator keeps its name in the plan, so a registration made later still applies. */
104
+ /** A type with a registered generator or built-in refinement type (`int`, `nat`, `posInt`, `nonZeroInt`, `intRange`, `uint8`/`16`/`32`, `int32`, `nonEmpty`, `nonEmptyString`, `asciiString`, `finite`). */
74
105
  registered(type, depth) {
75
106
  const symbol = type.aliasSymbol ?? type.getSymbol();
76
- if (symbol === undefined)
107
+ const name = symbol?.getName();
108
+ // Parameterized & aliased range refinement types (`intRange<Lo, Hi>`, `uint8`, `uint16`, `uint32`, `int32`, or user aliases).
109
+ const bounds = readIntRangeBounds(this.checker, type);
110
+ if (bounds !== undefined)
111
+ return { k: 'intRange', min: bounds[0], max: bounds[1] };
112
+ if (name === 'nonEmpty') {
113
+ const elem = readNonEmptyElement(this.checker, type);
114
+ if (elem !== undefined)
115
+ return { k: 'nonEmpty', of: this.plan(elem, depth + 1) };
116
+ }
117
+ if (symbol === undefined || name === undefined)
77
118
  return undefined;
78
- const name = symbol.getName();
79
119
  // The payload types of tslaws/security have their generators even when the law has not been loaded yet.
80
120
  const security = securityTypeNames.has(name) && declaredBySecurity(symbol);
81
121
  if (security && !arbitraryRegistry().has(name))
82
122
  registerSecurityGenerators();
83
123
  if (!arbitraryRegistry().has(name))
84
124
  return undefined;
85
- if (name === 'int')
125
+ if (name === 'int' ||
126
+ name === 'nat' ||
127
+ name === 'posInt' ||
128
+ name === 'nonZeroInt' ||
129
+ name === 'asciiString' ||
130
+ name === 'nonEmptyString' ||
131
+ name === 'finite')
86
132
  return { k: 'named', name };
87
133
  const tag = security ? { security: true } : {};
88
134
  // What to generate if the registration is not there where the plan is used (a worker has only the built-in ones).
package/dist/githubCli.js CHANGED
@@ -5,7 +5,8 @@
5
5
  // waits for an accept. Advisory: it runs the pull request's code, so it decides nothing about the lock.
6
6
  // command issue_comment: reads `/tslaws accept|reject ...`, checks the commenter may accept, and records the
7
7
  // fingerprints accepted in a comment of the bot's. Reads the pull request's files as data; runs none of it.
8
- // merge push to the configured branch, or workflow_dispatch by someone with admin or maintain access: runs the
8
+ // merge push to the configured branch, or workflow_dispatch by someone with admin or maintain access (plus
9
+ // merge_group with --results-out to run the laws ahead of the push): runs the
9
10
  // laws on the branch's code, accepts what passes (and, in comment mode, what was accepted for that exact
10
11
  // version) and commits tsc-laws.lock through the API as the bot. The only place the workflow writes the
11
12
  // lock. While a project's "local" is true (the default) a person may also change its lock by hand, through
@@ -31,7 +32,7 @@ import { discoverFromFiles, discoverySignature } from "./projects.js";
31
32
  import { build, readManifest } from "./compile.js";
32
33
  import { acceptedFingerprints, inert, recordComment, decide, parseCommands, isSharedBot, parseGithubConfig, proposalsOf, pullRequestVerdict, readApprovals, renderSticky, renderStickyAll, resolveNames, stickyMarkerFor, } from "./github.js";
33
34
  import { lockLevels } from "./lawKinds.js";
34
- import { acceptChanges, lawKey, lockChanges, readLock, writeLockValue } from "./lock.js";
35
+ import { acceptChanges, lawKey, lockChanges, parseLock, readLock, writeLockValue, } from "./lock.js";
35
36
  import { escapeGithubData, escapeGithubProperty } from "./reporters.js";
36
37
  import { plural } from "./plural.js";
37
38
  /** A project-relative file as the repository names it: the project's prefix, then the path. */
@@ -300,13 +301,58 @@ ${built.diagnostics}`);
300
301
  function lawsToProve(changes) {
301
302
  return changes.filter((c) => c.kind === 'law' && c.reason !== 'removed').map((c) => c.key);
302
303
  }
304
+ /** Reads a project's lock at a git commit (for example `merge_group.base_sha`), when that commit is present locally. */
305
+ function gitLockAt(cwd, lockPath, baseSha) {
306
+ if (typeof baseSha !== 'string' || !/^[0-9a-f]{40}$/.test(baseSha) || /^0+$/.test(baseSha))
307
+ return { found: false };
308
+ try {
309
+ execFileSync('git', ['-C', cwd, 'cat-file', '-e', `${baseSha}^{commit}`], { stdio: 'ignore' });
310
+ }
311
+ catch {
312
+ return { found: false };
313
+ }
314
+ try {
315
+ const bytes = execFileSync('git', ['-C', cwd, 'show', `${baseSha}:${lockPath}`], {
316
+ stdio: ['ignore', 'pipe', 'ignore'],
317
+ });
318
+ return { found: true, lock: parseLock(bytes.toString('utf8')) };
319
+ }
320
+ catch {
321
+ return { found: true, lock: undefined };
322
+ }
323
+ }
303
324
  /** `--results-out <file>`: run the laws of every project and write the reports, doing nothing else. Needs no token. */
304
325
  async function collect(ctx, mode, file) {
305
326
  const { active } = plan(ctx, unitsOf(ctx), (u) => u.cwd);
306
327
  const ev = event(ctx.env);
307
- const sha = String(mode === 'report' ? (ev.pull_request?.head?.sha ?? ctx.env.GITHUB_SHA) : (ev.after ?? ctx.env.GITHUB_SHA));
328
+ const eventName = ctx.env.GITHUB_EVENT_NAME;
329
+ if (mode === 'merge' &&
330
+ eventName !== undefined &&
331
+ eventName !== 'push' &&
332
+ eventName !== 'workflow_dispatch' &&
333
+ eventName !== 'merge_group') {
334
+ ctx.err('tslaws: merge --results-out runs on push, workflow_dispatch and merge_group only\n');
335
+ return 1;
336
+ }
337
+ const mergeGroup = mode === 'merge' && eventName === 'merge_group'
338
+ ? ev.merge_group
339
+ : undefined;
340
+ let targets = active;
341
+ if (mergeGroup !== undefined && typeof mergeGroup.base_ref === 'string' && mergeGroup.base_ref !== '') {
342
+ if (active.length === 0)
343
+ return 0;
344
+ targets = active.filter((a) => mergeGroup.base_ref === `refs/heads/${a.config.branch}`);
345
+ if (targets.length === 0) {
346
+ const branches = [...new Set(active.map((a) => `refs/heads/${a.config.branch}`))];
347
+ ctx.err(`tslaws: ${mergeGroup.base_ref} is not ${branches.join(' or ') || 'a branch any project writes'}; the lock is written only there\n`);
348
+ return 1;
349
+ }
350
+ }
351
+ const sha = String(mode === 'report'
352
+ ? (ev.pull_request?.head?.sha ?? ctx.env.GITHUB_SHA)
353
+ : (mergeGroup?.head_sha ?? ev.after ?? ctx.env.GITHUB_SHA));
308
354
  const projects = {};
309
- for (const { unit } of active) {
355
+ for (const { unit } of targets) {
310
356
  const entry = { lockSha: lockShaOf(unit) };
311
357
  try {
312
358
  const state = projectState(unit.options);
@@ -314,7 +360,19 @@ async function collect(ctx, mode, file) {
314
360
  entry.report = await runIsolated(unit, state);
315
361
  else {
316
362
  // A merge acts only on what the lock does not record, which it works out again from the same lock and files.
317
- const only = lawsToProve(lockChanges(state.lock, state.laws, state.exempt, state.levels));
363
+ // On merge_group, also compare against the queue's base lock when its commit is present locally so any law
364
+ // changed relative to the queue's base runs ahead of the push.
365
+ const base = mergeGroup
366
+ ? gitLockAt(ctx.cwd, joinRepo(unit.path, 'tsc-laws.lock'), mergeGroup.base_sha)
367
+ : { found: false };
368
+ const only = base.found
369
+ ? [
370
+ ...new Set([
371
+ ...lawsToProve(lockChanges(base.lock, state.laws, state.exempt, state.levels)),
372
+ ...lawsToProve(lockChanges(state.lock, state.laws, state.exempt, state.levels)),
373
+ ]),
374
+ ]
375
+ : lawsToProve(lockChanges(state.lock, state.laws, state.exempt, state.levels));
318
376
  if (only.length > 0)
319
377
  entry.report = await runIsolated(unit, state, only);
320
378
  else
@@ -327,7 +385,7 @@ async function collect(ctx, mode, file) {
327
385
  projects[unit.path] = entry;
328
386
  }
329
387
  writeFileSync(file, JSON.stringify({ version: 1, mode, sha, projects }));
330
- ctx.out(`tslaws: ran the laws of ${active.length} project${active.length === 1 ? '' : 's'}; results are in ${file}\n`);
388
+ ctx.out(`tslaws: ran the laws of ${targets.length} project${targets.length === 1 ? '' : 's'}; results are in ${file}\n`);
331
389
  return 0;
332
390
  }
333
391
  async function report(ctx) {
@@ -845,7 +903,9 @@ async function merge(ctx) {
845
903
  }
846
904
  const eventName = ctx.env.GITHUB_EVENT_NAME;
847
905
  if (eventName !== undefined && eventName !== 'push' && eventName !== 'workflow_dispatch') {
848
- ctx.err('tslaws: merge runs on push and workflow_dispatch only\n');
906
+ ctx.err(eventName === 'merge_group'
907
+ ? 'tslaws: merge runs on push and workflow_dispatch only; use --results-out on merge_group to run the laws ahead of the push\n'
908
+ : 'tslaws: merge runs on push and workflow_dispatch only\n');
849
909
  return 1;
850
910
  }
851
911
  // On demand there is no push and no pull request, so whoever started the run is the authority, and only someone