@smoothbricks/nx-plugin 0.4.29 → 0.4.30

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 (95) hide show
  1. package/README.md +83 -15
  2. package/dist/bin/smoo-nx-test-clocks.d.ts +3 -0
  3. package/dist/bin/smoo-nx-test-clocks.d.ts.map +1 -0
  4. package/dist/bin/smoo-nx-test-clocks.js +28 -0
  5. package/dist/bounded-test-policy.d.ts +1 -8
  6. package/dist/bounded-test-policy.d.ts.map +1 -1
  7. package/dist/bounded-test-policy.js +2 -8
  8. package/dist/cargo-closure-input.d.ts +11 -0
  9. package/dist/cargo-closure-input.d.ts.map +1 -1
  10. package/dist/cargo-closure-input.js +16 -6
  11. package/dist/ensure-built-receipt.d.ts +8 -2
  12. package/dist/ensure-built-receipt.d.ts.map +1 -1
  13. package/dist/ensure-built-receipt.js +45 -13
  14. package/dist/ensure-built-witness.d.ts +40 -4
  15. package/dist/ensure-built-witness.d.ts.map +1 -1
  16. package/dist/ensure-built-witness.js +68 -15
  17. package/dist/ensure-built.d.ts.map +1 -1
  18. package/dist/ensure-built.js +11 -3
  19. package/dist/executors/bounded-exec/cpu-pool.d.ts +7 -3
  20. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -1
  21. package/dist/executors/bounded-exec/cpu-pool.js +9 -4
  22. package/dist/executors/bounded-exec/executor.d.ts +1 -1
  23. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  24. package/dist/executors/bounded-exec/executor.js +35 -12
  25. package/dist/executors/bounded-exec/no-space.d.ts +8 -0
  26. package/dist/executors/bounded-exec/no-space.d.ts.map +1 -0
  27. package/dist/executors/bounded-exec/no-space.js +31 -0
  28. package/dist/executors/bounded-exec/ram-temp.d.ts +3 -0
  29. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -1
  30. package/dist/executors/bounded-exec/ram-temp.js +15 -4
  31. package/dist/executors/bounded-exec/verdict.d.ts +34 -4
  32. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -1
  33. package/dist/executors/bounded-exec/verdict.js +54 -3
  34. package/dist/graph-input-contract.d.ts +4 -0
  35. package/dist/graph-input-contract.d.ts.map +1 -1
  36. package/dist/graph-input-contract.js +17 -4
  37. package/dist/owned-installation.d.ts +14 -0
  38. package/dist/owned-installation.d.ts.map +1 -0
  39. package/dist/owned-installation.js +324 -0
  40. package/dist/producer-receipts.d.ts.map +1 -1
  41. package/dist/producer-receipts.js +15 -10
  42. package/dist/test-backstop.d.ts +9 -0
  43. package/dist/test-backstop.d.ts.map +1 -0
  44. package/dist/test-backstop.js +10 -0
  45. package/dist/test-clock-policy.d.ts +30 -0
  46. package/dist/test-clock-policy.d.ts.map +1 -0
  47. package/dist/test-clock-policy.js +686 -0
  48. package/dist/testing.d.ts.map +1 -1
  49. package/dist/testing.js +8 -1
  50. package/managed/raw/tooling/direnv/developer-links.ts +1 -8
  51. package/managed/raw/tooling/direnv/setup-environment.ts +0 -1
  52. package/package.json +15 -4
  53. package/src/__tests__/cargo-closure-fixture.ts +113 -0
  54. package/src/__tests__/counted-cargo.ts +8 -25
  55. package/src/__tests__/directory-change.ts +27 -0
  56. package/src/__tests__/owned-installation.ts +4 -164
  57. package/src/__tests__/past-tick.ts +12 -0
  58. package/src/bin/smoo-nx-test-clocks.ts +29 -0
  59. package/src/bounded-test-policy.ts +2 -8
  60. package/src/cargo-closure-input.property.test.ts +50 -0
  61. package/src/cargo-closure-input.test.ts +15 -112
  62. package/src/cargo-closure-input.ts +23 -6
  63. package/src/cargo-closure-key.test.ts +239 -0
  64. package/src/cargo-resolve-cache.test.ts +29 -7
  65. package/src/ensure-built-receipt.ts +56 -13
  66. package/src/ensure-built-witness.test.ts +113 -4
  67. package/src/ensure-built-witness.ts +75 -16
  68. package/src/ensure-built.test.ts +74 -2
  69. package/src/ensure-built.ts +13 -2
  70. package/src/executors/bounded-exec/cpu-pool.test.ts +18 -0
  71. package/src/executors/bounded-exec/cpu-pool.ts +10 -4
  72. package/src/executors/bounded-exec/disk-lease.test.ts +47 -13
  73. package/src/executors/bounded-exec/executor-host.test.ts +23 -11
  74. package/src/executors/bounded-exec/executor.test.ts +189 -63
  75. package/src/executors/bounded-exec/executor.ts +36 -11
  76. package/src/executors/bounded-exec/hang-diagnostics.test.ts +14 -8
  77. package/src/executors/bounded-exec/no-space.ts +40 -0
  78. package/src/executors/bounded-exec/ram-temp-host.test.ts +9 -8
  79. package/src/executors/bounded-exec/ram-temp.test.ts +32 -18
  80. package/src/executors/bounded-exec/ram-temp.ts +17 -4
  81. package/src/executors/bounded-exec/verdict.test.ts +125 -25
  82. package/src/executors/bounded-exec/verdict.ts +78 -3
  83. package/src/graph-input-contract.test.ts +8 -0
  84. package/src/graph-input-contract.ts +26 -4
  85. package/src/nextest-extraction.test.ts +114 -4
  86. package/src/nx-daemon-claim.test.ts +5 -3
  87. package/src/nx-daemon-idle-policy.test.ts +22 -18
  88. package/src/nx-daemon-validity.test.ts +5 -13
  89. package/src/owned-installation.ts +174 -0
  90. package/src/producer-receipts.ts +15 -10
  91. package/src/test-backstop.ts +11 -0
  92. package/src/test-clock-policy.test.ts +338 -0
  93. package/src/test-clock-policy.ts +708 -0
  94. package/src/testing.ts +8 -1
  95. package/test-timings.json +3 -0
