targeted-mutation 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/NOTICE +21 -0
- package/README.md +111 -2
- package/bin/tmt-compile.mjs +46 -0
- package/bin/tmt.mjs +117 -0
- package/build/typescript-syntax/LICENSE.txt +55 -0
- package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
- package/build/typescript-syntax/typescript-syntax.cjs +43 -0
- package/docs/analysis.md +218 -0
- package/docs/compiler.md +462 -0
- package/docs/development.md +61 -0
- package/docs/how-it-works.svg +188 -0
- package/docs/l1.md +94 -0
- package/docs/performance.md +647 -0
- package/docs/releasing.md +48 -0
- package/package.json +49 -4
- package/src/analysis.mjs +689 -0
- package/src/assertion-session.mjs +93 -0
- package/src/assertion-strength.mjs +795 -0
- package/src/builtin-mutations.mjs +755 -0
- package/src/builtin-switches.mjs +642 -0
- package/src/change-undone.mjs +524 -0
- package/src/cli-output.mjs +166 -0
- package/src/compiler-compat.cjs +108 -0
- package/src/compiler-maps.cjs +60 -0
- package/src/compiler-routes.cjs +391 -0
- package/src/compiler.cjs +98 -0
- package/src/compiler.mjs +1 -0
- package/src/conventional.mjs +172 -0
- package/src/displacement.mjs +19 -0
- package/src/extract.mjs +135 -0
- package/src/fallback-process.mjs +14 -0
- package/src/in-parallel.mjs +20 -0
- package/src/lean-replay.mjs +39 -0
- package/src/operator-analysis.mjs +123 -0
- package/src/playwright.mjs +139 -0
- package/src/probe-runtime.mjs +50 -0
- package/src/probe.mjs +170 -0
- package/src/prototype.mjs +230 -0
- package/src/regex-mutations.mjs +102 -0
- package/src/runner-process.mjs +59 -0
- package/src/runtime-binaries.mjs +50 -0
- package/src/scope.mjs +202 -0
- package/src/source-text.mjs +49 -0
- package/src/standard-plan.mjs +308 -0
- package/src/standard-runner.mjs +185 -0
- package/src/standard-session.mjs +362 -0
- package/src/standard-setup.mjs +20 -0
- package/src/targeted-gaps.mjs +85 -0
- package/src/threshold.mjs +185 -0
- package/src/trace-buffer.mjs +126 -0
- package/src/typescript-bindings.mjs +243 -0
- package/src/typescript-compiler.mjs +59 -0
- package/src/typescript-extraction.mjs +354 -0
- package/src/typescript-grammar.mjs +923 -0
- package/src/vitest-reporter.mjs +64 -0
- package/src/vitest.mjs +262 -0
- package/src/witness-analysis.mjs +234 -0
- package/src/witness-contracts.mjs +110 -0
- package/src/witness-discovery.mjs +239 -0
- package/src/witness-fixtures.mjs +148 -0
- package/src/witness-order.mjs +83 -0
- package/src/witness-rules.mjs +254 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
export const usage = `Usage: targeted-mutation <command> [options] (alias: tmts)
|
|
2
|
+
|
|
3
|
+
Commands:
|
|
4
|
+
analyze [PROJECT] [FILE...] Run the project's tests against targeted source edits and report test gaps.
|
|
5
|
+
extract FILE Print the comparison candidates found in one source file as JSON.
|
|
6
|
+
prototype PROJECT FILE Run the original threshold experiment on one file.
|
|
7
|
+
|
|
8
|
+
Scope (analyze):
|
|
9
|
+
--lines FILE:FROM-TO Limit to a line range. FILE:N selects one line. Repeatable.
|
|
10
|
+
--since REV Limit to lines added or changed since a Git revision.
|
|
11
|
+
--suggest-assertions For a survivor whose tests had the input: run the calls those tests make
|
|
12
|
+
without pinning the result, and give the value to compare with (Vitest).
|
|
13
|
+
--undo-changes With --since: also put each change back as it was at REV and run the suite.
|
|
14
|
+
A change the tests pass without is reported as UNTESTED CHANGE.
|
|
15
|
+
--copy-exclude PATH Leave a project path out of the temporary copies. Repeatable.
|
|
16
|
+
|
|
17
|
+
Profiles (analyze):
|
|
18
|
+
--mutators targeted|full targeted (default) edits comparison boundaries and integer thresholds
|
|
19
|
+
across <, <=, >, >=, plus value-aware targeted rules: an equality that
|
|
20
|
+
is always true or false, an operand of && || ?? that never decides,
|
|
21
|
+
?? for ||, == null for === null, another arithmetic operator, rounding or
|
|
22
|
+
end of a list, a sort without its comparison, a dropped await or copy.
|
|
23
|
+
Each survivor names the missing input or what to assert.
|
|
24
|
+
full adds the complete built-in mutation set (the StrykerJS mutators)
|
|
25
|
+
without requiring any external instrumenter package.
|
|
26
|
+
--witnesses Search for edits that survive and confirm a distinguishing test.
|
|
27
|
+
--spec FILE Specification with expected thresholds or witness plans.
|
|
28
|
+
--deterministic Declare a deterministic suite so recorded comparisons can decide a trial.
|
|
29
|
+
--audit Re-run predicted trials against the rewritten source.
|
|
30
|
+
--displace-thresholds Also try displaced thresholds (Vitest only).
|
|
31
|
+
--concurrency N Vitest workers that share the mutations (default: CPU count minus one).
|
|
32
|
+
With --witnesses: suite runs side by side (default: up to 8).
|
|
33
|
+
--verify-trials N Run N of the mutations decided inside workers again in fresh Vitest runs and
|
|
34
|
+
report any verdict that differs.
|
|
35
|
+
--isolated-trials Start a fresh Vitest run for every mutation instead of switching mutations
|
|
36
|
+
inside a running worker. Slower; for suites that leave state behind.
|
|
37
|
+
|
|
38
|
+
Runner (analyze):
|
|
39
|
+
--runner vitest|playwright Test runner (default: vitest).
|
|
40
|
+
--config FILE Runner configuration file inside the project.
|
|
41
|
+
--test FILE Run only this test file. Repeatable.
|
|
42
|
+
--timeout SECONDS Time limit for one run of the suite (default: 60).
|
|
43
|
+
--project NAME Playwright project. Repeatable.
|
|
44
|
+
|
|
45
|
+
Output:
|
|
46
|
+
--format text|json analyze prints text on a terminal and JSON otherwise.
|
|
47
|
+
--mode script|module extract: parse goal.
|
|
48
|
+
--dialect ts|tsx extract: source dialect.
|
|
49
|
+
-h, --help Show this help.
|
|
50
|
+
-v, --version Show the version.`;
|
|
51
|
+
|
|
52
|
+
export function chooseFormat(requested, terminal) {
|
|
53
|
+
if (requested === undefined) return terminal ? 'text' : 'json';
|
|
54
|
+
if (requested !== 'text' && requested !== 'json') throw new Error('Expected --format text|json');
|
|
55
|
+
return requested;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Test names and runner output come from the analyzed project and can carry terminal control sequences.
|
|
59
|
+
const printable = value => String(value).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '?');
|
|
60
|
+
const firstLine = value => printable(value).split('\n').find(line => line.trim())?.trim() ?? '';
|
|
61
|
+
const at = location => location ? `${location.file}:${location.line}:${location.column}` : '(unknown location)';
|
|
62
|
+
|
|
63
|
+
function describeEdit(mutant) {
|
|
64
|
+
const name = mutant.mutatorName ?? mutant.rule ?? 'edit';
|
|
65
|
+
if (mutant.since !== undefined) return `${name}: ${mutant.together ? 'the changes of the file together' : firstLine(mutant.original) || '(removed lines)'} as it was at ${printable(mutant.since.slice(0, 12))}`;
|
|
66
|
+
if (mutant.original !== undefined) return `${name}: ${firstLine(mutant.original)} -> ${firstLine(mutant.replacement)}`;
|
|
67
|
+
const operator = String(mutant.replacement).trim();
|
|
68
|
+
if (mutant.operator !== undefined && /^[<>=!&|?+*\/%-]+$/.test(operator)) return `${name}: ${mutant.operator} -> ${operator}`;
|
|
69
|
+
return `${name}: replace with ${firstLine(mutant.replacement)}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function describeBaseline(baseline = {}) {
|
|
73
|
+
const lines = [`The test suite did not pass before any edit (baseline ${baseline.status ?? 'unknown'}). Fix it and run again.`];
|
|
74
|
+
for (const failed of baseline.failedTests ?? []) {
|
|
75
|
+
lines.push(` FAILED ${printable(failed.file)} > ${printable(failed.name)}`);
|
|
76
|
+
for (const failure of failed.failures ?? []) lines.push(` ${firstLine(failure)}`);
|
|
77
|
+
}
|
|
78
|
+
for (const error of baseline.errors ?? []) lines.push(` ERROR ${firstLine(error)}`);
|
|
79
|
+
if (!baseline.failedTests?.length && !baseline.errors?.length && baseline.output?.trim()) {
|
|
80
|
+
lines.push(...printable(baseline.output).trim().split('\n').slice(-20).map(line => ` ${line}`));
|
|
81
|
+
}
|
|
82
|
+
return lines;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function describeGap(gap) {
|
|
86
|
+
const lines = [`${gap.kind ?? 'GAP'} ${at(gap.location)}${gap.rule ? ` ${gap.rule}` : ''}`];
|
|
87
|
+
const witness = gap.witness;
|
|
88
|
+
const inputs = witness?.arguments ?? witness?.operands;
|
|
89
|
+
if (inputs) {
|
|
90
|
+
lines.push(` ${witness.arguments ? 'arguments' : 'operands'} (${inputs.map(printable).join(', ')}): ` +
|
|
91
|
+
`original ${printable(witness.original)}, edited ${printable(witness.mutant)}`);
|
|
92
|
+
}
|
|
93
|
+
if (gap.expression !== undefined) {
|
|
94
|
+
const edit = gap.mutations?.[0]?.replacement;
|
|
95
|
+
lines.push(` \`${firstLine(gap.expression)}\` passes every test as \`${firstLine(edit)}\`` +
|
|
96
|
+
(gap.reachedBy === undefined ? '' : ` (${gap.reachedBy} ${gap.reachedBy === 1 ? 'test reaches' : 'tests reach'} it)`));
|
|
97
|
+
if (gap.advice) lines.push(` ${printable(gap.advice)}`);
|
|
98
|
+
else if (gap.missing && gap.uncertain) {
|
|
99
|
+
lines.push(` add ${printable(gap.missing)}, or an assertion that tells them apart: the recording cannot tell whether a test has such an input`);
|
|
100
|
+
} else if (gap.missing) lines.push(` add ${printable(gap.missing)}`);
|
|
101
|
+
else {
|
|
102
|
+
const shown = (gap.tests ?? []).slice(0, 3).map(test => `${printable(test.file)} > ${printable(test.name)}`);
|
|
103
|
+
const more = (gap.tests?.length ?? 0) - shown.length;
|
|
104
|
+
const where = [...shown, ...(more > 0 ? [`${more} more`] : []), ...(gap.outsideTests ? ['code outside the tests'] : [])].join('; ');
|
|
105
|
+
const operands = gap.example?.operands ? ` (operands ${gap.example.operands.map(printable).join(', ')})` : '';
|
|
106
|
+
lines.push(` the edit gives another value in: ${where}${operands}`, ' add an assertion on what this value decides');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (gap.kind === 'UNTESTED CHANGE') {
|
|
110
|
+
lines.push(` the tests pass with ${gap.together ? 'these changes of the file put back together as they were' : 'this change put back as it was'} at ${printable(String(gap.since).slice(0, 12))}`,
|
|
111
|
+
' add a test that fails without the change');
|
|
112
|
+
}
|
|
113
|
+
for (const [label, list] of [['also evaluates', gap.effects?.nowRuns], ['no longer evaluates', gap.effects?.noLongerRuns]]) {
|
|
114
|
+
for (const entry of list ?? []) {
|
|
115
|
+
lines.push(` with the edit, ${entry.test === undefined ? 'loading the file' : `\`${printable(entry.test)}\``} ${label} ` +
|
|
116
|
+
`\`${firstLine(entry.expression)}\` (${printable(entry.location.file)}:${entry.location.line})`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (gap.strengthens) {
|
|
120
|
+
lines.push(` ${printable(gap.strengthens.file)} > ${printable(gap.strengthens.test)} calls \`${printable(gap.strengthens.call)}\` without pinning its result: ` +
|
|
121
|
+
`it gives ${printable(gap.strengthens.original)}, and ${printable(gap.strengthens.edited)} with the edit`);
|
|
122
|
+
}
|
|
123
|
+
if (gap.suggestedTest) lines.push(` suggested test: ${printable(gap.suggestedTest)}`);
|
|
124
|
+
if (gap.seed) lines.push(` based on: ${printable(gap.seed.file)} > ${printable(gap.seed.test)}`);
|
|
125
|
+
if (gap.requirement) lines.push(` requirement: ${firstLine(gap.requirement)}`);
|
|
126
|
+
if (gap.suggestedTestFile) lines.push(` suggested test file: ${printable(gap.suggestedTestFile)}`);
|
|
127
|
+
if (gap.verification?.status) lines.push(` verification: ${printable(gap.verification.status)}`);
|
|
128
|
+
if (gap.verification?.baselineWithWitness) {
|
|
129
|
+
lines.push(` verification: original ${printable(gap.verification.baselineWithWitness)}, edited ${printable(gap.verification.rewriteWithWitness)}`);
|
|
130
|
+
}
|
|
131
|
+
return lines;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function renderText(report) {
|
|
135
|
+
const lines = [];
|
|
136
|
+
for (const file of report.extraction ?? []) {
|
|
137
|
+
if (file.path !== 'diagnostic') continue;
|
|
138
|
+
lines.push(`SKIPPED ${printable(file.file)}: ${file.reason ?? 'not analyzed'}`);
|
|
139
|
+
for (const diagnostic of file.diagnostics ?? []) lines.push(` ${firstLine(diagnostic.message)}`);
|
|
140
|
+
}
|
|
141
|
+
if (report.evaluation === 'baseline_error') {
|
|
142
|
+
lines.push(...describeBaseline(report.baseline));
|
|
143
|
+
return lines.join('\n');
|
|
144
|
+
}
|
|
145
|
+
const mutants = report.mutants ?? [];
|
|
146
|
+
for (const mutant of mutants) {
|
|
147
|
+
lines.push(`${at(mutant.location)} ${mutant.status} ${describeEdit(mutant)}`);
|
|
148
|
+
}
|
|
149
|
+
const gaps = report.diagnostics ?? [];
|
|
150
|
+
if (gaps.length) lines.push('', 'Test gaps:');
|
|
151
|
+
for (const gap of gaps) lines.push(...describeGap(gap));
|
|
152
|
+
if (lines.length) lines.push('');
|
|
153
|
+
if (report.evaluation === 'no_sites') {
|
|
154
|
+
lines.push('No edit sites in the selected scope.');
|
|
155
|
+
return lines.join('\n');
|
|
156
|
+
}
|
|
157
|
+
const counts = new Map();
|
|
158
|
+
for (const mutant of mutants) counts.set(mutant.status, (counts.get(mutant.status) ?? 0) + 1);
|
|
159
|
+
const tally = [...counts].map(([status, count]) => `${count} ${status}`).join(', ') || 'none';
|
|
160
|
+
const tests = report.baseline?.tests;
|
|
161
|
+
const size = Array.isArray(tests) ? tests.length : tests;
|
|
162
|
+
lines.push(`${report.runner}${size === undefined ? '' : `, ${size} baseline tests`}: ` +
|
|
163
|
+
`${mutants.length} edits (${tally}), ${gaps.length} test gaps` +
|
|
164
|
+
(report.evaluation === 'evaluated' ? '' : `, evaluation ${report.evaluation}`));
|
|
165
|
+
return lines.join('\n');
|
|
166
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const extensions = /\.(?:[cm]?[jt]s|[jt]sx)$/i;
|
|
4
|
+
|
|
5
|
+
function invalidModuleSyntax(ts, file, diagnostics) {
|
|
6
|
+
return () => (tree) => {
|
|
7
|
+
for (const statement of tree.statements) {
|
|
8
|
+
const assignment = ts.isExportAssignment(statement) && statement.isExportEquals;
|
|
9
|
+
const requireImport = ts.isImportEqualsDeclaration(statement) && !statement.isTypeOnly &&
|
|
10
|
+
ts.isExternalModuleReference(statement.moduleReference);
|
|
11
|
+
if (!assignment && !requireImport) continue;
|
|
12
|
+
diagnostics.push({
|
|
13
|
+
file, code: 'INCOMPATIBLE_MODULE_SYNTAX', severity: 'error',
|
|
14
|
+
message: 'An ECMAScript module cannot emit a TypeScript import = require() or export = declaration',
|
|
15
|
+
start: statement.getStart(tree), end: statement.end,
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
return tree;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function commonJsError(code, file) {
|
|
23
|
+
try {
|
|
24
|
+
require('node:vm').compileFunction(code, ['exports', 'require', 'module', '__filename', '__dirname'], { filename: file });
|
|
25
|
+
return null;
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
28
|
+
return { file, code: 'INVALID_COMMONJS_OUTPUT', severity: 'error', message: error.message, start: 0, end: 0 };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function transform(source, { file, target, outputModule, jsx, sourceMap }, verifyRuntimeExports, fail) {
|
|
33
|
+
const ts = require('typescript');
|
|
34
|
+
const extraDiagnostics = [];
|
|
35
|
+
const compilerFile = file.replace(/\.[cm]([jt]s)$/i, '.$1');
|
|
36
|
+
const result = ts.transpileModule(source, {
|
|
37
|
+
fileName: compilerFile,
|
|
38
|
+
reportDiagnostics: true,
|
|
39
|
+
transformers: outputModule === 'esm' ? { before: [invalidModuleSyntax(ts, file, extraDiagnostics)] } : undefined,
|
|
40
|
+
compilerOptions: {
|
|
41
|
+
target: target === 'esnext' ? ts.ScriptTarget.ESNext : ts.ScriptTarget[target === 'es6' ? 'ES2015' : target.toUpperCase()],
|
|
42
|
+
module: { preserve: ts.ModuleKind.Preserve, esm: ts.ModuleKind.ESNext, cjs: ts.ModuleKind.CommonJS }[outputModule],
|
|
43
|
+
jsx: { automatic: ts.JsxEmit.ReactJSX, classic: ts.JsxEmit.React, preserve: ts.JsxEmit.Preserve }[jsx],
|
|
44
|
+
verbatimModuleSyntax: true,
|
|
45
|
+
sourceMap,
|
|
46
|
+
inlineSources: sourceMap,
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
const diagnostics = result.diagnostics.map(diagnostic => ({
|
|
50
|
+
file,
|
|
51
|
+
code: diagnostic.code,
|
|
52
|
+
severity: ts.DiagnosticCategory[diagnostic.category].toLowerCase(),
|
|
53
|
+
message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
|
|
54
|
+
start: diagnostic.start ?? 0,
|
|
55
|
+
end: (diagnostic.start ?? 0) + (diagnostic.length ?? 0),
|
|
56
|
+
}));
|
|
57
|
+
diagnostics.push(...extraDiagnostics);
|
|
58
|
+
if (diagnostics.some(diagnostic => diagnostic.severity === 'error')) return fail('typescript', diagnostics);
|
|
59
|
+
const map = result.sourceMapText ? JSON.parse(result.sourceMapText) : null;
|
|
60
|
+
if (map) {
|
|
61
|
+
const { basename } = require('node:path');
|
|
62
|
+
map.sources = [basename(file)];
|
|
63
|
+
map.file = basename(file).replace(extensions, jsx === 'preserve' && /x$/i.test(file) ? '.jsx' :
|
|
64
|
+
outputModule === 'cjs' && /\.c[jt]s$/i.test(file) ? '.cjs' :
|
|
65
|
+
/\.m[jt]s$/i.test(file) && outputModule !== 'cjs' ? '.mjs' : '.js');
|
|
66
|
+
}
|
|
67
|
+
const code = map ? result.outputText.replace(/\/\/# sourceMappingURL=[^\r\n]*$/, '') : result.outputText;
|
|
68
|
+
if (outputModule === 'cjs' && !(jsx === 'preserve' && /x$/i.test(file))) {
|
|
69
|
+
const error = commonJsError(code, file);
|
|
70
|
+
if (error) return fail('typescript', [...diagnostics, error]);
|
|
71
|
+
}
|
|
72
|
+
const output = { backend: 'typescript', code, sourceMap: map, diagnostics };
|
|
73
|
+
return outputModule === 'cjs' ? output : verifyRuntimeExports(output, file);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function hasSplitDeclare(source, code) {
|
|
77
|
+
const leading = /\bdeclare(?=[^\S\r\n\u2028\u2029]*(?:[\r\n\u2028\u2029]|\/[/*]))/g;
|
|
78
|
+
const trivia = /(?:\s+|\/\/[^\r\n\u2028\u2029]*|\/\*[^]*?\*\/)*/y;
|
|
79
|
+
const declaration = /(?:const|let|var|class|function|enum|namespace|module|type|interface|abstract|global)\b/y;
|
|
80
|
+
const offsets = new Set();
|
|
81
|
+
for (const { index } of source.matchAll(leading)) {
|
|
82
|
+
if (code?.startsWith('declare', index)) continue;
|
|
83
|
+
trivia.lastIndex = index + 'declare'.length;
|
|
84
|
+
if (!/[\r\n\u2028\u2029]/.test(trivia.exec(source)[0])) continue;
|
|
85
|
+
declaration.lastIndex = trivia.lastIndex;
|
|
86
|
+
if (declaration.test(source)) offsets.add(index);
|
|
87
|
+
}
|
|
88
|
+
if (!offsets.size) return false;
|
|
89
|
+
|
|
90
|
+
// Raw matches can be inside erased comments or template-literal types.
|
|
91
|
+
let ts;
|
|
92
|
+
try {
|
|
93
|
+
ts = require('typescript');
|
|
94
|
+
} catch (error) {
|
|
95
|
+
if (error.code !== 'MODULE_NOT_FOUND') throw error;
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
const tree = ts.createSourceFile('context.ts', source, ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
|
|
99
|
+
function check(node) {
|
|
100
|
+
if (ts.isExpressionStatement(node) && ts.isIdentifier(node.expression) &&
|
|
101
|
+
node.expression.escapedText === 'declare' && offsets.has(node.expression.getStart(tree))) return true;
|
|
102
|
+
return ts.forEachChild(node, check);
|
|
103
|
+
}
|
|
104
|
+
return !!check(tree);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
exports.transform = transform;
|
|
108
|
+
exports.hasSplitDeclare = hasSplitDeclare;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// A type-erased output keeps every byte position, so its map comes from one native scan.
|
|
4
|
+
// Lowered output, a byte order mark and unusual names take the router, which asks TypeScript.
|
|
5
|
+
function mappedTypeScript(input, file, flags, addon) {
|
|
6
|
+
const slash = file.lastIndexOf('/');
|
|
7
|
+
const name = slash < 0 ? file : file.slice(slash + 1);
|
|
8
|
+
if (!name.endsWith('.mts') && !name.endsWith('.ts') && !name.endsWith('.tsx') || name.includes('\\')) return undefined;
|
|
9
|
+
const text = typeof input === 'string' ? input : Buffer.isBuffer(input) ? undefined : null;
|
|
10
|
+
if (text === null || text !== undefined && (!text.isWellFormed() || text.charCodeAt(0) === 0xFEFF)) return undefined;
|
|
11
|
+
const source = text === undefined ? input : Buffer.from(text);
|
|
12
|
+
if (source[0] === 0xEF) return undefined;
|
|
13
|
+
const emit = addon.emitTypeScript;
|
|
14
|
+
const result = emit === undefined ? undefined : emit(source, flags | 16);
|
|
15
|
+
if (result === undefined) return undefined;
|
|
16
|
+
return { backend: 'pulse', code: result[0], sourceMap: sourceMapObject(file, result[1], text ?? source.toString()), diagnostics: [] };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// The fields other than the mappings follow the map TypeScript writes for the same name.
|
|
20
|
+
function sourceMapObject(file, mappings, text) {
|
|
21
|
+
const name = file.slice(file.lastIndexOf('/') + 1);
|
|
22
|
+
const module = name.endsWith('.mts');
|
|
23
|
+
const width = module || name.endsWith('.tsx') ? 4 : 3;
|
|
24
|
+
return { version: 3, file: name.slice(0, -width) + (module ? '.mjs' : '.js'), sourceRoot: '', sources: [name], names: [],
|
|
25
|
+
mappings, sourcesContent: [text] };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// The source kinds and flags of the entry (src/compiler.cjs).
|
|
29
|
+
const classic = 4, esm = 2, script = 8;
|
|
30
|
+
|
|
31
|
+
// An option spelled out with its default value selects the same route as an omitted one. A module format of esm
|
|
32
|
+
// and a source map have native routes of their own. Returns undefined for everything the router has to decide.
|
|
33
|
+
function compileExplicit(input, options, compile, sourceKind, moduleAddon) {
|
|
34
|
+
const name = options.file;
|
|
35
|
+
const jsx = options.jsx;
|
|
36
|
+
const format = options.module;
|
|
37
|
+
const map = options.sourceMap;
|
|
38
|
+
if (options.mode !== undefined && options.mode !== 'transform' || options.target !== undefined && options.target !== 'esnext' ||
|
|
39
|
+
map !== undefined && typeof map !== 'boolean' || name !== undefined && typeof name !== 'string' ||
|
|
40
|
+
jsx !== undefined && jsx !== 'automatic' && jsx !== 'classic' ||
|
|
41
|
+
format !== undefined && format !== 'preserve' && format !== 'esm') return undefined;
|
|
42
|
+
const file = name === undefined ? 'input.ts' : name;
|
|
43
|
+
const kind = sourceKind(file);
|
|
44
|
+
if (map !== true && (format !== 'esm' || kind === (script | esm))) {
|
|
45
|
+
// Every option has its default value, or names the module format that an .mjs name already implies,
|
|
46
|
+
// so the default call gives the same result.
|
|
47
|
+
return compile(input, name === undefined && jsx === undefined ? undefined : { file, jsx });
|
|
48
|
+
}
|
|
49
|
+
if (kind < 0 || kind >= script) return undefined;
|
|
50
|
+
const flags = kind | (jsx === 'classic' ? classic : 0) | (format === 'esm' ? esm : 0);
|
|
51
|
+
if (map === true) return mappedTypeScript(input, file, flags, moduleAddon());
|
|
52
|
+
const source = Buffer.isBuffer(input) ? input : typeof input === 'string' && input.isWellFormed() ? Buffer.from(input) : null;
|
|
53
|
+
const emit = source === null ? undefined : moduleAddon().emitTypeScript;
|
|
54
|
+
const code = emit === undefined ? undefined : emit(source, flags);
|
|
55
|
+
return code === undefined ? undefined : { backend: 'pulse', code, sourceMap: null, diagnostics: [] };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
exports.compileExplicit = compileExplicit;
|
|
59
|
+
exports.mappedTypeScript = mappedTypeScript;
|
|
60
|
+
exports.sourceMapObject = sourceMapObject;
|