@carlosv2/glue
Version:
Dependency injection library that stays out of the way
78 lines (77 loc) • 2.96 kB
JavaScript
import ts from 'typescript';
import { gibberish, isString } from './utils.js';
const { factory } = ts;
export class Importer {
constructor() {
this.imports = {};
}
randomise(name) {
return `${name}_${gibberish(10)}`;
}
initPath(path) {
if (!(path in this.imports)) {
this.imports[path] = {
module: undefined,
default: undefined,
symbols: {},
};
}
}
module(path) {
this.initPath(path);
if (!isString(this.imports[path].module)) {
this.imports[path].module = this.randomise('Module');
}
return this.imports[path].module;
}
default(path) {
this.initPath(path);
if (!isString(this.imports[path].default)) {
this.imports[path].default = this.randomise('Default');
}
return this.imports[path].default;
}
symbol(path, symbol) {
this.initPath(path);
if (!(symbol in this.imports[path].symbols)) {
this.imports[path].symbols[symbol] = this.randomise(symbol);
}
return this.imports[path].symbols[symbol];
}
sanitise(path) {
if (path.endsWith('.ts') || path.endsWith('js')) {
return path.substring(0, path.length - 3);
}
return path;
}
compile() {
return Object.entries(this.imports)
.map(([path, importee]) => {
const declarations = [];
if (isString(importee.module)) {
declarations.push(factory.createImportDeclaration(undefined, factory.createImportClause(false, undefined, factory.createNamespaceImport(factory.createIdentifier(importee.module))), factory.createStringLiteral(this.sanitise(path))));
}
let defaultImport = undefined;
if (isString(importee.default)) {
defaultImport = factory.createIdentifier(importee.default);
}
let symbolsImport = undefined;
if (Object.keys(importee.symbols).length) {
symbolsImport = factory.createNamedImports(Object.entries(importee.symbols).map(([symbol, as]) => {
let propertyName = undefined;
let name = factory.createIdentifier(symbol);
if (isString(as)) {
propertyName = factory.createIdentifier(symbol);
name = factory.createIdentifier(as);
}
return factory.createImportSpecifier(false, propertyName, name);
}));
}
if (defaultImport || symbolsImport) {
declarations.push(factory.createImportDeclaration(undefined, factory.createImportClause(false, defaultImport, symbolsImport), factory.createStringLiteral(this.sanitise(path))));
}
return declarations;
})
.flat();
}
}