@intlify/unplugin-vue-i18n 5.0.0-beta.1 → 5.0.0-beta.2

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/lib/index.cjs CHANGED
@@ -3,65 +3,32 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  const unplugin$1 = require('unplugin');
6
- const pathe = require('pathe');
7
6
  const createDebug = require('debug');
8
- const fg = require('fast-glob');
9
- const shared = require('@intlify/shared');
10
- const pluginutils = require('@rollup/pluginutils');
11
- const bundleUtils = require('@intlify/bundle-utils');
12
- const compilerSfc = require('@vue/compiler-sfc');
13
7
  const fs = require('node:fs');
14
8
  const pc = require('picocolors');
15
9
  const module$1 = require('node:module');
16
10
  const path = require('node:path');
11
+ const pathe = require('pathe');
12
+ const shared = require('@intlify/shared');
13
+ const fg = require('fast-glob');
14
+ const pluginutils = require('@rollup/pluginutils');
15
+ const bundleUtils = require('@intlify/bundle-utils');
16
+ const compilerSfc = require('vue/compiler-sfc');
17
+ const vueI18nExtensions = require('@intlify/vue-i18n-extensions');
18
+ const scopeManager = require('@typescript-eslint/scope-manager');
19
+ const typescriptEstree = require('@typescript-eslint/typescript-estree');
20
+ const eslintUitls = require('@eslint-community/eslint-utils');
17
21
 
18
22
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
19
23
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
20
24
 
21
25
  const createDebug__default = /*#__PURE__*/_interopDefaultCompat(createDebug);
22
- const fg__default = /*#__PURE__*/_interopDefaultCompat(fg);
23
26
  const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
24
27
  const pc__default = /*#__PURE__*/_interopDefaultCompat(pc);
25
28
  const module__default = /*#__PURE__*/_interopDefaultCompat(module$1);
26
29
  const path__default = /*#__PURE__*/_interopDefaultCompat(path);
27
-
28
- function parseVueRequest(id) {
29
- const [filename, rawQuery] = id.split(`?`, 2);
30
- const params = new URLSearchParams(rawQuery);
31
- const ret = {};
32
- const langPart = Object.keys(Object.fromEntries(params)).find(
33
- (key) => /lang\./i.test(key)
34
- );
35
- ret.vue = params.has("vue");
36
- ret.global = params.has("global");
37
- ret.src = params.has("src");
38
- ret.raw = params.has("raw");
39
- if (params.has("type")) {
40
- ret.type = params.get("type");
41
- }
42
- if (params.has("blockType")) {
43
- ret.blockType = params.get("blockType");
44
- }
45
- if (params.has("index")) {
46
- ret.index = Number(params.get("index"));
47
- }
48
- if (params.has("locale")) {
49
- ret.locale = params.get("locale");
50
- }
51
- if (langPart) {
52
- const [, lang] = langPart.split(".");
53
- ret.lang = lang;
54
- } else if (params.has("lang")) {
55
- ret.lang = params.get("lang");
56
- }
57
- if (params.has("issuerPath")) {
58
- ret.issuerPath = params.get("issuerPath");
59
- }
60
- return {
61
- filename,
62
- query: ret
63
- };
64
- }
30
+ const fg__default = /*#__PURE__*/_interopDefaultCompat(fg);
31
+ const eslintUitls__default = /*#__PURE__*/_interopDefaultCompat(eslintUitls);
65
32
 
66
33
  const _require = module__default.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
67
34
  function checkInstallPackage(debug) {
@@ -88,6 +55,9 @@ function resolvePkgPath(id, debug) {
88
55
  return null;
89
56
  }
90
57
  }
58
+ function resolveNamespace(name) {
59
+ return `unplugin-vue-i18n:${name}`;
60
+ }
91
61
  function warn(...args) {
92
62
  console.warn(pc__default.yellow(pc__default.bold(`[unplugin-vue-i18n] `)), ...args);
93
63
  }
