Skip to content

implementation and test for SolutionBuilderAsync functionality #48920

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,336 changes: 2,336 additions & 0 deletions src/compiler/tsbuildPublicAsync.ts

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion src/compiler/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
"watch.ts",
"watchPublic.ts",
"tsbuild.ts",
"tsbuildPublic.ts"
"tsbuildPublic.ts",
"tsbuildPublicAsync.ts"
]
}
1 change: 1 addition & 0 deletions src/testRunner/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@
"unittests/tsbuildWatch/noEmitOnError.ts",
"unittests/tsbuildWatch/programUpdates.ts",
"unittests/tsbuildWatch/publicApi.ts",
"unittests/tsbuildWatch/publicApiAsync.ts",
"unittests/tsbuildWatch/reexport.ts",
"unittests/tsbuildWatch/watchEnvironment.ts",
"unittests/tsc/composite.ts",
Expand Down
205 changes: 205 additions & 0 deletions src/testRunner/unittests/tsbuildWatch/publicApiAsync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
namespace ts.tscWatch {
const verbose = false; // only set to true during development with this test function.
it("unittests:: tsbuildWatch:: publicAPIAsync", async () => {
interface DeferredPromise {
waitable: Promise<number>;
resolve: (x: number) => void;
};
function createDeferredPromise(): DeferredPromise{
const dp: Partial<DeferredPromise>={};
dp.waitable = new Promise(resolve=>{
dp.resolve=resolve;
});
return dp as DeferredPromise;
}
const solution: File = {
path: `${projectRoot}/tsconfig.json`,
content: JSON.stringify({
references: [
{ path: "./shared/tsconfig.json" },
{ path: "./webpack/tsconfig.json" }
],
files: []
})
};
const sharedConfig: File = {
path: `${projectRoot}/shared/tsconfig.json`,
content: JSON.stringify({
compilerOptions: { composite: true },
})
};
const sharedIndexWithErr: File = {
path: `${projectRoot}/shared/index.ts`,
content: `export function f1() { }
export class c { }
export enum e { }
// leading
export function f1() { } // trailing`
};
const sharedIndex: File = {
path: `${projectRoot}/shared/index.ts`,
content: `export function f1() { }
export class c { }
export enum e { }
// leading
export function f2() { } // trailing`
};
const webpackConfig: File = {
path: `${projectRoot}/webpack/tsconfig.json`,
content: JSON.stringify({
compilerOptions: { composite: true, },
references: [{ path: "../shared/tsconfig.json" }]
})
};
const webpackIndex: File = {
path: `${projectRoot}/webpack/index.ts`,
content: `export function f2() { }
export class c2 { }
export enum e2 { }
// leading
export function f22() { } // trailing`
};
const sys1 = createWatchedSystem([libFile, solution, sharedConfig, sharedIndexWithErr, webpackConfig, webpackIndex], { currentDirectory: projectRoot });
// @ts-ignore
const commandLineArgs = ["--b", "--w"];
// @ts-ignore
const { sys, baseline, oldSnap, cb:_cb, getPrograms } = createBaseline(sys1);
//const buildHost = createSolutionBuilderWithWatchHostForBaseline(sys, cb);
sys.write = (()=>{
const sysWriteOrig = (sys.write).bind(sys);
return (message: string)=>{
if (verbose) console.log(message);
sysWriteOrig(message);
};
})();
function testmsg(m: string){
sys.write(`test:: ${m+sys.newLine}`);
}
const buildHost = createSolutionBuilderWithWatchHostAsync(sys,
/*createProgram*/ undefined,
createDiagnosticReporter(sys, /*pretty*/ true),
createBuilderStatusReporter(sys, /*pretty*/ true),
createWatchStatusReporter(sys, /*pretty*/ true)
);
const handshake = {
settledErrorCount:createDeferredPromise()
};
buildHost.afterProgramEmitAndDiagnosticsAsync = async (program: EmitAndSemanticDiagnosticsBuilderProgram): Promise<void> =>{
const configFilePath = program.getCompilerOptions().configFilePath??"<configFilePath is undefined>";
testmsg(` afterProgramEmitAndDiagnosticsAsync: ${configFilePath}`);
};
buildHost.afterEmitBundleAsync = async (_config: ParsedCommandLine): Promise<void> => {
testmsg(` afterEmitBundleAsync`);
};
buildHost.solutionSettledAsync = async (totalErrors: number) =>{
testmsg(` solutionSettledAsync: totalErrors=${totalErrors}`);
handshake.settledErrorCount.resolve(totalErrors);
};
buildHost.getCustomTransformersAsync = getCustomTransformersAsync;
const builder = createSolutionBuilderWithWatchAsync(buildHost, [solution.path], { verbose: true });
let builderBuildAsync: ReturnType< typeof builder.buildAsync>;
return runWatchBaselineAsync({
scenario: "publicApiAsync",
subScenario: "with custom transformers",
commandLineArgs,
sys,
baseline,
oldSnap,
getPrograms,
changes: [
{
caption: "CHANGE:: builder.buildAsync()",
change: () => { builderBuildAsync = builder.buildAsync(); },
timeouts: async () => {
const actual = await handshake.settledErrorCount.waitable; // wait for settled
if (actual===0){
throw new Error(`expected >0 errors but found ${actual}`);
}
sys.write(`test:: first settled detection, ${actual} error(s)`);
handshake.settledErrorCount = createDeferredPromise();
}
},
{
caption: "CHANGE:: fix shared index",
change: sys => sys.writeFile(sharedIndex.path, sharedIndex.content),
timeouts: async () => {
const timeoutId = sys.getNextTimeoutId();
sys.write(`timeoutId=${timeoutId}`);
sys.checkTimeoutQueueLengthAndRun(1); // file change watches pass through delay
sys.checkTimeoutQueueLength(0);
const actual = await handshake.settledErrorCount.waitable; // wait for settled
if (actual!==0){
throw new Error(`expected 0 errors but found ${actual}`);
}
sys.write(`test:: second settled detection, ${actual} error(s)`);
handshake.settledErrorCount = createDeferredPromise();
}
},
{
caption: "CHANGE:: modify shared index",
change: sys => sys.prependFile(sharedIndex.path, "export function fooBar() {}"),
timeouts: async () => {
const timeoutId = sys.getNextTimeoutId();
sys.write(`timeoutId=${timeoutId}`);
sys.checkTimeoutQueueLengthAndRun(1); // file change watches pass through delay
sys.checkTimeoutQueueLength(0);
const actual = await handshake.settledErrorCount.waitable; // wait for settled
if (actual!==0){
throw new Error(`expected 0 errors but found ${actual}`);
}
sys.write(`test:: third settled detection, ${actual} error(s)`);
handshake.settledErrorCount = createDeferredPromise();
}
},
{
caption: "CHANGE:: builder.closeRequest()",
change: () => { builder.closeRequest(); },
timeouts: async () => {
await builderBuildAsync;
sys.write("test:: returned from await builder.buildAsync()");
}
}
],
// watchOrSolution: builder
});
async function getCustomTransformersAsync(project: string, program?: Program): Promise<CustomTransformers> {
const configFilePath = (()=>{
if (!program) return `<program is undefined>`;
return program.getCompilerOptions().configFilePath??"<configFilePath is undefined>";
})();
testmsg(` getCustomTransformersAsync: ${configFilePath}`);

const before: TransformerFactory<SourceFile> = context => {
return file => visitEachChild(file, visit, context);
function visit(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
return visitFunction(node as FunctionDeclaration);
default:
return visitEachChild(node, visit, context);
}
}
function visitFunction(node: FunctionDeclaration) {
addSyntheticLeadingComment(node, SyntaxKind.MultiLineCommentTrivia, `@before${project}`, /*hasTrailingNewLine*/ true);
return node;
}
};
const after: TransformerFactory<SourceFile> = context => {
return file => visitEachChild(file, visit, context);
function visit(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.VariableStatement:
return visitVariableStatement(node as VariableStatement);
default:
return visitEachChild(node, visit, context);
}
}
function visitVariableStatement(node: VariableStatement) {
addSyntheticLeadingComment(node, SyntaxKind.SingleLineCommentTrivia, `@after${project}`);
return node;
}
};
return { before: [before], after: [after] };
}
});
}
62 changes: 62 additions & 0 deletions src/testRunner/unittests/tscWatch/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,15 @@ namespace ts.tscWatch {
watchOrSolution: WatchOrSolution<T>
) => void;
}
export interface TscWatchCompileChangeAsync<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram> {
caption: string;
change: (sys: TestFSWithWatch.TestServerHostTrackingWrittenFiles) => Promise<void> | void;
timeouts: (
sys: TestFSWithWatch.TestServerHostTrackingWrittenFiles,
programs: readonly CommandLineProgram[],
watchOrSolution: WatchOrSolution<T>
) => Promise<void> | void;
}
export interface TscWatchCheckOptions {
baselineSourceMap?: boolean;
baselineDependencies?: boolean;
Expand All @@ -119,6 +128,12 @@ namespace ts.tscWatch {
commandLineArgs: readonly string[];
changes: readonly TscWatchCompileChange<T>[];
}
export interface TscWatchCompileBaseAsync<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram> extends TscWatchCheckOptions {
scenario: string;
subScenario: string;
commandLineArgs: readonly string[];
changes: readonly TscWatchCompileChangeAsync<T>[];
}
export interface TscWatchCompile extends TscWatchCompileBase {
sys: () => WatchedSystem;
}
Expand Down Expand Up @@ -245,6 +260,15 @@ namespace ts.tscWatch {
sys.diff(baseline, oldSnap);
return sys.snap();
}
export async function applyChangeAsync(sys: BaselineBase["sys"], baseline: BaselineBase["baseline"], change: TscWatchCompileChangeAsync["change"], caption?: TscWatchCompileChange["caption"]) {
const oldSnap = sys.snap();
baseline.push(`Change::${caption ? " " + caption : ""}`, "");
const changeResult = change(sys);
if (changeResult instanceof Promise) await changeResult;
baseline.push("Input::");
sys.diff(baseline, oldSnap);
return sys.snap();
}

export interface RunWatchBaseline<T extends BuilderProgram> extends BaselineBase, TscWatchCompileBase<T> {
sys: TestFSWithWatch.TestServerHostTrackingWrittenFiles;
Expand Down Expand Up @@ -283,6 +307,44 @@ namespace ts.tscWatch {
}
Harness.Baseline.runBaseline(`${isBuild(commandLineArgs) ? "tsbuild" : "tsc"}${isWatch(commandLineArgs) ? "Watch" : ""}/${scenario}/${subScenario.split(" ").join("-")}.js`, baseline.join("\r\n"));
}
export interface RunWatchBaselineAsync<T extends BuilderProgram> extends BaselineBase, TscWatchCompileBaseAsync<T> {
sys: TestFSWithWatch.TestServerHostTrackingWrittenFiles;
getPrograms: () => readonly CommandLineProgram[];
// watchOrSolution: SolutionBuilderAsync; // so far, not needed
}
export async function runWatchBaselineAsync<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>({
scenario, subScenario, commandLineArgs,
getPrograms, sys, baseline, oldSnap,
baselineSourceMap, baselineDependencies,
changes
}: RunWatchBaselineAsync<T>) {
baseline.push(`${sys.getExecutingFilePath()} ${commandLineArgs.join(" ")}`);
let programs = watchBaseline({
baseline,
getPrograms,
oldPrograms: emptyArray,
sys,
oldSnap,
baselineSourceMap,
baselineDependencies,
});

for (const { caption, change, timeouts } of changes) {
oldSnap = await applyChangeAsync(sys, baseline, change, caption);
const timeoutsResult = timeouts(sys, programs);
if (timeoutsResult instanceof Promise) await timeoutsResult;
programs = watchBaseline({
baseline,
getPrograms,
oldPrograms: programs,
sys,
oldSnap,
baselineSourceMap,
baselineDependencies,
});
}
Harness.Baseline.runBaseline(`${isBuild(commandLineArgs) ? "tsbuild" : "tsc"}${isWatch(commandLineArgs) ? "Watch" : ""}/${scenario}/${subScenario.split(" ").join("-")}.js`, baseline.join("\r\n"));
}

function isWatch(commandLineArgs: readonly string[]) {
return forEach(commandLineArgs, arg => {
Expand Down
Loading