Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Experimental extractor with SWC #25

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions dist/collect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const { extractFromFile } = require('./extract');
const fs = require('fs');
const path = require('path');

const _mergeCatalogs = (a, b) => {
const c = {};

[a, b].forEach(catalog => {
Object.entries(catalog).forEach(([str, options]) => {
if (c[str]) {
c[str].origin.push(...options.origin);
} else {
c[str] = {
translation: '',
origin: [...options.origin],
};
}
});
});

return c;
};

const collectFromFiles = (srcPaths, ignore = []) => {
const ignorePattern = ignore.length ? new RegExp(ignore.join("|"), "i") : null
let translatableStrings = {};

srcPaths.forEach(srcFilename => {
if (
!fs.existsSync(srcFilename) ||
(ignorePattern && ignorePattern.test(srcFilename))
)
return

if (fs.statSync(srcFilename).isDirectory()) {
const subdirs = fs
.readdirSync(srcFilename)
.map(filename => path.join(srcFilename, filename))

translatableStrings = _mergeCatalogs(translatableStrings, collectFromFiles(subdirs, ignore));
return
}

if (!srcFilename.endsWith('.ts') && !srcFilename.endsWith('.tsx')) {
return;
}

extractFromFile(srcFilename).forEach(str => {
if (!translatableStrings[str]) {
translatableStrings[str] = {
translation: "",
origin: [
[srcFilename, 0],
],
};
} else {
translatableStrings[str].origin.push([srcFilename, 0]);
}
});
});

return translatableStrings;
};

module.exports = { collectFromFiles };
35 changes: 35 additions & 0 deletions dist/exceptions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class ValueArgumentErrorMissing extends Error {
constructor (message) {
super(message);
this.name = "Value argument is missing";

// capturing the stack trace keeps the reference to your error class
Error.captureStackTrace(this, this.constructor);
}
}

class InvalidPluralRule extends Error {
constructor (message) {
super(message)
this.name = message

// capturing the stack trace keeps the reference to your error class
Error.captureStackTrace(this, this.constructor);
}
}

class MissingFallbackArgument extends Error {
constructor (message) {
super(message)
this.name = message

// capturing the stack trace keeps the reference to your error class
Error.captureStackTrace(this, this.constructor);
}
}

module.exports = {
ValueArgumentErrorMissing,
InvalidPluralRule,
MissingFallbackArgument
}
117 changes: 117 additions & 0 deletions dist/extract.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
const swc = require('@swc/core')
const { Visitor } = require('@swc/core/Visitor')
const { omit } = require('lodash');
const {
parseCallPlurals,
parseTextFromJSXElement,
parseJSXPlurals,
parseTextFromTemplateLiteral,
} = require('./parser');

// replace whitespace before/after newline with single space
const nlRe = /\s*(?:\r\n|\r|\n)+\s*/g
// remove whitespace before/after tag
const nlTagRe = /(?:(>)(?:\r\n|\r|\n)+\s+|(?:\r\n|\r|\n)+\s+(?=<))/g

