How to use the typescript.createSourceFile function in typescript

To help you get started, we’ve selected a few typescript examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github angular / angular / packages / compiler-cli / src / ngtsc / typecheck / src / diagnostics.ts View on Github external
};
  } else if (mapping.type === 'indirect' || mapping.type === 'external') {
    // For indirect mappings (template was declared inline, but ngtsc couldn't map it directly
    // to a string constant in the decorator), the component's file name is given with a suffix
    // indicating it's not the TS file being displayed, but a template.
    // For external temoplates, the HTML filename is used.
    const componentSf = mapping.componentClass.getSourceFile();
    const componentName = mapping.componentClass.name.text;
    // TODO(alxhub): remove cast when TS in g3 supports this narrowing.
    const fileName = mapping.type === 'indirect' ?
        `${componentSf.fileName} (${componentName} template)` :
        (mapping as ExternalTemplateSourceMapping).templateUrl;
    // TODO(alxhub): investigate creating a fake `ts.SourceFile` here instead of invoking the TS
    // parser against the template (HTML is just really syntactically invalid TypeScript code ;).
    // Also investigate caching the file to avoid running the parser multiple times.
    const sf = ts.createSourceFile(
        fileName, mapping.template, ts.ScriptTarget.Latest, false, ts.ScriptKind.JSX);

    let relatedInformation: ts.DiagnosticRelatedInformation[] = [];
    if (relatedMessage !== undefined) {
      relatedInformation.push({
        category: ts.DiagnosticCategory.Message,
        code: 0,
        file: sf,
        start: relatedMessage.span.start.offset,
        length: relatedMessage.span.end.offset - relatedMessage.span.start.offset,
        messageText: relatedMessage.text,
      });
    }

    relatedInformation.push({
      category: ts.DiagnosticCategory.Message,
github brunch / typescript-brunch / transpile.js View on Github external
options.allowNonTsExtensions = true;
  // We are not returning a sourceFile for lib file when asked by the program,
  // so pass --noLib to avoid reporting a file not found error.
  options.noLib = true;
  // In case it was defined, this is needed to work with noLib above.
  options.lib = undefined;
  // We are not doing a full typecheck, we are not resolving the whole context,
  // so pass --noResolve to avoid reporting missing file errors.
  options.noResolve = true;
  // We do want to emit here, so specifically enable it.
  options.noEmit = false;
  // if jsx is specified then treat file as .tsx
  const inputFileName = transpileOptions.fileName ||
    (options.jsx ? 'module.tsx' : 'module.ts');

  const sourceFile = ts.createSourceFile(inputFileName, input, options.target);

  if (transpileOptions.moduleName) {
    sourceFile.moduleName = transpileOptions.moduleName;
  }

  sourceFile.renamedDependencies = transpileOptions.renamedDependencies;

  const newLine = ts.getNewLineCharacter(options);

  // Output
  let outputText;
  let sourceMapText;

  // Create a compilerHost object to allow the compiler to read and write files
  const compilerHost = {
    getSourceFile(fileName /* target*/) {
github paulkoerbitz / resolve-types / src / resolve-types.ts View on Github external
const getSourceFile = (
        fileName: string,
        languageVersion: ts.ScriptTarget,
        ...args: any[]
    ) => {
        if (!FILENAME_RE.test(fileName)) {
            return (compilerHost.getSourceFile as any)(
                fileName,
                languageVersion,
                ...args
            );
        }
        if (inlineSourceFile == undefined) {
            inlineSourceFile = ts.createSourceFile(
                FILENAME,
                code,
                languageVersion
            );
        }
        return inlineSourceFile;
    };
    const options = getOptions();
github fossasia / susper.com / node_modules / @angular / cli / lib / ast-tools / route-utils.js View on Github external
function getRootNode(file) {
    return ts.createSourceFile(file, fs.readFileSync(file).toString(), ts.ScriptTarget.Latest, true);
}
//# sourceMappingURL=/users/hansl/sources/hansl/angular-cli/lib/ast-tools/route-utils.js.map
github compodoc / ngd / src / modules / core / dist / lang / utilities.js View on Github external
getSourceFile: function (fileName) {
            if (fileName.lastIndexOf('.ts') !== -1) {
                if (fileName === 'lib.d.ts') {
                    return undefined;
                }
                if (path.isAbsolute(fileName) === false) {
                    fileName = path.join(transpileOptions.tsconfigDirectory, fileName);
                }
                var libSource = '';
                try {
                    libSource = fs.readFileSync(fileName).toString();
                }
                catch (e) {
                    logger_1.logger.trace(e, fileName);
                }
                return ts.createSourceFile(fileName, libSource, transpileOptions.target, false);
            }
            return undefined;
        },
        writeFile: function (name, text) { },
github alibaba / kiwi / kiwi-linter / src / astUtils.ts View on Github external
export function removeFileComment(code: string, fileName: string) {
  const printer: ts.Printer = ts.createPrinter({ removeComments: true });
  const sourceFile: ts.SourceFile = ts.createSourceFile(
    '',
    code,
    ts.ScriptTarget.ES2015,
    true,
    fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS
  );
  return printer.printFile(sourceFile);
}
github apazureck / openui5vscodeTypescriptTools / client / src / language / searchFunctions.ts View on Github external
export function findNodesBySyntaxKind(document: TextDocument, searchKind: ts.SyntaxKind): IFoundNode[] {
    const foundNodes: IFoundNode[] = [];
    const sourcefile = ts.createSourceFile(document.fileName, document.getText(), ts.ScriptTarget.ES5, true);
    traverseNodes(sourcefile, foundNodes, document, searchKind);
    return foundNodes;
}
github tensorflow / tensorboard / tensorboard / tools / migration / src / polymerelementify.ts View on Github external
export function transform(
  fileName: string,
  sourceContent: string,
  exporter: Exporter
) {
  const range = ts.getLeadingCommentRanges(sourceContent, 0);
  const preamble = range
    ? range.map(({pos, end}) => sourceContent.slice(pos, end)).join('\n')
    : TS_LICENSE;
  let sourceFile = ts.createSourceFile(
    fileName,
    sourceContent,
    ts.ScriptTarget.ES2015,
    /*setParentNodes */ true
  );
  sourceFile = removeModuleWrappers(sourceFile);
  sourceFile = transformPolymer(sourceFile);
  const result = `${preamble}
${sourceFile.getText()}`;
  exporter.writeFile(fileName, result);
}
github NarikMe / narik-angular / projects / narik-cli / schematics / ng-add / index.ts View on Github external
export function hasNgModuleImport(
  tree: Tree,
  modulePath: string,
  className: string
): boolean {
  const moduleFileContent = tree.read(modulePath);

  if (!moduleFileContent) {
    throw new Error(`Could not read Angular module file: ${modulePath}`);
  }

  const parsedFile = ts.createSourceFile(
    modulePath,
    moduleFileContent.toString(),
    ts.ScriptTarget.Latest,
    true
  );
  let ngModuleMetadata: ts.ObjectLiteralExpression | null = null;

  const findModuleDecorator = (node: ts.Node) => {
    if (
      ts.isDecorator(node) &&
      ts.isCallExpression(node.expression) &&
      isNgModuleCallExpression(node.expression)
    ) {
      ngModuleMetadata = node.expression
        .arguments[0] as ts.ObjectLiteralExpression;
github GoogleChrome / lighthouse / lighthouse-core / scripts / i18n / collect-strings.js View on Github external
function parseUIStrings(sourceStr, liveUIStrings) {
  const tsAst = tsc.createSourceFile('uistrings', sourceStr, tsc.ScriptTarget.ES2019, true, tsc.ScriptKind.JS);

  const extractionError = new Error('UIStrings declaration was not extracted correctly by the collect-strings regex.');
  const uiStringsStatement = tsAst.statements[0];
  if (tsAst.statements.length !== 1) throw extractionError;
  if (!tsc.isVariableStatement(uiStringsStatement)) throw extractionError;

  const uiStringsDeclaration = uiStringsStatement.declarationList.declarations[0];
  if (!tsc.isVariableDeclaration(uiStringsDeclaration)) throw extractionError;
  if (getIdentifier(uiStringsDeclaration) !== 'UIStrings') throw extractionError;

  const uiStringsObject = uiStringsDeclaration.initializer;
  if (!uiStringsObject || !tsc.isObjectLiteralExpression(uiStringsObject)) throw extractionError;

  /** @type {Record} */
  const parsedMessages = {};