@@ -0,0 +1,686 @@
1
+ // TEST-CLOCK-ORACLE: a test's duration is a property of its work, not of the host. Bun legs delete the runner's
2
+ // per-test deadline with `--timeout=0`, the leg's no-progress bound (`BOUNDED_TEST_IDLE_TIMEOUT_MS`) is the only bound
3
+ // that decides a hang, and a test waits for the event it is waiting for however long a loaded host makes the work take
4
+ // (README "Bounded Test Targets"; specs/cowshed/08_testing.md). Within test code this refuses four kinds:
5
+ // - runner-deadline: a deadline handed to the test runner (`test(name, fn, 60_000)`, `{ timeout }`,
6
+ // `setDefaultTimeout`). It is deleted and nothing takes its place.
7
+ // - test-deadline: the Rust test's own deadline, a `recv_timeout`, `park_timeout` or `timeout` bounded by a literal
8
+ // below the backstop whose expiry fails the case (`.expect`/`.unwrap`). A quiet window (`.await.is_err()`) passes.
9
+ // - clock-delta (class A): an assertion that elapsed host time stays under a bound, `expect(Date.now() - t)
10
+ // .toBeLessThan(N)` or `assert!(started.elapsed() < d)`, which a loaded host breaks while the work is unchanged.
11
+ // Clock values are typed as a reading, a reading moved by a fixed span (a deadline) or time passed, so a lower bound
12
+ // (the wait really waited), ordering against a product timestamp, an epoch stamp, CPU time and an injected clock
13
+ // (`timer.now()`, `clock.elapsed()`) pass.
14
+ // - clocked-bound (class D): a literal product bound below the no-progress backstop in a case whose stand-in a timer or
15
+ // sleep ends before that backstop, so the bound races the stand-in's clock. A bound that is the case's subject with
16
+ // the event that would beat it held off by construction (a child that never answers, or one held at or past the
17
+ // backstop such as `exec sleep 3600`), 0 (disabled), or at the backstop passes.
18
+ // Callers choose the files and, for a diff-scoped check, the changed line ranges: a site is judged when the test case
19
+ // holding it overlaps a change (the whole case, so an edit cannot retain its old site), or, outside any case, when its
20
+ // own line changed. Existing sites therefore need no allowance table. Paused tokio time (`tokio::time::pause()`,
21
+ // `start_paused = true`) is virtual, so a Rust fn using it is not examined.
22
+ //
23
+ // What it cannot do. It stops new sites and removes none: a case nobody edits keeps its elapsed bound, its deadline
24
+ // and its racing bound until a migration touches it. It does not see: a bound passed positionally
25
+ // (`collect(child, 750)`) or held in a constant declared outside the case; a stand-in timer in another file or written
26
+ // by a helper; a bound below the backstop beside real work that no timer delays, which reads exactly like a subject
27
+ // bound whose event is held off by construction; a host clock read through a helper (`elapsedSince(t)`) or a struct
28
+ // field; a deadline enforced by `if (…) throw` or a `while` condition, which it reads as a hang guard, although
29
+ // `assert!(Instant::now() < deadline)` is refused; a Rust deadline in a socket option (`set_read_timeout`),
30
+ // `libc::poll`, a `Duration` held in a variable, or one whose expiry is matched rather than unwrapped; a Rust runner
31
+ // deadline (nextest's slow-timeout is configuration); timer waits themselves (`Bun.sleep` in a test); clock assertions
32
+ // in Python or shell.
33
+ import { existsSync, readFileSync } from 'node:fs';
34
+ import { extname, join } from 'node:path';
35
+ import ts from 'typescript';
36
+ import { BOUNDED_TEST_IDLE_TIMEOUT_MS } from './bounded-test-policy.js';
37
+ import { TEST_PATH, testCases } from './test-walk-policy.js';
38
+ export const TEST_CLOCK_ORACLE = {
39
+ id: 'TEST-CLOCK-ORACLE',
40
+ /** The leg's no-progress backstop: a bound at or above it, or 0 (disabled), cannot decide a case. */
41
+ backstopMs: BOUNDED_TEST_IDLE_TIMEOUT_MS,
42
+ message: {
43
+ 'runner-deadline': 'tests must not carry a per-test deadline',
44
+ 'test-deadline': 'a test-owned deadline decides the case',
45
+ 'clock-delta': 'tests must not bound elapsed host time',
46
+ 'clocked-bound': 'a configured bound races a stand-in that a timer ends',
47
+ },
48
+ help: {
49
+ 'runner-deadline': "Delete the deadline and put nothing in its place: every bun leg runs with --timeout=0 and the leg's " +
50
+ 'no-progress bound is the only bound that decides a hang.',
51
+ 'test-deadline': "Wait for the event itself: the leg's no-progress bound is the only bound that decides a hang. Assert a quiet " +
52
+ 'window with `.is_err()`, or advance virtual time with `tokio::time::pause()`.',
53
+ 'clock-delta': 'Elapsed time on a loaded host measures the host, not the work. Assert the order of events or the work done; ' +
54
+ 'time-dependent behavior uses an injected clock and asserts its readings.',
55
+ 'clocked-bound': "A bound a test configures is the case's subject, with the event that would beat it held off by construction " +
56
+ '(a child that never answers, a stand-in that never writes readiness), or it cannot decide: disabled, or at ' +
57
+ "the leg's no-progress backstop (BOUNDED_TEST_IDLE_TIMEOUT_MS). A stand-in that a timer or sleep ends races " +
58
+ 'the bound on a loaded host.',
59
+ },
60
+ };
61
+ const JS_EXTENSION = /^\.(?:[cm]?[jt]sx?)$/u;
62
+ /** A call that sleeps: the stand-in sleeps a child or helper runs. */
63
+ const SLEEP_CALL = /(?:\bBun\.sleep(?:Sync)?|\b(?:std::)?thread::sleep|\btokio::time::sleep|\b(?:asyncio|time)\.sleep|\bThread\.sleep|(?<![.\w])(?:sleep|sleep_for|sleep_until|usleep)|\b\w+\.waitForTimeout)\s*\(/u;
64
+ /** A call that arms a timer. */
65
+ const TIMER_CALL_PATTERN = /(?:(?<![.\w])(?:setTimeout|setInterval)|\b(?:globalThis|window)\.(?:setTimeout|setInterval))\s*\(/u;
66
+ /** A call that sleeps or arms a timer. */
67
+ const TIMER_CALL = new RegExp(`${SLEEP_CALL.source}|${TIMER_CALL_PATTERN.source}`, 'u');
68
+ /** Source text of a stand-in that a timer or sleep ends: a call, a child's `-e` script, a shell line, an argv `sleep`. */
69
+ const TIMED_STAND_IN = new RegExp(`${TIMER_CALL.source}|${/(?:^|[;&|\n"'`(]|\bexec)\s*sleep\s+(?:\d|["'$])|["'`]sleep["'`]/u.source}`, 'gu');
70
+ /** A span written as a number or one constant operation on two (`5000`, `1 << 30`, `2 ** 31`, `60 * 1000`). */
71
+ function spanValue(text) {
72
+ const operation = /^\s*(\d[\d_]*(?:\.\d+)?)\s*(?:(<<|\*\*|\*)\s*(\d[\d_]*(?:\.\d+)?))?\s*$/u.exec(text);
73
+ if (operation === null)
74
+ return undefined;
75
+ const left = Number((operation[1] ?? '').replaceAll('_', ''));
76
+ const right = Number((operation[3] ?? '').replaceAll('_', ''));
77
+ switch (operation[2]) {
78
+ case '<<':
79
+ return left * 2 ** right;
80
+ case '**':
81
+ return left ** right;
82
+ case '*':
83
+ return left * right;
84
+ default:
85
+ return left;
86
+ }
87
+ }
88
+ /** The span of the timer or sleep starting `text`, in milliseconds, when its source states one. */
89
+ function timerSpanMs(text) {
90
+ const shell = /^(?:[;&|\n"'`(]|exec)?\s*sleep\s+(\d+(?:\.\d+)?)([smhd]?)(?![\w.])/u.exec(text);
91
+ if (shell !== null)
92
+ return Number(shell[1]) * 1000 * ({ m: 60, h: 3600, d: 86_400 }[shell[2] ?? ''] ?? 1);
93
+ const argv = /^["'`]sleep["'`]\s*(?:,|\)\s*\.arg\()\s*["'`](\d+(?:\.\d+)?)["'`]/u.exec(text);
94
+ if (argv !== null)
95
+ return Number(argv[1]) * 1000;
96
+ const timer = /^(?:(?:globalThis|window)\.)?set(?:Timeout|Interval)\s*\([^;]*?,\s*([^,()]+?)\s*\)/u.exec(text.slice(0, 400));
97
+ if (timer !== null)
98
+ return spanValue(timer[1] ?? '');
99
+ const bun = /^Bun\.sleep(?:Sync)?\s*\(([^()]+)\)/u.exec(text);
100
+ if (bun !== null)
101
+ return spanValue(bun[1] ?? '');
102
+ const seconds = /^(?:asyncio|time)\.sleep\s*\(\s*(\d+(?:\.\d+)?)\s*\)/u.exec(text);
103
+ if (seconds !== null)
104
+ return Number(seconds[1]) * 1000;
105
+ const rust = /^(?:(?:std::)?thread|tokio::time)::sleep\s*\(\s*(?:std::time::)?Duration::from_(secs|millis)\s*\(\s*(\d[\d_]*)\s*\)\s*\)/u.exec(text);
106
+ if (rust !== null)
107
+ return Number((rust[2] ?? '').replaceAll('_', '')) * (rust[1] === 'secs' ? 1000 : 1);
108
+ return undefined;
109
+ }
110
+ /**
111
+ * Whether source text holds a stand-in whose timer can beat a bound before the leg's backstop. A one-shot timer or
112
+ * sleep ends or advances its stand-in when it fires. A repeating timer never ends one, so it races only a progress
113
+ * (idle) bound, and only when its callback does something. A span at or past the backstop (`exec sleep 3600`,
114
+ * `setInterval(() => {}, 1 << 30)`) outlasts the leg, so its stand-in is held off as surely as a child that never
115
+ * answers; an unstated span races.
116
+ */
117
+ function racesBound(text, idle) {
118
+ for (const match of text.matchAll(TIMED_STAND_IN)) {
119
+ const at = text.slice(match.index);
120
+ const repeating = /^(?:(?:globalThis|window)\.)?setInterval\s*\(/u.exec(at);
121
+ if (repeating !== null && (!idle || /^\s*\(\s*\)\s*=>\s*\{\s*\}\s*,/u.test(at.slice(repeating[0].length))))
122
+ continue;
123
+ const ms = timerSpanMs(at);
124
+ if (ms === undefined || ms < TEST_CLOCK_ORACLE.backstopMs)
125
+ return true;
126
+ }
127
+ return false;
128
+ }
129
+ /** A liveness bound by name: any timeout or deadline, or a grace, kill, budget or idle span carrying a time unit. */
130
+ function boundName(name) {
131
+ return (/time_?out|deadline/iu.test(name) ||
132
+ (/grace|kill_?after|budget|idle/iu.test(name) && /(?:ms|millis|milliseconds|seconds?|secs?)$/iu.test(name)));
133
+ }
134
+ /** A bound's value in milliseconds from its name's unit; one that is 0 or at the backstop cannot decide a case. */
135
+ function decides(name, value) {
136
+ const ms = /(?:seconds?|secs?|_s)$/iu.test(name) ? value * 1000 : value;
137
+ return ms > 0 && ms < TEST_CLOCK_ORACLE.backstopMs;
138
+ }
139
+ /** `--timeout=100`, `--idle-timeout 5s`, `--deadline-ms=50` inside a command string. */
140
+ const FLAG_BOUND = /--[\w-]*(?:timeout|deadline)[\w-]*[= ](\d[\d_]*(?:\.\d+)?)(ms|s)?\b/giu;
141
+ const CLOCK_RANK = { instant: 1, deadline: 2, duration: 3 };
142
+ function strongest(clocks) {
143
+ let found;
144
+ for (const clock of clocks)
145
+ if (clock !== undefined && (found === undefined || CLOCK_RANK[clock] > CLOCK_RANK[found]))
146
+ found = clock;
147
+ return found;
148
+ }
149
+ /**
150
+ * Whether asserting `lower` below `upper` bounds host time: a duration under any bound, or a reading under a deadline.
151
+ * A duration over a bound (the wait really waited) and a reading below a product timestamp (ordering) do not.
152
+ */
153
+ function boundsHostTime(lower, upper) {
154
+ return lower === 'duration' || (lower === 'instant' && upper === 'deadline');
155
+ }
156
+ function literalNumber(node) {
157
+ if (ts.isNumericLiteral(node))
158
+ return Number(node.text);
159
+ if (ts.isParenthesizedExpression(node))
160
+ return literalNumber(node.expression);
161
+ if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken) {
162
+ const value = literalNumber(node.operand);
163
+ return value === undefined ? undefined : -value;
164
+ }
165
+ if (!ts.isBinaryExpression(node))
166
+ return undefined;
167
+ const [left, right] = [literalNumber(node.left), literalNumber(node.right)];
168
+ if (left === undefined || right === undefined)
169
+ return undefined;
170
+ switch (node.operatorToken.kind) {
171
+ case ts.SyntaxKind.AsteriskToken:
172
+ return left * right;
173
+ case ts.SyntaxKind.SlashToken:
174
+ return left / right;
175
+ case ts.SyntaxKind.PlusToken:
176
+ return left + right;
177
+ case ts.SyntaxKind.MinusToken:
178
+ return left - right;
179
+ default:
180
+ return undefined;
181
+ }
182
+ }
183
+ const CLOCK_READ = /^(?:Date\.now|performance\.now|Bun\.nanoseconds|process\.hrtime\.bigint)$/u;
184
+ const COMPARISON = {
185
+ [ts.SyntaxKind.LessThanToken]: 'below',
186
+ [ts.SyntaxKind.LessThanEqualsToken]: 'below',
187
+ [ts.SyntaxKind.GreaterThanToken]: 'above',
188
+ [ts.SyntaxKind.GreaterThanEqualsToken]: 'above',
189
+ };
190
+ const ORDER_MATCHER = /^toBe(Less|Greater)Than(?:OrEqual)?$/u;
191
+ const TRUTH_MATCHER = /^to(?:Be|Equal|StrictEqual)$/u;
192
+ const CASE_CALLEE = /^(?:test|it)(?:\.\w+)*$/u;
193
+ /** A harness that runs its callback on faked timers: `onProgressClock`, `withFakeClock`, `underMemoryTimer`. */
194
+ const VIRTUAL_CLOCK_CALL = /^(?:on|with|under)\w*(?:Clock|Timers?)$/u;
195
+ /** Class A and class D sites of one TypeScript/JavaScript test file. */
196
+ function jsClockSites(parsed) {
197
+ const sites = [];
198
+ const site = (node, kind) => {
199
+ sites.push({ kind, offset: node.getStart(parsed), text: node.getText(parsed) });
200
+ };
201
+ // Lexical scopes of the names bound to a host clock value; an inner declaration or parameter shadows an outer one.
202
+ const scopes = [new Map()];
203
+ const lookup = (name) => {
204
+ for (let index = scopes.length - 1; index >= 0; index -= 1) {
205
+ const scope = scopes[index];
206
+ if (scope?.has(name))
207
+ return scope.get(name);
208
+ }
209
+ return undefined;
210
+ };
211
+ const clockOf = (node) => {
212
+ if (ts.isParenthesizedExpression(node) ||
213
+ ts.isAsExpression(node) ||
214
+ ts.isNonNullExpression(node) ||
215
+ ts.isSatisfiesExpression(node) ||
216
+ ts.isTypeAssertionExpression(node) ||
217
+ ts.isElementAccessExpression(node))
218
+ return clockOf(node.expression);
219
+ if (ts.isIdentifier(node))
220
+ return lookup(node.text);
221
+ if (ts.isNewExpression(node))
222
+ return ts.isIdentifier(node.expression) && node.expression.text === 'Date' && !node.arguments?.length
223
+ ? 'instant'
224
+ : undefined;
225
+ if (ts.isPrefixUnaryExpression(node))
226
+ return clockOf(node.operand);
227
+ if (ts.isConditionalExpression(node))
228
+ return strongest([clockOf(node.whenTrue), clockOf(node.whenFalse)]);
229
+ if (ts.isCallExpression(node)) {
230
+ const callee = node.expression.getText(parsed);
231
+ if (CLOCK_READ.test(callee))
232
+ return 'instant';
233
+ if (callee === 'process.hrtime')
234
+ return node.arguments.length === 0 ? 'instant' : 'duration';
235
+ if (ts.isPropertyAccessExpression(node.expression) && /^(?:getTime|valueOf)$/u.test(node.expression.name.text))
236
+ return clockOf(node.expression.expression);
237
+ if (/^(?:Math\.\w+|Number|BigInt)$/u.test(callee))
238
+ return strongest(node.arguments.map(clockOf));
239
+ return undefined;
240
+ }
241
+ if (!ts.isBinaryExpression(node))
242
+ return undefined;
243
+ const [left, right] = [clockOf(node.left), clockOf(node.right)];
244
+ switch (node.operatorToken.kind) {
245
+ case ts.SyntaxKind.MinusToken:
246
+ if (left === 'duration' || right === 'duration')
247
+ return 'duration';
248
+ if (left === undefined && right === undefined)
249
+ return undefined;
250
+ // A reading less a fixed span is still a moment; a reading less anything else is time passed.
251
+ return right === undefined && literalNumber(node.right) !== undefined ? 'deadline' : 'duration';
252
+ case ts.SyntaxKind.PlusToken:
253
+ if (left === 'duration' || right === 'duration')
254
+ return 'duration';
255
+ return left === undefined && right === undefined ? undefined : 'deadline';
256
+ case ts.SyntaxKind.AsteriskToken:
257
+ case ts.SyntaxKind.SlashToken:
258
+ case ts.SyntaxKind.PercentToken:
259
+ return strongest([left, right]);
260
+ case ts.SyntaxKind.CommaToken:
261
+ return right;
262
+ default:
263
+ return undefined;
264
+ }
265
+ };
266
+ // Whether an assertion over `node` asserts a comparison that bounds host time; `negated` when it asserts the
267
+ // comparison's negation. Nested functions are not the assertion's own comparison.
268
+ const comparesHostTime = (node, negated) => {
269
+ if (ts.isFunctionLike(node))
270
+ return false;
271
+ if (ts.isBinaryExpression(node)) {
272
+ const direction = COMPARISON[node.operatorToken.kind];
273
+ if (direction !== undefined) {
274
+ const [lower, upper] = (direction === 'below') !== negated ? [node.left, node.right] : [node.right, node.left];
275
+ return boundsHostTime(clockOf(lower), clockOf(upper));
276
+ }
277
+ }
278
+ if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.ExclamationToken)
279
+ return comparesHostTime(node.operand, !negated);
280
+ return ts.forEachChild(node, (child) => comparesHostTime(child, negated) || undefined) ?? false;
281
+ };
282
+ const expectation = (call) => {
283
+ if (!ts.isPropertyAccessExpression(call.expression))
284
+ return undefined;
285
+ let negated = false;
286
+ let receiver = call.expression.expression;
287
+ while (ts.isPropertyAccessExpression(receiver) && receiver.name.text === 'not') {
288
+ negated = !negated;
289
+ receiver = receiver.expression;
290
+ }
291
+ if (!ts.isCallExpression(receiver) || !ts.isIdentifier(receiver.expression))
292
+ return undefined;
293
+ const subject = receiver.arguments[0];
294
+ if (receiver.expression.text !== 'expect' || subject === undefined)
295
+ return undefined;
296
+ return { subject, negated, matcher: call.expression.name.text };
297
+ };
298
+ const assertsHostTime = (call) => {
299
+ const expected = expectation(call);
300
+ const argument = call.arguments[0];
301
+ if (expected === undefined) {
302
+ let root = call.expression;
303
+ while (ts.isPropertyAccessExpression(root))
304
+ root = root.expression;
305
+ return (ts.isIdentifier(root) &&
306
+ /^(?:assert\w*|ok)$/u.test(root.text) &&
307
+ call.arguments.some((each) => comparesHostTime(each, false)));
308
+ }
309
+ const { subject, negated, matcher } = expected;
310
+ const order = ORDER_MATCHER.exec(matcher);
311
+ if (order !== null && argument !== undefined) {
312
+ const [lower, upper] = (order[1] === 'Less') !== negated ? [subject, argument] : [argument, subject];
313
+ return boundsHostTime(clockOf(lower), clockOf(upper));
314
+ }
315
+ if (matcher === 'toBeCloseTo' && argument !== undefined)
316
+ return clockOf(subject) !== undefined || clockOf(argument) !== undefined;
317
+ const truth = matcher === 'toBeTruthy' || matcher === 'toBeTrue'
318
+ ? true
319
+ : matcher === 'toBeFalsy' || matcher === 'toBeFalse'
320
+ ? false
321
+ : TRUTH_MATCHER.test(matcher) && argument?.kind === ts.SyntaxKind.TrueKeyword
322
+ ? true
323
+ : TRUTH_MATCHER.test(matcher) && argument?.kind === ts.SyntaxKind.FalseKeyword
324
+ ? false
325
+ : undefined;
326
+ return truth !== undefined && comparesHostTime(subject, truth === negated);
327
+ };
328
+ // Top-level string constants a case may hand a child as its source (`const SLOW_TEST = \`…setTimeout(r, 5000)…\``).
329
+ const constants = new Map();
330
+ for (const statement of parsed.statements) {
331
+ if (!ts.isVariableStatement(statement))
332
+ continue;
333
+ for (const declaration of statement.declarationList.declarations) {
334
+ const value = declaration.initializer;
335
+ if (ts.isIdentifier(declaration.name) && value !== undefined && ts.isStringLiteralLike(value))
336
+ constants.set(declaration.name.text, value.getText(parsed));
337
+ if (ts.isIdentifier(declaration.name) && value !== undefined && ts.isTemplateExpression(value))
338
+ constants.set(declaration.name.text, value.getText(parsed));
339
+ }
340
+ }
341
+ // What the stand-ins under `scope` do to a bound: none is there, every one is held off, or one races it.
342
+ const standIns = (scope, idle) => {
343
+ let found = false;
344
+ const visit = (node) => {
345
+ const text = ts.isStringLiteralLike(node) || ts.isTemplateExpression(node)
346
+ ? node.getText(parsed)
347
+ : ts.isCallExpression(node) && TIMER_CALL.test(`${node.expression.getText(parsed)}(`)
348
+ ? node.getText(parsed)
349
+ : ts.isIdentifier(node)
350
+ ? constants.get(node.text)
351
+ : undefined;
352
+ if (text !== undefined && text.search(TIMED_STAND_IN) !== -1) {
353
+ found = true;
354
+ if (racesBound(text, idle))
355
+ return true;
356
+ }
357
+ return ts.forEachChild(node, (child) => visit(child) || undefined) ?? false;
358
+ };
359
+ return visit(scope) ? 'races' : found ? 'held' : 'none';
360
+ };
361
+ // The case a bound belongs to: its enclosing `test`/`it` call, else its function, else the file.
362
+ const owner = (node) => {
363
+ let fn;
364
+ for (let up = node.parent; up !== undefined; up = up.parent) {
365
+ if (ts.isCallExpression(up) && CASE_CALLEE.test(up.expression.getText(parsed)))
366
+ return up;
367
+ if (fn === undefined && ts.isFunctionLike(up))
368
+ fn = up;
369
+ }
370
+ return fn ?? parsed;
371
+ };
372
+ const bounds = [];
373
+ const runnerOptions = new Set();
374
+ const visit = (node) => {
375
+ const opens = node !== parsed && (ts.isFunctionLike(node) || ts.isBlock(node));
376
+ if (opens)
377
+ scopes.push(new Map());
378
+ if (ts.isFunctionLike(node))
379
+ for (const parameter of node.parameters)
380
+ if (ts.isIdentifier(parameter.name))
381
+ scopes.at(-1)?.set(parameter.name.text, undefined);
382
+ if (ts.isCallExpression(node) && assertsHostTime(node))
383
+ site(node, 'clock-delta');
384
+ if (ts.isCallExpression(node)) {
385
+ // `test(name, fn, 60_000)`, `test(name, fn, { timeout })`, `test.each(table)(name, fn, n)`, `setDefaultTimeout(n)`.
386
+ const callee = node.expression;
387
+ const runner = CASE_CALLEE.test(callee.getText(parsed)) ||
388
+ (ts.isCallExpression(callee) && /^(?:test|it)(?:\.\w+)*\.each$/u.test(callee.expression.getText(parsed)));
389
+ const body = node.arguments.findIndex((each) => ts.isArrowFunction(each) || ts.isFunctionExpression(each));
390
+ if (runner && body !== -1)
391
+ for (const option of node.arguments.slice(body + 1))
392
+ if (literalNumber(option) !== undefined ||
393
+ (ts.isObjectLiteralExpression(option) &&
394
+ option.properties.some((each) => each.name?.getText(parsed) === 'timeout'))) {
395
+ runnerOptions.add(option);
396
+ site(option, 'runner-deadline');
397
+ }
398
+ if (/^(?:setDefaultTimeout|jest\.setTimeout)$/u.test(callee.getText(parsed)))
399
+ site(node, 'runner-deadline');
400
+ }
401
+ // A runner's own `{ timeout }` is a runner deadline above, never also a product bound.
402
+ if ((ts.isPropertyAssignment(node) && !runnerOptions.has(node.parent)) || ts.isVariableDeclaration(node)) {
403
+ const name = ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : node.name.getText(parsed);
404
+ const value = node.initializer === undefined ? undefined : literalNumber(node.initializer);
405
+ if (boundName(name) && value !== undefined && decides(name, value))
406
+ bounds.push({ node, idle: /idle/iu.test(name) });
407
+ }
408
+ if (ts.isStringLiteralLike(node) || ts.isTemplateExpression(node)) {
409
+ for (const flag of node.getText(parsed).matchAll(FLAG_BOUND)) {
410
+ const value = Number((flag[1] ?? '').replaceAll('_', ''));
411
+ if (decides(flag[2] === 's' ? 'seconds' : 'ms', value))
412
+ bounds.push({ node, idle: /idle/iu.test(flag[0]) });
413
+ }
414
+ }
415
+ ts.forEachChild(node, visit);
416
+ // A declaration binds after its initializer is read; an assignment rebinds the nearest declaration.
417
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name))
418
+ scopes.at(-1)?.set(node.name.text, node.initializer === undefined ? undefined : clockOf(node.initializer));
419
+ if (ts.isBinaryExpression(node) &&
420
+ node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
421
+ ts.isIdentifier(node.left)) {
422
+ const name = node.left.text;
423
+ for (let index = scopes.length - 1; index >= 0; index -= 1) {
424
+ const scope = scopes[index];
425
+ if (scope?.has(name)) {
426
+ scope.set(name, clockOf(node.right));
427
+ break;
428
+ }
429
+ }
430
+ }
431
+ if (opens)
432
+ scopes.pop();
433
+ };
434
+ visit(parsed);
435
+ // A bound is judged against the stand-ins of the call it configures when that call names any (`verdictOf(command,
436
+ // { idleTimeoutMs })`), else against its case's: one case may hold a talking child under a ceiling and a silent one
437
+ // under a progress bound. A value an assertion expects (`toMatchObject({ idleMs: 400 })`) configures nothing, and a
438
+ // bound run under faked timers (`jest.useFakeTimers()` in its case, or inside a clock harness such as
439
+ // `onProgressClock(moves, step, run)`) expires only when the test moves the clock.
440
+ const reported = new Set();
441
+ for (const { node, idle } of bounds) {
442
+ if (reported.has(node))
443
+ continue;
444
+ let call;
445
+ let virtual = false;
446
+ for (let up = node.parent; up !== undefined; up = up.parent) {
447
+ if (!ts.isCallExpression(up))
448
+ continue;
449
+ call ??= up;
450
+ const callee = up.expression.getText(parsed);
451
+ if (VIRTUAL_CLOCK_CALL.test(callee.slice(callee.lastIndexOf('.') + 1)))
452
+ virtual = true;
453
+ }
454
+ const scope = owner(node);
455
+ if (virtual || /\buseFakeTimers\s*\(/u.test(scope.getText(parsed)))
456
+ continue;
457
+ if (call !== undefined && /^expect\s*\(/u.test(call.expression.getText(parsed)))
458
+ continue;
459
+ const near = call === undefined ? 'none' : standIns(call, idle);
460
+ if ((near === 'none' ? standIns(scope, idle) : near) !== 'races')
461
+ continue;
462
+ reported.add(node);
463
+ site(node, 'clocked-bound');
464
+ }
465
+ return sites;
466
+ }
467
+ /**
468
+ * Blank comments and, with `strings`, quoted text, keeping every byte position. A single quote never spans a line, so
469
+ * a Rust lifetime (`&'a str`) masks at most the rest of its own line.
470
+ */
471
+ function maskNative(source, strings) {
472
+ return source.replace(/\/\/[^\n]*|\/\*[\s\S]*?\*\/|"""[\s\S]*?"""|'''[\s\S]*?'''|\br(#*)"[\s\S]*?"\1|"(?:\\[\s\S]|[^"\\])*"|'(?:\\.|[^'\\\n])*'/gu, (text) => (strings || text.startsWith('/') ? text.replace(/[^\r\n]/g, ' ') : text));
473
+ }
474
+ /** Where a native file's test code starts: Rust src/ files are examined only inside their embedded test module. */
475
+ function testCodeStart(masked, file) {
476
+ if (extname(file) !== '.rs' || TEST_PATH.test(file))
477
+ return 0;
478
+ return /#\[cfg\(test\)\][\s\S]*?\bmod\s+tests\s*\{/u.exec(masked)?.index;
479
+ }
480
+ /** The index closing the group opened at `open` in comment/string-masked text. */
481
+ function closingIndex(masked, open) {
482
+ let depth = 0;
483
+ for (let index = open; index < masked.length; index += 1) {
484
+ const char = masked[index];
485
+ if (char === '(' || char === '[' || char === '{')
486
+ depth += 1;
487
+ else if (char === ')' || char === ']' || char === '}') {
488
+ depth -= 1;
489
+ if (depth === 0)
490
+ return index;
491
+ }
492
+ }
493
+ return masked.length;
494
+ }
495
+ /** The host clock value a Rust expression holds, given the `let` bindings of its fn. */
496
+ function rustClock(expression, bindings) {
497
+ // `elapsed`/`duration_since` on a host reading is time passed; on an injected clock (`clock.elapsed()`) it is not,
498
+ // and since `UNIX_EPOCH` it is a timestamp, still a reading.
499
+ for (const call of expression.matchAll(/(\b[a-z_]\w*|\b(?:Instant|SystemTime)::now\s*\(\s*\))\s*\.\s*(?:elapsed|(?:saturating_|checked_)?duration_since)\s*\(/gu)) {
500
+ if (/^\s*(?:std::time::)?(?:SystemTime::)?UNIX_EPOCH\b/u.test(expression.slice(call.index + call[0].length)))
501
+ continue;
502
+ const receiver = call[1] ?? '';
503
+ const held = bindings.get(receiver);
504
+ if (receiver.endsWith(')') || held === 'instant' || held === 'deadline')
505
+ return 'duration';
506
+ }
507
+ const clocks = (text) => strongest([
508
+ /\b(?:Instant|SystemTime)::now\s*\(\s*\)/u.test(text) ? 'instant' : undefined,
509
+ ...Array.from(text.matchAll(/\b[a-z_]\w*\b/gu), (name) => bindings.get(name[0])),
510
+ ]);
511
+ const base = clocks(expression);
512
+ if (base === undefined || base === 'duration')
513
+ return base;
514
+ const minus = /[\w)\]]\s*-(?!>)/u.exec(expression);
515
+ if (minus !== null) {
516
+ // A reading less a reading is time passed; a reading less a `Duration` is still a moment.
517
+ const right = clocks(expression.slice(minus.index + minus[0].length));
518
+ return right === 'instant' || right === 'deadline' ? 'duration' : 'deadline';
519
+ }
520
+ return /[\w)\]]\s*\+/u.test(expression) ? 'deadline' : base;
521
+ }
522
+ /** The first top-level comparison of a Rust assertion's condition, as its asserted lower and upper side. */
523
+ function rustComparison(condition) {
524
+ let depth = 0;
525
+ let angles = 0;
526
+ for (let index = 0; index < condition.length; index += 1) {
527
+ const char = condition[index] ?? '';
528
+ const next = condition[index + 1] ?? '';
529
+ const previous = condition[index - 1] ?? '';
530
+ if ('([{'.includes(char))
531
+ depth += 1;
532
+ else if (')]}'.includes(char))
533
+ depth -= 1;
534
+ if (depth !== 0)
535
+ continue;
536
+ if (char === '<' && condition.slice(index - 2, index) === '::') {
537
+ angles += 1;
538
+ continue;
539
+ }
540
+ if (char === '>' && angles > 0) {
541
+ angles -= 1;
542
+ continue;
543
+ }
544
+ if (char !== '<' && char !== '>')
545
+ continue;
546
+ if (next === char || previous === char || previous === '-' || previous === '=')
547
+ continue;
548
+ const width = next === '=' ? 2 : 1;
549
+ const [left, right] = [condition.slice(0, index), condition.slice(index + width)];
550
+ return char === '<' ? { lower: left, upper: right } : { lower: right, upper: left };
551
+ }
552
+ return undefined;
553
+ }
554
+ /** The text before a group's first top-level comma: an assertion's condition, a call's first argument. */
555
+ function firstArgument(group) {
556
+ let depth = 0;
557
+ for (let index = 0; index < group.length; index += 1) {
558
+ const char = group[index] ?? '';
559
+ if ('([{'.includes(char))
560
+ depth += 1;
561
+ else if (')]}'.includes(char))
562
+ depth -= 1;
563
+ else if (char === ',' && depth === 0)
564
+ return group.slice(0, index);
565
+ }
566
+ return group;
567
+ }
568
+ /** Milliseconds of a `Duration::from_*` unit. */
569
+ const DURATION_MS = { secs: 1000, millis: 1, micros: 1 / 1000, nanos: 1 / 1_000_000 };
570
+ /** Runner deadlines' Rust counterpart, and class A and class D sites, of one Rust file inside its test code. */
571
+ function rustClockSites(source, file) {
572
+ const masked = maskNative(source, true);
573
+ const begin = testCodeStart(masked, file);
574
+ if (begin === undefined)
575
+ return [];
576
+ const commentless = maskNative(source, false);
577
+ const sites = [];
578
+ for (const declaration of masked.slice(begin).matchAll(/\bfn\s+\w+/gu)) {
579
+ const start = begin + declaration.index;
580
+ const open = masked.indexOf('{', start);
581
+ if (open === -1)
582
+ continue;
583
+ const end = closingIndex(masked, open);
584
+ const body = masked.slice(open, end + 1);
585
+ // Paused tokio time is virtual: its `Instant::now()`, `sleep` and `timeout` advance with the test, not the host.
586
+ const attributes = masked.slice(Math.max(begin, start - 300), start);
587
+ if (/\btokio::time::pause\s*\(/u.test(body) || /\bstart_paused\s*=\s*true\b/u.test(attributes))
588
+ continue;
589
+ const bindings = new Map();
590
+ for (const binding of body.matchAll(/\blet\s+(?:mut\s+)?([a-z_]\w*)\s*(?::[^=;]*)?=([^;]*);/gu))
591
+ bindings.set(binding[1] ?? '', rustClock(binding[2] ?? '', bindings));
592
+ // A nested fn is examined as itself and again as part of its enclosing fn; the return keeps one site per offset.
593
+ // A deadline the test owns: a receive, park or `timeout` bounded below the backstop whose expiry fails the case.
594
+ // A quiet window (`timeout(d, f).await.is_err()`) asserts that nothing happened and passes.
595
+ // Anchored at the name (`timeout`, not `tokio::time::`), where a clocked-bound reading of it would start too.
596
+ for (const call of body.matchAll(/\b(?:recv_timeout|park_timeout|timeout)\s*\(/gu)) {
597
+ const opening = open + call.index + call[0].length - 1;
598
+ const closing = closingIndex(masked, opening);
599
+ const span = /^\s*(?:std::time::|core::time::)?Duration::from_(secs|millis|micros|nanos)(?:_f32|_f64)?\s*\(\s*(\d[\d_]*(?:\.\d+)?)\s*\)\s*$/u.exec(firstArgument(masked.slice(opening + 1, closing)));
600
+ const ms = span === null ? undefined : Number((span[2] ?? '').replaceAll('_', '')) * (DURATION_MS[span[1] ?? ''] ?? 1);
601
+ if (ms === undefined || !decides('ms', ms))
602
+ continue;
603
+ if (!/^\s*(?:\.await)?\s*\.(?:expect|unwrap|unwrap_or_else)\b/u.test(masked.slice(closing + 1, closing + 200)))
604
+ continue;
605
+ sites.push({
606
+ kind: 'test-deadline',
607
+ offset: open + call.index,
608
+ text: source.slice(open + call.index, closing + 1),
609
+ });
610
+ }
611
+ for (const assertion of body.matchAll(/\b(?:debug_|prop_)?assert!\s*\(/gu)) {
612
+ const opening = open + assertion.index + assertion[0].length - 1;
613
+ const closing = closingIndex(masked, opening);
614
+ const compared = rustComparison(firstArgument(masked.slice(opening + 1, closing)));
615
+ if (compared !== undefined &&
616
+ boundsHostTime(rustClock(compared.lower, bindings), rustClock(compared.upper, bindings)))
617
+ sites.push({
618
+ kind: 'clock-delta',
619
+ offset: open + assertion.index,
620
+ text: source.slice(open + assertion.index, closing + 1),
621
+ });
622
+ }
623
+ const fnText = commentless.slice(open, end + 1);
624
+ if (fnText.search(TIMED_STAND_IN) === -1)
625
+ continue;
626
+ for (const bound of body.matchAll(/\b([a-z_]\w*)\s*(?::(?!:)|=(?![=>])|\()\s*(?:Duration::from_(secs|millis|micros|nanos)(?:_f32|_f64)?\s*\(\s*)?(\d[\d_]*(?:\.\d+)?)/giu)) {
627
+ const name = bound[1] ?? '';
628
+ const value = Number((bound[3] ?? '').replaceAll('_', ''));
629
+ const unit = bound[2];
630
+ const decided = unit === undefined ? decides(name, value) : decides('ms', value * (DURATION_MS[unit] ?? 1));
631
+ // A `timeout(d, f)` / `recv_timeout(d)` call is the test's own wait, judged above as a test-deadline (a quiet
632
+ // window passes there); only a bound handed to the product is a clocked-bound.
633
+ const deadlineCall = /^(?:recv_timeout|park_timeout|timeout)$/u.test(name) &&
634
+ bound[0].slice(name.length).trimStart().startsWith('(');
635
+ if (deadlineCall || !boundName(name) || !decided || !racesBound(fnText, /idle/iu.test(name)))
636
+ continue;
637
+ const offset = open + bound.index;
638
+ sites.push({ kind: 'clocked-bound', offset, text: source.slice(offset, offset + bound[0].length) });
639
+ }
640
+ }
641
+ // One site per offset, the first found: a test-owned deadline is not also reported as the bound it carries.
642
+ const kept = new Map();
643
+ for (const site of sites)
644
+ if (!kept.has(site.offset))
645
+ kept.set(site.offset, site);
646
+ return [...kept.values()];
647
+ }
648
+ /** Class A and D sites and runner deadlines of one test file, or undefined for a file holding no test code. */
649
+ function clockSites(file, text) {
650
+ if (JS_EXTENSION.test(extname(file)))
651
+ return TEST_PATH.test(file)
652
+ ? jsClockSites(ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true))
653
+ : undefined;
654
+ return extname(file) === '.rs' ? rustClockSites(text, file) : undefined;
655
+ }
656
+ export function findClockOracles(root, files, changes) {
657
+ const found = [];
658
+ for (const file of files) {
659
+ const path = join(root, file);
660
+ if (!existsSync(path))
661
+ continue;
662
+ const text = readFileSync(path, 'utf8');
663
+ const sites = clockSites(file, text);
664
+ if (sites === undefined || sites.length === 0)
665
+ continue;
666
+ const ranges = changes?.get(file);
667
+ const cases = ranges === undefined ? [] : (testCases(file, text) ?? []);
668
+ for (const site of sites.sort((left, right) => left.offset - right.offset)) {
669
+ const prefix = text.slice(0, site.offset);
670
+ const line = prefix.split('\n').length;
671
+ if (ranges !== undefined) {
672
+ const owner = cases.find((test) => test.start <= line && test.end >= line);
673
+ const [start, end] = owner === undefined ? [line, line] : [owner.start, owner.end];
674
+ if (!ranges.some((range) => range.start <= end && range.end >= start))
675
+ continue;
676
+ }
677
+ found.push({ kind: site.kind, file, line, column: site.offset - prefix.lastIndexOf('\n'), text: site.text });
678
+ }
679
+ }
680
+ return found;
681
+ }
682
+ export function formatClockOracle(oracle) {
683
+ return (`error[${TEST_CLOCK_ORACLE.id}]: ${TEST_CLOCK_ORACLE.message[oracle.kind]}: ${oracle.text}\n` +
684
+ ` --> ${oracle.file}:${oracle.line}:${oracle.column}\n` +
685
+ ` = help: ${TEST_CLOCK_ORACLE.help[oracle.kind]}`);
686
+ }