@lingui/macro 4.0.0-next.2 → 4.0.0-next.4

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,885 @@
1
+ 'use strict';
2
+
3
+ const babelPluginMacros = require('babel-plugin-macros');
4
+ const conf = require('@lingui/conf');
5
+ const types = require('@babel/types');
6
+ const api = require('@lingui/cli/api');
7
+
8
+ const metaOptions = ["id", "comment", "props"];
9
+ const escapedMetaOptionsRe = new RegExp(`^_(${metaOptions.join("|")})$`);
10
+ class ICUMessageFormat {
11
+ fromTokens(tokens) {
12
+ return (Array.isArray(tokens) ? tokens : [tokens]).map((token) => this.processToken(token)).filter(Boolean).reduce(
13
+ (props, message) => ({
14
+ ...message,
15
+ message: props.message + message.message,
16
+ values: { ...props.values, ...message.values },
17
+ jsxElements: { ...props.jsxElements, ...message.jsxElements }
18
+ }),
19
+ {
20
+ message: "",
21
+ values: {},
22
+ jsxElements: {}
23
+ }
24
+ );
25
+ }
26
+ processToken(token) {
27
+ const jsxElements = {};
28
+ if (token.type === "text") {
29
+ return {
30
+ message: token.value
31
+ };
32
+ } else if (token.type === "arg") {
33
+ if (token.value !== void 0 && types.isJSXEmptyExpression(token.value)) {
34
+ return null;
35
+ }
36
+ const values = token.value !== void 0 ? { [token.name]: token.value } : {};
37
+ switch (token.format) {
38
+ case "plural":
39
+ case "select":
40
+ case "selectordinal":
41
+ const formatOptions = Object.keys(token.options).filter((key) => token.options[key] != null).map((key) => {
42
+ let value = token.options[key];
43
+ key = key.replace(escapedMetaOptionsRe, "$1");
44
+ if (key === "offset") {
45
+ return `offset:${value}`;
46
+ }
47
+ if (typeof value !== "string") {
48
+ const {
49
+ message,
50
+ values: childValues,
51
+ jsxElements: childJsxElements
52
+ } = this.fromTokens(value);
53
+ Object.assign(values, childValues);
54
+ Object.assign(jsxElements, childJsxElements);
55
+ value = message;
56
+ }
57
+ return `${key} {${value}}`;
58
+ }).join(" ");
59
+ return {
60
+ message: `{${token.name}, ${token.format}, ${formatOptions}}`,
61
+ values,
62
+ jsxElements
63
+ };
64
+ default:
65
+ return {
66
+ message: `{${token.name}}`,
67
+ values
68
+ };
69
+ }
70
+ } else if (token.type === "element") {
71
+ let message = "";
72
+ let elementValues = {};
73
+ Object.assign(jsxElements, { [token.name]: token.value });
74
+ token.children.forEach((child) => {
75
+ const {
76
+ message: childMessage,
77
+ values: childValues,
78
+ jsxElements: childJsxElements
79
+ } = this.fromTokens(child);
80
+ message += childMessage;
81
+ Object.assign(elementValues, childValues);
82
+ Object.assign(jsxElements, childJsxElements);
83
+ });
84
+ return {
85
+ message: token.children.length ? `<${token.name}>${message}</${token.name}>` : `<${token.name}/>`,
86
+ values: elementValues,
87
+ jsxElements
88
+ };
89
+ }
90
+ throw new Error(`Unknown token type ${token.type}`);
91
+ }
92
+ }
93
+
94
+ const makeCounter = (index = 0) => () => index++;
95
+
96
+ const ID = "id";
97
+ const MESSAGE = "message";
98
+ const COMMENT = "comment";
99
+ const EXTRACT_MARK = "i18n";
100
+ const CONTEXT = "context";
101
+
102
+ const keepSpaceRe$1 = /(?:\\(?:\r\n|\r|\n))+\s+/g;
103
+ const keepNewLineRe = /(?:\r\n|\r|\n)+\s+/g;
104
+ function normalizeWhitespace$1(text) {
105
+ return text.replace(keepSpaceRe$1, " ").replace(keepNewLineRe, "\n").trim();
106
+ }
107
+ function buildICUFromTokens(tokens) {
108
+ const messageFormat = new ICUMessageFormat();
109
+ const { message, values } = messageFormat.fromTokens(tokens);
110
+ return { message: normalizeWhitespace$1(message), values };
111
+ }
112
+ class MacroJs {
113
+ constructor({ types }, opts) {
114
+ // Positional expressions counter (e.g. for placeholders `Hello {0}, today is {1}`)
115
+ this._expressionIndex = makeCounter();
116
+ this.replacePathWithMessage = (path, tokens, linguiInstance) => {
117
+ const newNode = this.createI18nCall(
118
+ this.createMessageDescriptorFromTokens(tokens, path.node.loc),
119
+ linguiInstance
120
+ );
121
+ path.replaceWith(newNode);
122
+ };
123
+ // Returns a boolean indicating if the replacement requires i18n import
124
+ this.replacePath = (path) => {
125
+ this._expressionIndex = makeCounter();
126
+ if (this.types.isCallExpression(path.node) && this.isDefineMessage(path.node.callee)) {
127
+ let descriptor = this.processDescriptor(path.node.arguments[0]);
128
+ path.replaceWith(descriptor);
129
+ return false;
130
+ }
131
+ if (this.types.isTaggedTemplateExpression(path.node) && this.isDefineMessage(path.node.tag)) {
132
+ const tokens2 = this.tokenizeTemplateLiteral(path.node.quasi);
133
+ const descriptor = this.createMessageDescriptorFromTokens(
134
+ tokens2,
135
+ path.node.loc
136
+ );
137
+ path.replaceWith(descriptor);
138
+ return false;
139
+ }
140
+ if (this.types.isCallExpression(path.node) && this.types.isTaggedTemplateExpression(path.parentPath.node) && this.types.isExpression(path.node.arguments[0]) && this.isLinguiIdentifier(path.node.callee, "t")) {
141
+ const i18nInstance = path.node.arguments[0];
142
+ const tokens2 = this.tokenizeNode(path.parentPath.node);
143
+ this.replacePathWithMessage(path.parentPath, tokens2, i18nInstance);
144
+ return false;
145
+ }
146
+ if (this.types.isCallExpression(path.node) && this.types.isCallExpression(path.parentPath.node) && this.types.isExpression(path.node.arguments[0]) && path.parentPath.node.callee === path.node && this.isLinguiIdentifier(path.node.callee, "t")) {
147
+ const i18nInstance = path.node.arguments[0];
148
+ this.replaceTAsFunction(
149
+ path.parentPath,
150
+ i18nInstance
151
+ );
152
+ return false;
153
+ }
154
+ if (this.types.isCallExpression(path.node) && this.isLinguiIdentifier(path.node.callee, "t")) {
155
+ this.replaceTAsFunction(path);
156
+ return true;
157
+ }
158
+ const tokens = this.tokenizeNode(path.node);
159
+ this.replacePathWithMessage(path, tokens);
160
+ return true;
161
+ };
162
+ /**
163
+ * macro `t` is called with MessageDescriptor, after that
164
+ * we create a new node to append it to i18n._
165
+ */
166
+ this.replaceTAsFunction = (path, linguiInstance) => {
167
+ const descriptor = this.processDescriptor(path.node.arguments[0]);
168
+ path.replaceWith(this.createI18nCall(descriptor, linguiInstance));
169
+ };
170
+ /**
171
+ * `processDescriptor` expand macros inside message descriptor.
172
+ * Message descriptor is used in `defineMessage`.
173
+ *
174
+ * {
175
+ * comment: "Description",
176
+ * message: plural("value", { one: "book", other: "books" })
177
+ * }
178
+ *
179
+ * ↓ ↓ ↓ ↓ ↓ ↓
180
+ *
181
+ * {
182
+ * comment: "Description",
183
+ * id: <hash>
184
+ * message: "{value, plural, one {book} other {books}}"
185
+ * }
186
+ *
187
+ */
188
+ this.processDescriptor = (descriptor_) => {
189
+ const descriptor = descriptor_;
190
+ const messageProperty = this.getObjectPropertyByKey(descriptor, MESSAGE);
191
+ const idProperty = this.getObjectPropertyByKey(descriptor, ID);
192
+ const contextProperty = this.getObjectPropertyByKey(descriptor, CONTEXT);
193
+ const properties = [idProperty];
194
+ if (!this.stripNonEssentialProps) {
195
+ properties.push(contextProperty);
196
+ }
197
+ if (messageProperty) {
198
+ const tokens = this.types.isTemplateLiteral(messageProperty.value) ? this.tokenizeTemplateLiteral(messageProperty.value) : this.tokenizeNode(messageProperty.value, true);
199
+ let messageNode = messageProperty.value;
200
+ if (tokens) {
201
+ const { message, values } = buildICUFromTokens(tokens);
202
+ messageNode = this.types.stringLiteral(message);
203
+ properties.push(this.createValuesProperty(values));
204
+ }
205
+ if (!this.stripNonEssentialProps) {
206
+ properties.push(
207
+ this.createObjectProperty(MESSAGE, messageNode)
208
+ );
209
+ }
210
+ if (!idProperty && this.types.isStringLiteral(messageNode)) {
211
+ const context = contextProperty && this.getTextFromExpression(contextProperty.value);
212
+ properties.push(this.createIdProperty(messageNode.value, context));
213
+ }
214
+ }
215
+ if (!this.stripNonEssentialProps) {
216
+ properties.push(this.getObjectPropertyByKey(descriptor, COMMENT));
217
+ }
218
+ return this.createMessageDescriptor(properties, descriptor.loc);
219
+ };
220
+ this.types = types;
221
+ this.i18nImportName = opts.i18nImportName;
222
+ this.stripNonEssentialProps = opts.stripNonEssentialProps;
223
+ this.nameMap = opts.nameMap;
224
+ this.nameMapReversed = Array.from(opts.nameMap.entries()).reduce(
225
+ (map, [key, value]) => map.set(value, key),
226
+ /* @__PURE__ */ new Map()
227
+ );
228
+ }
229
+ createIdProperty(message, context) {
230
+ return this.createObjectProperty(
231
+ ID,
232
+ this.types.stringLiteral(api.generateMessageId(message, context))
233
+ );
234
+ }
235
+ createValuesProperty(values) {
236
+ const valuesObject = Object.keys(values).map(
237
+ (key) => this.types.objectProperty(this.types.identifier(key), values[key])
238
+ );
239
+ if (!valuesObject.length)
240
+ return;
241
+ return this.types.objectProperty(
242
+ this.types.identifier("values"),
243
+ this.types.objectExpression(valuesObject)
244
+ );
245
+ }
246
+ tokenizeNode(node, ignoreExpression = false) {
247
+ if (this.isI18nMethod(node)) {
248
+ return this.tokenizeTemplateLiteral(node);
249
+ } else if (this.isChoiceMethod(node)) {
250
+ return [this.tokenizeChoiceComponent(node)];
251
+ } else if (!ignoreExpression) {
252
+ return [this.tokenizeExpression(node)];
253
+ }
254
+ }
255
+ /**
256
+ * `node` is a TemplateLiteral. node.quasi contains
257
+ * text chunks and node.expressions contains expressions.
258
+ * Both arrays must be zipped together to get the final list of tokens.
259
+ */
260
+ tokenizeTemplateLiteral(node) {
261
+ const tpl = this.types.isTaggedTemplateExpression(node) ? node.quasi : node;
262
+ const expressions = tpl.expressions;
263
+ return tpl.quasis.flatMap((text, i) => {
264
+ const value = /\\u[a-fA-F0-9]{4}|\\x[a-fA-F0-9]{2}/g.test(text.value.raw) ? text.value.cooked : text.value.raw;
265
+ let argTokens = [];
266
+ const currExp = expressions[i];
267
+ if (currExp) {
268
+ argTokens = this.types.isCallExpression(currExp) ? this.tokenizeNode(currExp) : [this.tokenizeExpression(currExp)];
269
+ }
270
+ return [
271
+ ...value ? [
272
+ {
273
+ type: "text",
274
+ value: this.clearBackslashes(value)
275
+ }
276
+ ] : [],
277
+ ...argTokens
278
+ ];
279
+ });
280
+ }
281
+ tokenizeChoiceComponent(node) {
282
+ const name = node.callee.name;
283
+ const format = (this.nameMapReversed.get(name) || name).toLowerCase();
284
+ const token = {
285
+ ...this.tokenizeExpression(node.arguments[0]),
286
+ format,
287
+ options: {
288
+ offset: void 0
289
+ }
290
+ };
291
+ const props = node.arguments[1].properties;
292
+ for (const attr of props) {
293
+ const { key, value: attrValue } = attr;
294
+ const name2 = this.types.isNumericLiteral(key) ? `=${key.value}` : key.name || key.value;
295
+ if (format !== "select" && name2 === "offset") {
296
+ token.options.offset = attrValue.value;
297
+ } else {
298
+ let value;
299
+ if (this.types.isTemplateLiteral(attrValue)) {
300
+ value = this.tokenizeTemplateLiteral(attrValue);
301
+ } else if (this.types.isCallExpression(attrValue)) {
302
+ value = this.tokenizeNode(attrValue);
303
+ } else if (this.types.isStringLiteral(attrValue)) {
304
+ value = attrValue.value;
305
+ } else if (this.types.isExpression(attrValue)) {
306
+ value = this.tokenizeExpression(attrValue);
307
+ } else {
308
+ value = attrValue.value;
309
+ }
310
+ token.options[name2] = value;
311
+ }
312
+ }
313
+ return token;
314
+ }
315
+ tokenizeExpression(node) {
316
+ if (this.isArg(node) && this.types.isCallExpression(node)) {
317
+ return {
318
+ type: "arg",
319
+ name: node.arguments[0].value,
320
+ value: void 0
321
+ };
322
+ }
323
+ return {
324
+ type: "arg",
325
+ name: this.expressionToArgument(node),
326
+ value: node
327
+ };
328
+ }
329
+ expressionToArgument(exp) {
330
+ if (this.types.isIdentifier(exp)) {
331
+ return exp.name;
332
+ } else if (this.types.isStringLiteral(exp)) {
333
+ return exp.value;
334
+ } else {
335
+ return String(this._expressionIndex());
336
+ }
337
+ }
338
+ /**
339
+ * We clean '//\` ' to just '`'
340
+ */
341
+ clearBackslashes(value) {
342
+ return value.replace(/\\`/g, "`");
343
+ }
344
+ createI18nCall(messageDescriptor, linguiInstance) {
345
+ return this.types.callExpression(
346
+ this.types.memberExpression(
347
+ linguiInstance ?? this.types.identifier(this.i18nImportName),
348
+ this.types.identifier("_")
349
+ ),
350
+ [messageDescriptor]
351
+ );
352
+ }
353
+ createMessageDescriptorFromTokens(tokens, oldLoc) {
354
+ const { message, values } = buildICUFromTokens(tokens);
355
+ const properties = [
356
+ this.createIdProperty(message),
357
+ !this.stripNonEssentialProps ? this.createObjectProperty(MESSAGE, this.types.stringLiteral(message)) : null,
358
+ this.createValuesProperty(values)
359
+ ];
360
+ return this.createMessageDescriptor(
361
+ properties,
362
+ // preserve line numbers for extractor
363
+ oldLoc
364
+ );
365
+ }
366
+ createMessageDescriptor(properties, oldLoc) {
367
+ const newDescriptor = this.types.objectExpression(
368
+ properties.filter(Boolean)
369
+ );
370
+ this.types.addComment(newDescriptor, "leading", EXTRACT_MARK);
371
+ if (oldLoc) {
372
+ newDescriptor.loc = oldLoc;
373
+ }
374
+ return newDescriptor;
375
+ }
376
+ createObjectProperty(key, value) {
377
+ return this.types.objectProperty(this.types.identifier(key), value);
378
+ }
379
+ getObjectPropertyByKey(objectExp, key) {
380
+ return objectExp.properties.find(
381
+ (property) => types.isObjectProperty(property) && this.isLinguiIdentifier(property.key, key)
382
+ );
383
+ }
384
+ /**
385
+ * Custom matchers
386
+ */
387
+ isLinguiIdentifier(node, name) {
388
+ return this.types.isIdentifier(node, {
389
+ name: this.nameMap.get(name) || name
390
+ });
391
+ }
392
+ isDefineMessage(node) {
393
+ return this.isLinguiIdentifier(node, "defineMessage") || this.isLinguiIdentifier(node, "msg");
394
+ }
395
+ isArg(node) {
396
+ return this.types.isCallExpression(node) && this.isLinguiIdentifier(node.callee, "arg");
397
+ }
398
+ isI18nMethod(node) {
399
+ return this.types.isTaggedTemplateExpression(node) && (this.isLinguiIdentifier(node.tag, "t") || this.types.isCallExpression(node.tag) && this.isLinguiIdentifier(node.tag.callee, "t"));
400
+ }
401
+ isChoiceMethod(node) {
402
+ return this.types.isCallExpression(node) && (this.isLinguiIdentifier(node.callee, "plural") || this.isLinguiIdentifier(node.callee, "select") || this.isLinguiIdentifier(node.callee, "selectOrdinal"));
403
+ }
404
+ getTextFromExpression(exp) {
405
+ if (this.types.isStringLiteral(exp)) {
406
+ return exp.value;
407
+ }
408
+ if (this.types.isTemplateLiteral(exp)) {
409
+ if (exp?.quasis.length === 1) {
410
+ return exp.quasis[0]?.value?.cooked;
411
+ }
412
+ }
413
+ }
414
+ }
415
+
416
+ const pluralRuleRe = /(_[\d\w]+|zero|one|two|few|many|other)/;
417
+ const jsx2icuExactChoice = (value) => value.replace(/_(\d+)/, "=$1").replace(/_(\w+)/, "$1");
418
+ const keepSpaceRe = /\s*(?:\r\n|\r|\n)+\s*/g;
419
+ const stripAroundTagsRe = /(?:([>}])(?:\r\n|\r|\n)+\s*|(?:\r\n|\r|\n)+\s*(?=[<{]))/g;
420
+ function maybeNodeValue(node) {
421
+ if (!node)
422
+ return null;
423
+ if (node.type === "StringLiteral")
424
+ return node.value;
425
+ if (node.type === "JSXAttribute")
426
+ return maybeNodeValue(node.value);
427
+ if (node.type === "JSXExpressionContainer")
428
+ return maybeNodeValue(node.expression);
429
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0)
430
+ return node.quasis[0].value.raw;
431
+ return null;
432
+ }
433
+ function normalizeWhitespace(text) {
434
+ return text.replace(stripAroundTagsRe, "$1").replace(keepSpaceRe, " ").replace(/\\n/g, "\n").replace(/\\s/g, " ").replace(/(\s+})/gm, "}").replace(/({\s+)/gm, "{").trim();
435
+ }
436
+ class MacroJSX {
437
+ constructor({ types }, opts) {
438
+ this.expressionIndex = makeCounter();
439
+ this.elementIndex = makeCounter();
440
+ this.createStringJsxAttribute = (name, value) => {
441
+ return this.types.jsxAttribute(
442
+ this.types.jsxIdentifier(name),
443
+ this.types.jsxExpressionContainer(this.types.stringLiteral(value))
444
+ );
445
+ };
446
+ this.replacePath = (path) => {
447
+ const tokens = this.tokenizeNode(path);
448
+ const messageFormat = new ICUMessageFormat();
449
+ const {
450
+ message: messageRaw,
451
+ values,
452
+ jsxElements
453
+ } = messageFormat.fromTokens(tokens);
454
+ const message = normalizeWhitespace(messageRaw);
455
+ const { attributes, id, comment, context } = this.stripMacroAttributes(
456
+ path
457
+ );
458
+ if (!id && !message) {
459
+ return;
460
+ }
461
+ if (id) {
462
+ attributes.push(
463
+ this.types.jsxAttribute(
464
+ this.types.jsxIdentifier(ID),
465
+ this.types.stringLiteral(id)
466
+ )
467
+ );
468
+ } else {
469
+ attributes.push(
470
+ this.createStringJsxAttribute(ID, api.generateMessageId(message, context))
471
+ );
472
+ }
473
+ if (!this.stripNonEssentialProps) {
474
+ if (message) {
475
+ attributes.push(this.createStringJsxAttribute(MESSAGE, message));
476
+ }
477
+ if (comment) {
478
+ attributes.push(
479
+ this.types.jsxAttribute(
480
+ this.types.jsxIdentifier(COMMENT),
481
+ this.types.stringLiteral(comment)
482
+ )
483
+ );
484
+ }
485
+ if (context) {
486
+ attributes.push(
487
+ this.types.jsxAttribute(
488
+ this.types.jsxIdentifier(CONTEXT),
489
+ this.types.stringLiteral(context)
490
+ )
491
+ );
492
+ }
493
+ }
494
+ const valuesObject = Object.keys(values).map(
495
+ (key) => this.types.objectProperty(this.types.identifier(key), values[key])
496
+ );
497
+ if (valuesObject.length) {
498
+ attributes.push(
499
+ this.types.jsxAttribute(
500
+ this.types.jsxIdentifier("values"),
501
+ this.types.jsxExpressionContainer(
502
+ this.types.objectExpression(valuesObject)
503
+ )
504
+ )
505
+ );
506
+ }
507
+ if (Object.keys(jsxElements).length) {
508
+ attributes.push(
509
+ this.types.jsxAttribute(
510
+ this.types.jsxIdentifier("components"),
511
+ this.types.jsxExpressionContainer(
512
+ this.types.objectExpression(
513
+ Object.keys(jsxElements).map(
514
+ (key) => this.types.objectProperty(
515
+ this.types.identifier(key),
516
+ jsxElements[key]
517
+ )
518
+ )
519
+ )
520
+ )
521
+ )
522
+ );
523
+ }
524
+ const newNode = this.types.jsxElement(
525
+ this.types.jsxOpeningElement(
526
+ this.types.jsxIdentifier("Trans"),
527
+ attributes,
528
+ true
529
+ ),
530
+ null,
531
+ [],
532
+ true
533
+ );
534
+ newNode.loc = path.node.loc;
535
+ path.replaceWith(newNode);
536
+ };
537
+ this.attrName = (names, exclude = false) => {
538
+ const namesRe = new RegExp("^(" + names.join("|") + ")$");
539
+ return (attr) => {
540
+ const name = attr.name.name;
541
+ return exclude ? !namesRe.test(name) : namesRe.test(name);
542
+ };
543
+ };
544
+ this.stripMacroAttributes = (path) => {
545
+ const { attributes } = path.node.openingElement;
546
+ const id = attributes.find(this.attrName([ID]));
547
+ const message = attributes.find(this.attrName([MESSAGE]));
548
+ const comment = attributes.find(this.attrName([COMMENT]));
549
+ const context = attributes.find(this.attrName([CONTEXT]));
550
+ let reserved = [ID, MESSAGE, COMMENT, CONTEXT];
551
+ if (this.isChoiceComponent(path)) {
552
+ reserved = [
553
+ ...reserved,
554
+ "_\\w+",
555
+ "_\\d+",
556
+ "zero",
557
+ "one",
558
+ "two",
559
+ "few",
560
+ "many",
561
+ "other",
562
+ "value",
563
+ "offset"
564
+ ];
565
+ }
566
+ return {
567
+ id: maybeNodeValue(id),
568
+ message: maybeNodeValue(message),
569
+ comment: maybeNodeValue(comment),
570
+ context: maybeNodeValue(context),
571
+ attributes: attributes.filter(this.attrName(reserved, true))
572
+ };
573
+ };
574
+ this.tokenizeNode = (path) => {
575
+ if (this.isTransComponent(path)) {
576
+ return this.tokenizeTrans(path);
577
+ } else if (this.isChoiceComponent(path)) {
578
+ return [this.tokenizeChoiceComponent(path)];
579
+ } else if (path.isJSXElement()) {
580
+ return [this.tokenizeElement(path)];
581
+ } else {
582
+ return [this.tokenizeExpression(path)];
583
+ }
584
+ };
585
+ this.tokenizeTrans = (path) => {
586
+ return path.get("children").flatMap((child) => this.tokenizeChildren(child)).filter(Boolean);
587
+ };
588
+ this.tokenizeChildren = (path) => {
589
+ if (path.isJSXExpressionContainer()) {
590
+ const exp = path.get("expression");
591
+ if (exp.isStringLiteral()) {
592
+ return [this.tokenizeText(exp.node.value.replace(/\n/g, "\\n"))];
593
+ }
594
+ if (exp.isTemplateLiteral()) {
595
+ return this.tokenizeTemplateLiteral(exp);
596
+ }
597
+ if (exp.isConditionalExpression()) {
598
+ return [this.tokenizeConditionalExpression(exp)];
599
+ }
600
+ if (exp.isJSXElement()) {
601
+ return this.tokenizeNode(exp);
602
+ }
603
+ return [this.tokenizeExpression(exp)];
604
+ } else if (path.isJSXElement()) {
605
+ return this.tokenizeNode(path);
606
+ } else if (path.isJSXSpreadChild()) ; else if (path.isJSXText()) {
607
+ return [this.tokenizeText(path.node.value)];
608
+ } else ;
609
+ };
610
+ this.tokenizeChoiceComponent = (path) => {
611
+ const element = path.get("openingElement");
612
+ const name = this.getJsxTagName(path.node);
613
+ const format = (this.nameMapReversed.get(name) || name).toLowerCase();
614
+ const props = element.get("attributes").filter((attr) => {
615
+ return this.attrName(
616
+ [
617
+ ID,
618
+ COMMENT,
619
+ MESSAGE,
620
+ CONTEXT,
621
+ "key",
622
+ // we remove <Trans /> react props that are not useful for translation
623
+ "render",
624
+ "component",
625
+ "components"
626
+ ],
627
+ true
628
+ )(attr.node);
629
+ });
630
+ const token = {
631
+ type: "arg",
632
+ format,
633
+ name: null,
634
+ value: void 0,
635
+ options: {
636
+ offset: void 0
637
+ }
638
+ };
639
+ for (const _attr of props) {
640
+ if (_attr.isJSXSpreadAttribute()) {
641
+ continue;
642
+ }
643
+ const attr = _attr;
644
+ if (this.types.isJSXNamespacedName(attr.node.name)) {
645
+ continue;
646
+ }
647
+ const name2 = attr.node.name.name;
648
+ const value = attr.get("value");
649
+ if (name2 === "value") {
650
+ const exp = value.isLiteral() ? value : value.get("expression");
651
+ token.name = this.expressionToArgument(exp);
652
+ token.value = exp.node;
653
+ } else if (format !== "select" && name2 === "offset") {
654
+ token.options.offset = value.isStringLiteral() || value.isNumericLiteral() ? value.node.value : value.get(
655
+ "expression"
656
+ ).node.value;
657
+ } else {
658
+ let option;
659
+ if (value.isStringLiteral()) {
660
+ option = value.node.extra.raw.replace(
661
+ /(["'])(.*)\1/,
662
+ "$2"
663
+ );
664
+ } else {
665
+ option = this.tokenizeChildren(value);
666
+ }
667
+ if (pluralRuleRe.test(name2)) {
668
+ token.options[jsx2icuExactChoice(name2)] = option;
669
+ } else {
670
+ token.options[name2] = option;
671
+ }
672
+ }
673
+ }
674
+ return token;
675
+ };
676
+ this.tokenizeElement = (path) => {
677
+ const name = this.elementIndex();
678
+ return {
679
+ type: "element",
680
+ name,
681
+ value: {
682
+ ...path.node,
683
+ children: [],
684
+ openingElement: {
685
+ ...path.node.openingElement,
686
+ selfClosing: true
687
+ }
688
+ },
689
+ children: this.tokenizeTrans(path)
690
+ };
691
+ };
692
+ this.tokenizeExpression = (path) => {
693
+ return {
694
+ type: "arg",
695
+ name: this.expressionToArgument(path),
696
+ value: path.node
697
+ };
698
+ };
699
+ this.tokenizeConditionalExpression = (exp) => {
700
+ exp.traverse({
701
+ JSXElement: (el) => {
702
+ if (this.isTransComponent(el) || this.isChoiceComponent(el)) {
703
+ this.replacePath(el);
704
+ el.skip();
705
+ }
706
+ }
707
+ });
708
+ return {
709
+ type: "arg",
710
+ name: this.expressionToArgument(exp),
711
+ value: exp.node
712
+ };
713
+ };
714
+ this.tokenizeText = (value) => {
715
+ return {
716
+ type: "text",
717
+ value
718
+ };
719
+ };
720
+ this.isLinguiComponent = (path, name) => {
721
+ return path.isJSXElement() && this.types.isJSXIdentifier(path.node.openingElement.name, {
722
+ name: this.nameMap.get(name) || name
723
+ });
724
+ };
725
+ this.isTransComponent = (path) => {
726
+ return this.isLinguiComponent(path, "Trans");
727
+ };
728
+ this.isChoiceComponent = (path) => {
729
+ return this.isLinguiComponent(path, "Plural") || this.isLinguiComponent(path, "Select") || this.isLinguiComponent(path, "SelectOrdinal");
730
+ };
731
+ this.getJsxTagName = (node) => {
732
+ if (this.types.isJSXIdentifier(node.openingElement.name)) {
733
+ return node.openingElement.name.name;
734
+ }
735
+ };
736
+ this.types = types;
737
+ this.stripNonEssentialProps = opts.stripNonEssentialProps;
738
+ this.nameMap = opts.nameMap;
739
+ this.nameMapReversed = Array.from(opts.nameMap.entries()).reduce(
740
+ (map, [key, value]) => map.set(value, key),
741
+ /* @__PURE__ */ new Map()
742
+ );
743
+ }
744
+ tokenizeTemplateLiteral(exp) {
745
+ const expressions = exp.get("expressions");
746
+ return exp.get("quasis").flatMap(({ node: text }, i) => {
747
+ const value = /\\u[a-fA-F0-9]{4}|\\x[a-fA-F0-9]{2}/g.test(text.value.raw) ? text.value.cooked : text.value.raw;
748
+ let argTokens = [];
749
+ const currExp = expressions[i];
750
+ if (currExp) {
751
+ argTokens = currExp.isCallExpression() ? this.tokenizeNode(currExp) : [this.tokenizeExpression(currExp)];
752
+ }
753
+ return [
754
+ ...value ? [this.tokenizeText(this.clearBackslashes(value))] : [],
755
+ ...argTokens
756
+ ];
757
+ });
758
+ }
759
+ expressionToArgument(path) {
760
+ return path.isIdentifier() ? path.node.name : String(this.expressionIndex());
761
+ }
762
+ /**
763
+ * We clean '//\` ' to just '`'
764
+ **/
765
+ clearBackslashes(value) {
766
+ return value.replace(/\\`/g, "`");
767
+ }
768
+ }
769
+
770
+ const jsMacroTags = /* @__PURE__ */ new Set([
771
+ "defineMessage",
772
+ "msg",
773
+ "arg",
774
+ "t",
775
+ "plural",
776
+ "select",
777
+ "selectOrdinal"
778
+ ]);
779
+ const jsxMacroTags = /* @__PURE__ */ new Set(["Trans", "Plural", "Select", "SelectOrdinal"]);
780
+ let config;
781
+ function getConfig(_config) {
782
+ if (_config) {
783
+ config = _config;
784
+ }
785
+ if (!config) {
786
+ config = conf.getConfig();
787
+ }
788
+ return config;
789
+ }
790
+ function macro({ references, state, babel, config: config2 }) {
791
+ const opts = config2;
792
+ const {
793
+ i18nImportModule,
794
+ i18nImportName,
795
+ TransImportModule,
796
+ TransImportName
797
+ } = getConfig(opts.linguiConfig).runtimeConfigModule;
798
+ const jsxNodes = /* @__PURE__ */ new Set();
799
+ const jsNodes = /* @__PURE__ */ new Set();
800
+ let needsI18nImport = false;
801
+ let nameMap = /* @__PURE__ */ new Map();
802
+ Object.keys(references).forEach((tagName) => {
803
+ const nodes = references[tagName];
804
+ if (jsMacroTags.has(tagName)) {
805
+ nodes.forEach((path) => {
806
+ nameMap.set(tagName, path.node.name);
807
+ jsNodes.add(path.parentPath);
808
+ });
809
+ } else if (jsxMacroTags.has(tagName)) {
810
+ nodes.forEach((path) => {
811
+ nameMap.set(tagName, path.node.name);
812
+ jsxNodes.add(path.parentPath.parentPath);
813
+ });
814
+ } else {
815
+ throw nodes[0].buildCodeFrameError(`Unknown macro ${tagName}`);
816
+ }
817
+ });
818
+ const stripNonEssentialProps = process.env.NODE_ENV == "production" && !opts.extract;
819
+ const jsNodesArray = Array.from(jsNodes);
820
+ jsNodesArray.filter(isRootPath(jsNodesArray)).forEach((path) => {
821
+ const macro2 = new MacroJs(babel, {
822
+ i18nImportName,
823
+ stripNonEssentialProps,
824
+ nameMap
825
+ });
826
+ if (macro2.replacePath(path))
827
+ needsI18nImport = true;
828
+ });
829
+ const jsxNodesArray = Array.from(jsxNodes);
830
+ jsxNodesArray.filter(isRootPath(jsxNodesArray)).forEach((path) => {
831
+ const macro2 = new MacroJSX(babel, { stripNonEssentialProps, nameMap });
832
+ macro2.replacePath(path);
833
+ });
834
+ if (needsI18nImport) {
835
+ addImport(babel, state, i18nImportModule, i18nImportName);
836
+ }
837
+ if (jsxNodes.size) {
838
+ addImport(babel, state, TransImportModule, TransImportName);
839
+ }
840
+ }
841
+ function addImport(babel, state, module2, importName) {
842
+ const { types: t } = babel;
843
+ const linguiImport = state.file.path.node.body.find(
844
+ (importNode) => t.isImportDeclaration(importNode) && importNode.source.value === module2 && // https://github.com/lingui/js-lingui/issues/777
845
+ importNode.importKind !== "type"
846
+ );
847
+ const tIdentifier = t.identifier(importName);
848
+ if (linguiImport) {
849
+ if (linguiImport.specifiers.findIndex(
850
+ (specifier) => types.isImportSpecifier(specifier) && types.isIdentifier(specifier.imported, { name: importName })
851
+ ) === -1) {
852
+ linguiImport.specifiers.push(t.importSpecifier(tIdentifier, tIdentifier));
853
+ }
854
+ } else {
855
+ state.file.path.node.body.unshift(
856
+ t.importDeclaration(
857
+ [t.importSpecifier(tIdentifier, tIdentifier)],
858
+ t.stringLiteral(module2)
859
+ )
860
+ );
861
+ }
862
+ }
863
+ function isRootPath(allPath) {
864
+ return (node) => function traverse(path) {
865
+ if (!path.parentPath) {
866
+ return true;
867
+ } else {
868
+ return !allPath.includes(path.parentPath) && traverse(path.parentPath);
869
+ }
870
+ }(node);
871
+ }
872
+ [...jsMacroTags, ...jsxMacroTags].forEach((name) => {
873
+ Object.defineProperty(module.exports, name, {
874
+ get() {
875
+ throw new Error(
876
+ `The macro you imported from "@lingui/macro" is being executed outside the context of compilation with babel-plugin-macros. This indicates that you don't have the babel plugin "babel-plugin-macros" configured correctly. Please see the documentation for how to configure babel-plugin-macros properly: https://github.com/kentcdodds/babel-plugin-macros/blob/main/other/docs/user.md`
877
+ );
878
+ }
879
+ });
880
+ });
881
+ const index = babelPluginMacros.createMacro(macro, {
882
+ configName: "lingui"
883
+ });
884
+
885
+ module.exports = index;