@saykit/transform-jsx 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,7 @@ function generateSayJSXElement(message) {
7
7
  const attributes = [
8
8
  t.jsxAttribute(t.jsxIdentifier("id"), t.stringLiteral(id)),
9
9
  ...message.whitespace === void 0 ? [] : [t.jsxAttribute(t.jsxIdentifier("whitespace"), t.jsxExpressionContainer(t.booleanLiteral(message.whitespace)))],
10
- ...children.map(([k, e]) => t.jsxAttribute(t.jsxIdentifier(Number.isNaN(+k) ? k : `_${k}`), t.jsxExpressionContainer(e)))
10
+ ...[...new Map(children).entries()].map(([k, e]) => t.jsxAttribute(t.jsxIdentifier(`_${k}`), t.jsxExpressionContainer(e)))
11
11
  ];
12
12
  return t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier("Say"), attributes, true), null, []);
13
13
  }
package/dist/index.mjs CHANGED
@@ -5,7 +5,7 @@ import * as parser from "@babel/parser";
5
5
  import traverse_ from "@babel/traverse";
6
6
  import { assignSequenceIdentifiers } from "@saykit/config/features/messages";
7
7
  import { generateSayCallExpression } from "@saykit/transform-js/generator";
8
- import { parseExpression } from "@saykit/transform-js/parser";
8
+ import { isEquivalentPlaceholder, parseExpression } from "@saykit/transform-js/parser";
9
9
  //#region src/index.ts
10
10
  const traverse = traverse_.default || traverse_;