@@ -100,22 +70,34 @@ async function getRaw(path2) {
100
70
  function raiseError(message) {
101
71
  throw new Error(`[unplugin-vue-i18n] ${message}`);
102
72
  }
103
-
104
- const INTLIFY_BUNDLE_IMPORT_ID = "@intlify/unplugin-vue-i18n/messages";
105
- const VIRTUAL_PREFIX = "\0";
106
- const debug = createDebug__default("unplugin-vue-i18n");
107
- const installedPkgInfo = checkInstallPackage(debug);
108
- const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
109
- debug("plugin options:", options, meta.framework);
110
- if (!["vite", "webpack"].includes(meta.framework)) {
111
- raiseError(`This plugin is supported 'vite' and 'webpack' only`);
73
+ function getVitePlugin(config, name) {
74
+ return config.plugins.find((p) => p.name === name);
75
+ }
76
+ function checkVuePlugin(vuePlugin) {
77
+ if (vuePlugin == null || !vuePlugin.api) {
78
+ error(
79
+ "`@vitejs/plugin-vue` plugin is not found or invalid version. Please install `@vitejs/plugin-vue` v4.3.4 or later version."
80
+ );
81
+ return false;
112
82
  }
83
+ return true;
84
+ }
85
+ const isWindows = typeof process !== "undefined" && process.platform === "win32";
86
+ const windowsSlashRE = /\\/g;
87
+ function slash(p) {
88
+ return p.replace(windowsSlashRE, "/");
89
+ }
90
+ function normalizePath(id) {
91
+ return path__default.posix.normalize(isWindows ? slash(id) : id);
92
+ }
93
+
94
+ function resolveOptions(options, installedPkgInfo) {
113
95
  let onlyLocales = [];
114
96
  if (options.onlyLocales) {
115
- onlyLocales = Array.isArray(options.onlyLocales) ? options.onlyLocales : [options.onlyLocales];
97
+ onlyLocales = shared.isArray(options.onlyLocales) ? options.onlyLocales : [options.onlyLocales];
116
98
  }
117
99
  let include = options.include;
118
- let exclude = null;
100
+ let exclude = void 0;
119
101
  if (include) {
120
102
  if (shared.isArray(include)) {
121
103
  include = include.map((item) => pathe.normalize(item));
@@ -125,35 +107,137 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
125
107
  } else {
126
108
  exclude = "**/**";
127
109
  }
128
- const filter = pluginutils.createFilter(include, exclude);
129
110
  const forceStringify = !!options.forceStringify;
130
111
  const defaultSFCLang = shared.isString(options.defaultSFCLang) ? options.defaultSFCLang : "json";
131
112
  const globalSFCScope = !!options.globalSFCScope;
132
113
  const runtimeOnly = shared.isBoolean(options.runtimeOnly) ? options.runtimeOnly : true;
133
- debug("runtimeOnly", runtimeOnly);
134
114
  const dropMessageCompiler = !!options.dropMessageCompiler;
135
- debug("dropMessageCompiler", dropMessageCompiler);
136
115
  const compositionOnly = installedPkgInfo.pkg === "vue-i18n" ? shared.isBoolean(options.compositionOnly) ? options.compositionOnly : true : true;
137
- debug("compositionOnly", compositionOnly);
138
116
  const fullInstall = installedPkgInfo.pkg === "vue-i18n" ? shared.isBoolean(options.fullInstall) ? options.fullInstall : true : false;
139
- debug("fullInstall", fullInstall);
140
117
  const ssrBuild = !!options.ssr;
141
- debug("ssr", ssrBuild);
142
- const getVueI18nAliasPath = ({ ssr = false, runtimeOnly: runtimeOnly2 = false }) => {
143
- return `${installedPkgInfo.alias}/dist/${installedPkgInfo.pkg}${runtimeOnly2 ? ".runtime" : ""}.${!ssr ? "esm-bundler.js" : "node.mjs"}`;
144
- };
145
118
  const allowDynamic = !!options.allowDynamic;
146
- debug("allowDynamic", allowDynamic);
147
119
  const strictMessage = shared.isBoolean(options.strictMessage) ? options.strictMessage : true;
148
- debug("strictMessage", strictMessage);
149
120
  const escapeHtml = !!options.escapeHtml;
150
- debug("escapeHtml", escapeHtml);
121
+ const optimizeTranslationDirective = shared.isString(options.optimizeTranslationDirective) || shared.isArray(options.optimizeTranslationDirective) ? options.optimizeTranslationDirective : !!options.optimizeTranslationDirective;
122
+ const translationIdentifiers = /* @__PURE__ */ new Map();
123
+ return {
124
+ include,
125
+ exclude,
126
+ onlyLocales,
127
+ forceStringify,
128
+ defaultSFCLang,
129
+ globalSFCScope,
130
+ runtimeOnly,
131
+ dropMessageCompiler,
132
+ compositionOnly,
133
+ fullInstall,
134
+ ssrBuild,
135
+ allowDynamic,
136
+ strictMessage,
137
+ escapeHtml,
138
+ optimizeTranslationDirective,
139
+ translationIdentifiers
140
+ };
141
+ }
142
+
143
+ function parseVueRequest(id) {
144
+ const [filename, rawQuery] = id.split(`?`, 2);
145
+ const params = new URLSearchParams(rawQuery);
146
+ const ret = {};
147
+ const langPart = Object.keys(Object.fromEntries(params)).find(
148
+ (key) => /lang\./i.test(key)
149
+ );
150
+ ret.vue = params.has("vue");
151
+ ret.global = params.has("global");
152
+ ret.src = params.has("src");
153
+ ret.raw = params.has("raw");
154
+ if (params.has("type")) {
155
+ ret.type = params.get("type");
156
+ }
157
+ if (params.has("blockType")) {
158
+ ret.blockType = params.get("blockType");
159
+ }
160
+ if (params.has("index")) {
161
+ ret.index = Number(params.get("index"));
162
+ }
163
+ if (params.has("locale")) {
164
+ ret.locale = params.get("locale");
165
+ }
166
+ if (langPart) {
167
+ const [, lang] = langPart.split(".");
168
+ ret.lang = lang;
169
+ } else if (params.has("lang")) {
170
+ ret.lang = params.get("lang");
171
+ }
172
+ if (params.has("issuerPath")) {
173
+ ret.issuerPath = params.get("issuerPath");
174
+ }
175
+ return {
176
+ filename,
177
+ query: ret
178
+ };
179
+ }
180
+
181
+ function getVueCompiler(vuePlugin) {
182
+ return vuePlugin?.api?.options.compiler;
183
+ }
184
+ function getVuePluginOptions(vuePlugin) {
185
+ return {
186
+ isProduction: vuePlugin?.api?.options.isProduction,
187
+ root: vuePlugin?.api?.options.root,
188
+ template: vuePlugin?.api?.options.template,
189
+ compiler: vuePlugin?.api?.options.compiler
190
+ };
191
+ }
192
+
193
+ function createDescriptor(filename, source, { template, compiler }) {
194
+ const { descriptor, errors } = compiler.parse(source, {
195
+ filename,
196
+ templateParseOptions: template?.compilerOptions
197
+ });
198
+ return { descriptor, errors };
199
+ }
200
+ function getDescriptor(filename, code, options) {
201
+ const { descriptor, errors } = createDescriptor(filename, code, options);
202
+ if (errors.length) {
203
+ throw errors[0];
204
+ }
205
+ return descriptor;
206
+ }
207
+
208
+ const INTLIFY_BUNDLE_IMPORT_ID = "@intlify/unplugin-vue-i18n/messages";
209
+ const VIRTUAL_PREFIX = "\0";
210
+ const debug$2 = createDebug__default(resolveNamespace("resource"));
211
+ function resourcePlugin({
212
+ onlyLocales,
213
+ include,
214
+ exclude,
215
+ forceStringify,
216
+ defaultSFCLang,
217
+ globalSFCScope,
218
+ runtimeOnly,
219
+ dropMessageCompiler,
220
+ compositionOnly,
221
+ fullInstall,
222
+ ssrBuild,
223
+ strictMessage,
224
+ allowDynamic,
225
+ escapeHtml
226
+ }, meta, installedPkgInfo) {
227
+ const filter = pluginutils.createFilter(include, exclude);
228
+ const getVueI18nAliasPath = ({ ssr = false, runtimeOnly: runtimeOnly2 = false }) => {
229
+ return `${installedPkgInfo.alias}/dist/${installedPkgInfo.pkg}${runtimeOnly2 ? ".runtime" : ""}.${!ssr ? "esm-bundler.js" : "node.mjs"}`;
230
+ };
151
231
  let isProduction = false;
152
232
  let sourceMap = false;
153
233
  const vueI18nAliasName = installedPkgInfo.alias;
154
- debug(`vue-i18n alias name: ${vueI18nAliasName}`);
234
+ debug$2(`vue-i18n alias name: ${vueI18nAliasName}`);
235
+ let vuePlugin = null;
236
+ const getSfcParser = () => {
237
+ return vuePlugin ? getVueCompiler(vuePlugin).parse : compilerSfc.parse;
238
+ };
155
239
  return {
156
- name: "unplugin-vue-i18n",
240
+ name: resolveNamespace("resource"),
157
241
  /**
158
242
  * NOTE:
159
243
  *
@@ -173,7 +257,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
173
257
  __VUE_I18N_PROD_DEVTOOLS__: false
174
258
  }
175
259
  };
176
- debug("define Config:", defineConfig);
260
+ debug$2("define Config:", defineConfig);
177
261
  const aliasConfig = {
178
262
  resolve: {
179
263
  alias: {
@@ -184,16 +268,20 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
184
268
  }
185
269
  }
186
270
  };
187
- debug("alias Config:", aliasConfig);
271
+ debug$2("alias Config:", aliasConfig);
188
272
  return shared.assign(defineConfig, aliasConfig);
189
273
  },
190
274
  configResolved(config) {
275
+ vuePlugin = getVitePlugin(config, "vite:vue");
276
+ if (!checkVuePlugin(vuePlugin)) {
277
+ return;
278
+ }
191
279
  isProduction = config.isProduction;
192
280
  sourceMap = config.command === "build" ? !!config.build.sourcemap : false;
193
- debug(
281
+ debug$2(
194
282
  `configResolved: isProduction = ${isProduction}, sourceMap = ${sourceMap}`
195
283
  );
196
- const jsonPlugin = config.plugins.find((p) => p.name === "vite:json");
284
+ const jsonPlugin = getVitePlugin(config, "vite:json");
197
285
  if (jsonPlugin) {
198
286
  const orgTransform = jsonPlugin.transform;
199
287
  jsonPlugin.transform = async function(code, id) {
@@ -204,13 +292,11 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
204
292
  if (query.vue) {
205
293
  return;
206
294
  }
207
- debug("org json plugin");
295
+ debug$2("org json plugin");
208
296
  return orgTransform.apply(this, [code, id]);
209
297
  };
210
298
  }
211
- const esbuildPlugin = config.plugins.find(
212
- (p) => p.name === "vite:esbuild"
213
- );
299
+ const esbuildPlugin = getVitePlugin(config, "vite:esbuild");
214
300
  if (esbuildPlugin) {
215
301
  const orgTransform = esbuildPlugin.transform;
216
302
  esbuildPlugin.transform = async function(code, id) {
@@ -243,10 +329,10 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
243
329
  forceStringify
244
330
  }
245
331
  );
246
- debug("parseOptions", parseOptions);
332
+ debug$2("parseOptions", parseOptions);
247
333
  const { code: generatedCode, map } = generate(_code, parseOptions);
248
- debug("generated code", generatedCode);
249
- debug("sourcemap", map, sourceMap);
334
+ debug$2("generated code", generatedCode);
335
+ debug$2("sourcemap", map, sourceMap);
250
336
  if (_code === generatedCode)
251
337
  return;
252
338
  return {
@@ -274,7 +360,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
274
360
  webpack(compiler) {
275
361
  isProduction = compiler.options.mode !== "development";
276
362
  sourceMap = !!compiler.options.devtool;
277
- debug(`webpack: isProduction = ${isProduction}, sourceMap = ${sourceMap}`);
363
+ debug$2(`webpack: isProduction = ${isProduction}, sourceMap = ${sourceMap}`);
278
364
  compiler.options.resolve = normalizeConfigResolveAlias(
279
365
  compiler.options.resolve,
280
366
  meta.framework
@@ -283,7 +369,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
283
369
  ssr: ssrBuild,
284
370
  runtimeOnly
285
371
  });
286
- debug(
372
+ debug$2(
287
373
  `set ${vueI18nAliasName}: ${getVueI18nAliasPath({
288
374
  ssr: ssrBuild,
289
375
  runtimeOnly
@@ -298,10 +384,10 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
298
384
  __INTLIFY_PROD_DEVTOOLS__: "false"
299
385
  })
300
386
  );
301
- debug(`set __VUE_I18N_LEGACY_API__ is '${compositionOnly}'`);
302
- debug(`set __VUE_I18N_FULL_INSTALL__ is '${fullInstall}'`);
387
+ debug$2(`set __VUE_I18N_LEGACY_API__ is '${compositionOnly}'`);
388
+ debug$2(`set __VUE_I18N_FULL_INSTALL__ is '${fullInstall}'`);
303
389
  } else {
304
- debug("ignore vue-i18n feature flags with webpack.DefinePlugin");
390
+ debug$2("ignore vue-i18n feature flags with webpack.DefinePlugin");
305
391
  }
306
392
  });
307
393
  if (compiler.options.module) {
@@ -315,15 +401,14 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
315
401
  }
316
402
  },
317
403
  resolveId(id, importer) {
318
- debug("resolveId", id, importer);
404
+ debug$2("resolveId", id, importer);
319
405
  if (id === INTLIFY_BUNDLE_IMPORT_ID) {
320
406
  return asVirtualId(id, meta.framework);
321
407
  }
322
408
  },
323
409
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
324
410
  async load(id) {
325
- debug("load", id);
326
- const { query } = parseVueRequest(id);
411
+ debug$2("load", id);
327
412
  if (INTLIFY_BUNDLE_IMPORT_ID === getVirtualId(id, meta.framework) && include) {
328
413
  let resourcePaths = [];
329
414
  const includePaths = shared.isArray(include) ? include : [include];
@@ -335,7 +420,6 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
335
420
  );
336
421
  const code = await generateBundleResources(
337
422
  resourcePaths,
338
- query,
339
423
  isProduction,
340
424
  {
341
425
  forceStringify,
@@ -350,7 +434,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
350
434
  }
351
435
  },
352
436
  transformInclude(id) {
353
- debug("transformInclude", id);
437
+ debug$2("transformInclude", id);
354
438
  if (meta.framework === "vite") {
355
439
  return true;
356
440
  } else {
@@ -360,7 +444,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
360
444
  },
361
445
  async transform(code, id) {
362
446
  const { filename, query } = parseVueRequest(id);
363
- debug("transform", id, JSON.stringify(query), filename);
447
+ debug$2("transform", id, JSON.stringify(query), filename);
364
448
  let langInfo = defaultSFCLang;
365
449
  let inSourceMap;
366
450
  if (!query.vue) {
@@ -383,10 +467,10 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
383
467
  forceStringify
384
468
  }
385
469
  );
386
- debug("parseOptions", parseOptions);
470
+ debug$2("parseOptions", parseOptions);
387
471
  const { code: generatedCode, map } = generate(code, parseOptions);
388
- debug("generated code", generatedCode);
389
- debug("sourcemap", map, sourceMap);
472
+ debug$2("generated code", generatedCode);
473
+ debug$2("sourcemap", map, sourceMap);
390
474
  if (code === generatedCode)
391
475
  return;
392
476
  return {
@@ -402,7 +486,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
402
486
  } else if (defaultSFCLang) {
403
487
  langInfo = defaultSFCLang;
404
488
  }
405
- debug("langInfo", langInfo);
489
+ debug$2("langInfo", langInfo);
406
490
  const generate = /\.?json5?/.test(langInfo) ? bundleUtils.generateJSON : bundleUtils.generateYAML;
407
491
  const parseOptions = getOptions(
408
492
  filename,
@@ -419,17 +503,18 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
419
503
  forceStringify
420
504
  }
421
505
  );
422
- debug("parseOptions", parseOptions);
506
+ debug$2("parseOptions", parseOptions);
423
507
  const source = await getCode(
424
508
  code,
425
509
  filename,
426
510
  sourceMap,
427
511
  query,
512
+ getSfcParser(),
428
513
  meta.framework
429
514
  );
430
515
  const { code: generatedCode, map } = generate(source, parseOptions);
431
- debug("generated code", generatedCode);
432
- debug("sourcemap", map, sourceMap);
516
+ debug$2("generated code", generatedCode);
517
+ debug$2("sourcemap", map, sourceMap);
433
518
  if (code === generatedCode)
434
519
  return;
435
520
  return {
@@ -441,7 +526,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
441
526
  }
442
527
  }
443
528
  };
444
- });
529
+ }
445
530
  function getGenerator(ext, defaultGen = bundleUtils.generateJSON) {
446
531
  return /\.?json5?$/.test(ext) ? bundleUtils.generateJSON : /\.ya?ml$/.test(ext) ? bundleUtils.generateYAML : /\.([c|m]?js|[c|m]?ts)$/.test(ext) ? bundleUtils.generateJavaScript : defaultGen;
447
532
  }
@@ -474,7 +559,7 @@ async function loadWebpack() {
474
559
  }
475
560
  return webpack;
476
561
  }
477
- async function generateBundleResources(resources, query, isProduction, {
562
+ async function generateBundleResources(resources, isProduction, {
478
563
  forceStringify = false,
479
564
  isGlobal = false,
480
565
  onlyLocales = [],
@@ -484,7 +569,7 @@ async function generateBundleResources(resources, query, isProduction, {
484
569
  }) {
485
570
  const codes = [];
486
571
  for (const res of resources) {
487
- debug(`${res} bundle loading ...`);
572
+ debug$2(`${res} bundle loading ...`);
488
573
  if (/\.(json5?|ya?ml)$/.test(res)) {
489
574
  const { ext, name } = pathe.parse(res);
490
575
  const source = await getRaw(res);
@@ -499,7 +584,7 @@ async function generateBundleResources(resources, query, isProduction, {
499
584
  });
500
585
  parseOptions.type = "bare";
501
586
  const { code } = generate(source, parseOptions);
502
- debug("generated code", code);
587
+ debug$2("generated code", code);
503
588
  codes.push(`${JSON.stringify(name)}: ${code}`);
504
589
  }
505
590
  }
@@ -527,24 +612,24 @@ export default mergeDeep({},
527
612
  ${codes.map((code) => `{${code}}`).join(",\n")}
528
613
  );`;
529
614
  }
530
- async function getCode(source, filename, sourceMap, query, framework = "vite") {
615
+ async function getCode(source, filename, sourceMap, query, parser, framework = "vite") {
531
616
  const { index, issuerPath } = query;
532
617
  if (!shared.isNumber(index)) {
533
618
  raiseError(`unexpected index: ${index}`);
534
619
  }
535
620
  if (framework === "webpack") {
536
621
  if (issuerPath) {
537
- debug(`getCode (webpack) ${index} via issuerPath`, issuerPath);
622
+ debug$2(`getCode (webpack) ${index} via issuerPath`, issuerPath);
538
623
  return await getRaw(filename);
539
624
  } else {
540
- const result = compilerSfc.parse(await getRaw(filename), {
625
+ const result = parser(await getRaw(filename), {
541
626
  sourceMap,
542
627
  filename
543
628
  });
544
629
  const block = result.descriptor.customBlocks[index];
545
630
  if (block) {
546
631
  const code = block.src ? await getRaw(block.src) : block.content;
547
- debug(`getCode (webpack) ${index} from SFC`, code);
632
+ debug$2(`getCode (webpack) ${index} from SFC`, code);
548
633
  return code;
549
634
  } else {
550
635
  return source;
@@ -620,5 +705,295 @@ function asVirtualId(id, framework = "vite") {
620
705
  return framework === "vite" ? VIRTUAL_PREFIX + id : id;
621
706
  }
622
707
 
708
+ const debug$1 = createDebug__default(resolveNamespace("directive"));
709
+ function directivePlugin({
710
+ optimizeTranslationDirective,
711
+ translationIdentifiers
712
+ }) {
713
+ let vuePlugin = null;
714
+ let vuePluginOptions = null;
715
+ return {
716
+ name: resolveNamespace("directive"),
717
+ enforce: "pre",
718
+ vite: {
719
+ config(config) {
720
+ vuePlugin = getVitePlugin(config, "vite:vue");
721
+ if (!checkVuePlugin(vuePlugin)) {
722
+ return;
723
+ }
724
+ if (optimizeTranslationDirective) {
725
+ vuePlugin.api.options = resolveVueOptions(
726
+ vuePlugin,
727
+ optimizeTranslationDirective,
728
+ translationIdentifiers
729
+ );
730
+ debug$1(`vite:vue options['template']:`, vuePlugin.api.options);
731
+ }
732
+ },
733
+ configResolved(config) {
734
+ vuePlugin = getVitePlugin(config, "vite:vue");
735
+ if (!checkVuePlugin(vuePlugin)) {
736
+ return;
737
+ }
738
+ }
739
+ },
740
+ async transform(code, id) {
741
+ const { filename } = parseVueRequest(id);
742
+ if (vuePluginOptions == null) {
743
+ vuePluginOptions = getVuePluginOptions(vuePlugin);
744
+ }
745
+ if (id.endsWith(".vue")) {
746
+ analyzeIdentifiers(
747
+ getDescriptor(filename, code, vuePluginOptions),
748
+ vuePluginOptions,
749
+ translationIdentifiers
750
+ );
751
+ }
752
+ return code;
753
+ }
754
+ };
755
+ }
756
+ function resolveVueOptions(vuePlugin, optimizeTranslationDirective, translationIdentifiers) {
757
+ var _a, _b;
758
+ const vueOptions = vuePlugin.api.options;
759
+ vueOptions.template || (vueOptions.template = {});
760
+ (_a = vueOptions.template).compilerOptions || (_a.compilerOptions = {});
761
+ (_b = vueOptions.template.compilerOptions).directiveTransforms || (_b.directiveTransforms = {});
762
+ const translationSignatureResolver = (context, baseResolver) => {
763
+ const { filename } = context;
764
+ const vuePluginOptions = getVuePluginOptions(vuePlugin);
765
+ const normalizedFilename = normalizePath(
766
+ path__default.relative(vuePluginOptions.root, filename)
767
+ );
768
+ const resolveIdentifier2 = translationIdentifiers.get(normalizedFilename);
769
+ debug$1("resolved vue-i18n Identifier", resolveIdentifier2);
770
+ if (resolveIdentifier2 == null) {
771
+ return void 0;
772
+ }
773
+ if (resolveIdentifier2.type === "identifier") {
774
+ return baseResolver(context, resolveIdentifier2.key);
775
+ } else {
776
+ const resolvedSignature = baseResolver(context, resolveIdentifier2.key);
777
+ return resolveIdentifier2?.style === "script-setup" ? `${resolvedSignature}.t` : resolvedSignature;
778
+ }
779
+ };
780
+ vueOptions.template.compilerOptions.directiveTransforms.t = vueI18nExtensions.transformVTDirective({
781
+ translationSignatures: shared.isBoolean(optimizeTranslationDirective) ? translationSignatureResolver : optimizeTranslationDirective
782
+ });
783
+ return vueOptions;
784
+ }
785
+ function analyzeIdentifiers(descriptor, { root }, translationIdentifiers) {
786
+ const source = descriptor.scriptSetup?.content || descriptor.script?.content;
787
+ debug$1("getDescriptor content", source);
788
+ if (!source) {
789
+ return;
790
+ }
791
+ const ast = typescriptEstree.parse(source, { range: true });
792
+ typescriptEstree.simpleTraverse(ast, {
793
+ enter(node, parent) {
794
+ if (parent) {
795
+ node.parent = parent;
796
+ }
797
+ }
798
+ });
799
+ const scopeManager$1 = scopeManager.analyze(ast, { sourceType: "module" });
800
+ const scope = getScope(scopeManager$1, ast);
801
+ const importLocalName = getImportLocalName(scope, "vue-i18n", "useI18n");
802
+ if (importLocalName == null) {
803
+ return;
804
+ }
805
+ debug$1("importLocalName", importLocalName);
806
+ const resolvedIdentifier = getVueI18nIdentifier(scope, importLocalName);
807
+ if (resolvedIdentifier) {
808
+ const normalizedFilename = normalizePath(
809
+ path__default.relative(root, descriptor.filename)
810
+ );
811
+ debug$1("set vue-i18n resolved identifier: ", resolvedIdentifier);
812
+ translationIdentifiers.set(normalizedFilename, resolvedIdentifier);
813
+ }
814
+ }
815
+ function getScope(manager, node) {
816
+ const scope = manager.acquire(node, true);
817
+ if (scope) {
818
+ if (scope.type === "function-expression-name") {
819
+ return scope.childScopes[0];
820
+ }
821
+ return scope;
822
+ }
823
+ return manager.scopes[0];
824
+ }
825
+ function getImportLocalName(scope, source, imported) {
826
+ const importDecl = getImportDeclaration(scope, source);
827
+ if (importDecl) {
828
+ const specifierNode = importDecl.specifiers.find(
829
+ (specifierNode2) => isImportedIdentifierInImportClause(specifierNode2) && specifierNode2.imported.name === imported
830
+ );
831
+ return specifierNode ? specifierNode.local.name : null;
832
+ }
833
+ return null;
834
+ }
835
+ function getImportDeclaration(scope, source) {
836
+ const tracker = new eslintUitls__default.ReferenceTracker(scope);
837
+ const traceMap = {
838
+ [source]: {
839
+ [eslintUitls__default.ReferenceTracker.ESM]: true,
840
+ [eslintUitls__default.ReferenceTracker.READ]: true
841
+ }
842
+ };
843
+ const refs = Array.from(tracker.iterateEsmReferences(traceMap));
844
+ return refs.length ? refs[0].node : null;
845
+ }
846
+ function isImportedIdentifierInImportClause(node) {
847
+ return "imported" in node;
848
+ }
849
+ function getVueI18nIdentifier(scope, local) {
850
+ const { callExpression, returnStatement } = getCallExpressionAndReturnStatement(scope, local);
851
+ if (callExpression == null) {
852
+ return null;
853
+ }
854
+ const id = getVariableDeclarationIdFrom(callExpression);
855
+ if (id == null) {
856
+ return null;
857
+ }
858
+ const variableIdPairs = parseVariableId(id);
859
+ debug$1("variableIdPairs:", variableIdPairs);
860
+ const returnVariableIdPairs = parseReturnStatement(returnStatement);
861
+ debug$1("returnVariableIdPairs:", returnVariableIdPairs);
862
+ return resolveIdentifier(variableIdPairs, returnVariableIdPairs);
863
+ }
864
+ const EMPTY_NODE_RETURN = {
865
+ callExpression: null,
866
+ returnStatement: null
867
+ };
868
+ function getCallExpressionAndReturnStatement(scope, local) {
869
+ const variable = eslintUitls__default.findVariable(scope, local);
870
+ if (variable == null) {
871
+ return EMPTY_NODE_RETURN;
872
+ }
873
+ const callExpressionRef = variable.references.find((ref) => {
874
+ return ref.identifier.parent?.type === typescriptEstree.AST_NODE_TYPES.CallExpression;
875
+ });
876
+ if (callExpressionRef == null) {
877
+ return EMPTY_NODE_RETURN;
878
+ }
879
+ let returnStatement = null;
880
+ if (callExpressionRef.from.type === "function" && callExpressionRef.from.block.type === typescriptEstree.AST_NODE_TYPES.FunctionExpression && callExpressionRef.from.block.parent.type === typescriptEstree.AST_NODE_TYPES.Property && callExpressionRef.from.block.parent.key.type === typescriptEstree.AST_NODE_TYPES.Identifier && callExpressionRef.from.block.parent.key.name === "setup") {
881
+ returnStatement = callExpressionRef.from.block.body.body.find(
882
+ (statement) => {
883
+ return statement.type === typescriptEstree.AST_NODE_TYPES.ReturnStatement;
884
+ }
885
+ );
886
+ }
887
+ return {
888
+ callExpression: callExpressionRef.identifier.parent,
889
+ returnStatement
890
+ };
891
+ }
892
+ function getVariableDeclarationIdFrom(node) {
893
+ if (node.parent?.type !== typescriptEstree.AST_NODE_TYPES.VariableDeclarator) {
894
+ return null;
895
+ }
896
+ return node.parent.id;
897
+ }
898
+ function parseVariableId(node) {
899
+ if (node.type === typescriptEstree.AST_NODE_TYPES.Identifier) {
900
+ return [{ key: node.name, value: null }];
901
+ } else {
902
+ const props = node.properties.filter(
903
+ // ignore RestElement
904
+ (prop) => prop.type === typescriptEstree.AST_NODE_TYPES.Property
905
+ );
906
+ const pairs = [];
907
+ for (const prop of props) {
908
+ if (prop?.key.type === typescriptEstree.AST_NODE_TYPES.Identifier && prop?.value.type === typescriptEstree.AST_NODE_TYPES.Identifier) {
909
+ pairs.push({ key: prop.key.name, value: prop.value.name });
910
+ }
911
+ }
912
+ return pairs;
913
+ }
914
+ }
915
+ function parseReturnStatement(node) {
916
+ const pairs = [];
917
+ if (node == null || node.argument == null) {
918
+ return pairs;
919
+ }
920
+ if (node.argument.type === typescriptEstree.AST_NODE_TYPES.ObjectExpression) {
921
+ for (const prop of node.argument.properties) {
922
+ if (prop.type === typescriptEstree.AST_NODE_TYPES.Property) {
923
+ if (prop.key.type === typescriptEstree.AST_NODE_TYPES.Identifier && prop.value.type === typescriptEstree.AST_NODE_TYPES.Identifier) {
924
+ pairs.push({ key: prop.key.name, value: prop.value.name });
925
+ } else if (prop.key.type === typescriptEstree.AST_NODE_TYPES.Identifier && prop.value.type === typescriptEstree.AST_NODE_TYPES.MemberExpression && prop.value.object.type === typescriptEstree.AST_NODE_TYPES.Identifier && prop.value.property.type === typescriptEstree.AST_NODE_TYPES.Identifier) {
926
+ pairs.push({
927
+ key: prop.key.name,
928
+ value: `${prop.value.object.name}.${prop.value.property.name}`
929
+ });
930
+ }
931
+ }
932
+ }
933
+ return pairs;
934
+ } else if (node.argument.type === typescriptEstree.AST_NODE_TYPES.Identifier) {
935
+ return pairs;
936
+ } else {
937
+ return pairs;
938
+ }
939
+ }
940
+ function resolveIdentifier(localVariables, returnVariable) {
941
+ if (returnVariable.length === 0) {
942
+ const variable = localVariables.find((pair) => pair.key === "t");
943
+ if (variable && variable.value) {
944
+ return { type: "identifier", key: variable.value };
945
+ }
946
+ const identifierOnly = localVariables.find((pair) => pair.value === null);
947
+ if (identifierOnly && identifierOnly.key) {
948
+ return { type: "object", key: identifierOnly.key, style: "script-setup" };
949
+ }
950
+ return null;
951
+ } else {
952
+ const variable = localVariables.find((pair) => pair.key === "t");
953
+ if (variable && variable.value) {
954
+ const returnVar = returnVariable.find(
955
+ (pair) => pair.value === variable.value
956
+ );
957
+ if (returnVar && returnVar.key) {
958
+ return { type: "identifier", key: returnVar.key };
959
+ }
960
+ }
961
+ const identifierOnly = localVariables.find((pair) => pair.value === null);
962
+ if (identifierOnly && identifierOnly.key) {
963
+ const targetKey = identifierOnly.key;
964
+ const returnVar = returnVariable.find(
965
+ (pair) => pair.value?.startsWith(targetKey)
966
+ );
967
+ if (returnVar && returnVar.key) {
968
+ return { type: "object", key: returnVar.key, style: "setup-hook" };
969
+ }
970
+ }
971
+ return null;
972
+ }
973
+ }
974
+
975
+ const debug = createDebug__default(resolveNamespace("root"));
976
+ const installedPkgInfo = checkInstallPackage(debug);
977
+ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
978
+ debug("meta framework", meta.framework);
979
+ if (!["vite", "webpack"].includes(meta.framework)) {
980
+ raiseError(`This plugin is supported 'vite' and 'webpack' only`);
981
+ }
982
+ debug("plugin options (resolving):", options);
983
+ const resolvedOptions = resolveOptions(options, installedPkgInfo);
984
+ debug("plugin options (resolved):", resolvedOptions);
985
+ const plugins = [resourcePlugin(resolvedOptions, meta, installedPkgInfo)];
986
+ if (resolvedOptions.optimizeTranslationDirective) {
987
+ if (meta.framework === "webpack") {
988
+ raiseError(
989
+ `The 'optimizeTranslationDirective' option still is not supported for webpack.
990
+ We are waiting for your Pull Request \u{1F642}.`
991
+ );
992
+ }
993
+ plugins.push(directivePlugin(resolvedOptions));
994
+ }
995
+ return plugins;
996
+ });
997
+
623
998
  exports.default = unplugin;
624
999
  exports.unplugin = unplugin;