@intlayer/lsp 8.11.4 → 9.0.0-canary.12

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.
Files changed (46) hide show
  1. package/dist/esm/_virtual/_rolldown/runtime.mjs +36 -0
  2. package/dist/esm/callers/index.mjs +12 -0
  3. package/dist/esm/callers/index.mjs.map +1 -0
  4. package/dist/esm/callers/patterns.mjs +37 -0
  5. package/dist/esm/callers/patterns.mjs.map +1 -0
  6. package/dist/esm/dictionaryUtils.mjs +84 -0
  7. package/dist/esm/dictionaryUtils.mjs.map +1 -0
  8. package/dist/esm/findFieldInFile.mjs +22 -125
  9. package/dist/esm/findFieldInFile.mjs.map +1 -1
  10. package/dist/esm/findKeyAtOffset.mjs +20 -24
  11. package/dist/esm/findKeyAtOffset.mjs.map +1 -1
  12. package/dist/esm/findKeyInContentFile.mjs +259 -40
  13. package/dist/esm/findKeyInContentFile.mjs.map +1 -1
  14. package/dist/esm/findTCallAtOffset.mjs +33 -0
  15. package/dist/esm/findTCallAtOffset.mjs.map +1 -0
  16. package/dist/esm/findUsageFieldAtOffset.mjs +12 -51
  17. package/dist/esm/findUsageFieldAtOffset.mjs.map +1 -1
  18. package/dist/esm/index.mjs +338 -170
  19. package/dist/esm/index.mjs.map +1 -1
  20. package/dist/esm/oxcUtils.mjs +99 -29
  21. package/dist/esm/oxcUtils.mjs.map +1 -1
  22. package/dist/esm/usageAnalyzer.mjs +692 -0
  23. package/dist/esm/usageAnalyzer.mjs.map +1 -0
  24. package/dist/esm/utils.mjs +12 -1
  25. package/dist/types/callers/index.d.ts +8 -0
  26. package/dist/types/callers/index.d.ts.map +1 -0
  27. package/dist/types/callers/patterns.d.ts +30 -0
  28. package/dist/types/callers/patterns.d.ts.map +1 -0
  29. package/dist/types/dictionaryUtils.d.ts +12 -0
  30. package/dist/types/dictionaryUtils.d.ts.map +1 -0
  31. package/dist/types/findFieldInFile.d.ts +12 -14
  32. package/dist/types/findFieldInFile.d.ts.map +1 -1
  33. package/dist/types/findKeyAtOffset.d.ts +13 -10
  34. package/dist/types/findKeyAtOffset.d.ts.map +1 -1
  35. package/dist/types/findKeyInContentFile.d.ts +15 -13
  36. package/dist/types/findKeyInContentFile.d.ts.map +1 -1
  37. package/dist/types/findTCallAtOffset.d.ts +24 -0
  38. package/dist/types/findTCallAtOffset.d.ts.map +1 -0
  39. package/dist/types/findUsageFieldAtOffset.d.ts +2 -1
  40. package/dist/types/findUsageFieldAtOffset.d.ts.map +1 -1
  41. package/dist/types/oxcUtils.d.ts +42 -13
  42. package/dist/types/oxcUtils.d.ts.map +1 -1
  43. package/dist/types/usageAnalyzer.d.ts +129 -0
  44. package/dist/types/usageAnalyzer.d.ts.map +1 -0
  45. package/dist/types/utils.d.ts +15 -1
  46. package/package.json +9 -22