11
11
  function createProgram(code, id) {
@@ -40,7 +40,7 @@ function createJsxTransformer() {
40
40
  path.node.leadingComments = path.node.leadingComments ?? [];
41
41
  const message = parseExpression(path.node);
42
42
  if (message) {
43
- assignSequenceIdentifiers(message, { current: 0 });
43
+ assignSequenceIdentifiers(message, { current: 0 }, isEquivalentPlaceholder);
44
44
  messages.push(message);
45
45
  path.skip();
46
46
  }
@@ -49,7 +49,7 @@ function createJsxTransformer() {
49
49
  path.node.leadingComments = path.node.leadingComments ?? [];
50
50
  const message = parseJSXElement(path.node);
51
51
  if (message) {
52
- assignSequenceIdentifiers(message, { current: 0 });
52
+ assignSequenceIdentifiers(message, { current: 0 }, isEquivalentPlaceholder);
53
53
  messages.push(message);
54
54
  path.skip();
55
55
  }
@@ -71,7 +71,7 @@ function createJsxTransformer() {
71
71
  path.node.leadingComments = path.node.leadingComments ?? [];
72
72
  const message = parseExpression(path.node);
73
73
  if (message) {
74
- assignSequenceIdentifiers(message, { current: 0 });
74
+ assignSequenceIdentifiers(message, { current: 0 }, isEquivalentPlaceholder);
75
75
  const replacement = generateSayCallExpression(message);
76
76
  path.replaceWith(replacement);
77
77
  path.skip();
@@ -81,7 +81,7 @@ function createJsxTransformer() {
81
81
  path.node.leadingComments = path.node.leadingComments ?? [];
82
82
  const message = parseJSXElement(path.node);
83
83
  if (message) {
84
- assignSequenceIdentifiers(message, { current: 0 });
84
+ assignSequenceIdentifiers(message, { current: 0 }, isEquivalentPlaceholder);
85
85
  const replacement = generateSayJSXElement(message);
86
86
  path.replaceWith(replacement);
87
87
  path.skip();
package/dist/parser.mjs CHANGED
@@ -1,6 +1,14 @@
1
- import { AUTO_INCREMENT_IDENTIFIER, ArgumentMessage, ChoiceMessage, CompositeMessage, ElementMessage, LiteralMessage } from "@saykit/config/features/messages";
1
+ import { AUTO_INCREMENT_IDENTIFIER, ArgumentMessage, ChoiceMessage, CompositeMessage, ElementMessage, LiteralMessage, validateBranchIdentifier } from "@saykit/config/features/messages";
2
+ import { unwrapPlaceholder } from "@saykit/transform-js/parser";
2
3
  import * as t from "@babel/types";
3
4
  //#region src/parser.ts
5
+ /**
6
+ * Attribute used to name the ICU tag an embedded element extracts as, e.g.
7
+ * `<a say-tag="link">` becomes `<link></link>` rather than `<0></0>`. It never
8
+ * reaches the real element.
9
+ */
10
+ const TAG_ATTRIBUTE = "say-tag";
11
+ const TAG_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
4
12
  function parseJSXContainerElement(element) {
5
13
  if (element.openingElement.selfClosing) return null;
6
14
  const processed = processJSXOpeningElement(element.openingElement);
@@ -8,15 +16,16 @@ function parseJSXContainerElement(element) {
8
16
  const [accessor] = processed;
9
17
  const children = element.children.reduce((p, c, i, a) => {
10
18
  if (t.isJSXText(c)) {
11
- let text = c.value.replace(/\s+/g, " ");
12
- if (i === 0) text = text.trimStart();
13
- if (i === a.length - 1) text = text.trimEnd();
19
+ const text = normalizeJSXText(c.value, i === 0, i === a.length - 1);
14
20
  if (text) p.push(new LiteralMessage(text));
15
21
  }
16
22
  if (t.isJSXElement(c)) p.push(parseJSXElement(c, true));
17
23
  else if (t.isJSXFragment(c)) p.push(new ElementMessage(AUTO_INCREMENT_IDENTIFIER, [], c));
18
24
  else if (t.isJSXExpressionContainer(c)) {
19
- if (t.isExpression(c.expression)) p.push(new ArgumentMessage(getExpressionAsIdentifier(c.expression), c.expression));
25
+ if (t.isExpression(c.expression)) {
26
+ const [identifier, value] = unwrapPlaceholder(c.expression);
27
+ p.push(new ArgumentMessage(identifier, value));
28
+ }
20
29
  }
21
30
  return p;
22
31
  }, []);
@@ -26,7 +35,7 @@ function parseJSXContainerElement(element) {
26
35
  return new CompositeMessage({
27
36
  id: descriptorId,
28
37
  context: descriptorContext
29
- }, [], [], children, accessor, whitespace);
38
+ }, [], getReferences(element), children, accessor, whitespace);
30
39
  }
31
40
  function parseJSXOpeningElement(element) {
32
41
  if (!element.selfClosing) return null;
@@ -56,23 +65,53 @@ function parseJSXOpeningElement(element) {
56
65
  identifier,
57
66
  value: new ElementMessage(AUTO_INCREMENT_IDENTIFIER, [], a.value.expression)
58
67
  });
59
- else if (t.isExpression(a.value.expression)) b.push({
60
- identifier,
61
- value: new ArgumentMessage(getExpressionAsIdentifier(a.value.expression), a.value.expression)
62
- });
68
+ else if (t.isExpression(a.value.expression)) {
69
+ const [name, value] = unwrapPlaceholder(a.value.expression);
70
+ b.push({
71
+ identifier,
72
+ value: new ArgumentMessage(name, value)
73
+ });
74
+ }
63
75
  }
64
76
  return b;
65
77
  }, []);
78
+ for (const branch of branches) validateBranchIdentifier(kind, branch.identifier);
66
79
  const initialiser = findAttributeValueIfExpressionOrStringLiteral(element.attributes, "_");
67
80
  if (!initialiser) return null;
68
- const choice = new ChoiceMessage(kind, getExpressionAsIdentifier(initialiser), branches, initialiser);
81
+ const [identifier, selector] = unwrapPlaceholder(initialiser);
82
+ const choice = new ChoiceMessage(kind, identifier, branches, selector);
69
83
  return new CompositeMessage({
70
84
  id: findAttributeValueIfStringLiteralAsString(element.attributes, "id"),
71
85
  context: findAttributeValueIfStringLiteralAsString(element.attributes, "context")
72
- }, [], [], [choice], accessor);
86
+ }, [], getReferences(element), [choice], accessor);
73
87
  }
74
88
  return null;
75
89
  }
