Skip to content
Merged
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
84 changes: 54 additions & 30 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,51 @@ function isMethodCall(
);
}

// Should be pretty fast: https://stackoverflow.com/a/34491287/14379
// tslint:disable-next-line:no-any
function emptyObject(obj: any) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
}

// just a map of string to string
interface Message {
[key: string]: string;
/**
* Represents a react-intl message descriptor
*/
export interface Message {
defaultMessage: string;
description?: string;
id: string;
}

// This is the only JSX element we can extract messages from:
type ElementName = "FormattedMessage";
// These are the two methods we can extract messages from:
type MethodName = "defineMessages" | "formatMessage";
// MessageExtracter defines a function type which can extract zero or more
// valid Messages from an ObjectLiteralExpression:
type MessageExtracter = (obj: ts.ObjectLiteralExpression) => Message[];

// sets `target[key] = value`, but only if it is a legal Message key
function copyIfMessageKey(
target: Partial<Message>,
key: string,
value: string,
) {
switch (key) {
case "defaultMessage":
case "description":
case "id":
target[key] = value;
break;
default:
break;
}
}

// are the required keys of a valid Message present?
function isValidMessage(obj: Partial<Message>): obj is Message {
return "id" in obj && "defaultMessage" in obj;
}

function extractMessagesForDefineMessages(
objLiteral: ts.ObjectLiteralExpression,
): Message[] {
const messages: Message[] = [];
objLiteral.properties.forEach((p) => {
const message: Message = {};
const msg: Partial<Message> = {};
if (
ts.isPropertyAssignment(p) &&
ts.isObjectLiteralExpression(p.initializer) &&
Expand All @@ -55,12 +74,12 @@ function extractMessagesForDefineMessages(
ts.isPropertyAssignment(ip) &&
ts.isStringLiteral(ip.initializer)
) {
message[name] = ip.initializer.text;
copyIfMessageKey(msg, name, ip.initializer.text);
}
// else: key/value is not a string literal/identifier
}
});
messages.push(message);
isValidMessage(msg) && messages.push(msg);
}
});
return messages;
Expand All @@ -69,18 +88,18 @@ function extractMessagesForDefineMessages(
function extractMessagesForFormatMessage(
objLiteral: ts.ObjectLiteralExpression,
): Message[] {
const message: Message = {};
const msg: Partial<Message> = {};
objLiteral.properties.forEach((p) => {
if (
ts.isPropertyAssignment(p) &&
(ts.isIdentifier(p.name) || ts.isLiteralExpression(p.name)) &&
ts.isStringLiteral(p.initializer)
) {
message[p.name.text] = p.initializer.text;
copyIfMessageKey(msg, p.name.text, p.initializer.text);
}
// else: key/value is not a string literal/identifier
});
return [message];
return isValidMessage(msg) ? [msg] : [];
}

function extractMessagesForNode(
Expand Down Expand Up @@ -137,7 +156,6 @@ function findMethodCallsWithName(
extractMessages: MessageExtracter,
) {
let messages: Message[] = [];
// getNamedDeclarations is not currently public
forAllVarDecls(sourceFile, (decl: ts.Declaration) => {
if (isMethodCall(decl, methodName)) {
if (
Expand All @@ -157,9 +175,7 @@ function findMethodCallsWithName(
/**
* Parse tsx files
*/
// TODO perhaps we should expose the Message interface
// tslint:disable-next-line:array-type
function main(contents: string): {}[] {
function main(contents: string): Message[] {
const sourceFile = ts.createSourceFile(
"file.ts",
contents,
Expand Down Expand Up @@ -188,23 +204,31 @@ function main(contents: string): {}[] {
// convert JsxOpeningLikeElements to Message maps
const jsxMessages = elements
.map((element) => {
const msg: Message = {};
element.attributes &&
const msg: Partial<Message> = {};
if (element.attributes) {
element.attributes.properties.forEach((attr: ts.JsxAttributeLike) => {
// found nothing
// tslint:disable-next-line:no-any
const a = attr as any; // TODO find correct types to avoid "any"
if (!a.name || !a.initializer) {
return;
}
msg[a.name.text] =
a.initializer.text || a.initializer.expression.text;
copyIfMessageKey(
msg,
a.name.text,
a.initializer.text || a.initializer.expression.text,
);
});
return msg;
}
return isValidMessage(msg) ? msg : null;
})
.filter((r) => !emptyObject(r));
.filter(notNull);

return jsxMessages.concat(dm).concat(fm);
}

function notNull<T>(value: T | null): value is T {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this return a boolean value. if so why need value is T

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does return a boolean at runtime, but this bit of typing enables the result of filter to be Message instead of Message | null as far as the type checker is concerned. It's a user-defined type guard: https://www.typescriptlang.org/docs/handbook/advanced-types.html

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@seanf Thanks. I didn't use this type guard before. 😄

return value !== null;
}

export default main;
13 changes: 12 additions & 1 deletion lib/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,13 @@
declare function main(contents: string): {}[];
/**
* Represents a react-intl message descriptor
*/
export interface Message {
defaultMessage: string;
description?: string;
id: string;
}
/**
* Parse tsx files
*/
declare function main(contents: string): Message[];
export default main;
62 changes: 43 additions & 19 deletions lib/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/index.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading