Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

JavaScript · 129 lines · 4.9 KiB · at f30ac63

// Per-file compilation shared by `tsus build`, `tsus check`, and the bundler// plugins: preprocess, run the strictness rules, and emit JS with a source// map that points at the original .tsus file.import path from "node:path";import ts from "typescript";import { preprocess } from "./preprocess.js";import { checkSource } from "./check.js";import { lineStarts, positionOf, decodeMappings, encodeMappings } from "./sourcemap.js";// Preprocess one .tsus source and run the syntactic rules over the result.// Every diagnostic carries a 1-based line/col in the .tsus file.export const compileTsus = (source, fileName) => {  const pre = preprocess(source);  const starts = lineStarts(source);  const locateSource = (offset) => {    const { line, character } = positionOf(starts, offset);    return { line: line + 1, col: character + 1 };  };  const locate = (offset) => locateSource(pre.toSource(offset));  const diagnostics = [    ...pre.diagnostics.map(({ offset, ...d }) => ({ ...d, file: fileName, ...locateSource(offset) })),    ...checkSource(fileName, pre.code, locate),  ];  return { ...pre, source, fileName, locate, locateSource, diagnostics };};const rewriteSpecifier = (spec) =>  /^\.{1,2}\//.test(spec) && /\.(tsus|ts)$/.test(spec) && !spec.endsWith(".d.ts")    ? spec.replace(/\.(tsus|ts)$/, ".js")    : spec;// TS transformer: relative `.tsus`/`.ts` import specifiers become `.js`, so// the emitted dist tree resolves on its own. Done on the AST rather than the// text so source map columns stay right.const specifierTransformer = (context) => {  const f = context.factory;  const visit = (node) => {    if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {      const next = rewriteSpecifier(node.moduleSpecifier.text);      if (next !== node.moduleSpecifier.text) {        return f.updateImportDeclaration(          node,          node.modifiers,          node.importClause,          f.createStringLiteral(next),          node.attributes,        );      }    }    if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {      const next = rewriteSpecifier(node.moduleSpecifier.text);      if (next !== node.moduleSpecifier.text) {        return f.updateExportDeclaration(          node,          node.modifiers,          node.isTypeOnly,          node.exportClause,          f.createStringLiteral(next),          node.attributes,        );      }    }    if (      ts.isCallExpression(node) &&      node.expression.kind === ts.SyntaxKind.ImportKeyword &&      node.arguments.length > 0 &&      ts.isStringLiteral(node.arguments[0])    ) {      const next = rewriteSpecifier(node.arguments[0].text);      if (next !== node.arguments[0].text) {        return f.updateCallExpression(node, node.expression, node.typeArguments, [          f.createStringLiteral(next),          ...node.arguments.slice(1),        ]);      }    }    return ts.visitEachChild(node, visit, context);  };  return (sf) => ts.visitNode(sf, visit);};const COMPILER_OPTIONS = {  module: ts.ModuleKind.ESNext,  target: ts.ScriptTarget.ES2022,  sourceMap: true,  inlineSources: false,};// Emit JS for already-lowered TypeScript `code`. `toSource` maps offsets in// `code` back to `sourceText` (identity for plain .ts). Returns the JS (with// a sourceMappingURL comment unless `inlineMap`) and a v3 source map whose// single source is `sourcePath` (relative to the output file).export const emitJs = ({ code, toSource, sourceText, sourcePath, outName, rewriteImports = true, inlineMap = false }) => {  const out = ts.transpileModule(code, {    compilerOptions: COMPILER_OPTIONS,    fileName: "module.ts",    transformers: rewriteImports ? { before: [specifierTransformer] } : undefined,  });  const js = out.outputText.replace(/\n?\/\/# sourceMappingURL=.*\s*$/, "\n");  const raw = JSON.parse(out.sourceMapText);  const genStarts = lineStarts(code);  const srcStarts = lineStarts(sourceText);  const lines = decodeMappings(raw.mappings).map((segs) =>    segs.map((seg) => {      if (seg.length < 4) {        return seg;      }      const line = Math.min(seg[2], genStarts.length - 1);      const offset = Math.min(genStarts[line] + seg[3], code.length);      const pos = positionOf(srcStarts, toSource(offset));      return [seg[0], 0, pos.line, pos.character];    }),  );  const map = {    version: 3,    file: outName,    sources: [sourcePath],    sourcesContent: [sourceText],    names: [],    mappings: encodeMappings(lines),  };  const comment = inlineMap    ? `//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(map)).toString("base64")}`    : `//# sourceMappingURL=${outName}.map`;  return { js: `${js}${comment}\n`, map };};export const relativeSourcePath = (fromFile, toFile) =>  path.relative(path.dirname(fromFile), toFile).split(path.sep).join("/");