sensorium-trace 0.18.2__py3-none-any.whl
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.
- sensorium/__init__.py +0 -0
- sensorium/__main__.py +4 -0
- sensorium/_c/rt/sensorium_c_rt.c +1446 -0
- sensorium/_typescript/package-lock.json +68 -0
- sensorium/_typescript/package.json +39 -0
- sensorium/_typescript/src/bindings.mjs +792 -0
- sensorium/_typescript/src/cap.mjs +227 -0
- sensorium/_typescript/src/capabilities.mjs +40 -0
- sensorium/_typescript/src/dbg.mjs +348 -0
- sensorium/_typescript/src/escape.mjs +351 -0
- sensorium/_typescript/src/focus.mjs +135 -0
- sensorium/_typescript/src/hook.mjs +127 -0
- sensorium/_typescript/src/index.mjs +1 -0
- sensorium/_typescript/src/naming.mjs +63 -0
- sensorium/_typescript/src/positions.mjs +37 -0
- sensorium/_typescript/src/probe.mjs +246 -0
- sensorium/_typescript/src/qualname.mjs +236 -0
- sensorium/_typescript/src/redact.mjs +711 -0
- sensorium/_typescript/src/register.mjs +15 -0
- sensorium/_typescript/src/resolve.mjs +260 -0
- sensorium/_typescript/src/rt.mjs +798 -0
- sensorium/_typescript/src/setup.mjs +11 -0
- sensorium/_typescript/src/tally.mjs +164 -0
- sensorium/_typescript/src/tasks.mjs +175 -0
- sensorium/_typescript/src/transform.mjs +800 -0
- sensorium/_typescript/src/vite.mjs +99 -0
- sensorium/c/__init__.py +8 -0
- sensorium/c/cc.py +612 -0
- sensorium/c/cli.py +60 -0
- sensorium/c/convert.py +669 -0
- sensorium/c/decode.py +300 -0
- sensorium/c/driver.py +365 -0
- sensorium/c/dwarf.py +706 -0
- sensorium/c/format.py +271 -0
- sensorium/c/pkg.py +187 -0
- sensorium/c/plan.py +277 -0
- sensorium/cli.py +140 -0
- sensorium/driver.py +47 -0
- sensorium/exit.py +33 -0
- sensorium/invocations.py +83 -0
- sensorium/limits.py +253 -0
- sensorium/mcp/__init__.py +0 -0
- sensorium/mcp/audit.py +162 -0
- sensorium/mcp/child.py +240 -0
- sensorium/mcp/cmd.py +101 -0
- sensorium/mcp/jsonrpc.py +172 -0
- sensorium/mcp/result.py +187 -0
- sensorium/mcp/schema.py +390 -0
- sensorium/mcp/server.py +493 -0
- sensorium/mcp/tools.py +299 -0
- sensorium/paths.py +80 -0
- sensorium/query/__init__.py +0 -0
- sensorium/query/caps.py +150 -0
- sensorium/query/dbg_dialects.py +64 -0
- sensorium/query/diff_cmd.py +748 -0
- sensorium/query/diff_notes.py +117 -0
- sensorium/query/exceptions_c.py +263 -0
- sensorium/query/exceptions_cmd.py +788 -0
- sensorium/query/exceptions_group.py +571 -0
- sensorium/query/exceptions_invocation.py +487 -0
- sensorium/query/exceptions_rust.py +683 -0
- sensorium/query/exceptions_typescript.py +688 -0
- sensorium/query/expr.py +606 -0
- sensorium/query/failures_cmd.py +306 -0
- sensorium/query/flow_cmd.py +778 -0
- sensorium/query/flow_report.py +128 -0
- sensorium/query/flow_values.py +195 -0
- sensorium/query/fmt.py +280 -0
- sensorium/query/frame_cmd.py +237 -0
- sensorium/query/grep_cmd.py +156 -0
- sensorium/query/help.py +18 -0
- sensorium/query/info_cmd.py +527 -0
- sensorium/query/info_rust.py +214 -0
- sensorium/query/info_typescript.py +261 -0
- sensorium/query/js_inspect.py +394 -0
- sensorium/query/moves.py +254 -0
- sensorium/query/redact_cmd.py +304 -0
- sensorium/query/refocus_cmd.py +661 -0
- sensorium/query/refocus_env.py +493 -0
- sensorium/query/refocus_facts.py +269 -0
- sensorium/query/refocus_licence.py +187 -0
- sensorium/query/refocus_report.py +327 -0
- sensorium/query/refocus_rust.py +537 -0
- sensorium/query/refocus_threads.py +197 -0
- sensorium/query/refocus_typescript.py +756 -0
- sensorium/query/refocus_world.py +666 -0
- sensorium/query/runs_cmd.py +213 -0
- sensorium/query/rust_debug.py +176 -0
- sensorium/query/sites.py +171 -0
- sensorium/query/tree_cmd.py +511 -0
- sensorium/query/tree_threads.py +168 -0
- sensorium/query/vocab.py +723 -0
- sensorium/query/watch_cmd.py +657 -0
- sensorium/record/__init__.py +0 -0
- sensorium/record/boot.py +797 -0
- sensorium/record/boot_io.py +141 -0
- sensorium/record/budget.py +135 -0
- sensorium/record/capture.py +433 -0
- sensorium/record/children.py +755 -0
- sensorium/record/children_merge.py +179 -0
- sensorium/record/elide.py +55 -0
- sensorium/record/fingerprint.py +26 -0
- sensorium/record/thread_starts.py +261 -0
- sensorium/record/tracer.py +798 -0
- sensorium/record/tracer_exc.py +199 -0
- sensorium/record/tracer_frames.py +618 -0
- sensorium/redact.py +304 -0
- sensorium/redact_content.py +156 -0
- sensorium/redact_key.py +317 -0
- sensorium/redact_store.py +502 -0
- sensorium/redact_values.py +433 -0
- sensorium/store/__init__.py +0 -0
- sensorium/store/db.py +284 -0
- sensorium/store/gc.py +360 -0
- sensorium/store/payloads.py +69 -0
- sensorium/store/reader.py +438 -0
- sensorium/store/writer.py +283 -0
- sensorium/ts/__init__.py +10 -0
- sensorium/ts/build.py +783 -0
- sensorium/ts/cli.py +130 -0
- sensorium/ts/driver.py +472 -0
- sensorium/ts/focus.py +146 -0
- sensorium/ts/harness.py +314 -0
- sensorium/ts/ingest.py +380 -0
- sensorium/ts/invocation.py +252 -0
- sensorium/ts/pkg.py +167 -0
- sensorium/ts/redaction.py +64 -0
- sensorium/ts/spool.py +168 -0
- sensorium/ts/truncation.py +81 -0
- sensorium/ts/wrapper.py +255 -0
- sensorium_trace-0.18.2.dist-info/METADATA +245 -0
- sensorium_trace-0.18.2.dist-info/RECORD +135 -0
- sensorium_trace-0.18.2.dist-info/WHEEL +4 -0
- sensorium_trace-0.18.2.dist-info/entry_points.txt +3 -0
- sensorium_trace-0.18.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,800 @@
|
|
|
1
|
+
// The rewriter. Source text + path + root in; edited text, a source map and a
|
|
2
|
+
// per-file manifest out. Nothing here runs the program and nothing here does I/O.
|
|
3
|
+
//
|
|
4
|
+
// Two properties the whole recorder rests on:
|
|
5
|
+
// * NO edit contains a newline, so every line of the output is the same line
|
|
6
|
+
// of the input and `firstlineno` is the line a human sees (design §3).
|
|
7
|
+
// * Positions come from the consumer's own TypeScript AST, and edits are
|
|
8
|
+
// magic-string splices: closing insertions that land on one offset are made
|
|
9
|
+
// with `prependRight`, which orders them innermost-first.
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
import MagicString from 'magic-string';
|
|
14
|
+
|
|
15
|
+
import { paramNames, receiverName } from './bindings.mjs';
|
|
16
|
+
import { callbackHow, catchHow, deferredExit, finallyCompletes } from './escape.mjs';
|
|
17
|
+
import { specMatches } from './focus.mjs';
|
|
18
|
+
// `positions.mjs` is imported by `probe.mjs` too, and by neither of us at
|
|
19
|
+
// module-evaluation time; the edge into `probe.mjs` below is one-way, which is
|
|
20
|
+
// what `test/graph.test.mjs` holds the whole of `src/` to.
|
|
21
|
+
import { lineOf, terminatorFor } from './positions.mjs';
|
|
22
|
+
import { pairsOf, spliceFocused } from './probe.mjs';
|
|
23
|
+
import { qualnameFor } from './qualname.mjs';
|
|
24
|
+
// `tasks.mjs` names nothing of ours at runtime — only the `Splicer` type, in
|
|
25
|
+
// JSDoc — so this edge is one-way; either way both modules only define.
|
|
26
|
+
import { isTestFile, spliceTaskBoundary } from './tasks.mjs';
|
|
27
|
+
|
|
28
|
+
/** @typedef {typeof import('typescript')} TS */
|
|
29
|
+
/** @typedef {import('typescript').Node} Node */
|
|
30
|
+
/** @typedef {import('typescript').SourceFile} SourceFile */
|
|
31
|
+
/** @typedef {import('typescript').FunctionLikeDeclaration} FunctionLike */
|
|
32
|
+
/** @typedef {'function'|'coroutine'|'generator'|'async_generator'} FrameKind */
|
|
33
|
+
/** @typedef {{qualname: string, line: number, kind: FrameKind, focused: boolean, deferred: boolean}} Site */
|
|
34
|
+
/** @typedef {{qualname: string, line: number, reason: string}} ExcludedSite */
|
|
35
|
+
/** @typedef {{file: string, rel: string, sha256: string, instrumented: Site[], focused: string[], excluded: Record<string, number>, diagnostics?: string[]}} Manifest */
|
|
36
|
+
|
|
37
|
+
/** Extensions the recorder can instrument; CommonJS is counted, never transformed. */
|
|
38
|
+
const ELIGIBLE = new Set(['.ts', '.tsx', '.mts', '.js', '.jsx', '.mjs']);
|
|
39
|
+
const COMMONJS = new Set(['.cjs', '.cts']);
|
|
40
|
+
const DECLARATION = /\.d\.[cm]?ts$/;
|
|
41
|
+
|
|
42
|
+
/** `vi.*` calls vitest hoists above every import, our header included. */
|
|
43
|
+
const HOISTED_VI = new Set(['mock', 'doMock', 'hoisted', 'unmock']);
|
|
44
|
+
|
|
45
|
+
/** Suspension kinds on the wire: `await` parks a coroutine, `yield` a generator. */
|
|
46
|
+
const AWAIT = 0;
|
|
47
|
+
const YIELD = 1;
|
|
48
|
+
/** `for await` iterator wrapper. Same `y`/`r` as `await`. No newline in the edit. */
|
|
49
|
+
const FOR_AWAIT_TAIL =
|
|
50
|
+
');const __am=__o==null?null:__o[Symbol.asyncIterator];' +
|
|
51
|
+
'const __m=__am==null?(__o==null?null:__o[Symbol.iterator]):__am;' +
|
|
52
|
+
'if(typeof __m!="function")throw new TypeError("for await of a non-iterable");' +
|
|
53
|
+
'const __i=__m.call(__o);const __sync=__am==null;' +
|
|
54
|
+
'const __park=async(p)=>__srt.r(__sf,await __srt.y(__sf,(p),0));' +
|
|
55
|
+
'const __box=async(q)=>{if(!__sync||!q||q.value==null||typeof q.value.then!="function")return q;' +
|
|
56
|
+
'return{done:q.done,value:await __park(q.value)}};' +
|
|
57
|
+
'return{next:(...a)=>__park(__i.next(...a)).then(__box),' +
|
|
58
|
+
'"return":(...a)=>typeof __i.return=="function"?__park(__i.return(...a)).then(__box):{done:true,value:a[0]},' +
|
|
59
|
+
'"throw":(...a)=>typeof __i.throw=="function"?__park(__i.throw(...a)).then(__box):Promise.reject(a[0])}}})';
|
|
60
|
+
|
|
61
|
+
const CLOSE_BLOCK = ';__srt.ret(__sf,undefined)}catch(__se){__srt.thr(__sf,__se);throw __se}';
|
|
62
|
+
/**
|
|
63
|
+
* A generator's close (R40). A consumer that abandons a generator — `break` out
|
|
64
|
+
* of a `for…of`, an explicit `.return()` — resumes the body at its `yield` with
|
|
65
|
+
* a RETURN completion: the `ret` above never runs and the `catch` never fires,
|
|
66
|
+
* so only a `finally` can see it. `gclose` is a no-op on a frame either of the
|
|
67
|
+
* other two already closed.
|
|
68
|
+
*/
|
|
69
|
+
const CLOSE_BLOCK_GEN = `${CLOSE_BLOCK}finally{__srt.gclose(__sf)}`;
|
|
70
|
+
/**
|
|
71
|
+
* The close of a SEAL-DEFERRED body (2026-09-12 §4.2): the body's own exits
|
|
72
|
+
* `pend` the value and leave the frame OPEN, so the program's `finally` mints
|
|
73
|
+
* its rows and a call it makes opens under this frame; the wrapper's own
|
|
74
|
+
* `finally` then seals — emitting RETURN after them. A frame `thr` closed in
|
|
75
|
+
* the `catch` above is left exactly as it left it.
|
|
76
|
+
*/
|
|
77
|
+
const CLOSE_BLOCK_DEFERRED = ';__srt.pend(__sf,undefined)}catch(__se){__srt.thr(__sf,__se);throw __se}finally{__srt.seal(__sf)}';
|
|
78
|
+
/**
|
|
79
|
+
* A deferred generator's close (§4.4). ONE `finally`, `seal` first: it closes
|
|
80
|
+
* the frame with the pended value, and `gclose` — which is what a consumer
|
|
81
|
+
* that abandons the generator would otherwise close it with — meets a closed
|
|
82
|
+
* frame and is the no-op it promises. Two clauses would be two exits.
|
|
83
|
+
*/
|
|
84
|
+
const CLOSE_BLOCK_GEN_DEFERRED = ';__srt.pend(__sf,undefined)}catch(__se){__srt.thr(__sf,__se);throw __se}finally{__srt.seal(__sf);__srt.gclose(__sf)}';
|
|
85
|
+
/** The two frame kinds whose bodies a consumer can close from outside. */
|
|
86
|
+
const GENERATORS = new Set(['generator', 'async_generator']);
|
|
87
|
+
const CLOSE_EXPRESSION = '))}catch(__se){__srt.thr(__sf,__se);throw __se}}';
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Whether a file is transformed, skipped outright, or skipped but counted.
|
|
91
|
+
*
|
|
92
|
+
* `commonjs` is the one exclusion the per-file manifest cannot carry — the file
|
|
93
|
+
* has no manifest, because it is never parsed — so the caller (the vite plugin)
|
|
94
|
+
* tallies it into the run's `transform_excluded` from this verdict.
|
|
95
|
+
* @param {string} filePath absolute path to the file
|
|
96
|
+
* @param {string} root absolute path to the invocation root
|
|
97
|
+
* @returns {'transform'|'skip'|'commonjs'}
|
|
98
|
+
*/
|
|
99
|
+
export function classify(filePath, root) {
|
|
100
|
+
const rel = path.relative(root, filePath);
|
|
101
|
+
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return 'skip';
|
|
102
|
+
if (rel.split(path.sep).includes('node_modules')) return 'skip';
|
|
103
|
+
if (DECLARATION.test(filePath)) return 'skip';
|
|
104
|
+
const ext = path.extname(filePath);
|
|
105
|
+
if (COMMONJS.has(ext)) return 'commonjs';
|
|
106
|
+
return ELIGIBLE.has(ext) ? 'transform' : 'skip';
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* @param {TS} ts
|
|
111
|
+
* @param {Node} node
|
|
112
|
+
* @returns {node is FunctionLike}
|
|
113
|
+
*/
|
|
114
|
+
function isFunctionLike(ts, node) {
|
|
115
|
+
return (
|
|
116
|
+
ts.isFunctionDeclaration(node) ||
|
|
117
|
+
ts.isFunctionExpression(node) ||
|
|
118
|
+
ts.isArrowFunction(node) ||
|
|
119
|
+
ts.isMethodDeclaration(node) ||
|
|
120
|
+
ts.isConstructorDeclaration(node) ||
|
|
121
|
+
ts.isGetAccessorDeclaration(node) ||
|
|
122
|
+
ts.isSetAccessorDeclaration(node)
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* @param {TS} ts
|
|
128
|
+
* @param {Node} node
|
|
129
|
+
* @param {import('typescript').SyntaxKind} kind
|
|
130
|
+
* @returns {boolean}
|
|
131
|
+
*/
|
|
132
|
+
function hasModifier(ts, node, kind) {
|
|
133
|
+
const modifiers = /** @type {{modifiers?: readonly import('typescript').ModifierLike[]}} */ (node)
|
|
134
|
+
.modifiers;
|
|
135
|
+
return !!modifiers && modifiers.some((m) => m.kind === kind);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* @param {TS} ts
|
|
140
|
+
* @param {FunctionLike} node
|
|
141
|
+
* @returns {FrameKind} the contract's frame kind
|
|
142
|
+
*/
|
|
143
|
+
function frameKind(ts, node) {
|
|
144
|
+
const isAsync = hasModifier(ts, node, ts.SyntaxKind.AsyncKeyword);
|
|
145
|
+
const isGenerator = !!(/** @type {{asteriskToken?: Node}} */ (node).asteriskToken);
|
|
146
|
+
if (isAsync && isGenerator) return 'async_generator';
|
|
147
|
+
if (isAsync) return 'coroutine';
|
|
148
|
+
if (isGenerator) return 'generator';
|
|
149
|
+
return 'function';
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* @param {TS} ts
|
|
154
|
+
* @param {Node} node
|
|
155
|
+
* @returns {boolean} whether the node sits in a `declare`d context
|
|
156
|
+
*/
|
|
157
|
+
function isAmbient(ts, node) {
|
|
158
|
+
/** @type {Node|undefined} */
|
|
159
|
+
let cur = node;
|
|
160
|
+
while (cur) {
|
|
161
|
+
if (hasModifier(ts, cur, ts.SyntaxKind.DeclareKeyword)) return true;
|
|
162
|
+
cur = cur.parent;
|
|
163
|
+
}
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Why a function with no body is not instrumented. Each reason is named so the
|
|
169
|
+
* count in the trace is a number, not a hope.
|
|
170
|
+
* @param {TS} ts
|
|
171
|
+
* @param {FunctionLike} node
|
|
172
|
+
* @returns {string}
|
|
173
|
+
*/
|
|
174
|
+
function bodilessReason(ts, node) {
|
|
175
|
+
if (isAmbient(ts, node)) return 'ambient';
|
|
176
|
+
if (hasModifier(ts, node, ts.SyntaxKind.AbstractKeyword)) return 'abstract';
|
|
177
|
+
return 'overload-signature';
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* @param {TS} ts
|
|
182
|
+
* @param {Node} node
|
|
183
|
+
* @returns {boolean} whether the node is a `vi.mock`/`doMock`/`hoisted`/`unmock` call
|
|
184
|
+
*/
|
|
185
|
+
function isHoistedCall(ts, node) {
|
|
186
|
+
return (
|
|
187
|
+
ts.isCallExpression(node) &&
|
|
188
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
189
|
+
ts.isIdentifier(node.expression.expression) &&
|
|
190
|
+
node.expression.expression.text === 'vi' &&
|
|
191
|
+
HOISTED_VI.has(node.expression.name.text)
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Pass one: number every function-like in source order, decide eligibility,
|
|
197
|
+
* name every one of them (an excluded function still needs a name, because a
|
|
198
|
+
* function nested inside it is named against it), and mark the ones a focus
|
|
199
|
+
* selected.
|
|
200
|
+
*
|
|
201
|
+
* Only an INSTRUMENTED function can be focused: an excluded one opens no frame,
|
|
202
|
+
* so there is nothing for a statement of it to be a statement OF.
|
|
203
|
+
* @param {TS} ts
|
|
204
|
+
* @param {SourceFile} sf
|
|
205
|
+
* @param {string} rel the root-relative path a spec's file part is matched on
|
|
206
|
+
* @param {string[]} focus the specs, `[]` for no focus at all
|
|
207
|
+
* @returns {{sites: Site[], indexOf: Map<Node, number>, focused: Set<Node>,
|
|
208
|
+
* deferred: Set<Node>, excluded: Record<string, number>,
|
|
209
|
+
* excludedSites: ExcludedSite[]}}
|
|
210
|
+
* `excluded` COUNTS the exclusions and is what a manifest carries;
|
|
211
|
+
* `excludedSites` NAMES them, one entry each, and is for the resolver
|
|
212
|
+
* (R26), which has to tell a spec that matched nothing from a spec that
|
|
213
|
+
* matched only functions this recorder never instruments.
|
|
214
|
+
*/
|
|
215
|
+
function planSites(ts, sf, rel, focus) {
|
|
216
|
+
/** @type {Site[]} */
|
|
217
|
+
const sites = [];
|
|
218
|
+
/** @type {Map<Node, number>} */
|
|
219
|
+
const indexOf = new Map();
|
|
220
|
+
/** @type {Set<Node>} */
|
|
221
|
+
const focused = new Set();
|
|
222
|
+
/** @type {Set<Node>} */
|
|
223
|
+
const deferred = new Set();
|
|
224
|
+
/** @type {Map<Node, string>} */
|
|
225
|
+
const qualnames = new Map();
|
|
226
|
+
/** @type {Record<string, number>} */
|
|
227
|
+
const excluded = {};
|
|
228
|
+
/** @type {ExcludedSite[]} */
|
|
229
|
+
const excludedSites = [];
|
|
230
|
+
let hoistedDepth = 0;
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* @param {Node} node the function-like this recorder is not instrumenting
|
|
234
|
+
* @param {string} reason
|
|
235
|
+
*/
|
|
236
|
+
const exclude = (node, reason) => {
|
|
237
|
+
excluded[reason] = (excluded[reason] ?? 0) + 1;
|
|
238
|
+
excludedSites.push({
|
|
239
|
+
qualname: /** @type {string} */ (qualnames.get(node)),
|
|
240
|
+
line: lineOf(sf, node.getStart(sf)),
|
|
241
|
+
reason,
|
|
242
|
+
});
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
/** @param {Node} node */
|
|
246
|
+
const visit = (node) => {
|
|
247
|
+
if (isHoistedCall(ts, node)) {
|
|
248
|
+
hoistedDepth += 1;
|
|
249
|
+
ts.forEachChild(node, visit);
|
|
250
|
+
hoistedDepth -= 1;
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (isFunctionLike(ts, node)) {
|
|
254
|
+
qualnames.set(node, qualnameFor(ts, node, qualnames));
|
|
255
|
+
if (hoistedDepth > 0) exclude(node, 'vitest-hoisted-factory');
|
|
256
|
+
else if (!node.body) exclude(node, bodilessReason(ts, node));
|
|
257
|
+
else {
|
|
258
|
+
const qualname = /** @type {string} */ (qualnames.get(node));
|
|
259
|
+
const selected = focus.some((spec) => specMatches(spec, rel, qualname));
|
|
260
|
+
if (selected) focused.add(node);
|
|
261
|
+
// The seal is a frame-lifetime fix and asks nothing about the focus:
|
|
262
|
+
// every tier attributes a call the finally makes to the frame that
|
|
263
|
+
// made it, and every tier's RETURN follows the finally's rows.
|
|
264
|
+
const defers = deferredExit(ts, /** @type {FunctionLike} */ (node));
|
|
265
|
+
if (defers) deferred.add(node);
|
|
266
|
+
indexOf.set(node, sites.length);
|
|
267
|
+
sites.push({
|
|
268
|
+
qualname,
|
|
269
|
+
line: lineOf(sf, node.getStart(sf)),
|
|
270
|
+
kind: frameKind(ts, node),
|
|
271
|
+
focused: selected,
|
|
272
|
+
deferred: defers,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
ts.forEachChild(node, visit);
|
|
277
|
+
};
|
|
278
|
+
visit(sf);
|
|
279
|
+
return { sites, indexOf, focused, deferred, excluded, excludedSites };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* The state pass two threads through every splice: the consumer's TypeScript,
|
|
284
|
+
* the parsed file, the edit buffer, which function-likes are recorded, and
|
|
285
|
+
* which of those the focus selected.
|
|
286
|
+
* @typedef {{ts: TS, sf: SourceFile, s: MagicString, indexOf: Map<Node, number>, focused: Set<Node>, deferred: Set<Node>, isTestFile: boolean}} Splicer
|
|
287
|
+
*/
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* The function-like a node's frame belongs to: the NEAREST one above it, which
|
|
291
|
+
* is the only one a statement, a return or a suspension is a part of.
|
|
292
|
+
* @param {Splicer} ctx
|
|
293
|
+
* @param {Node} node
|
|
294
|
+
* @returns {Node|null} null outside every function-like
|
|
295
|
+
*/
|
|
296
|
+
function enclosingFunction(ctx, node) {
|
|
297
|
+
let parent = node.parent;
|
|
298
|
+
while (parent) {
|
|
299
|
+
if (isFunctionLike(ctx.ts, parent)) return parent;
|
|
300
|
+
parent = parent.parent;
|
|
301
|
+
}
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* @param {Splicer} ctx
|
|
307
|
+
* @param {Node} node
|
|
308
|
+
* @returns {boolean} whether the node sits inside a recorded frame
|
|
309
|
+
*/
|
|
310
|
+
function isRecorded(ctx, node) {
|
|
311
|
+
const fn = enclosingFunction(ctx, node);
|
|
312
|
+
return fn !== null && ctx.indexOf.has(fn);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Whether the node's own frame is seal-deferred — the enclosing function
|
|
317
|
+
* returns THROUGH a `finally` (§4.2), so its exits pend and its wrapper seals.
|
|
318
|
+
* Asked of a `return` so the splice matches the wrapper it will close under: a
|
|
319
|
+
* `ret` beneath a sealing wrapper would close the frame twice, and a `pend`
|
|
320
|
+
* beneath 0.3.0's would never close it at all.
|
|
321
|
+
* @param {Splicer} ctx
|
|
322
|
+
* @param {Node} node
|
|
323
|
+
* @returns {boolean}
|
|
324
|
+
*/
|
|
325
|
+
function isDeferredFrame(ctx, node) {
|
|
326
|
+
const fn = enclosingFunction(ctx, node);
|
|
327
|
+
return fn !== null && ctx.deferred.has(fn);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* @param {Splicer} ctx
|
|
332
|
+
* @param {Node} node
|
|
333
|
+
* @returns {string} the frame variable, spelled `null` outside every frame
|
|
334
|
+
*/
|
|
335
|
+
function frameVar(ctx, node) {
|
|
336
|
+
return isRecorded(ctx, node) ? '__sf' : 'null';
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Whether the node sits inside a FOCUSED frame — the nearest function-like
|
|
341
|
+
* above it is one the focus selected. Every statement of such a frame owes the
|
|
342
|
+
* record a row; a statement of a nested function that the focus did not reach
|
|
343
|
+
* is that function's business, not this one's (spec §3.1).
|
|
344
|
+
* @param {Splicer} ctx
|
|
345
|
+
* @param {Node} node
|
|
346
|
+
* @returns {boolean}
|
|
347
|
+
*/
|
|
348
|
+
function isFocusedFrame(ctx, node) {
|
|
349
|
+
let parent = node.parent;
|
|
350
|
+
while (parent) {
|
|
351
|
+
if (isFunctionLike(ctx.ts, parent)) return ctx.focused.has(parent);
|
|
352
|
+
parent = parent.parent;
|
|
353
|
+
}
|
|
354
|
+
return false;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* The frame's entry and the arguments it was entered with, read at body
|
|
359
|
+
* entry so a default is the value the body saw (spec §3.3). Every site
|
|
360
|
+
* passes the list, including an empty one: "no parameters" and "not read"
|
|
361
|
+
* stay different facts, and the runtime's omitted third argument is the
|
|
362
|
+
* second of them. `--focus` still decides the per-statement rows.
|
|
363
|
+
* @param {Splicer} ctx
|
|
364
|
+
* @param {FunctionLike} node a recorded function-like
|
|
365
|
+
*/
|
|
366
|
+
function spliceFunction(ctx, node) {
|
|
367
|
+
const { ts, sf, s } = ctx;
|
|
368
|
+
const index = ctx.indexOf.get(node);
|
|
369
|
+
const names = paramNames(ts, node);
|
|
370
|
+
// Focused method/getter/setter/non-derived constructor only. Arrow and
|
|
371
|
+
// derived constructor stay null (lexical `this`, TDZ before `super()`).
|
|
372
|
+
if (ctx.focused.has(node)) {
|
|
373
|
+
const recv = receiverName(ts, node);
|
|
374
|
+
if (recv !== null) names.unshift(recv);
|
|
375
|
+
}
|
|
376
|
+
const args = `,[${pairsOf(names)}]`;
|
|
377
|
+
const body = /** @type {import('typescript').Block|import('typescript').Expression} */ (
|
|
378
|
+
node.body
|
|
379
|
+
);
|
|
380
|
+
if (ts.isBlock(body)) {
|
|
381
|
+
s.appendLeft(body.getStart(sf) + 1, `const __sf=__srt.call(__sfile,${index}${args});try{`);
|
|
382
|
+
// Only a generator gets the `finally`: nothing else can be resumed with a
|
|
383
|
+
// completion its own body did not choose, and an extra clause on every
|
|
384
|
+
// function would be an edit with no fact behind it. A SEAL-DEFERRED body
|
|
385
|
+
// gets one for a different reason (§4.2), and a deferred generator gets
|
|
386
|
+
// exactly one clause holding both (§4.4).
|
|
387
|
+
const gen = GENERATORS.has(frameKind(ts, node));
|
|
388
|
+
const defers = ctx.deferred.has(node);
|
|
389
|
+
s.prependRight(body.end - 1,
|
|
390
|
+
defers
|
|
391
|
+
? (gen ? CLOSE_BLOCK_GEN_DEFERRED : CLOSE_BLOCK_DEFERRED)
|
|
392
|
+
: (gen ? CLOSE_BLOCK_GEN : CLOSE_BLOCK));
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
s.appendLeft(
|
|
396
|
+
body.getStart(sf),
|
|
397
|
+
`{const __sf=__srt.call(__sfile,${index}${args});try{return __srt.ret(__sf,(`,
|
|
398
|
+
);
|
|
399
|
+
s.prependRight(body.end, CLOSE_EXPRESSION);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* @param {Splicer} ctx
|
|
404
|
+
* @param {import('typescript').ReturnStatement} node
|
|
405
|
+
*/
|
|
406
|
+
function spliceReturn(ctx, node) {
|
|
407
|
+
const { sf, s } = ctx;
|
|
408
|
+
if (!isRecorded(ctx, node)) return;
|
|
409
|
+
// `pend` STORES the value and leaves the frame open; the wrapper's own
|
|
410
|
+
// `finally` is what closes it, after the program's `finally` has run. Which
|
|
411
|
+
// of the two a return takes is decided by its FRAME, not by its own place:
|
|
412
|
+
// every exit of a deferred body closes under the same sealing wrapper.
|
|
413
|
+
const exit = isDeferredFrame(ctx, node) ? 'pend' : 'ret';
|
|
414
|
+
if (!node.expression) {
|
|
415
|
+
const end = terminatorFor(ctx, node);
|
|
416
|
+
s.appendLeft(node.getStart(sf) + 'return'.length, ` __srt.${exit}(__sf,undefined)${end}`);
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
s.appendLeft(node.expression.getStart(sf), `__srt.${exit}(__sf,(`);
|
|
420
|
+
s.prependRight(node.expression.end, '))');
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* `await X` and `yield X` take one form: the value flows out through `y` and
|
|
425
|
+
* back in through `r`, so the runtime can pop the frame while it is parked.
|
|
426
|
+
* @param {Splicer} ctx
|
|
427
|
+
* @param {import('typescript').AwaitExpression|import('typescript').YieldExpression} node
|
|
428
|
+
* @param {number} kind
|
|
429
|
+
* @param {string} keyword
|
|
430
|
+
*/
|
|
431
|
+
function spliceSuspension(ctx, node, kind, keyword) {
|
|
432
|
+
const { ts, sf, s } = ctx;
|
|
433
|
+
if (!isRecorded(ctx, node)) return;
|
|
434
|
+
s.appendLeft(node.getStart(sf), '__srt.r(__sf,');
|
|
435
|
+
if (!node.expression) {
|
|
436
|
+
// Only a whole statement may take a terminator; a nested `yield` may not.
|
|
437
|
+
const parent = node.parent;
|
|
438
|
+
const end = ts.isExpressionStatement(parent) && parent.expression === node
|
|
439
|
+
? terminatorFor(ctx, parent)
|
|
440
|
+
: '';
|
|
441
|
+
s.appendLeft(node.getStart(sf) + keyword.length, ` __srt.y(__sf,(undefined),${kind}))${end}`);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
s.appendLeft(node.expression.getStart(sf), '__srt.y(__sf,(');
|
|
445
|
+
s.prependRight(node.expression.end, `),${kind}))`);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** `for await` parks like `await`. @param {Splicer} ctx @param {import('typescript').ForOfStatement} node */
|
|
449
|
+
function spliceForAwait(ctx, node) {
|
|
450
|
+
if (!node.awaitModifier || !isRecorded(ctx, node)) return;
|
|
451
|
+
const { sf, s } = ctx;
|
|
452
|
+
const expr = node.expression;
|
|
453
|
+
s.appendLeft(expr.getStart(sf), '({[Symbol.asyncIterator](){const __o=(');
|
|
454
|
+
s.prependRight(expr.end, FOR_AWAIT_TAIL);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* @param {Splicer} ctx
|
|
459
|
+
* @param {import('typescript').ThrowStatement} node
|
|
460
|
+
*/
|
|
461
|
+
function spliceThrow(ctx, node) {
|
|
462
|
+
const { sf, s } = ctx;
|
|
463
|
+
const line = lineOf(sf, node.getStart(sf));
|
|
464
|
+
s.appendLeft(node.expression.getStart(sf), `__srt.raise(${frameVar(ctx, node)},(`);
|
|
465
|
+
s.prependRight(node.expression.end, `),${line})`);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* A `catch` clause records a HANDLED as its first statement; a clause with no
|
|
470
|
+
* binding is given one, and an empty block is a sink, not a silence. The `how`
|
|
471
|
+
* word is the escape rule's verdict about what the body did with the binding
|
|
472
|
+
* (`escape.mjs`, spec §2.1) — the record says whether the failure got out, not
|
|
473
|
+
* merely that something caught it.
|
|
474
|
+
* @param {Splicer} ctx
|
|
475
|
+
* @param {import('typescript').CatchClause} node
|
|
476
|
+
*/
|
|
477
|
+
function spliceCatch(ctx, node) {
|
|
478
|
+
const { ts, sf, s } = ctx;
|
|
479
|
+
const line = lineOf(sf, node.getStart(sf));
|
|
480
|
+
const how = `"${catchHow(ts, node)}"`;
|
|
481
|
+
const open = node.block.getStart(sf) + 1;
|
|
482
|
+
const declared = node.variableDeclaration;
|
|
483
|
+
if (!declared) {
|
|
484
|
+
s.appendLeft(node.getStart(sf) + 'catch'.length, '(__sce)');
|
|
485
|
+
s.appendLeft(open, `__srt.handled(${frameVar(ctx, node)},__sce,${line},${how});`);
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
// A destructuring binding has no name to hand back; the HANDLED is recorded
|
|
489
|
+
// without the object rather than guessed at.
|
|
490
|
+
const bound = ts.isIdentifier(declared.name) ? declared.name.text : 'undefined';
|
|
491
|
+
s.appendLeft(open, `__srt.handled(${frameVar(ctx, node)},${bound},${line},${how});`);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* A rejection handler — `p.catch(<arg>)` or the second argument of
|
|
496
|
+
* `p.then(<x>, <arg>)` — wrapped so the reason it is given is recorded before it
|
|
497
|
+
* runs (spec §2.2). `p.catch()` with no argument, `.then(x)` with one and
|
|
498
|
+
* `.finally(fn)` are not handlers and are not touched (P4).
|
|
499
|
+
*
|
|
500
|
+
* The `how` word is the splice's own verdict about the handler's SHAPE, decided
|
|
501
|
+
* here and written down by the runtime unexamined. The argument is wrapped in
|
|
502
|
+
* parentheses of its own so that whatever expression it is — an arrow, a
|
|
503
|
+
* conditional, an `await` — arrives at `catchCb` as exactly one argument, and so
|
|
504
|
+
* that a closer a descendant registers on the same offset lands inside ours.
|
|
505
|
+
*
|
|
506
|
+
* A call holding a SPREAD argument is left alone entirely. `...args` is not an
|
|
507
|
+
* expression and cannot be parenthesised, so wrapping it produces source the
|
|
508
|
+
* consumer's own parser rejects — the recorder breaking the program it observes
|
|
509
|
+
* — and a spread also hides which argument the handler even IS: `p.then(...a)`
|
|
510
|
+
* may carry two, and `p.then(...a, b)`'s `b` may be the third. One argument the
|
|
511
|
+
* splice cannot read is enough to leave the whole call to the program.
|
|
512
|
+
* @param {Splicer} ctx
|
|
513
|
+
* @param {import('typescript').CallExpression} node
|
|
514
|
+
* @returns {boolean} whether this call was a rejection handler
|
|
515
|
+
*/
|
|
516
|
+
function spliceRejectionCallback(ctx, node) {
|
|
517
|
+
const { ts, sf, s } = ctx;
|
|
518
|
+
const callee = node.expression;
|
|
519
|
+
if (!ts.isPropertyAccessExpression(callee)) return false;
|
|
520
|
+
if (node.arguments.some((a) => ts.isSpreadElement(a))) return false;
|
|
521
|
+
const name = callee.name.text;
|
|
522
|
+
const arg = name === 'catch' && node.arguments.length === 1
|
|
523
|
+
? node.arguments[0]
|
|
524
|
+
: name === 'then' && node.arguments.length === 2
|
|
525
|
+
? node.arguments[1]
|
|
526
|
+
: null;
|
|
527
|
+
if (!arg) return false;
|
|
528
|
+
const line = lineOf(sf, callee.name.getStart(sf));
|
|
529
|
+
const how = callbackHow(ts, arg);
|
|
530
|
+
s.appendLeft(arg.getStart(sf), `__srt.catchCb(${frameVar(ctx, node)},${line},"${how}",(`);
|
|
531
|
+
s.prependRight(arg.end, '))');
|
|
532
|
+
return true;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* A `finally` block that COMPLETES — `return`, `break` or `continue` at closure
|
|
537
|
+
* depth 0 — discards whatever was travelling through the frame, so it is a sink
|
|
538
|
+
* and gains `handledFinally` as its first statement (spec §2.3).
|
|
539
|
+
*
|
|
540
|
+
* A `try` with no `catch` of its own also gains one: `catch(__sfe){mark;throw}`
|
|
541
|
+
* spliced before the `finally` keyword, which is how a library's throw and an
|
|
542
|
+
* awaited rejection — neither of them a `throw` statement this recorder saw —
|
|
543
|
+
* reach the frame's mark (P1). It rethrows the very value it caught, so the
|
|
544
|
+
* program's control flow, and the `finally`'s own precedence over it, are
|
|
545
|
+
* unchanged. A `try` with a `catch` needs none: that clause's HANDLED already
|
|
546
|
+
* ends the flight, and the mark it clears is what keeps the `finally` beneath a
|
|
547
|
+
* caught throw from claiming a swallow.
|
|
548
|
+
*
|
|
549
|
+
* A `try` outside every recorded frame has no mark to read and is left alone.
|
|
550
|
+
* @param {Splicer} ctx
|
|
551
|
+
* @param {import('typescript').TryStatement} node
|
|
552
|
+
*/
|
|
553
|
+
function spliceFinally(ctx, node) {
|
|
554
|
+
const { ts, sf, s } = ctx;
|
|
555
|
+
if (!node.finallyBlock || !finallyCompletes(ts, node.finallyBlock)) return;
|
|
556
|
+
if (!isRecorded(ctx, node)) return;
|
|
557
|
+
const keyword = node.getChildren(sf).find((c) => c.kind === ts.SyntaxKind.FinallyKeyword);
|
|
558
|
+
if (!keyword) return;
|
|
559
|
+
const frame = frameVar(ctx, node);
|
|
560
|
+
const line = lineOf(sf, keyword.getStart(sf));
|
|
561
|
+
if (!node.catchClause) {
|
|
562
|
+
s.appendLeft(keyword.getStart(sf), `catch(__sfe){__srt.mark(${frame},__sfe);throw __sfe}`);
|
|
563
|
+
}
|
|
564
|
+
s.appendLeft(node.finallyBlock.getStart(sf) + 1, `__srt.handledFinally(${frame},${line});`);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* Pass two: the splices. Every insertion is newline-free; every closing
|
|
569
|
+
* insertion uses `prependRight` so two closers landing on one offset come out
|
|
570
|
+
* innermost first.
|
|
571
|
+
* @param {Splicer} ctx
|
|
572
|
+
*/
|
|
573
|
+
function splice(ctx) {
|
|
574
|
+
const { ts, sf } = ctx;
|
|
575
|
+
/** @param {Node} node */
|
|
576
|
+
const visit = (node) => {
|
|
577
|
+
if (isHoistedCall(ts, node)) return; // vitest hoists it above our header
|
|
578
|
+
if (isFunctionLike(ts, node) && ctx.indexOf.has(node)) spliceFunction(ctx, node);
|
|
579
|
+
else if (ts.isReturnStatement(node)) spliceReturn(ctx, node);
|
|
580
|
+
else if (ts.isAwaitExpression(node)) spliceSuspension(ctx, node, AWAIT, 'await');
|
|
581
|
+
else if (ts.isYieldExpression(node)) spliceSuspension(ctx, node, YIELD, 'yield');
|
|
582
|
+
else if (ts.isThrowStatement(node)) spliceThrow(ctx, node);
|
|
583
|
+
else if (ts.isTryStatement(node)) spliceFinally(ctx, node);
|
|
584
|
+
else if (ts.isCatchClause(node)) spliceCatch(ctx, node);
|
|
585
|
+
else if (ts.isCallExpression(node) && !spliceRejectionCallback(ctx, node)) {
|
|
586
|
+
spliceTaskBoundary(ctx, node);
|
|
587
|
+
} else if (ts.isForOfStatement(node)) spliceForAwait(ctx, node);
|
|
588
|
+
// After the chain and before the children: the focus tier's rows (spec
|
|
589
|
+
// §3.1). A `CatchClause`'s head row must follow the HANDLED the chain just
|
|
590
|
+
// registered, and every statement's row must be registered before its own
|
|
591
|
+
// descendants' closers (plan P3).
|
|
592
|
+
if (isFocusedFrame(ctx, node)) spliceFocused(ctx, node);
|
|
593
|
+
ts.forEachChild(node, visit);
|
|
594
|
+
};
|
|
595
|
+
visit(sf);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* The parser's own complaints about a file. TypeScript's parser recovers from
|
|
600
|
+
* anything, so a broken file still yields a tree — with positions that mean
|
|
601
|
+
* nothing. Splicing into it would corrupt the source, so a file that does not
|
|
602
|
+
* parse is reported and left alone (R10).
|
|
603
|
+
* @param {SourceFile} sf
|
|
604
|
+
* @returns {string[]} the first three message texts, flattened
|
|
605
|
+
*/
|
|
606
|
+
function parseErrors(sf) {
|
|
607
|
+
const diagnostics = /** @type {import('typescript').Diagnostic[]|undefined} */ (
|
|
608
|
+
/** @type {any} */ (sf).parseDiagnostics
|
|
609
|
+
);
|
|
610
|
+
// An absent field is not an absence of errors. A TypeScript build that dropped
|
|
611
|
+
// or renamed it would have us splice into a tree we cannot vouch for (R10a).
|
|
612
|
+
if (!Array.isArray(diagnostics)) {
|
|
613
|
+
throw new Error(
|
|
614
|
+
'sensorium-ts: this TypeScript build exposes no parseDiagnostics; refusing to transform blind',
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
if (diagnostics.length === 0) return [];
|
|
618
|
+
return diagnostics.slice(0, 3).map((d) =>
|
|
619
|
+
typeof d.messageText === 'string' ? d.messageText : d.messageText.messageText,
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* @param {TS} ts
|
|
625
|
+
* @param {string} filePath
|
|
626
|
+
* @returns {import('typescript').ScriptKind}
|
|
627
|
+
*/
|
|
628
|
+
function scriptKindFor(ts, filePath) {
|
|
629
|
+
const ext = path.extname(filePath);
|
|
630
|
+
if (ext === '.tsx') return ts.ScriptKind.TSX;
|
|
631
|
+
if (ext === '.ts' || ext === '.mts') return ts.ScriptKind.TS;
|
|
632
|
+
// JSX in a `.js` file is common and parsing it as plain JS would mangle
|
|
633
|
+
// positions; `.ts` is the only extension where JSX mode changes meaning.
|
|
634
|
+
return ts.ScriptKind.JSX;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Where the header goes. Two things must stay ahead of it, and neither may be
|
|
639
|
+
* pushed onto a line of its own: a shebang, which has to be the first line, and
|
|
640
|
+
* a directive prologue — `'use client'` stops being a directive the moment an
|
|
641
|
+
* import precedes it, and demoting it would change what the program does.
|
|
642
|
+
*
|
|
643
|
+
* A directive written without its semicolon (prettier `--semi false`) needs one
|
|
644
|
+
* supplied, or the header is glued to it: `'use client'import * as __srt` is a
|
|
645
|
+
* syntax error. A shebang needs no terminator — it ends at its newline, and a
|
|
646
|
+
* semicolon there would be an empty statement of pure noise.
|
|
647
|
+
* @param {TS} ts
|
|
648
|
+
* @param {SourceFile} sf
|
|
649
|
+
* @param {string} code
|
|
650
|
+
* @returns {{offset: number, terminator: string}|null} null for a file with no code
|
|
651
|
+
*/
|
|
652
|
+
function headerPlacement(ts, sf, code) {
|
|
653
|
+
let offset = 0;
|
|
654
|
+
let terminator = '';
|
|
655
|
+
if (code.startsWith('#!')) {
|
|
656
|
+
const newline = code.indexOf('\n');
|
|
657
|
+
// A file that is nothing but a shebang line has no code to record.
|
|
658
|
+
if (newline === -1) return null;
|
|
659
|
+
offset = newline + 1;
|
|
660
|
+
}
|
|
661
|
+
for (const statement of sf.statements) {
|
|
662
|
+
if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) break;
|
|
663
|
+
offset = statement.end;
|
|
664
|
+
terminator = code[offset - 1] === ';' ? '' : ';';
|
|
665
|
+
}
|
|
666
|
+
return { offset, terminator };
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* The header carries the file's identity: the root-relative path the fingerprint
|
|
671
|
+
* hashes, the absolute path the contract stores, the site table, and the digest
|
|
672
|
+
* of the source as it was read. It never adds a line.
|
|
673
|
+
* @param {MagicString} s
|
|
674
|
+
* @param {{offset: number, terminator: string}|null} placement
|
|
675
|
+
* @param {string} header
|
|
676
|
+
*/
|
|
677
|
+
function prependHeader(s, placement, header) {
|
|
678
|
+
if (!placement) return;
|
|
679
|
+
const text = placement.terminator + header;
|
|
680
|
+
if (placement.offset === 0) s.prepend(text);
|
|
681
|
+
else s.appendLeft(placement.offset, text);
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* The parse every pass starts from, or a verdict instead of one.
|
|
686
|
+
* @param {string} code
|
|
687
|
+
* @param {string} filePath
|
|
688
|
+
* @param {{root: string, ts: TS}} opts
|
|
689
|
+
* @returns {{rel: string, sf: SourceFile, diagnostics: string[]}|null} null for
|
|
690
|
+
* a path this recorder does not transform
|
|
691
|
+
* @throws when the TypeScript build exposes no `parseDiagnostics` (R10a)
|
|
692
|
+
*/
|
|
693
|
+
function parseFile(code, filePath, opts) {
|
|
694
|
+
if (classify(filePath, opts.root) !== 'transform') return null;
|
|
695
|
+
const ts = opts.ts;
|
|
696
|
+
const rel = path.relative(opts.root, filePath).split(path.sep).join('/');
|
|
697
|
+
const sf = ts.createSourceFile(
|
|
698
|
+
filePath,
|
|
699
|
+
code,
|
|
700
|
+
ts.ScriptTarget.Latest,
|
|
701
|
+
true,
|
|
702
|
+
scriptKindFor(ts, filePath),
|
|
703
|
+
);
|
|
704
|
+
return { rel, sf, diagnostics: parseErrors(sf) };
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Pass one alone: what functions this file offers and what a focus would
|
|
709
|
+
* select, with nothing spliced and no source produced. The resolver asks it
|
|
710
|
+
* before a run, to answer `--focus` with a list or a refusal rather than with
|
|
711
|
+
* a recording nobody wanted.
|
|
712
|
+
* @param {string} code the source as read
|
|
713
|
+
* @param {string} filePath absolute path to the file
|
|
714
|
+
* @param {{root: string, ts: TS, focus?: string[]}} opts
|
|
715
|
+
* @returns {{rel: string, sites: Site[], excluded: Record<string, number>,
|
|
716
|
+
* excludedSites: ExcludedSite[]}|null}
|
|
717
|
+
* null for a path this recorder does not transform. A file that did not parse
|
|
718
|
+
* offers no sites and says why: `excluded['parse-error']`, never a guess --
|
|
719
|
+
* and it names no excluded function either, because a file this recorder
|
|
720
|
+
* could not read the shape of has no functions to have skipped.
|
|
721
|
+
*/
|
|
722
|
+
export function sitesOf(code, filePath, opts) {
|
|
723
|
+
const parsed = parseFile(code, filePath, opts);
|
|
724
|
+
if (parsed === null) return null;
|
|
725
|
+
const { rel, sf, diagnostics } = parsed;
|
|
726
|
+
if (diagnostics.length > 0) {
|
|
727
|
+
return { rel, sites: [], excluded: { 'parse-error': 1 }, excludedSites: [] };
|
|
728
|
+
}
|
|
729
|
+
const { sites, excluded, excludedSites } = planSites(opts.ts, sf, rel, opts.focus ?? []);
|
|
730
|
+
return { rel, sites, excluded, excludedSites };
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Instrument one file.
|
|
735
|
+
* @param {string} code the source as read
|
|
736
|
+
* @param {string} filePath absolute path to the file
|
|
737
|
+
* @param {{root: string, ts: TS, rtPath: string, focus?: string[]}} opts the
|
|
738
|
+
* invocation root, the consumer's own TypeScript, the import specifier of the
|
|
739
|
+
* runtime module, and the focus specs (none by default; with none, no
|
|
740
|
+
* statement row is emitted, and every call still passes its arguments)
|
|
741
|
+
* @returns {{code: string|null, map: import('magic-string').SourceMap|null, manifest: Manifest}|null}
|
|
742
|
+
* null for a path this recorder does not transform — outside the root, under
|
|
743
|
+
* any `node_modules`, a declaration file, CommonJS, or an ineligible
|
|
744
|
+
* extension. A bare null carries no manifest and means 'not ours'; `classify`
|
|
745
|
+
* says which it was. A manifest with `code: null` means 'ours, untouched,
|
|
746
|
+
* counted': the file did not parse, and `excluded['parse-error']` says so.
|
|
747
|
+
* @throws when the TypeScript build exposes no `parseDiagnostics` (R10a): an
|
|
748
|
+
* absent field is not an absence of errors, and this refuses to splice blind.
|
|
749
|
+
*/
|
|
750
|
+
export function transformSource(code, filePath, opts) {
|
|
751
|
+
const parsed = parseFile(code, filePath, opts);
|
|
752
|
+
if (parsed === null) return null;
|
|
753
|
+
const ts = opts.ts;
|
|
754
|
+
const { rel, sf, diagnostics } = parsed;
|
|
755
|
+
|
|
756
|
+
const sha256 = crypto.createHash('sha256').update(code).digest('hex');
|
|
757
|
+
if (diagnostics.length > 0) {
|
|
758
|
+
return {
|
|
759
|
+
code: null,
|
|
760
|
+
map: null,
|
|
761
|
+
manifest: {
|
|
762
|
+
file: filePath,
|
|
763
|
+
rel,
|
|
764
|
+
sha256,
|
|
765
|
+
instrumented: [],
|
|
766
|
+
focused: [],
|
|
767
|
+
excluded: { 'parse-error': 1 },
|
|
768
|
+
diagnostics,
|
|
769
|
+
},
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
const { sites, indexOf, focused, deferred, excluded } = planSites(ts, sf, rel, opts.focus ?? []);
|
|
774
|
+
const s = new MagicString(code);
|
|
775
|
+
splice({ ts, sf, s, indexOf, focused, deferred, isTestFile: isTestFile(ts, sf, filePath) });
|
|
776
|
+
|
|
777
|
+
// The header's table stays three columns: the runtime never needs to know
|
|
778
|
+
// which sites were focused — a focused CALL says so by carrying its `a`.
|
|
779
|
+
const codes = sites.map((site) => [site.qualname, site.line, site.kind]);
|
|
780
|
+
prependHeader(
|
|
781
|
+
s,
|
|
782
|
+
headerPlacement(ts, sf, code),
|
|
783
|
+
`import * as __srt from ${JSON.stringify(opts.rtPath)};` +
|
|
784
|
+
`const __sfile=__srt.file(${JSON.stringify(rel)},${JSON.stringify(filePath)},` +
|
|
785
|
+
`${JSON.stringify(codes)},${JSON.stringify(sha256)});`,
|
|
786
|
+
);
|
|
787
|
+
|
|
788
|
+
return {
|
|
789
|
+
code: s.toString(),
|
|
790
|
+
map: s.generateMap({ hires: true, source: filePath, includeContent: true }),
|
|
791
|
+
manifest: {
|
|
792
|
+
file: filePath,
|
|
793
|
+
rel,
|
|
794
|
+
sha256,
|
|
795
|
+
instrumented: sites,
|
|
796
|
+
focused: sites.filter((site) => site.focused).map((site) => site.qualname),
|
|
797
|
+
excluded,
|
|
798
|
+
},
|
|
799
|
+
};
|
|
800
|
+
}
|