@@ -0,0 +1,692 @@
1
+ import { callers_exports } from "./callers/index.mjs";
2
+ import { buildParentMap, getObjectPropertyNode, getObjectPropertyString, getPropertyKeyName, getStaticStringValue, nodeEnd, nodeStart, parseText, walkAst } from "./oxcUtils.mjs";
3
+
4
+ //#region src/usageAnalyzer.ts
5
+ /**
6
+ * Property names that are framework accessors rather than content fields
7
+ * (react `.value`, vue refs `.value`, editor `.raw`/`.use`): they are skipped
8
+ * when building field paths.
9
+ */
10
+ const ACCESSOR_PROPERTY_NAMES = new Set([
11
+ "value",
12
+ "raw",
13
+ "use"
14
+ ]);
15
+ /**
16
+ * Resolve a value source against a call expression's arguments.
17
+ */
18
+ const readValueSource = (callNode, source) => {
19
+ const argumentsList = callNode["arguments"];
20
+ switch (source.from) {
21
+ case "argument": return getStaticStringValue(argumentsList?.[source.index]);
22
+ case "option": return getObjectPropertyString(argumentsList?.[source.argumentIndex], source.property);
23
+ case "fixed": return source.value;
24
+ case "path-first-segment": return null;
25
+ }
26
+ };
27
+ /** Read the first matching value from a list of sources. */
28
+ const readValueSources = (callNode, sources) => {
29
+ for (const source of sources ?? []) {
30
+ const value = readValueSource(callNode, source);
31
+ if (value !== null) return value;
32
+ }
33
+ return null;
34
+ };
35
+ /**
36
+ * Apply nested-namespace semantics: for descriptors flagged
37
+ * `nestedNamespace`, a dotted namespace is split at the first `.` into the
38
+ * dictionary key and a key-prefix path (next-intl:
39
+ * `useTranslations('about.counter')` → dictionary `about`, prefix
40
+ * `['counter']`).
41
+ */
42
+ const splitNestedNamespace = (descriptor, rawNamespace) => {
43
+ if (!descriptor.nestedNamespace || !rawNamespace.includes(".")) return {
44
+ dictionaryKey: rawNamespace,
45
+ prefixPath: []
46
+ };
47
+ const segments = rawNamespace.split(".");
48
+ return {
49
+ dictionaryKey: segments[0],
50
+ prefixPath: segments.slice(1)
51
+ };
52
+ };
53
+ /**
54
+ * Return the caller name matched by a call/tagged-template callee: the bare
55
+ * identifier name, or the property name of a member expression when the
56
+ * descriptor allows method matching.
57
+ */
58
+ const getCalleeName = (calleeNode) => {
59
+ if (!calleeNode) return null;
60
+ if (calleeNode["type"] === "Identifier") return {
61
+ name: calleeNode["name"],
62
+ isMethod: false
63
+ };
64
+ if (calleeNode["type"] === "MemberExpression" && calleeNode["computed"] !== true) {
65
+ const propertyNode = calleeNode["property"];
66
+ if (propertyNode?.["type"] === "Identifier") return {
67
+ name: propertyNode["name"],
68
+ isMethod: true
69
+ };
70
+ }
71
+ return null;
72
+ };
73
+ /**
74
+ * The message id of a self caller: either the first string argument or the
75
+ * `id` property of a descriptor-object first argument
76
+ * (`formatMessage({ id: 'home.title' })`, `i18n._({ id: '…' })`).
77
+ */
78
+ const getSelfCallMessageId = (callNode) => {
79
+ const firstArgument = callNode["arguments"]?.[0];
80
+ if (!firstArgument) return null;
81
+ return getStaticStringValue(firstArgument) ?? getObjectPropertyString(firstArgument, "id");
82
+ };
83
+ /**
84
+ * Split a message id into dictionary key + field path according to the
85
+ * descriptor semantics.
86
+ */
87
+ const resolveMessageId = (descriptor, fixedDictionaryKey, messageId) => {
88
+ if (fixedDictionaryKey !== null) return {
89
+ dictionaryKey: fixedDictionaryKey,
90
+ fieldPath: descriptor.flatKey ? [messageId] : messageId.split(".")
91
+ };
92
+ if (!descriptor.namespaceSources.some((source) => source.from === "path-first-segment")) return null;
93
+ const segments = messageId.split(".");
94
+ if (!segments[0]) return null;
95
+ return {
96
+ dictionaryKey: segments[0],
97
+ fieldPath: segments.slice(1)
98
+ };
99
+ };
100
+ /**
101
+ * i18next-style `ns:key` ids override the bound namespace:
102
+ * `t('about:title')` reads the `about` dictionary even when the translator
103
+ * was created with another namespace.
104
+ */
105
+ const splitNamespacePrefixedId = (messageId) => {
106
+ const separatorIndex = messageId.indexOf(":");
107
+ if (separatorIndex <= 0) return {
108
+ namespaceOverride: null,
109
+ messagePath: messageId
110
+ };
111
+ return {
112
+ namespaceOverride: messageId.slice(0, separatorIndex),
113
+ messagePath: messageId.slice(separatorIndex + 1)
114
+ };
115
+ };
116
+ /** Unwrap `await expression` down to the awaited expression. */
117
+ const unwrapAwait = (node) => node?.["type"] === "AwaitExpression" ? node["argument"] : node;
118
+ /** Collect every module specifier imported by the program. */
119
+ const collectImportSources = (program) => {
120
+ const importSources = /* @__PURE__ */ new Set();
121
+ for (const statement of program["body"] ?? []) {
122
+ if (statement["type"] !== "ImportDeclaration") continue;
123
+ const sourceValue = statement["source"]?.["value"];
124
+ if (typeof sourceValue === "string") importSources.add(sourceValue);
125
+ }
126
+ return importSources;
127
+ };
128
+ /** Map each imported local name to its module specifier. */
129
+ const collectImportedLocalNames = (program) => {
130
+ const localNameToSource = /* @__PURE__ */ new Map();
131
+ for (const statement of program["body"] ?? []) {
132
+ if (statement["type"] !== "ImportDeclaration") continue;
133
+ const sourceValue = statement["source"]?.["value"];
134
+ if (typeof sourceValue !== "string") continue;
135
+ for (const specifier of statement["specifiers"] ?? []) {
136
+ const localName = specifier["local"]?.["name"];
137
+ if (typeof localName === "string") localNameToSource.set(localName, sourceValue);
138
+ }
139
+ }
140
+ return localNameToSource;
141
+ };
142
+ /**
143
+ * Find the descriptor matching a call (or tagged template) callee among the
144
+ * active descriptors.
145
+ */
146
+ const matchDescriptorForCallee = (state, calleeNode, filter) => {
147
+ const callee = getCalleeName(calleeNode);
148
+ if (!callee) return null;
149
+ for (const descriptor of state.activeDescriptors) {
150
+ if (descriptor.callerName !== callee.name) continue;
151
+ if (callee.isMethod && !descriptor.matchAsMethod) continue;
152
+ if (filter && !filter(descriptor)) continue;
153
+ return descriptor;
154
+ }
155
+ return null;
156
+ };
157
+ /** The module specifier a caller local name was imported from, if any. */
158
+ const getModuleSource = (state, descriptor) => state.importedLocalNames.get(descriptor.callerName) ?? void 0;
159
+ /**
160
+ * Recursively register a content destructure pattern: each property key is a
161
+ * field usage, each bound identifier becomes a content binding, and nested
162
+ * patterns extend the field path.
163
+ *
164
+ * const { searchInput: { text: alias } } = useIntlayer('key')
165
+ * → usages: ['searchInput'], ['searchInput', 'text']
166
+ * → binding: alias → ['searchInput', 'text']
167
+ */
168
+ const collectContentDestructure = (state, pattern, dictionaryKey, basePath, descriptor, moduleSource) => {
169
+ for (const property of pattern["properties"] ?? []) {
170
+ const propertyType = property["type"];
171
+ if (propertyType !== "Property" && propertyType !== "ObjectProperty") continue;
172
+ const keyNode = property["key"];
173
+ const fieldName = getPropertyKeyName(keyNode);
174
+ if (!keyNode || !fieldName) continue;
175
+ const fieldPath = [...basePath, fieldName];
176
+ state.usages.push({
177
+ dictionaryKey,
178
+ fieldPath,
179
+ start: nodeStart(keyNode),
180
+ end: nodeEnd(keyNode),
181
+ kind: "destructure",
182
+ callerName: descriptor.callerName,
183
+ library: descriptor.library,
184
+ moduleSource
185
+ });
186
+ let valueNode = property["value"];
187
+ if (valueNode?.["type"] === "AssignmentPattern") valueNode = valueNode["left"];
188
+ if (valueNode?.["type"] === "Identifier") state.contentBindings.set(valueNode["name"], {
189
+ dictionaryKey,
190
+ basePath: fieldPath,
191
+ descriptor,
192
+ moduleSource
193
+ });
194
+ else if (valueNode?.["type"] === "ObjectPattern") collectContentDestructure(state, valueNode, dictionaryKey, fieldPath, descriptor, moduleSource);
195
+ }
196
+ };
197
+ /**
198
+ * Register bindings created by `const … = caller(…)` declarations, and record
199
+ * dictionary-level (`namespace`) usages for every matched caller call.
200
+ */
201
+ const collectBindings = (state, program) => {
202
+ walkAst(program, (node) => {
203
+ if (node["type"] === "CallExpression") {
204
+ const descriptor = matchDescriptorForCallee(state, node["callee"], (candidate) => candidate.translationFunction !== "self");
205
+ if (descriptor) {
206
+ const rawNamespace = readValueSources(node, descriptor.namespaceSources);
207
+ if (rawNamespace) {
208
+ const { dictionaryKey } = splitNestedNamespace(descriptor, rawNamespace);
209
+ state.usages.push({
210
+ dictionaryKey,
211
+ fieldPath: [],
212
+ start: nodeStart(node),
213
+ end: nodeEnd(node),
214
+ kind: "namespace",
215
+ callerName: descriptor.callerName,
216
+ library: descriptor.library,
217
+ moduleSource: getModuleSource(state, descriptor)
218
+ });
219
+ }
220
+ }
221
+ return;
222
+ }
223
+ if (node["type"] !== "VariableDeclarator") return;
224
+ const initializer = unwrapAwait(node["init"]);
225
+ if (initializer?.["type"] !== "CallExpression") return;
226
+ const descriptor = matchDescriptorForCallee(state, initializer["callee"], (candidate) => candidate.translationFunction !== "self");
227
+ if (!descriptor) return;
228
+ const rawNamespace = readValueSources(initializer, descriptor.namespaceSources);
229
+ if (!rawNamespace && !descriptor.allowRootScope) return;
230
+ const namespaceSplit = rawNamespace ? splitNestedNamespace(descriptor, rawNamespace) : {
231
+ dictionaryKey: null,
232
+ prefixPath: []
233
+ };
234
+ const keyPrefixValue = readValueSources(initializer, descriptor.keyPrefixSources);
235
+ const keyPrefix = [...namespaceSplit.prefixPath, ...keyPrefixValue ? keyPrefixValue.split(".") : []];
236
+ const dictionaryKey = namespaceSplit.dictionaryKey;
237
+ const moduleSource = getModuleSource(state, descriptor);
238
+ const idNode = node["id"];
239
+ if (!idNode) return;
240
+ if (idNode["type"] === "Identifier") {
241
+ const variableName = idNode["name"];
242
+ if (descriptor.translationFunction === "return-value") state.translatorBindings.set(variableName, {
243
+ dictionaryKey,
244
+ keyPrefix,
245
+ descriptor,
246
+ moduleSource
247
+ });
248
+ else if (descriptor.translationFunction === "content" && dictionaryKey) state.contentBindings.set(variableName, {
249
+ dictionaryKey,
250
+ basePath: keyPrefix,
251
+ descriptor,
252
+ moduleSource
253
+ });
254
+ return;
255
+ }
256
+ if (idNode["type"] !== "ObjectPattern") return;
257
+ if (descriptor.translationFunction === "content") {
258
+ if (!dictionaryKey) return;
259
+ collectContentDestructure(state, idNode, dictionaryKey, keyPrefix, descriptor, moduleSource);
260
+ return;
261
+ }
262
+ if (descriptor.translationFunction !== "destructured-t") return;
263
+ for (const property of idNode["properties"] ?? []) {
264
+ const propertyType = property["type"];
265
+ if (propertyType !== "Property" && propertyType !== "ObjectProperty") continue;
266
+ const keyNode = property["key"];
267
+ const valueNode = property["value"];
268
+ const fieldName = getPropertyKeyName(keyNode);
269
+ const localName = valueNode?.["type"] === "Identifier" ? valueNode["name"] : null;
270
+ if (fieldName !== "t" || !localName) continue;
271
+ state.translatorBindings.set(localName, {
272
+ dictionaryKey,
273
+ keyPrefix,
274
+ descriptor,
275
+ moduleSource
276
+ });
277
+ }
278
+ });
279
+ };
280
+ /**
281
+ * Record `t('path.to.field')` calls on translator bindings, and self-caller
282
+ * calls (`formatMessage({ id })`, `i18n._('id')`).
283
+ */
284
+ const collectCallUsages = (state, program) => {
285
+ walkAst(program, (node) => {
286
+ if (node["type"] === "TaggedTemplateExpression") {
287
+ collectTaggedTemplateUsage(state, node);
288
+ return;
289
+ }
290
+ if (node["type"] !== "CallExpression") return;
291
+ const callee = node["callee"];
292
+ if (callee?.["type"] === "Identifier") {
293
+ const binding = state.translatorBindings.get(callee["name"]);
294
+ if (binding) {
295
+ const argumentsList = node["arguments"];
296
+ const messageId = getStaticStringValue(argumentsList?.[0]);
297
+ if (messageId) {
298
+ const { namespaceOverride, messagePath } = splitNamespacePrefixedId(messageId);
299
+ let dictionaryKey = namespaceOverride ?? binding.dictionaryKey;
300
+ let fieldPath = namespaceOverride ? messagePath.split(".") : [...binding.keyPrefix, ...messagePath.split(".")];
301
+ if (dictionaryKey === null) {
302
+ const segments = messagePath.split(".");
303
+ dictionaryKey = segments[0] ?? null;
304
+ fieldPath = segments.slice(1);
305
+ }
306
+ if (dictionaryKey) state.usages.push({
307
+ dictionaryKey,
308
+ fieldPath,
309
+ start: nodeStart(node),
310
+ end: nodeEnd(node),
311
+ kind: "call",
312
+ callerName: binding.descriptor.callerName,
313
+ library: binding.descriptor.library,
314
+ moduleSource: binding.moduleSource
315
+ });
316
+ }
317
+ return;
318
+ }
319
+ }
320
+ const descriptor = matchDescriptorForCallee(state, callee, (candidate) => candidate.translationFunction === "self");
321
+ if (!descriptor) return;
322
+ const messageId = getSelfCallMessageId(node);
323
+ if (!messageId) return;
324
+ const resolved = resolveMessageId(descriptor, readValueSources(node, descriptor.namespaceSources), messageId);
325
+ if (!resolved) return;
326
+ state.usages.push({
327
+ ...resolved,
328
+ start: nodeStart(node),
329
+ end: nodeEnd(node),
330
+ kind: "call",
331
+ callerName: descriptor.callerName,
332
+ library: descriptor.library,
333
+ moduleSource: getModuleSource(state, descriptor)
334
+ });
335
+ });
336
+ };
337
+ /**
338
+ * Lingui macro tagged template: ``t`Hello ${name}` `` — the catalog id is the
339
+ * template text with `{placeholder}` slots for each expression.
340
+ */
341
+ const collectTaggedTemplateUsage = (state, node) => {
342
+ const descriptor = matchDescriptorForCallee(state, node["tag"], (candidate) => candidate.matchAsTaggedTemplate === true);
343
+ if (!descriptor) return;
344
+ const quasiNode = node["quasi"];
345
+ const quasis = quasiNode?.["quasis"] ?? [];
346
+ const expressions = quasiNode?.["expressions"] ?? [];
347
+ let messageId = "";
348
+ for (let index = 0; index < quasis.length; index++) {
349
+ const valueNode = quasis[index]?.["value"];
350
+ messageId += valueNode?.["cooked"] ?? valueNode?.["raw"] ?? "";
351
+ if (index < expressions.length) {
352
+ const expression = expressions[index];
353
+ const placeholder = expression["type"] === "Identifier" ? expression["name"] : String(index);
354
+ messageId += `{${placeholder}}`;
355
+ }
356
+ }
357
+ if (!messageId) return;
358
+ const resolved = resolveMessageId(descriptor, readValueSources(node, descriptor.namespaceSources), messageId);
359
+ if (!resolved) return;
360
+ state.usages.push({
361
+ ...resolved,
362
+ start: nodeStart(node),
363
+ end: nodeEnd(node),
364
+ kind: "tagged-template",
365
+ callerName: descriptor.callerName,
366
+ library: descriptor.library,
367
+ moduleSource: getModuleSource(state, descriptor)
368
+ });
369
+ };
370
+ /** Read a static string JSX attribute from an opening element. */
371
+ const getJsxAttributeString = (openingElement, attributeName) => {
372
+ for (const attribute of openingElement["attributes"] ?? []) {
373
+ if (attribute["type"] !== "JSXAttribute") continue;
374
+ if (attribute["name"]?.["name"] !== attributeName) continue;
375
+ const valueNode = attribute["value"];
376
+ if (!valueNode) return null;
377
+ const directValue = getStaticStringValue(valueNode);
378
+ if (directValue !== null) return directValue;
379
+ if (valueNode["type"] === "JSXExpressionContainer") return getStaticStringValue(valueNode["expression"]);
380
+ return null;
381
+ }
382
+ return null;
383
+ };
384
+ /**
385
+ * Record JSX message components: `<FormattedMessage id="home.title" />`,
386
+ * `<Trans i18nKey="richText" />`, `<Trans id="…" />`.
387
+ */
388
+ const collectJsxUsages = (state, program) => {
389
+ const translatorNamespaces = new Set([...state.translatorBindings.values()].map((binding) => binding.dictionaryKey).filter((dictionaryKey) => dictionaryKey !== null));
390
+ const fallbackNamespace = translatorNamespaces.size === 1 ? [...translatorNamespaces][0] : null;
391
+ walkAst(program, (node) => {
392
+ if (node["type"] !== "JSXOpeningElement") return;
393
+ const nameNode = node["name"];
394
+ if (nameNode?.["type"] !== "JSXIdentifier") return;
395
+ const elementName = nameNode["name"];
396
+ for (const descriptor of state.activeDescriptors) {
397
+ if (!descriptor.jsxIdAttribute) continue;
398
+ if (descriptor.callerName !== elementName) continue;
399
+ const messageId = getJsxAttributeString(node, descriptor.jsxIdAttribute);
400
+ if (messageId === null) continue;
401
+ const namespaceFromAttribute = descriptor.jsxNamespaceAttribute ? getJsxAttributeString(node, descriptor.jsxNamespaceAttribute) : null;
402
+ const fixedNamespace = descriptor.namespaceSources.find((source) => source.from === "fixed");
403
+ const dictionaryKey = namespaceFromAttribute ?? (fixedNamespace?.from === "fixed" ? fixedNamespace.value : null) ?? fallbackNamespace;
404
+ let resolved;
405
+ if (dictionaryKey) resolved = {
406
+ dictionaryKey,
407
+ fieldPath: descriptor.flatKey ? [messageId] : messageId.split(".")
408
+ };
409
+ else resolved = resolveMessageId(descriptor, null, messageId);
410
+ if (!resolved) continue;
411
+ state.usages.push({
412
+ ...resolved,
413
+ start: nodeStart(node),
414
+ end: nodeEnd(node),
415
+ kind: "jsx",
416
+ callerName: descriptor.callerName,
417
+ library: descriptor.library,
418
+ moduleSource: getModuleSource(state, descriptor)
419
+ });
420
+ return;
421
+ }
422
+ });
423
+ };
424
+ /** Identifier positions that are declarations, not references. */
425
+ const isDeclarationPosition = (identifierNode, parentMap) => {
426
+ const parent = parentMap.get(identifierNode);
427
+ if (!parent) return false;
428
+ const parentType = parent["type"];
429
+ if (parentType === "VariableDeclarator" && parent["id"] === identifierNode) return true;
430
+ if ((parentType === "Property" || parentType === "ObjectProperty") && parentMap.get(parent)?.["type"] === "ObjectPattern") return true;
431
+ if (parentType === "ImportSpecifier" || parentType === "PropertyDefinition") return true;
432
+ if (parentType === "FunctionDeclaration" || parentType === "FunctionExpression" || parentType === "ArrowFunctionExpression") return true;
433
+ if ((parentType === "Property" || parentType === "ObjectProperty") && parent["key"] === identifierNode && parentMap.get(parent)?.["type"] === "ObjectExpression") return true;
434
+ return false;
435
+ };
436
+ /** Identifier used as the (non-computed) property name of a member access. */
437
+ const isPropertyNamePosition = (identifierNode, parentMap) => {
438
+ const parent = parentMap.get(identifierNode);
439
+ if (!parent) return false;
440
+ const parentType = parent["type"];
441
+ return parentType === "MemberExpression" && parent["property"] === identifierNode && parent["computed"] !== true || parentType === "JSXMemberExpression" && parent["property"] === identifierNode;
442
+ };
443
+ /**
444
+ * Record member-access / bare-reference usages of content bindings:
445
+ * `content.section.title`, `{title}` (destructured field reference),
446
+ * Svelte's `$content.title`, Vue's `content.value.title`.
447
+ */
448
+ const collectMemberUsages = (state, program, parentMap) => {
449
+ if (state.contentBindings.size === 0) return;
450
+ walkAst(program, (node) => {
451
+ const nodeType = node["type"];
452
+ if (nodeType !== "Identifier" && nodeType !== "JSXIdentifier") return;
453
+ const rawName = node["name"];
454
+ const variableName = rawName.startsWith("$") ? rawName.slice(1) : rawName;
455
+ const binding = state.contentBindings.get(variableName);
456
+ if (!binding) return;
457
+ const parentType = parentMap.get(node)?.["type"];
458
+ if (parentType?.startsWith("TS") || parentType === "JSXAttribute") return;
459
+ if (isDeclarationPosition(node, parentMap)) return;
460
+ if (isPropertyNamePosition(node, parentMap)) return;
461
+ const fieldPath = [...binding.basePath];
462
+ const fieldSpans = fieldPath.map(() => ({
463
+ start: nodeStart(node),
464
+ end: nodeEnd(node)
465
+ }));
466
+ let currentNode = node;
467
+ while (true) {
468
+ const parent = parentMap.get(currentNode);
469
+ if (!parent) break;
470
+ const parentType = parent["type"];
471
+ if (parentType === "MemberExpression" && parent["object"] === currentNode && parent["computed"] !== true || parentType === "JSXMemberExpression" && parent["object"] === currentNode) {
472
+ const propertyNode = parent["property"];
473
+ const propertyName = propertyNode["name"];
474
+ if (!ACCESSOR_PROPERTY_NAMES.has(propertyName)) {
475
+ fieldPath.push(propertyName);
476
+ fieldSpans.push({
477
+ start: nodeStart(propertyNode),
478
+ end: nodeEnd(propertyNode)
479
+ });
480
+ }
481
+ currentNode = parent;
482
+ continue;
483
+ }
484
+ if (parentType === "MemberExpression" && parent["object"] === currentNode && parent["computed"] === true) {
485
+ const propertyValue = getStaticStringValue(parent["property"]);
486
+ if (propertyValue === null) break;
487
+ fieldPath.push(propertyValue);
488
+ fieldSpans.push({
489
+ start: nodeStart(parent["property"]),
490
+ end: nodeEnd(parent["property"])
491
+ });
492
+ currentNode = parent;
493
+ continue;
494
+ }
495
+ if (parentType === "CallExpression" && parent["callee"] === currentNode) {
496
+ currentNode = parent;
497
+ continue;
498
+ }
499
+ break;
500
+ }
501
+ state.usages.push({
502
+ dictionaryKey: binding.dictionaryKey,
503
+ fieldPath,
504
+ fieldSpans,
505
+ start: nodeStart(node),
506
+ end: nodeEnd(currentNode),
507
+ kind: "member",
508
+ callerName: binding.descriptor.callerName,
509
+ library: binding.descriptor.library,
510
+ moduleSource: binding.moduleSource,
511
+ isBareReference: fieldPath.length === binding.basePath.length
512
+ });
513
+ return true;
514
+ });
515
+ };
516
+ /**
517
+ * Analyse a source file and return every resolvable translation usage:
518
+ * base-intlayer content access and all compat-library forms (translation
519
+ * functions, self calls, JSX message components, tagged templates).
520
+ *
521
+ * Pure and self-contained (oxc parse only) — shared by the LSP handlers and
522
+ * the VS Code extension providers/decorations.
523
+ *
524
+ * @param text - Full source text (a script: TS/TSX or an extracted SFC block).
525
+ * @returns Usages ordered by start offset.
526
+ */
527
+ const collectMessageUsages = (text) => {
528
+ const program = parseText(text);
529
+ if (!program) return [];
530
+ const fileImportSources = collectImportSources(program);
531
+ const state = {
532
+ usages: [],
533
+ translatorBindings: /* @__PURE__ */ new Map(),
534
+ contentBindings: /* @__PURE__ */ new Map(),
535
+ activeDescriptors: callers_exports.ALL_CALLERS.filter((descriptor) => (0, callers_exports.isCallerActive)(descriptor, fileImportSources)),
536
+ importedLocalNames: collectImportedLocalNames(program)
537
+ };
538
+ collectBindings(state, program);
539
+ collectCallUsages(state, program);
540
+ collectJsxUsages(state, program);
541
+ collectMemberUsages(state, program, buildParentMap(program));
542
+ return state.usages.sort((first, second) => first.start - second.start);
543
+ };
544
+ /**
545
+ * Resolve the dictionary key declared by a single call-expression node when
546
+ * it matches any registered non-self caller (`useIntlayer("key")`,
547
+ * `useI18n({ namespace })`, …). Used for on-the-fly checks where the full
548
+ * file analysis is not needed (e.g. completion context).
549
+ *
550
+ * @param callNode - A candidate CallExpression node.
551
+ */
552
+ const matchCallNamespace = (callNode) => {
553
+ if (callNode["type"] !== "CallExpression") return null;
554
+ const callee = getCalleeName(callNode["callee"]);
555
+ if (!callee) return null;
556
+ for (const descriptor of callers_exports.ALL_CALLERS) {
557
+ if (descriptor.translationFunction === "self") continue;
558
+ if (descriptor.callerName !== callee.name) continue;
559
+ if (callee.isMethod && !descriptor.matchAsMethod) continue;
560
+ const namespaceValue = readValueSources(callNode, descriptor.namespaceSources);
561
+ if (namespaceValue !== null) return splitNestedNamespace(descriptor, namespaceValue).dictionaryKey;
562
+ }
563
+ return null;
564
+ };
565
+ /**
566
+ * The AST node holding the namespace string for a given value source, when
567
+ * that source is addressable in the call (positional argument or options
568
+ * property).
569
+ */
570
+ const getNamespaceArgumentNode = (callNode, source) => {
571
+ const argumentsList = callNode["arguments"];
572
+ if (source.from === "argument") return argumentsList?.[source.index] ?? null;
573
+ if (source.from === "option") return getObjectPropertyNode(argumentsList?.[source.argumentIndex], source.property)?.["value"] ?? null;
574
+ return null;
575
+ };
576
+ /**
577
+ * Collect every call site with an addressable namespace argument (positional
578
+ * or options property) resolving to a static string. Powers the
579
+ * unknown-dictionary diagnostics and `findKeyAtOffset`.
580
+ *
581
+ * Self callers (`formatMessage`, lingui `t`/`_`) don't declare a namespace at
582
+ * the call site and are excluded.
583
+ *
584
+ * @param text - Full source text.
585
+ */
586
+ const collectNamespaceReferences = (text) => {
587
+ const program = parseText(text);
588
+ if (!program) return [];
589
+ const fileImportSources = collectImportSources(program);
590
+ const activeDescriptors = callers_exports.ALL_CALLERS.filter((descriptor) => descriptor.translationFunction !== "self" && (0, callers_exports.isCallerActive)(descriptor, fileImportSources));
591
+ const references = [];
592
+ walkAst(program, (node) => {
593
+ if (node["type"] !== "CallExpression") return;
594
+ const calleeNode = node["callee"];
595
+ const callee = getCalleeName(calleeNode);
596
+ if (!callee) return;
597
+ for (const descriptor of activeDescriptors) {
598
+ if (descriptor.callerName !== callee.name) continue;
599
+ if (callee.isMethod && !descriptor.matchAsMethod) continue;
600
+ const calleeNameNode = callee.isMethod && calleeNode ? calleeNode["property"] : calleeNode;
601
+ for (const source of descriptor.namespaceSources) {
602
+ const namespaceNode = getNamespaceArgumentNode(node, source);
603
+ const namespaceValue = getStaticStringValue(namespaceNode ?? void 0);
604
+ if (!namespaceNode || namespaceValue === null) continue;
605
+ references.push({
606
+ dictionaryKey: splitNestedNamespace(descriptor, namespaceValue).dictionaryKey,
607
+ callerName: descriptor.callerName,
608
+ library: descriptor.library,
609
+ callStart: nodeStart(node),
610
+ callEnd: nodeEnd(node),
611
+ calleeStart: nodeStart(calleeNameNode),
612
+ calleeEnd: nodeEnd(calleeNameNode),
613
+ namespaceStart: nodeStart(namespaceNode),
614
+ namespaceEnd: nodeEnd(namespaceNode)
615
+ });
616
+ return;
617
+ }
618
+ }
619
+ });
620
+ return references;
621
+ };
622
+ /**
623
+ * Collect every variable bound to a dictionary in the file. Used by consumers
624
+ * that scan non-script regions (Vue/Angular templates) for references to
625
+ * those variables, or that need to know which dictionaries a file consumes.
626
+ *
627
+ * @param text - Full source text (a script: TS/TSX or an extracted SFC block).
628
+ */
629
+ const collectCallerBindings = (text) => {
630
+ const program = parseText(text);
631
+ if (!program) return [];
632
+ const fileImportSources = collectImportSources(program);
633
+ const state = {
634
+ usages: [],
635
+ translatorBindings: /* @__PURE__ */ new Map(),
636
+ contentBindings: /* @__PURE__ */ new Map(),
637
+ activeDescriptors: callers_exports.ALL_CALLERS.filter((descriptor) => (0, callers_exports.isCallerActive)(descriptor, fileImportSources)),
638
+ importedLocalNames: collectImportedLocalNames(program)
639
+ };
640
+ collectBindings(state, program);
641
+ return [...[...state.contentBindings.entries()].map(([variableName, binding]) => ({
642
+ variableName,
643
+ dictionaryKey: binding.dictionaryKey,
644
+ basePath: binding.basePath,
645
+ bindingKind: "content",
646
+ callerName: binding.descriptor.callerName,
647
+ library: binding.descriptor.library
648
+ })), ...[...state.translatorBindings.entries()].filter(([, binding]) => binding.dictionaryKey !== null).map(([variableName, binding]) => ({
649
+ variableName,
650
+ dictionaryKey: binding.dictionaryKey,
651
+ basePath: binding.keyPrefix,
652
+ bindingKind: "translator",
653
+ callerName: binding.descriptor.callerName,
654
+ library: binding.descriptor.library
655
+ }))];
656
+ };
657
+ /**
658
+ * Find the most specific translation usage at `offset`.
659
+ *
660
+ * For member chains the field path is trimmed to the segment under the
661
+ * cursor: hovering `section` in `content.section.title` yields
662
+ * `['section']`, not the full chain.
663
+ *
664
+ * Dictionary-level `namespace` usages are only returned when no field-level
665
+ * usage matches the offset.
666
+ *
667
+ * @param text - Full source text.
668
+ * @param offset - Cursor offset in `text`.
669
+ */
670
+ const findMessageUsageAtOffset = (text, offset) => {
671
+ const usages = collectMessageUsages(text);
672
+ let bestMatch = null;
673
+ for (const usage of usages) {
674
+ if (offset < usage.start || offset > usage.end) continue;
675
+ if (!bestMatch || bestMatch.kind === "namespace" && usage.kind !== "namespace" || usage.end - usage.start < bestMatch.end - bestMatch.start && !(bestMatch.kind !== "namespace" && usage.kind === "namespace")) bestMatch = usage;
676
+ }
677
+ if (!bestMatch) return null;
678
+ if (bestMatch.kind === "member" && bestMatch.fieldSpans) {
679
+ let lastIncludedIndex = -1;
680
+ for (let index = 0; index < bestMatch.fieldSpans.length; index++) if (offset >= bestMatch.fieldSpans[index].start) lastIncludedIndex = index;
681
+ return {
682
+ ...bestMatch,
683
+ fieldPath: bestMatch.fieldPath.slice(0, lastIncludedIndex + 1),
684
+ fieldSpans: bestMatch.fieldSpans.slice(0, lastIncludedIndex + 1)
685
+ };
686
+ }
687
+ return bestMatch;
688
+ };
689
+
690
+ //#endregion
691
+ export { collectCallerBindings, collectMessageUsages, collectNamespaceReferences, findMessageUsageAtOffset, matchCallNamespace };
692
+ //# sourceMappingURL=usageAnalyzer.mjs.map