class ExtractVisitor extends Visitor {
constructor() {
super();

this.localTransComponentName = 'Trans';
this.localSelectOrdinalImportName = 'SelectOrdinal';
this.localPluralImportName = 'Plural';
this.translatableStrings = {};
this.visitedStrings = {};
}

visitTaggedTemplateExpression(n) {
const expr = super.visitTaggedTemplateExpression(n);
if (expr.tag.object.type !== 'Identifier' || expr.tag.object.value !== 'i18n') {
return expr;
}

const str = this.cleanText(parseTextFromTemplateLiteral(expr.template));
this.translatableStrings[str.trim()] = true;
return expr;
}

visitTsType(n) {
}

visitImportDeclaration(node) {
const moduleName = node.source.value
if ("@lingui/react" !== moduleName) return

const importDeclarations = {}
node.specifiers.forEach((specifier) => {
if(specifier.imported && specifier.imported.value) {
importDeclarations[specifier.imported.value] =
specifier.local.value
}
})

this.localTransComponentName = importDeclarations["Trans"] || "Trans";
this.localSelectOrdinalImportName = importDeclarations["SelectOrdinal"] || "SelectOrdinal";
this.localPluralImportName = importDeclarations["Plural"] || "Plural";
}

visitJSXElement(n) {
const expr = super.visitJSXElement(n);
if(expr.opening.name.value === this.localSelectOrdinalImportName || expr.opening.name.value === this.localPluralImportName) {
const str = this.cleanText(parseJSXPlurals(expr, { index: 0, localTransComponentName: this.localTransComponentName, visitedStrings: this.visitedStrings }));
if(str) {
this.translatableStrings[str] = true;
}
} else if (expr.opening.name.value === this.localTransComponentName) {
const str = this.cleanText(parseTextFromJSXElement(expr, { elementIndex: 0, unknownIndex: 0, localTransComponentName: this.localTransComponentName, visitedStrings: this.visitedStrings }));
if(str) {
this.translatableStrings[str] = true;
}
}

return expr;
}

visitCallExpression(n) {
const expr = super.visitCallExpression(n);
if(!expr.callee.object || !expr.callee.property){
return expr;
}
if(expr.callee.object.type !== 'Identifier' || expr.callee.object.value !== 'i18n' || expr.callee.property.value !== 'plural'){
return expr;
}
const str = this.cleanText(parseCallPlurals(expr));
this.translatableStrings[str] = true;
return expr;
}

getCleanedStrings() {
return Object.keys(omit(this.translatableStrings, Object.keys(this.visitedStrings)));
}

cleanText(value) {
return value.replace(nlTagRe, "$1").replace(nlRe, " ").trim();
}
}

const extractFromFile = (filename) => {
const module = swc
.parseFileSync(filename, {
syntax: "typescript", // "ecmascript" | "typescript"
comments: false,
script: true,
tsx: true,

// Defaults to es3
target: "es5",
// Input source code are treated as module by default
isModule: true,
});

const visitor = new ExtractVisitor();
visitor.visitProgram(module);

return visitor.getCleanedStrings();
};

module.exports = { extractFromFile };
17 changes: 12 additions & 5 deletions dist/lingui-multi.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ const uglifyJS = require("uglify-js")
const path = require('path')
const fs = require('fs')

const { collectFromFiles } = require('./collect');

// Set up version command
commander.version(require('../package.json').version)

Expand All @@ -28,6 +30,7 @@ commander

extractCatalogs(packageFile, packageObject, localesDir, locales, args)
} catch (error) {
throw error;
console.error(error.message)
process.exit(1)
}
Expand Down Expand Up @@ -71,9 +74,12 @@ const extractCatalogs = (packageFile, packageObject, localesDir, locales, args)
if (args.upwardBabelRoot) {
options.babelOptions = { "rootMode": "upward" };
}
extract.extract(options.srcPathDirs, targetDir, options)

const rawCatalog = extract.collect(targetDir)
// extract.extract(options.srcPathDirs, targetDir, options)

// const rawCatalog = extract.collect(targetDir)
const rawCatalog = collectFromFiles(options.srcPathDirs, options.ignore);
// console.log(rawCatalog);

// Prepopulate with empty translations
const linguiCatalog = Object.keys(rawCatalog).reduce((final, key) => Object.assign(final, {
Expand Down Expand Up @@ -335,13 +341,14 @@ const filterTranslationOnly = catalog =>
[translationKey]: filterProperties(catalog[translationKey], ['translation'])
}), {})

const simplifyComplexCatalog = catalog =>
Object.keys(catalog)
const simplifyComplexCatalog = catalog => {
return Object.keys(catalog)
.reduce((simplifiedCatalog, key) => Object.assign(simplifiedCatalog, {
[key]: Object.assign(catalog[key], {
origin: catalog[key].origin.map(originArray => originArray.shift())
})
}), {})
}), {});
};

module.exports = {
loadLinguiCatalog,
Expand Down
Loading