perf - inline package.json and product.json (#219841)

This commit is contained in:
Benjamin Pasero
2024-07-04 07:59:10 +02:00
committed by GitHub
parent 34f8428e4b
commit 82c54248fd
15 changed files with 248 additions and 56 deletions

56
build/lib/inlineMeta.ts Normal file
View File

@@ -0,0 +1,56 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as es from 'event-stream';
import { basename } from 'path';
import * as File from 'vinyl';
export interface IInlineMetaContext {
readonly targetPaths: string[];
readonly packageJsonFn: () => string;
readonly productJsonFn: () => string;
}
const packageJsonMarkerId = 'BUILD_INSERT_PACKAGE_CONFIGURATION';
const productJsonMarkerId = 'BUILD_INSERT_PRODUCT_CONFIGURATION';
export function inlineMeta(result: NodeJS.ReadWriteStream, ctx: IInlineMetaContext): NodeJS.ReadWriteStream {
return result.pipe(es.through(function (file: File) {
if (matchesFile(file, ctx)) {
let content = file.contents.toString();
let markerFound = false;
const packageMarker = `${packageJsonMarkerId}:"${packageJsonMarkerId}"`; // this needs to be the format after esbuild has processed the file (e.g. double quotes)
if (content.includes(packageMarker)) {
content = content.replace(packageMarker, JSON.stringify(JSON.parse(ctx.packageJsonFn())).slice(1, -1) /* trim braces */);
markerFound = true;
}
const productMarker = `${productJsonMarkerId}:"${productJsonMarkerId}"`; // this needs to be the format after esbuild has processed the file (e.g. double quotes)
if (content.includes(productMarker)) {
content = content.replace(productMarker, JSON.stringify(JSON.parse(ctx.productJsonFn())).slice(1, -1) /* trim braces */);
markerFound = true;
}
if (markerFound) {
file.contents = Buffer.from(content);
} else if (content.includes(packageJsonMarkerId) || content.includes(productJsonMarkerId)) {
this.emit('error', new Error(`Unable to inline metadata because expected markers where not found in ${file.basename}.`));
return;
}
}
this.emit('data', file);
}));
}
function matchesFile(file: File, ctx: IInlineMetaContext): boolean {
for (const targetPath of ctx.targetPaths) {
if (file.basename === basename(targetPath)) { // TODO would be nicer to figure out root relative path to not match on false positives
return true;
}
}
return false;
}