@lingui/macro 5.0.0-next.1 → 5.0.0-next.3

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