angular-server-side-configuration
Version:
Configure an angular application on the server
62 lines • 2.78 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.VariableDetector = void 0;
const typescript_1 = require("typescript");
/** Detect environment variables in given file. */
class VariableDetector {
constructor(_logger) {
this._logger = _logger;
}
detect(fileContent) {
const sourceFile = (0, typescript_1.createSourceFile)('environment.ts', fileContent, typescript_1.ScriptTarget.ESNext, true);
let variant = 'process';
const ngEnvVariables = [];
const processVariables = [];
iterateNodes(sourceFile, (node) => {
if ((0, typescript_1.isImportDeclaration)(node) &&
node.moduleSpecifier.getText().match(/angular-server-side-configuration\/ng-env/)) {
variant = 'NG_ENV';
}
else if (!(0, typescript_1.isIdentifier)(node)) {
return;
}
if (node.getText() === 'NG_ENV') {
const variable = this._extractVariable(node, (n) => n.parent);
if (variable) {
ngEnvVariables.push(variable);
}
}
else if (node.getText() === 'process') {
const variable = this._extractVariable(node, (n) => n.parent.parent);
if (variable) {
processVariables.push(variable);
}
}
});
if (ngEnvVariables.length && processVariables.length) {
this._logger?.warn(`Detected both process.env.* and NG_ENV.* variables with selected variant ${variant}. Only the variables matching the current variant will be used.`);
}
const variables = (variant === 'process' ? processVariables : ngEnvVariables).sort();
return { variables, variant };
}
_extractVariable(node, resolveRoot) {
if (!(0, typescript_1.isPropertyAccessExpression)(node.parent) && !(0, typescript_1.isElementAccessExpression)(node.parent)) {
return undefined;
}
const root = resolveRoot(node);
if ((0, typescript_1.isPropertyAccessExpression)(root)) {
return root.name.getText();
}
if ((0, typescript_1.isElementAccessExpression)(root) && (0, typescript_1.isStringLiteralLike)(root.argumentExpression)) {
return root.argumentExpression.getText().replace(/['"`]/g, '');
}
this._logger?.warn(`Unable to resolve variable from ${node.getText()}. Please use direct assignment.`);
return undefined;
}
}
exports.VariableDetector = VariableDetector;
function iterateNodes(node, action) {
action(node);
(0, typescript_1.forEachChild)(node, (n) => iterateNodes(n, action));
}
//# sourceMappingURL=variable-detector.js.map
;