90
+ /**
91
+ * Punctuation that never takes a space in front of it. A formatter wrapping
92
+ * long JSX regularly strands these at the start of a line, on their own or
93
+ * ahead of the rest of a clause.
94
+ */
95
+ const CLOSING_PUNCTUATION = /^[.,;:!?)\]}»”’]/;
96
+ /**
97
+ * Collapse the whitespace in a JSX text child the way the source reads.
98
+ *
99
+ * A line break between a word and its neighbour is only how a formatter wrapped
100
+ * a long line, so it still means a space. Dropping it would run the words
101
+ * together — and because ids are content hashes, silently orphan every existing
102
+ * translation for the message.
103
+ *
104
+ * The exception is a line that begins with punctuation, which belongs tight
105
+ * against whatever precedes it. Only an implicit break is treated this way: a
106
+ * space the author wrote on the same line is deliberate and always survives.
107
+ */
108
+ function normalizeJSXText(value, isFirst, isLast) {
109
+ let text = value.replace(/\s+/g, " ");
110
+ if (isFirst) text = text.trimStart();
111
+ else if (text.startsWith(" ") && /^[^\S\n]*\n/.test(value) && CLOSING_PUNCTUATION.test(text.slice(1))) text = text.slice(1);
112
+ if (isLast) text = text.trimEnd();
113
+ return text;
114
+ }
76
115
  function processJSXOpeningElement(element) {
77
116
  if (t.isJSXIdentifier(element.name) && element.name.name === "Say") return [element.name, null];
78
117
  if (t.isJSXMemberExpression(element.name) && t.isJSXIdentifier(element.name.object) && element.name.object.name === "Say" && t.isJSXIdentifier(element.name.property)) return [element.name.object, element.name.property.name.toLowerCase()];
@@ -82,8 +121,31 @@ function parseJSXElement(element, fallback) {
82
121
  const message = element.openingElement.selfClosing ? parseJSXOpeningElement(element.openingElement) : parseJSXContainerElement(element);
83
122
  if (message) return message;
84
123
  if (!fallback) return null;
85
- if (element.openingElement.selfClosing) return new ElementMessage(AUTO_INCREMENT_IDENTIFIER, [], element);
86
- return new ElementMessage(AUTO_INCREMENT_IDENTIFIER, [parseJSXElement(t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier("Say"), []), t.jsxClosingElement(t.jsxIdentifier("Say")), element.children), true)], element);
124
+ const identifier = takeElementTag(element) ?? AUTO_INCREMENT_IDENTIFIER;
125
+ if (element.openingElement.selfClosing) return new ElementMessage(identifier, [], element);
126
+ return new ElementMessage(identifier, [parseJSXElement(t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier("Say"), []), t.jsxClosingElement(t.jsxIdentifier("Say")), element.children), true)], element);
127
+ }
128
+ /**
129
+ * Read the tag name off an embedded element and remove the attribute so it
130
+ * never reaches the rendered element. Only static strings name a tag; anything
131
+ * else is left in place and the element falls back to an auto-incremented
132
+ * identifier.
133
+ */
134
+ function takeElementTag(element) {
135
+ const attributes = element.openingElement.attributes;
136
+ const index = attributes.findIndex((a) => t.isJSXAttribute(a) && getAttributeNameAsString(a) === TAG_ATTRIBUTE);
137
+ if (index === -1) return void 0;
138
+ const attribute = attributes[index];
139
+ const value = t.isJSXExpressionContainer(attribute.value) ? attribute.value.expression : attribute.value;
140
+ if (!t.isStringLiteral(value)) return void 0;
141
+ const tag = value.value;
142
+ if (!TAG_PATTERN.test(tag)) throw new Error(`Invalid '${TAG_ATTRIBUTE}' value '${tag}', expected a letter or underscore followed by letters, digits, or underscores`);
143
+ attributes.splice(index, 1);
144
+ return tag;
145
+ }
146
+ function getReferences(node) {
147
+ if (!node.loc?.filename) return [];
148
+ return [`${node.loc.filename}:${node.loc.start.line}`];
87
149
  }
88
150
  function getAttributeNameAsString(attribute) {
89
151
  return t.isJSXIdentifier(attribute.name) ? attribute.name.name : attribute.name.name.name;
@@ -113,11 +175,5 @@ function findAttributeValueAsBoolean(attributes, identifier) {
113
175
  if (t.isJSXExpressionContainer(attribute.value) && t.isBooleanLiteral(attribute.value.expression)) return attribute.value.expression.value;
114
176
  }
115
177
  }
116
- function getExpressionAsIdentifier(node) {
117
- if (t.isIdentifier(node)) return node.name;
118
- /* v8 ignore next */
119
- if (t.isJSXIdentifier(node)) return node.name;
120
- return AUTO_INCREMENT_IDENTIFIER;
121
- }
122
178
  //#endregion
123
179
  export { parseJSXContainerElement, parseJSXElement, parseJSXOpeningElement };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saykit/transform-jsx",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "JSX and TSX source transformer for SayKit",
5
5
  "keywords": [
6
6
  "i18n",
@@ -47,8 +47,8 @@
47
47
  "@babel/parser": "^7.29.7",
48
48
  "@babel/traverse": "^7.29.7",
49
49
  "@babel/types": "^7.29.7",
50
- "@saykit/config": "^0.5.0",
51
- "@saykit/transform-js": "^0.5.0"
50
+ "@saykit/config": "^0.6.1",
51
+ "@saykit/transform-js": "^0.6.1"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@babel/core": "^7.29.7",