@intlayer/babel 9.1.3 → 9.3.0
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/cjs/babel-plugin-intlayer-field-rename.cjs +32 -0
- package/dist/cjs/babel-plugin-intlayer-field-rename.cjs.map +1 -1
- package/dist/cjs/babel-plugin-intlayer-optimize.cjs +26 -10
- package/dist/cjs/babel-plugin-intlayer-optimize.cjs.map +1 -1
- package/dist/cjs/babel-plugin-intlayer-purge.cjs +161 -16
- package/dist/cjs/babel-plugin-intlayer-purge.cjs.map +1 -1
- package/dist/cjs/babel-plugin-intlayer-usage-analyzer.cjs +45 -0
- package/dist/cjs/babel-plugin-intlayer-usage-analyzer.cjs.map +1 -1
- package/dist/cjs/getOptimizePluginOptions.cjs +2 -0
- package/dist/cjs/getOptimizePluginOptions.cjs.map +1 -1
- package/dist/cjs/getPurgePluginOptions.cjs +3 -0
- package/dist/cjs/getPurgePluginOptions.cjs.map +1 -1
- package/dist/cjs/index.cjs +3 -0
- package/dist/cjs/transformers.cjs.map +1 -1
- package/dist/esm/babel-plugin-intlayer-field-rename.mjs +32 -1
- package/dist/esm/babel-plugin-intlayer-field-rename.mjs.map +1 -1
- package/dist/esm/babel-plugin-intlayer-optimize.mjs +26 -10
- package/dist/esm/babel-plugin-intlayer-optimize.mjs.map +1 -1
- package/dist/esm/babel-plugin-intlayer-purge.mjs +160 -18
- package/dist/esm/babel-plugin-intlayer-purge.mjs.map +1 -1
- package/dist/esm/babel-plugin-intlayer-usage-analyzer.mjs +45 -1
- package/dist/esm/babel-plugin-intlayer-usage-analyzer.mjs.map +1 -1
- package/dist/esm/getOptimizePluginOptions.mjs +2 -0
- package/dist/esm/getOptimizePluginOptions.mjs.map +1 -1
- package/dist/esm/getPurgePluginOptions.mjs +3 -0
- package/dist/esm/getPurgePluginOptions.mjs.map +1 -1
- package/dist/esm/index.mjs +4 -4
- package/dist/esm/transformers.mjs.map +1 -1
- package/dist/types/babel-plugin-intlayer-field-rename.d.ts +29 -1
- package/dist/types/babel-plugin-intlayer-field-rename.d.ts.map +1 -1
- package/dist/types/babel-plugin-intlayer-optimize.d.ts +15 -0
- package/dist/types/babel-plugin-intlayer-optimize.d.ts.map +1 -1
- package/dist/types/babel-plugin-intlayer-purge.d.ts +36 -1
- package/dist/types/babel-plugin-intlayer-purge.d.ts.map +1 -1
- package/dist/types/babel-plugin-intlayer-usage-analyzer.d.ts +30 -1
- package/dist/types/babel-plugin-intlayer-usage-analyzer.d.ts.map +1 -1
- package/dist/types/getOptimizePluginOptions.d.ts.map +1 -1
- package/dist/types/getPurgePluginOptions.d.ts.map +1 -1
- package/dist/types/index.d.ts +4 -4
- package/dist/types/transformers.d.ts +2 -2
- package/dist/types/transformers.d.ts.map +1 -1
- package/package.json +11 -10
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
|
|
2
3
|
const require_babel_plugin_intlayer_usage_analyzer = require('./babel-plugin-intlayer-usage-analyzer.cjs');
|
|
3
4
|
const require_extractScriptBlocks = require('./extractScriptBlocks.cjs');
|
|
4
5
|
const require_babel_plugin_intlayer_field_rename = require('./babel-plugin-intlayer-field-rename.cjs');
|
|
5
6
|
const require_transformers = require('./transformers.cjs');
|
|
6
7
|
let node_path = require("node:path");
|
|
8
|
+
let _intlayer_config_colors = require("@intlayer/config/colors");
|
|
9
|
+
_intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
10
|
+
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
11
|
+
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
7
12
|
let node_fs = require("node:fs");
|
|
8
13
|
let _babel_core = require("@babel/core");
|
|
9
14
|
|
|
@@ -11,7 +16,7 @@ let _babel_core = require("@babel/core");
|
|
|
11
16
|
/**
|
|
12
17
|
* Cache of built {@link PruneContext} objects, keyed by the project's
|
|
13
18
|
* `baseDir`. Each context is built exactly once per Node.js process:
|
|
14
|
-
* {@link
|
|
19
|
+
* {@link runIntlayerPurgePipeline} registers the context before running so every
|
|
15
20
|
* subsequent transform is a no-op cache hit.
|
|
16
21
|
*/
|
|
17
22
|
const _pruneContextCache = /* @__PURE__ */ new Map();
|
|
@@ -165,7 +170,8 @@ const analyzeSourceFileSync = (sourceFilePath, pruneContext, compatCallers) => {
|
|
|
165
170
|
* `buildStart` hook. Results are stored in
|
|
166
171
|
* `pruneContext.dictionaryKeyToFieldRenameMap`.
|
|
167
172
|
*/
|
|
168
|
-
const buildRenameMapsSynchronously = (dictionariesDir, dynamicDictionariesDir, dictionaryKeyToImportModeMap, pruneContext) => {
|
|
173
|
+
const buildRenameMapsSynchronously = (dictionariesDir, dynamicDictionariesDir, dictionaryKeyToImportModeMap, pruneContext, logger) => {
|
|
174
|
+
let partiallyMinifiedDictionariesCount = 0;
|
|
169
175
|
for (const [dictionaryKey, fieldUsage] of pruneContext.dictionaryKeyToFieldUsageMap) {
|
|
170
176
|
if (fieldUsage === "all") continue;
|
|
171
177
|
if (dictionaryKeyToImportModeMap[dictionaryKey] === "fetch") continue;
|
|
@@ -189,12 +195,50 @@ const buildRenameMapsSynchronously = (dictionariesDir, dynamicDictionariesDir, d
|
|
|
189
195
|
if (!dictionaryContent) continue;
|
|
190
196
|
const nestedRenameMap = require_babel_plugin_intlayer_field_rename.buildNestedRenameMapFromContent(dictionaryContent);
|
|
191
197
|
const opaqueFieldMap = pruneContext.dictionaryKeysWithOpaqueFields.get(dictionaryKey);
|
|
192
|
-
if (opaqueFieldMap)
|
|
193
|
-
const
|
|
194
|
-
if (
|
|
198
|
+
if (opaqueFieldMap) {
|
|
199
|
+
const dangerousOccurrences = [...opaqueFieldMap.values()].filter((occurrence) => (require_babel_plugin_intlayer_field_rename.getNestedRenameEntryAtPath(nestedRenameMap, occurrence.fieldPath)?.children.size ?? 0) > 0);
|
|
200
|
+
if (dangerousOccurrences.length > 0) {
|
|
201
|
+
partiallyMinifiedDictionariesCount += 1;
|
|
202
|
+
logger([
|
|
203
|
+
`Dictionary`,
|
|
204
|
+
(0, _intlayer_config_logger.colorizeKey)(dictionaryKey),
|
|
205
|
+
`partially minified.`,
|
|
206
|
+
...dangerousOccurrences.flatMap((occurrence) => [
|
|
207
|
+
`\n Opaque field:`,
|
|
208
|
+
(0, _intlayer_config_logger.colorize)(`'${occurrence.fieldPath.join(".")}'`, _intlayer_config_colors.BLUE),
|
|
209
|
+
`(nested keys preserved for stability).`,
|
|
210
|
+
...occurrence.locations.map((location) => `\n at ${(0, _intlayer_engine_utils.formatPath)(location)}`)
|
|
211
|
+
])
|
|
212
|
+
], {
|
|
213
|
+
level: "warn",
|
|
214
|
+
isVerbose: true
|
|
215
|
+
});
|
|
216
|
+
for (const occurrence of dangerousOccurrences) {
|
|
217
|
+
const renameEntry = require_babel_plugin_intlayer_field_rename.getNestedRenameEntryAtPath(nestedRenameMap, occurrence.fieldPath);
|
|
218
|
+
if (renameEntry) renameEntry.children = /* @__PURE__ */ new Map();
|
|
219
|
+
}
|
|
220
|
+
}
|
|
195
221
|
}
|
|
196
222
|
if (nestedRenameMap.size > 0) pruneContext.dictionaryKeyToFieldRenameMap.set(dictionaryKey, nestedRenameMap);
|
|
197
223
|
}
|
|
224
|
+
if (partiallyMinifiedDictionariesCount > 0) logger([
|
|
225
|
+
`Partially minified`,
|
|
226
|
+
(0, _intlayer_config_logger.colorizeNumber)(partiallyMinifiedDictionariesCount),
|
|
227
|
+
`dictionar${partiallyMinifiedDictionariesCount === 1 ? "y" : "ies"}`,
|
|
228
|
+
`(preserved nested keys for opaque fields).`
|
|
229
|
+
]);
|
|
230
|
+
};
|
|
231
|
+
/**
|
|
232
|
+
* Names of the top-level content fields of a compiled dictionary, whatever
|
|
233
|
+
* shape its `content` uses. Used to report which fields the purge removed.
|
|
234
|
+
*/
|
|
235
|
+
const readContentFieldNames = (content) => {
|
|
236
|
+
if (isTranslationNode(content)) {
|
|
237
|
+
const firstLocaleValue = Object.values(content.translation)[0];
|
|
238
|
+
return isPlainRecord(firstLocaleValue) ? Object.keys(firstLocaleValue) : [];
|
|
239
|
+
}
|
|
240
|
+
if (isPlainRecord(content)) return Object.keys(content);
|
|
241
|
+
return [];
|
|
198
242
|
};
|
|
199
243
|
/**
|
|
200
244
|
* Reads a compiled dictionary JSON file, applies the purge and/or minify
|
|
@@ -204,7 +248,7 @@ const buildRenameMapsSynchronously = (dictionariesDir, dynamicDictionariesDir, d
|
|
|
204
248
|
* static dictionaries keep `{ key, content }`, dynamic per-locale
|
|
205
249
|
* dictionaries additionally keep `locale`.
|
|
206
250
|
*/
|
|
207
|
-
const processDictionaryFile = (filePath, dictionaryKind, pruneContext, shouldPurge, shouldMinify) => {
|
|
251
|
+
const processDictionaryFile = (filePath, dictionaryKind, pruneContext, shouldPurge, shouldMinify, logger, stats) => {
|
|
208
252
|
let parsedDict;
|
|
209
253
|
try {
|
|
210
254
|
parsedDict = JSON.parse((0, node_fs.readFileSync)(filePath, "utf-8"));
|
|
@@ -212,19 +256,56 @@ const processDictionaryFile = (filePath, dictionaryKind, pruneContext, shouldPur
|
|
|
212
256
|
return;
|
|
213
257
|
}
|
|
214
258
|
const { key: dictionaryKey } = parsedDict;
|
|
215
|
-
if (!dictionaryKey)
|
|
259
|
+
if (!dictionaryKey) {
|
|
260
|
+
logger([
|
|
261
|
+
`Dictionary file`,
|
|
262
|
+
(0, _intlayer_engine_utils.formatPath)(filePath),
|
|
263
|
+
`is missing a "key" field. Skipping prune for this file.`
|
|
264
|
+
], { level: "warn" });
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
216
267
|
if (pruneContext.dictionariesWithEdgeCases.has(dictionaryKey)) return;
|
|
217
268
|
let modified = false;
|
|
218
269
|
if (shouldPurge) {
|
|
219
270
|
const fieldUsage = pruneContext.dictionaryKeyToFieldUsageMap.get(dictionaryKey);
|
|
220
271
|
if (fieldUsage && fieldUsage !== "all") {
|
|
221
|
-
const
|
|
272
|
+
const pruneDictionaryContent = dictionaryKind === "static" ? pruneStaticDictionaryContent : pruneDynamicDictionaryContent;
|
|
273
|
+
const originalFieldNames = readContentFieldNames(parsedDict.content);
|
|
274
|
+
const { prunedDictionary, wasRecognised } = pruneDictionaryContent(parsedDict, fieldUsage);
|
|
222
275
|
if (!wasRecognised) {
|
|
223
276
|
pruneContext.dictionariesWithEdgeCases.add(dictionaryKey);
|
|
277
|
+
logger([
|
|
278
|
+
`Unrecognised content structure in dictionary`,
|
|
279
|
+
(0, _intlayer_config_logger.colorizeKey)(dictionaryKey),
|
|
280
|
+
`(file:`,
|
|
281
|
+
`${(0, _intlayer_engine_utils.formatPath)(filePath)}).`,
|
|
282
|
+
`Skipping prune for this dictionary.`
|
|
283
|
+
], { level: "warn" });
|
|
224
284
|
return;
|
|
225
285
|
}
|
|
286
|
+
const removedFieldNames = originalFieldNames.filter((fieldName) => !fieldUsage.has(fieldName));
|
|
287
|
+
if (removedFieldNames.length > 0) {
|
|
288
|
+
stats.prunedFieldsCountPerDictionary.set(dictionaryKey, removedFieldNames.length);
|
|
289
|
+
if (!stats.loggedPrunedDictionaryKeys.has(dictionaryKey)) {
|
|
290
|
+
stats.loggedPrunedDictionaryKeys.add(dictionaryKey);
|
|
291
|
+
logger([
|
|
292
|
+
`Pruned`,
|
|
293
|
+
(0, _intlayer_config_logger.colorizeNumber)(removedFieldNames.length),
|
|
294
|
+
`unused field${removedFieldNames.length === 1 ? "" : "s"} from`,
|
|
295
|
+
`${(0, _intlayer_config_logger.colorizeKey)(dictionaryKey)}:`,
|
|
296
|
+
removedFieldNames.map((fieldName) => (0, _intlayer_config_logger.colorize)(fieldName, _intlayer_config_colors.GREY_LIGHT)).join(", ")
|
|
297
|
+
], { isVerbose: true });
|
|
298
|
+
}
|
|
299
|
+
}
|
|
226
300
|
parsedDict = prunedDictionary;
|
|
227
301
|
modified = true;
|
|
302
|
+
} else if (!fieldUsage && pruneContext.hasUnparsableSourceFiles && !stats.loggedIncompleteAnalysisKeys.has(dictionaryKey)) {
|
|
303
|
+
stats.loggedIncompleteAnalysisKeys.add(dictionaryKey);
|
|
304
|
+
logger([
|
|
305
|
+
`Skipping prune for dictionary`,
|
|
306
|
+
(0, _intlayer_config_logger.colorizeKey)(dictionaryKey),
|
|
307
|
+
`: analysis is incomplete due to earlier source-file parse failures.`
|
|
308
|
+
], { level: "warn" });
|
|
228
309
|
}
|
|
229
310
|
}
|
|
230
311
|
if (shouldMinify) {
|
|
@@ -247,41 +328,104 @@ const processDictionaryFile = (filePath, dictionaryKind, pruneContext, shouldPur
|
|
|
247
328
|
(0, node_fs.writeFileSync)(filePath, JSON.stringify(outputDict), "utf-8");
|
|
248
329
|
} catch {}
|
|
249
330
|
};
|
|
250
|
-
const processAllDictionaryFiles = (dictionariesDir, dynamicDictionariesDir, pruneContext, shouldPurge, shouldMinify) => {
|
|
331
|
+
const processAllDictionaryFiles = (dictionariesDir, dynamicDictionariesDir, pruneContext, shouldPurge, shouldMinify, logger) => {
|
|
332
|
+
const stats = {
|
|
333
|
+
prunedFieldsCountPerDictionary: /* @__PURE__ */ new Map(),
|
|
334
|
+
loggedPrunedDictionaryKeys: /* @__PURE__ */ new Set(),
|
|
335
|
+
loggedIncompleteAnalysisKeys: /* @__PURE__ */ new Set()
|
|
336
|
+
};
|
|
251
337
|
if ((0, node_fs.existsSync)(dictionariesDir)) for (const entry of (0, node_fs.readdirSync)(dictionariesDir)) {
|
|
252
338
|
if (!entry.endsWith(".json")) continue;
|
|
253
|
-
processDictionaryFile((0, node_path.join)(dictionariesDir, entry), "static", pruneContext, shouldPurge, shouldMinify);
|
|
339
|
+
processDictionaryFile((0, node_path.join)(dictionariesDir, entry), "static", pruneContext, shouldPurge, shouldMinify, logger, stats);
|
|
254
340
|
}
|
|
255
341
|
if ((0, node_fs.existsSync)(dynamicDictionariesDir)) for (const keyDir of (0, node_fs.readdirSync)(dynamicDictionariesDir)) {
|
|
256
342
|
const keyDirPath = (0, node_path.join)(dynamicDictionariesDir, keyDir);
|
|
257
343
|
try {
|
|
258
344
|
for (const localeFile of (0, node_fs.readdirSync)(keyDirPath)) {
|
|
259
345
|
if (!localeFile.endsWith(".json")) continue;
|
|
260
|
-
processDictionaryFile((0, node_path.join)(keyDirPath, localeFile), "dynamic", pruneContext, shouldPurge, shouldMinify);
|
|
346
|
+
processDictionaryFile((0, node_path.join)(keyDirPath, localeFile), "dynamic", pruneContext, shouldPurge, shouldMinify, logger, stats);
|
|
261
347
|
}
|
|
262
348
|
} catch {}
|
|
263
349
|
}
|
|
350
|
+
const totalPrunedFieldsCount = [...stats.prunedFieldsCountPerDictionary.values()].reduce((total, count) => total + count, 0);
|
|
351
|
+
const totalPrunedDictionariesCount = stats.prunedFieldsCountPerDictionary.size;
|
|
352
|
+
if (totalPrunedFieldsCount > 0) logger([
|
|
353
|
+
`Pruned`,
|
|
354
|
+
(0, _intlayer_config_logger.colorizeNumber)(totalPrunedFieldsCount),
|
|
355
|
+
`unused field${totalPrunedFieldsCount === 1 ? "" : "s"} across`,
|
|
356
|
+
(0, _intlayer_config_logger.colorizeNumber)(totalPrunedDictionariesCount),
|
|
357
|
+
`dictionar${totalPrunedDictionariesCount === 1 ? "y" : "ies"}.`
|
|
358
|
+
]);
|
|
359
|
+
};
|
|
360
|
+
/**
|
|
361
|
+
* Explains why the requested steps did nothing: the visual editor needs the
|
|
362
|
+
* full dictionary content, so both purge and minify stand down when it is on.
|
|
363
|
+
*/
|
|
364
|
+
const logStepDisabledByEditor = (logger, purge, minify) => {
|
|
365
|
+
const explainDisabled = (stepLabel) => logger([
|
|
366
|
+
stepLabel,
|
|
367
|
+
"is",
|
|
368
|
+
(0, _intlayer_config_logger.colorize)("disabled", _intlayer_config_colors.GREY_DARK),
|
|
369
|
+
"because",
|
|
370
|
+
(0, _intlayer_config_logger.colorize)("editor.enabled", _intlayer_config_colors.BLUE),
|
|
371
|
+
"is",
|
|
372
|
+
(0, _intlayer_config_logger.colorize)("true", _intlayer_config_colors.GREY_DARK),
|
|
373
|
+
(0, _intlayer_config_logger.colorize)("— the editor requires full dictionary content", _intlayer_config_colors.GREY)
|
|
374
|
+
]);
|
|
375
|
+
if (purge) explainDisabled("Dictionary purge");
|
|
376
|
+
if (minify) explainDisabled("Dictionary minification");
|
|
377
|
+
};
|
|
378
|
+
/**
|
|
379
|
+
* Reports the dictionaries whose consumption could not be tracked statically,
|
|
380
|
+
* with the source files responsible — those keep their full content.
|
|
381
|
+
*/
|
|
382
|
+
const logUntrackedBindings = (logger, pruneContext) => {
|
|
383
|
+
for (const [dictionaryKey, sourceFilePaths] of pruneContext.dictionaryKeysWithUntrackedBindings) logger([
|
|
384
|
+
`Dictionary`,
|
|
385
|
+
(0, _intlayer_config_logger.colorizeKey)(dictionaryKey),
|
|
386
|
+
`cannot be purged or minified.`,
|
|
387
|
+
`\n Reason: the result of`,
|
|
388
|
+
`${(0, _intlayer_config_logger.colorize)(`useIntlayer(`, _intlayer_config_colors.GREY_LIGHT)}${(0, _intlayer_config_logger.colorizeKey)(`'${dictionaryKey}'`)}${(0, _intlayer_config_logger.colorize)(`)`, _intlayer_config_colors.GREY_LIGHT)}`,
|
|
389
|
+
`is assigned to a plain variable in:`,
|
|
390
|
+
...sourceFilePaths.map((filePath) => `\n - ${(0, _intlayer_engine_utils.formatPath)(filePath)}`)
|
|
391
|
+
], { level: "warn" });
|
|
264
392
|
};
|
|
265
393
|
/**
|
|
266
394
|
* Runs the full purge/minify pipeline for the given options, using a
|
|
267
395
|
* module-level cache so the work happens at most once per process per
|
|
268
396
|
* unique `baseDir`.
|
|
397
|
+
*
|
|
398
|
+
* Exported so bundler integrations that do not go through Babel can drive the
|
|
399
|
+
* same pipeline. The Next.js integration is the main consumer: its SWC plugin
|
|
400
|
+
* runs as a per-file Wasm transform with no filesystem access, so the analysis
|
|
401
|
+
* and the dictionary rewrite happen here, in Node, and only the resulting
|
|
402
|
+
* field-rename tables (see {@link serializeFieldRenameMap}) are forwarded to
|
|
403
|
+
* the plugin.
|
|
404
|
+
*
|
|
405
|
+
* **This performs file I/O**: it reads every source file listed in
|
|
406
|
+
* `componentFilesList` and overwrites the compiled dictionary JSON files
|
|
407
|
+
* in-place. Call it at most once per build, after the dictionaries have been
|
|
408
|
+
* built.
|
|
269
409
|
*/
|
|
270
|
-
const
|
|
271
|
-
const { baseDir, purge, minify, optimize, editorEnabled, dictionariesDir, dynamicDictionariesDir, componentFilesList, dictionaryKeyToImportModeMap, compatCallers } = options;
|
|
410
|
+
const runIntlayerPurgePipeline = (options) => {
|
|
411
|
+
const { baseDir, purge, minify, optimize, editorEnabled, dictionariesDir, dynamicDictionariesDir, componentFilesList, dictionaryKeyToImportModeMap, nestedDictionaryReferences, compatCallers, logConfig } = options;
|
|
272
412
|
const cachedContext = _pruneContextCache.get(baseDir);
|
|
273
413
|
if (cachedContext) return cachedContext;
|
|
274
414
|
const pruneContext = require_babel_plugin_intlayer_usage_analyzer.createPruneContext();
|
|
275
415
|
_pruneContextCache.set(baseDir, pruneContext);
|
|
416
|
+
const logger = (0, _intlayer_config_logger.getAppLogger)(logConfig);
|
|
276
417
|
const shouldPurge = purge && !editorEnabled;
|
|
277
418
|
const shouldMinify = minify && !editorEnabled;
|
|
419
|
+
if (editorEnabled && (purge || minify)) logStepDisabledByEditor(logger, purge, minify);
|
|
278
420
|
if (!shouldPurge && !shouldMinify || optimize === false) return pruneContext;
|
|
279
421
|
for (const sourceFilePath of componentFilesList) {
|
|
280
422
|
if (!require_transformers.SOURCE_FILE_REGEX.test(sourceFilePath)) continue;
|
|
281
423
|
analyzeSourceFileSync(sourceFilePath, pruneContext, compatCallers);
|
|
282
424
|
}
|
|
283
|
-
if (
|
|
284
|
-
|
|
425
|
+
if (nestedDictionaryReferences) require_babel_plugin_intlayer_usage_analyzer.preserveNestedDictionaryFields(pruneContext, nestedDictionaryReferences);
|
|
426
|
+
logUntrackedBindings(logger, pruneContext);
|
|
427
|
+
if (shouldMinify) buildRenameMapsSynchronously(dictionariesDir, dynamicDictionariesDir, dictionaryKeyToImportModeMap, pruneContext, logger);
|
|
428
|
+
processAllDictionaryFiles(dictionariesDir, dynamicDictionariesDir, pruneContext, shouldPurge, shouldMinify, logger);
|
|
285
429
|
return pruneContext;
|
|
286
430
|
};
|
|
287
431
|
/**
|
|
@@ -335,7 +479,7 @@ const runPurgePipeline = (options) => {
|
|
|
335
479
|
const intlayerPurgeBabelPlugin = (_babel) => ({
|
|
336
480
|
name: "intlayer-purge",
|
|
337
481
|
pre() {
|
|
338
|
-
|
|
482
|
+
runIntlayerPurgePipeline(this.opts);
|
|
339
483
|
},
|
|
340
484
|
visitor: {}
|
|
341
485
|
});
|
|
@@ -343,4 +487,5 @@ const intlayerPurgeBabelPlugin = (_babel) => ({
|
|
|
343
487
|
//#endregion
|
|
344
488
|
exports.getSharedPruneContext = getSharedPruneContext;
|
|
345
489
|
exports.intlayerPurgeBabelPlugin = intlayerPurgeBabelPlugin;
|
|
490
|
+
exports.runIntlayerPurgePipeline = runIntlayerPurgePipeline;
|
|
346
491
|
//# sourceMappingURL=babel-plugin-intlayer-purge.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"babel-plugin-intlayer-purge.cjs","names":["makeUsageAnalyzerBabelPlugin","BABEL_PARSER_OPTIONS","getUsageCheckRegex","extractScriptBlocks","buildNestedRenameMapFromContent","getNestedRenameEntryAtPath","createPruneContext","SOURCE_FILE_REGEX"],"sources":["../../src/babel-plugin-intlayer-purge.ts"],"sourcesContent":["import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { PluginObject, PluginPass } from '@babel/core';\nimport { transformSync } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\nimport {\n buildNestedRenameMapFromContent,\n getNestedRenameEntryAtPath,\n} from './babel-plugin-intlayer-field-rename';\nimport {\n type CompatCallerConfig,\n createPruneContext,\n makeUsageAnalyzerBabelPlugin,\n type NestedRenameMap,\n type PruneContext,\n} from './babel-plugin-intlayer-usage-analyzer';\nimport { extractScriptBlocks } from './extractScriptBlocks';\nimport {\n BABEL_PARSER_OPTIONS,\n getUsageCheckRegex,\n SOURCE_FILE_REGEX,\n} from './transformers';\n\n// ── Plugin options ────────────────────────────────────────────────────────────\n\n/**\n * Pre-resolved options accepted by {@link intlayerPurgeBabelPlugin}.\n *\n * All values are resolved at babel.config.js load time (via\n * {@link getPurgePluginOptions}) so the plugin itself does not need to read\n * the configuration file on every file transform.\n */\nexport type PurgePluginOptions = {\n /**\n * Absolute path to the project root. Used as the cache key for the shared\n * {@link PruneContext} so two Babel transform pipelines for different\n * workspaces in the same process do not share state.\n */\n baseDir: string;\n\n /**\n * When `true`, remove unused content fields from compiled dictionary JSON\n * files. Mirrors `build.purge` in `intlayer.config.ts`.\n */\n purge: boolean;\n\n /**\n * When `true`, rename content fields to short alphabetic aliases\n * (`title` → `a`, etc.) and strip top-level metadata from compiled\n * dictionaries. Mirrors `build.minify` in `intlayer.config.ts`.\n */\n minify: boolean;\n\n /**\n * Build optimisation toggle. `undefined` means \"auto\" (active for\n * production builds). When explicitly `false`, the plugin is a no-op.\n * Mirrors `build.optimize`.\n */\n optimize: boolean | undefined;\n\n /**\n * When `true` the plugin skips all processing to preserve full dictionary\n * content for the visual editor. Mirrors `editor.enabled`.\n */\n editorEnabled: boolean;\n\n /**\n * Absolute path to the compiled static dictionaries directory\n * (`.intlayer/dictionaries/` by default).\n */\n dictionariesDir: string;\n\n /**\n * Absolute path to the compiled per-locale dynamic dictionaries directory\n * (`.intlayer/dynamic_dictionaries/` by default).\n */\n dynamicDictionariesDir: string;\n\n /**\n * Pre-built list of component source file paths to analyse for field-usage.\n * Populated by {@link getPurgePluginOptions} from the intlayer config's\n * `content` glob patterns.\n */\n componentFilesList: string[];\n\n /**\n * Per-dictionary import-mode overrides, keyed by dictionary `key`.\n * Dictionaries with mode `'fetch'` are excluded from field renaming because\n * their JSON is served from a remote API using the original field names.\n */\n dictionaryKeyToImportModeMap: Record<\n string,\n 'static' | 'dynamic' | 'fetch' | undefined\n >;\n\n /**\n * Compat-adapter namespace caller configurations.\n *\n * When set, the usage analyser recognises these additional translation\n * function patterns and maps them to dictionary field usage. Each compat\n * adapter package (e.g. `@intlayer/react-i18next`) provides its own caller\n * list; they are NOT hardcoded here so that `@intlayer/babel` stays\n * framework-agnostic.\n *\n * Defaults to `[]` (no compat callers) when omitted.\n */\n compatCallers?: CompatCallerConfig[];\n};\n\n// ── Shared module-level state ─────────────────────────────────────────────────\n\n/**\n * Cache of built {@link PruneContext} objects, keyed by the project's\n * `baseDir`. Each context is built exactly once per Node.js process:\n * {@link runPurgePipeline} registers the context before running so every\n * subsequent transform is a no-op cache hit.\n */\nconst _pruneContextCache = new Map<string, PruneContext>();\n\n/**\n * Returns the shared {@link PruneContext} for the given base directory, or\n * `null` if {@link intlayerPurgeBabelPlugin} has not yet been initialised for\n * that directory.\n *\n * Used by {@link intlayerMinifyBabelPlugin} to read the rename map without\n * creating a circular dependency.\n */\nexport const getSharedPruneContext = (baseDir: string): PruneContext | null =>\n _pruneContextCache.get(baseDir) ?? null;\n\n// ── Dictionary JSON types ─────────────────────────────────────────────────────\n\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, unknown>;\n};\n\ntype CompiledDictionaryJson = {\n key: string;\n content: TranslationNode | Record<string, unknown>;\n locale?: string;\n [extraKey: string]: unknown;\n};\n\n// ── Type guards ───────────────────────────────────────────────────────────────\n\nconst isTranslationNode = (value: unknown): value is TranslationNode =>\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>).nodeType === 'translation' &&\n typeof (value as Record<string, unknown>).translation === 'object';\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// ── Prune helpers (mirrors intlayerPrunePlugin) ───────────────────────────────\n\ntype PruneResult = {\n prunedDictionary: CompiledDictionaryJson;\n wasRecognised: boolean;\n};\n\n/** Returns a copy of `record` keeping only the keys listed in `usedFieldNames`. */\nconst filterRecordByUsedFields = (\n record: Record<string, unknown>,\n usedFieldNames: Set<string>\n): Record<string, unknown> => {\n const filteredRecord: Record<string, unknown> = {};\n for (const [fieldName, fieldValue] of Object.entries(record)) {\n if (usedFieldNames.has(fieldName)) {\n filteredRecord[fieldName] = fieldValue;\n }\n }\n return filteredRecord;\n};\n\n/**\n * Removes unused fields from a **static** dictionary (all locales in one\n * file). Supports shape A (translation node at the root) and shape B (flat\n * record of translation nodes per field).\n */\nconst pruneStaticDictionaryContent = (\n dictionary: CompiledDictionaryJson,\n usedFieldNames: Set<string>\n): PruneResult => {\n const { content } = dictionary;\n\n // Shape A: { nodeType: \"translation\", translation: { en: { f1, f2 } } }\n if (isTranslationNode(content)) {\n const firstLocaleValue = Object.values(content.translation)[0];\n if (isPlainRecord(firstLocaleValue)) {\n const prunedTranslation: Record<string, unknown> = {};\n for (const [locale, localeContent] of Object.entries(\n content.translation\n )) {\n prunedTranslation[locale] = isPlainRecord(localeContent)\n ? filterRecordByUsedFields(localeContent, usedFieldNames)\n : localeContent;\n }\n return {\n prunedDictionary: {\n ...dictionary,\n content: { ...content, translation: prunedTranslation },\n },\n wasRecognised: true,\n };\n }\n }\n\n // Shape B: { field1: { nodeType: \"translation\", … }, field2: { … } }\n if (isPlainRecord(content) && !isTranslationNode(content)) {\n return {\n prunedDictionary: {\n ...dictionary,\n content: filterRecordByUsedFields(content, usedFieldNames),\n },\n wasRecognised: true,\n };\n }\n\n return { prunedDictionary: dictionary, wasRecognised: false };\n};\n\n/**\n * Removes unused fields from a **dynamic / per-locale** dictionary file\n * (one JSON per locale, flat `content` record).\n */\nconst pruneDynamicDictionaryContent = (\n dictionary: CompiledDictionaryJson,\n usedFieldNames: Set<string>\n): PruneResult => {\n const { content } = dictionary;\n if (!isPlainRecord(content)) {\n return { prunedDictionary: dictionary, wasRecognised: false };\n }\n return {\n prunedDictionary: {\n ...dictionary,\n content: filterRecordByUsedFields(content, usedFieldNames),\n },\n wasRecognised: true,\n };\n};\n\n// ── Minify helpers (mirrors intlayerMinifyPlugin) ─────────────────────────────\n\n/**\n * Recursively renames user-defined content fields using `renameMap`.\n * Translation nodes, arrays, and primitives follow the same traversal rules\n * as in the Vite-based minify plugin.\n */\nconst renameContentRecursively = (\n value: unknown,\n renameMap: NestedRenameMap\n): unknown => {\n if (Array.isArray(value)) {\n return (value as unknown[]).map((element) =>\n renameContentRecursively(element, renameMap)\n );\n }\n if (!value || typeof value !== 'object') return value;\n\n const record = value as Record<string, unknown>;\n\n // Translation node: recurse into each locale value with the same map.\n if (\n typeof record.nodeType === 'string' &&\n record.translation &&\n typeof record.translation === 'object' &&\n !Array.isArray(record.translation)\n ) {\n const renamedTranslation: Record<string, unknown> = {};\n for (const [locale, localeValue] of Object.entries(\n record.translation as Record<string, unknown>\n )) {\n renamedTranslation[locale] = renameContentRecursively(\n localeValue,\n renameMap\n );\n }\n return { ...record, translation: renamedTranslation };\n }\n\n // User-defined record: rename keys and recurse into values.\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(record)) {\n const renameEntry = renameMap.get(key);\n if (renameEntry) {\n result[renameEntry.shortName] = renameContentRecursively(\n val,\n renameEntry.children\n );\n } else {\n result[key] = val;\n }\n }\n return result;\n};\n\n/**\n * Applies a {@link NestedRenameMap} to a parsed dictionary object, renaming\n * only the keys inside `content` while leaving top-level metadata untouched.\n */\nconst applyFieldRenameToDict = (\n dict: Record<string, unknown>,\n renameMap: NestedRenameMap\n): Record<string, unknown> => {\n const content = dict.content;\n if (!content || typeof content !== 'object' || Array.isArray(content))\n return dict;\n return {\n ...dict,\n content: renameContentRecursively(content, renameMap),\n };\n};\n\n// ── Synchronous source-file analysis ─────────────────────────────────────────\n\n/**\n * Runs the usage-analyser Babel plugin synchronously on a single code block,\n * accumulating results into `pruneContext`.\n */\nconst analyzeCodeBlockSync = (\n code: string,\n sourceFilePath: string,\n pruneContext: PruneContext,\n compatCallers?: CompatCallerConfig[]\n): void => {\n try {\n transformSync(code, {\n filename: sourceFilePath,\n plugins: [makeUsageAnalyzerBabelPlugin(pruneContext, { compatCallers })],\n parserOpts: BABEL_PARSER_OPTIONS,\n ast: false,\n code: false,\n });\n } catch {\n pruneContext.hasUnparsableSourceFiles = true;\n }\n};\n\n/**\n * Reads a source file from disk and runs the usage-analyser synchronously.\n * SFC files (Vue / Svelte) are handled by extracting script blocks first.\n */\nconst analyzeSourceFileSync = (\n sourceFilePath: string,\n pruneContext: PruneContext,\n compatCallers?: CompatCallerConfig[]\n): void => {\n let code: string;\n try {\n code = readFileSync(sourceFilePath, 'utf-8');\n } catch {\n return;\n }\n\n const usageCheckRegex = getUsageCheckRegex(compatCallers);\n\n if (!usageCheckRegex.test(code)) return;\n\n const scriptBlocks = extractScriptBlocks(sourceFilePath, code);\n for (const block of scriptBlocks) {\n if (!usageCheckRegex.test(block.content)) continue;\n analyzeCodeBlockSync(\n block.content,\n sourceFilePath,\n pruneContext,\n compatCallers\n );\n }\n};\n\n// ── Build rename maps ─────────────────────────────────────────────────────────\n\n/**\n * Reads compiled dictionary JSON files to build the nested field-rename maps,\n * mirroring the Phase 4 logic in the Vite `intlayerOptimize` plugin's\n * `buildStart` hook. Results are stored in\n * `pruneContext.dictionaryKeyToFieldRenameMap`.\n */\nconst buildRenameMapsSynchronously = (\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n dictionaryKeyToImportModeMap: PurgePluginOptions['dictionaryKeyToImportModeMap'],\n pruneContext: PruneContext\n): void => {\n for (const [\n dictionaryKey,\n fieldUsage,\n ] of pruneContext.dictionaryKeyToFieldUsageMap) {\n if (fieldUsage === 'all') continue;\n if (dictionaryKeyToImportModeMap[dictionaryKey] === 'fetch') continue;\n if (pruneContext.dictionariesSkippingFieldRename.has(dictionaryKey))\n continue;\n\n let dictionaryContent: unknown = null;\n\n const staticJsonPath = join(dictionariesDir, `${dictionaryKey}.json`);\n if (existsSync(staticJsonPath)) {\n try {\n const raw = readFileSync(staticJsonPath, 'utf-8');\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n dictionaryContent = parsed.content;\n } catch {\n // Fall through to dynamic dict.\n }\n }\n\n if (!dictionaryContent) {\n const dynamicDirPath = join(dynamicDictionariesDir, dictionaryKey);\n if (existsSync(dynamicDirPath)) {\n try {\n const localeFiles = readdirSync(dynamicDirPath);\n const firstJsonFile = localeFiles.find((file) =>\n file.endsWith('.json')\n );\n if (firstJsonFile) {\n const raw = readFileSync(\n join(dynamicDirPath, firstJsonFile),\n 'utf-8'\n );\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n dictionaryContent = parsed.content;\n }\n } catch {\n // Dictionary not readable – skip rename for this key.\n }\n }\n }\n\n if (!dictionaryContent) continue;\n\n const nestedRenameMap = buildNestedRenameMapFromContent(dictionaryContent);\n\n // Preserve children of opaque values to avoid breaking child components.\n const opaqueFieldMap =\n pruneContext.dictionaryKeysWithOpaqueFields.get(dictionaryKey);\n if (opaqueFieldMap) {\n for (const occurrence of opaqueFieldMap.values()) {\n const renameEntry = getNestedRenameEntryAtPath(\n nestedRenameMap,\n occurrence.fieldPath\n );\n if (renameEntry && renameEntry.children.size > 0) {\n renameEntry.children = new Map();\n }\n }\n }\n\n if (nestedRenameMap.size > 0) {\n pruneContext.dictionaryKeyToFieldRenameMap.set(\n dictionaryKey,\n nestedRenameMap\n );\n }\n }\n};\n\n// ── Dictionary file writing ───────────────────────────────────────────────────\n\n/**\n * Reads a compiled dictionary JSON file, applies the purge and/or minify\n * transformations, and writes it back in-place when something changed.\n *\n * `dictionaryKind` selects the prune strategy and the minified output shape:\n * static dictionaries keep `{ key, content }`, dynamic per-locale\n * dictionaries additionally keep `locale`.\n */\nconst processDictionaryFile = (\n filePath: string,\n dictionaryKind: 'static' | 'dynamic',\n pruneContext: PruneContext,\n shouldPurge: boolean,\n shouldMinify: boolean\n): void => {\n let parsedDict: CompiledDictionaryJson;\n try {\n parsedDict = JSON.parse(\n readFileSync(filePath, 'utf-8')\n ) as CompiledDictionaryJson;\n } catch {\n return; // Unreadable or invalid JSON – leave file unchanged.\n }\n\n const { key: dictionaryKey } = parsedDict;\n if (!dictionaryKey) return;\n if (pruneContext.dictionariesWithEdgeCases.has(dictionaryKey)) return;\n\n let modified = false;\n\n if (shouldPurge) {\n const fieldUsage =\n pruneContext.dictionaryKeyToFieldUsageMap.get(dictionaryKey);\n if (fieldUsage && fieldUsage !== 'all') {\n const pruneDictionaryContent =\n dictionaryKind === 'static'\n ? pruneStaticDictionaryContent\n : pruneDynamicDictionaryContent;\n const { prunedDictionary, wasRecognised } = pruneDictionaryContent(\n parsedDict,\n fieldUsage\n );\n if (!wasRecognised) {\n pruneContext.dictionariesWithEdgeCases.add(dictionaryKey);\n return;\n }\n parsedDict = prunedDictionary;\n modified = true;\n }\n }\n\n if (shouldMinify) {\n const fieldRenameMap =\n pruneContext.dictionaryKeyToFieldRenameMap.get(dictionaryKey);\n if (fieldRenameMap && fieldRenameMap.size > 0) {\n parsedDict = applyFieldRenameToDict(\n parsedDict as Record<string, unknown>,\n fieldRenameMap\n ) as CompiledDictionaryJson;\n modified = true;\n }\n }\n\n if (!modified) return;\n\n const outputDict = shouldMinify\n ? dictionaryKind === 'static'\n ? { key: parsedDict.key, content: parsedDict.content }\n : {\n key: parsedDict.key,\n content: parsedDict.content,\n locale: parsedDict.locale,\n }\n : parsedDict;\n\n try {\n writeFileSync(filePath, JSON.stringify(outputDict), 'utf-8');\n } catch {\n // Write failure – leave file unchanged.\n }\n};\n\nconst processAllDictionaryFiles = (\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n pruneContext: PruneContext,\n shouldPurge: boolean,\n shouldMinify: boolean\n): void => {\n if (existsSync(dictionariesDir)) {\n for (const entry of readdirSync(dictionariesDir)) {\n if (!entry.endsWith('.json')) continue;\n processDictionaryFile(\n join(dictionariesDir, entry),\n 'static',\n pruneContext,\n shouldPurge,\n shouldMinify\n );\n }\n }\n\n if (existsSync(dynamicDictionariesDir)) {\n for (const keyDir of readdirSync(dynamicDictionariesDir)) {\n const keyDirPath = join(dynamicDictionariesDir, keyDir);\n try {\n for (const localeFile of readdirSync(keyDirPath)) {\n if (!localeFile.endsWith('.json')) continue;\n processDictionaryFile(\n join(keyDirPath, localeFile),\n 'dynamic',\n pruneContext,\n shouldPurge,\n shouldMinify\n );\n }\n } catch {\n // Unreadable key directory – skip.\n }\n }\n }\n};\n\n// ── Main initialisation ───────────────────────────────────────────────────────\n\n/**\n * Runs the full purge/minify pipeline for the given options, using a\n * module-level cache so the work happens at most once per process per\n * unique `baseDir`.\n */\nconst runPurgePipeline = (options: PurgePluginOptions): PruneContext => {\n const {\n baseDir,\n purge,\n minify,\n optimize,\n editorEnabled,\n dictionariesDir,\n dynamicDictionariesDir,\n componentFilesList,\n dictionaryKeyToImportModeMap,\n compatCallers,\n } = options;\n\n const cachedContext = _pruneContextCache.get(baseDir);\n if (cachedContext) return cachedContext;\n\n const pruneContext = createPruneContext();\n _pruneContextCache.set(baseDir, pruneContext);\n\n const shouldPurge = purge && !editorEnabled;\n const shouldMinify = minify && !editorEnabled;\n\n if ((!shouldPurge && !shouldMinify) || optimize === false)\n return pruneContext;\n\n // Phase 1: Synchronously analyse all component source files.\n for (const sourceFilePath of componentFilesList) {\n if (!SOURCE_FILE_REGEX.test(sourceFilePath)) continue;\n analyzeSourceFileSync(sourceFilePath, pruneContext, compatCallers);\n }\n\n // Phase 2: Build field-rename maps (minify only).\n if (shouldMinify) {\n buildRenameMapsSynchronously(\n dictionariesDir,\n dynamicDictionariesDir,\n dictionaryKeyToImportModeMap,\n pruneContext\n );\n }\n\n // Phase 3: Write pruned / minified dictionary JSON files to disk.\n processAllDictionaryFiles(\n dictionariesDir,\n dynamicDictionariesDir,\n pruneContext,\n shouldPurge,\n shouldMinify\n );\n\n return pruneContext;\n};\n\n// ── Babel plugin ──────────────────────────────────────────────────────────────\n\n/**\n * Babel plugin that analyses all project source files and rewrites compiled\n * dictionary JSON files in-place to remove unused content fields\n * (`build.purge`) and/or rename them to short alphabetic aliases\n * (`build.minify`).\n *\n * All option values must be pre-resolved via {@link getPurgePluginOptions}\n * before being passed here — the plugin does not load the intlayer\n * configuration itself.\n *\n * This plugin performs **file I/O as a side effect**: on the very first Babel\n * transform in a given Node.js process it synchronously scans the component\n * files listed in `options.componentFilesList`, builds field-usage data, and\n * writes the processed dictionaries to disk. Subsequent transforms are\n * no-ops.\n *\n * Source-code field renames (rewriting `content.title` → `content.a`) are\n * handled by the companion {@link intlayerMinifyBabelPlugin}.\n *\n * @example\n * ```js\n * // babel.config.js\n * const {\n * intlayerPurgeBabelPlugin,\n * intlayerMinifyBabelPlugin,\n * intlayerOptimizeBabelPlugin,\n * getPurgePluginOptions,\n * getMinifyPluginOptions,\n * getOptimizePluginOptions,\n * } = require(\"@intlayer/babel\");\n *\n * module.exports = {\n * presets: [\"next/babel\"],\n * plugins: [\n * [intlayerPurgeBabelPlugin, getPurgePluginOptions()],\n * [intlayerMinifyBabelPlugin, getMinifyPluginOptions()],\n * [intlayerOptimizeBabelPlugin, getOptimizePluginOptions()],\n * ],\n * };\n * ```\n *\n * @remarks\n * - Intended for **production builds** only. Dictionary JSON files are\n * overwritten in-place; running `intlayer build` afterwards restores the\n * originals.\n * - The plugin is a no-op when `optimize` is `false` or `editorEnabled` is\n * `true`.\n */\nexport const intlayerPurgeBabelPlugin = (_babel: {\n types: typeof BabelTypes;\n}): PluginObject => ({\n name: 'intlayer-purge',\n\n pre(this: PluginPass) {\n runPurgePipeline(this.opts as PurgePluginOptions);\n },\n\n visitor: {\n // No AST transforms: all work is done as a side effect in pre().\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;AAqHA,MAAM,qCAAqB,IAAI,IAA0B;;;;;;;;;AAUzD,MAAa,yBAAyB,YACpC,mBAAmB,IAAI,OAAO,KAAK;AAkBrC,MAAM,qBAAqB,UACzB,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,aAAa,iBAChD,OAAQ,MAAkC,gBAAgB;AAE5D,MAAM,iBAAiB,UACrB,OAAO,UAAU,YAAY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IAAI;GACF,KAAK,MAAM,uCAA0B,UAAU,GAAG;IAChD,IAAI,CAAC,WAAW,SAAS,OAAO,GAAG;IACnC,0CACO,YAAY,UAAU,GAC3B,WACA,cACA,aACA,YACF;GACF;EACF,QAAQ,CAER;CACF;AAEJ;;;;;;AASA,MAAM,oBAAoB,YAA8C;CACtE,MAAM,EACJ,SACA,OACA,QACA,UACA,eACA,iBACA,wBACA,oBACA,8BACA,kBACE;CAEJ,MAAM,gBAAgB,mBAAmB,IAAI,OAAO;CACpD,IAAI,eAAe,OAAO;CAE1B,MAAM,eAAeC,gEAAmB;CACxC,mBAAmB,IAAI,SAAS,YAAY;CAE5C,MAAM,cAAc,SAAS,CAAC;CAC9B,MAAM,eAAe,UAAU,CAAC;CAEhC,IAAK,CAAC,eAAe,CAAC,gBAAiB,aAAa,OAClD,OAAO;CAGT,KAAK,MAAM,kBAAkB,oBAAoB;EAC/C,IAAI,CAACC,uCAAkB,KAAK,cAAc,GAAG;EAC7C,sBAAsB,gBAAgB,cAAc,aAAa;CACnE;CAGA,IAAI,cACF,6BACE,iBACA,wBACA,8BACA,YACF;CAIF,0BACE,iBACA,wBACA,cACA,aACA,YACF;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,MAAa,4BAA4B,YAEpB;CACnB,MAAM;CAEN,MAAsB;EACpB,iBAAiB,KAAK,IAA0B;CAClD;CAEA,SAAS,CAET;AACF"}
|
|
1
|
+
{"version":3,"file":"babel-plugin-intlayer-purge.cjs","names":["makeUsageAnalyzerBabelPlugin","BABEL_PARSER_OPTIONS","getUsageCheckRegex","extractScriptBlocks","buildNestedRenameMapFromContent","getNestedRenameEntryAtPath","ANSIColors","createPruneContext","SOURCE_FILE_REGEX"],"sources":["../../src/babel-plugin-intlayer-purge.ts"],"sourcesContent":["import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { PluginObject, PluginPass } from '@babel/core';\nimport { transformSync } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeKey,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { NestedFieldReferences } from '@intlayer/core/dictionaryManipulator';\nimport { formatPath } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport {\n buildNestedRenameMapFromContent,\n getNestedRenameEntryAtPath,\n} from './babel-plugin-intlayer-field-rename';\nimport {\n type CompatCallerConfig,\n createPruneContext,\n makeUsageAnalyzerBabelPlugin,\n type NestedRenameMap,\n type PruneContext,\n preserveNestedDictionaryFields,\n} from './babel-plugin-intlayer-usage-analyzer';\nimport { extractScriptBlocks } from './extractScriptBlocks';\nimport {\n BABEL_PARSER_OPTIONS,\n getUsageCheckRegex,\n SOURCE_FILE_REGEX,\n} from './transformers';\n\n// ── Plugin options ────────────────────────────────────────────────────────────\n\n/**\n * Pre-resolved options accepted by {@link intlayerPurgeBabelPlugin}.\n *\n * All values are resolved at babel.config.js load time (via\n * {@link getPurgePluginOptions}) so the plugin itself does not need to read\n * the configuration file on every file transform.\n */\nexport type PurgePluginOptions = {\n /**\n * Absolute path to the project root. Used as the cache key for the shared\n * {@link PruneContext} so two Babel transform pipelines for different\n * workspaces in the same process do not share state.\n */\n baseDir: string;\n\n /**\n * When `true`, remove unused content fields from compiled dictionary JSON\n * files. Mirrors `build.purge` in `intlayer.config.ts`.\n */\n purge: boolean;\n\n /**\n * When `true`, rename content fields to short alphabetic aliases\n * (`title` → `a`, etc.) and strip top-level metadata from compiled\n * dictionaries. Mirrors `build.minify` in `intlayer.config.ts`.\n */\n minify: boolean;\n\n /**\n * Build optimisation toggle. `undefined` means \"auto\" (active for\n * production builds). When explicitly `false`, the plugin is a no-op.\n * Mirrors `build.optimize`.\n */\n optimize: boolean | undefined;\n\n /**\n * When `true` the plugin skips all processing to preserve full dictionary\n * content for the visual editor. Mirrors `editor.enabled`.\n */\n editorEnabled: boolean;\n\n /**\n * Absolute path to the compiled static dictionaries directory\n * (`.intlayer/dictionaries/` by default).\n */\n dictionariesDir: string;\n\n /**\n * Absolute path to the compiled per-locale dynamic dictionaries directory\n * (`.intlayer/dynamic_dictionaries/` by default).\n */\n dynamicDictionariesDir: string;\n\n /**\n * Pre-built list of component source file paths to analyse for field-usage.\n * Populated by {@link getPurgePluginOptions} from the intlayer config's\n * `content` glob patterns.\n */\n componentFilesList: string[];\n\n /**\n * Dictionaries referenced through `nest()`, mapped to the top-level fields\n * those references read (`'all'` when the whole dictionary is nested).\n *\n * Those fields are resolved at runtime by `getNesting` using their original\n * names, so they must survive purging and must never be renamed.\n */\n nestedDictionaryReferences?: Map<string, NestedFieldReferences>;\n\n /**\n * Per-dictionary import-mode overrides, keyed by dictionary `key`.\n * Dictionaries with mode `'fetch'` are excluded from field renaming because\n * their JSON is served from a remote API using the original field names.\n */\n dictionaryKeyToImportModeMap: Record<\n string,\n 'static' | 'dynamic' | 'fetch' | undefined\n >;\n\n /**\n * Compat-adapter namespace caller configurations.\n *\n * When set, the usage analyser recognises these additional translation\n * function patterns and maps them to dictionary field usage. Each compat\n * adapter package (e.g. `@intlayer/react-i18next`) provides its own caller\n * list; they are NOT hardcoded here so that `@intlayer/babel` stays\n * framework-agnostic.\n *\n * Defaults to `[]` (no compat callers) when omitted.\n */\n compatCallers?: CompatCallerConfig[];\n\n /**\n * Logging configuration used to report what the pipeline purged and\n * minified, so a Babel- or SWC-driven build prints the same summary as the\n * Vite one. Mirrors `log` in `intlayer.config.ts`; omit to fall back to the\n * logger defaults.\n */\n logConfig?: Pick<IntlayerConfig, 'log'>;\n};\n\n/** Application logger used to report the pipeline's progress. */\ntype PurgeLogger = ReturnType<typeof getAppLogger>;\n\n// ── Shared module-level state ─────────────────────────────────────────────────\n\n/**\n * Cache of built {@link PruneContext} objects, keyed by the project's\n * `baseDir`. Each context is built exactly once per Node.js process:\n * {@link runIntlayerPurgePipeline} registers the context before running so every\n * subsequent transform is a no-op cache hit.\n */\nconst _pruneContextCache = new Map<string, PruneContext>();\n\n/**\n * Returns the shared {@link PruneContext} for the given base directory, or\n * `null` if {@link intlayerPurgeBabelPlugin} has not yet been initialised for\n * that directory.\n *\n * Used by {@link intlayerMinifyBabelPlugin} to read the rename map without\n * creating a circular dependency.\n */\nexport const getSharedPruneContext = (baseDir: string): PruneContext | null =>\n _pruneContextCache.get(baseDir) ?? null;\n\n// ── Dictionary JSON types ─────────────────────────────────────────────────────\n\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, unknown>;\n};\n\ntype CompiledDictionaryJson = {\n key: string;\n content: TranslationNode | Record<string, unknown>;\n locale?: string;\n [extraKey: string]: unknown;\n};\n\n// ── Type guards ───────────────────────────────────────────────────────────────\n\nconst isTranslationNode = (value: unknown): value is TranslationNode =>\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>).nodeType === 'translation' &&\n typeof (value as Record<string, unknown>).translation === 'object';\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// ── Prune helpers (mirrors intlayerPrunePlugin) ───────────────────────────────\n\ntype PruneResult = {\n prunedDictionary: CompiledDictionaryJson;\n wasRecognised: boolean;\n};\n\n/** Returns a copy of `record` keeping only the keys listed in `usedFieldNames`. */\nconst filterRecordByUsedFields = (\n record: Record<string, unknown>,\n usedFieldNames: Set<string>\n): Record<string, unknown> => {\n const filteredRecord: Record<string, unknown> = {};\n for (const [fieldName, fieldValue] of Object.entries(record)) {\n if (usedFieldNames.has(fieldName)) {\n filteredRecord[fieldName] = fieldValue;\n }\n }\n return filteredRecord;\n};\n\n/**\n * Removes unused fields from a **static** dictionary (all locales in one\n * file). Supports shape A (translation node at the root) and shape B (flat\n * record of translation nodes per field).\n */\nconst pruneStaticDictionaryContent = (\n dictionary: CompiledDictionaryJson,\n usedFieldNames: Set<string>\n): PruneResult => {\n const { content } = dictionary;\n\n // Shape A: { nodeType: \"translation\", translation: { en: { f1, f2 } } }\n if (isTranslationNode(content)) {\n const firstLocaleValue = Object.values(content.translation)[0];\n if (isPlainRecord(firstLocaleValue)) {\n const prunedTranslation: Record<string, unknown> = {};\n for (const [locale, localeContent] of Object.entries(\n content.translation\n )) {\n prunedTranslation[locale] = isPlainRecord(localeContent)\n ? filterRecordByUsedFields(localeContent, usedFieldNames)\n : localeContent;\n }\n return {\n prunedDictionary: {\n ...dictionary,\n content: { ...content, translation: prunedTranslation },\n },\n wasRecognised: true,\n };\n }\n }\n\n // Shape B: { field1: { nodeType: \"translation\", … }, field2: { … } }\n if (isPlainRecord(content) && !isTranslationNode(content)) {\n return {\n prunedDictionary: {\n ...dictionary,\n content: filterRecordByUsedFields(content, usedFieldNames),\n },\n wasRecognised: true,\n };\n }\n\n return { prunedDictionary: dictionary, wasRecognised: false };\n};\n\n/**\n * Removes unused fields from a **dynamic / per-locale** dictionary file\n * (one JSON per locale, flat `content` record).\n */\nconst pruneDynamicDictionaryContent = (\n dictionary: CompiledDictionaryJson,\n usedFieldNames: Set<string>\n): PruneResult => {\n const { content } = dictionary;\n if (!isPlainRecord(content)) {\n return { prunedDictionary: dictionary, wasRecognised: false };\n }\n return {\n prunedDictionary: {\n ...dictionary,\n content: filterRecordByUsedFields(content, usedFieldNames),\n },\n wasRecognised: true,\n };\n};\n\n// ── Minify helpers (mirrors intlayerMinifyPlugin) ─────────────────────────────\n\n/**\n * Recursively renames user-defined content fields using `renameMap`.\n * Translation nodes, arrays, and primitives follow the same traversal rules\n * as in the Vite-based minify plugin.\n */\nconst renameContentRecursively = (\n value: unknown,\n renameMap: NestedRenameMap\n): unknown => {\n if (Array.isArray(value)) {\n return (value as unknown[]).map((element) =>\n renameContentRecursively(element, renameMap)\n );\n }\n if (!value || typeof value !== 'object') return value;\n\n const record = value as Record<string, unknown>;\n\n // Translation node: recurse into each locale value with the same map.\n if (\n typeof record.nodeType === 'string' &&\n record.translation &&\n typeof record.translation === 'object' &&\n !Array.isArray(record.translation)\n ) {\n const renamedTranslation: Record<string, unknown> = {};\n for (const [locale, localeValue] of Object.entries(\n record.translation as Record<string, unknown>\n )) {\n renamedTranslation[locale] = renameContentRecursively(\n localeValue,\n renameMap\n );\n }\n return { ...record, translation: renamedTranslation };\n }\n\n // User-defined record: rename keys and recurse into values.\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(record)) {\n const renameEntry = renameMap.get(key);\n if (renameEntry) {\n result[renameEntry.shortName] = renameContentRecursively(\n val,\n renameEntry.children\n );\n } else {\n result[key] = val;\n }\n }\n return result;\n};\n\n/**\n * Applies a {@link NestedRenameMap} to a parsed dictionary object, renaming\n * only the keys inside `content` while leaving top-level metadata untouched.\n */\nconst applyFieldRenameToDict = (\n dict: Record<string, unknown>,\n renameMap: NestedRenameMap\n): Record<string, unknown> => {\n const content = dict.content;\n if (!content || typeof content !== 'object' || Array.isArray(content))\n return dict;\n return {\n ...dict,\n content: renameContentRecursively(content, renameMap),\n };\n};\n\n// ── Synchronous source-file analysis ─────────────────────────────────────────\n\n/**\n * Runs the usage-analyser Babel plugin synchronously on a single code block,\n * accumulating results into `pruneContext`.\n */\nconst analyzeCodeBlockSync = (\n code: string,\n sourceFilePath: string,\n pruneContext: PruneContext,\n compatCallers?: CompatCallerConfig[]\n): void => {\n try {\n transformSync(code, {\n filename: sourceFilePath,\n plugins: [makeUsageAnalyzerBabelPlugin(pruneContext, { compatCallers })],\n parserOpts: BABEL_PARSER_OPTIONS,\n ast: false,\n code: false,\n });\n } catch {\n pruneContext.hasUnparsableSourceFiles = true;\n }\n};\n\n/**\n * Reads a source file from disk and runs the usage-analyser synchronously.\n * SFC files (Vue / Svelte) are handled by extracting script blocks first.\n */\nconst analyzeSourceFileSync = (\n sourceFilePath: string,\n pruneContext: PruneContext,\n compatCallers?: CompatCallerConfig[]\n): void => {\n let code: string;\n try {\n code = readFileSync(sourceFilePath, 'utf-8');\n } catch {\n return;\n }\n\n const usageCheckRegex = getUsageCheckRegex(compatCallers);\n\n if (!usageCheckRegex.test(code)) return;\n\n const scriptBlocks = extractScriptBlocks(sourceFilePath, code);\n for (const block of scriptBlocks) {\n if (!usageCheckRegex.test(block.content)) continue;\n analyzeCodeBlockSync(\n block.content,\n sourceFilePath,\n pruneContext,\n compatCallers\n );\n }\n};\n\n// ── Build rename maps ─────────────────────────────────────────────────────────\n\n/**\n * Reads compiled dictionary JSON files to build the nested field-rename maps,\n * mirroring the Phase 4 logic in the Vite `intlayerOptimize` plugin's\n * `buildStart` hook. Results are stored in\n * `pruneContext.dictionaryKeyToFieldRenameMap`.\n */\nconst buildRenameMapsSynchronously = (\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n dictionaryKeyToImportModeMap: PurgePluginOptions['dictionaryKeyToImportModeMap'],\n pruneContext: PruneContext,\n logger: PurgeLogger\n): void => {\n let partiallyMinifiedDictionariesCount = 0;\n\n for (const [\n dictionaryKey,\n fieldUsage,\n ] of pruneContext.dictionaryKeyToFieldUsageMap) {\n if (fieldUsage === 'all') continue;\n if (dictionaryKeyToImportModeMap[dictionaryKey] === 'fetch') continue;\n if (pruneContext.dictionariesSkippingFieldRename.has(dictionaryKey))\n continue;\n\n let dictionaryContent: unknown = null;\n\n const staticJsonPath = join(dictionariesDir, `${dictionaryKey}.json`);\n if (existsSync(staticJsonPath)) {\n try {\n const raw = readFileSync(staticJsonPath, 'utf-8');\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n dictionaryContent = parsed.content;\n } catch {\n // Fall through to dynamic dict.\n }\n }\n\n if (!dictionaryContent) {\n const dynamicDirPath = join(dynamicDictionariesDir, dictionaryKey);\n if (existsSync(dynamicDirPath)) {\n try {\n const localeFiles = readdirSync(dynamicDirPath);\n const firstJsonFile = localeFiles.find((file) =>\n file.endsWith('.json')\n );\n if (firstJsonFile) {\n const raw = readFileSync(\n join(dynamicDirPath, firstJsonFile),\n 'utf-8'\n );\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n dictionaryContent = parsed.content;\n }\n } catch {\n // Dictionary not readable – skip rename for this key.\n }\n }\n }\n\n if (!dictionaryContent) continue;\n\n const nestedRenameMap = buildNestedRenameMapFromContent(dictionaryContent);\n\n // Preserve children of opaque values to avoid breaking child components.\n const opaqueFieldMap =\n pruneContext.dictionaryKeysWithOpaqueFields.get(dictionaryKey);\n if (opaqueFieldMap) {\n const dangerousOccurrences = [...opaqueFieldMap.values()].filter(\n (occurrence) =>\n (getNestedRenameEntryAtPath(nestedRenameMap, occurrence.fieldPath)\n ?.children.size ?? 0) > 0\n );\n\n if (dangerousOccurrences.length > 0) {\n partiallyMinifiedDictionariesCount += 1;\n\n logger(\n [\n `Dictionary`,\n colorizeKey(dictionaryKey),\n `partially minified.`,\n ...dangerousOccurrences.flatMap((occurrence) => [\n `\\n Opaque field:`,\n colorize(`'${occurrence.fieldPath.join('.')}'`, ANSIColors.BLUE),\n `(nested keys preserved for stability).`,\n ...occurrence.locations.map(\n (location) => `\\n at ${formatPath(location)}`\n ),\n ]),\n ],\n { level: 'warn', isVerbose: true }\n );\n\n for (const occurrence of dangerousOccurrences) {\n const renameEntry = getNestedRenameEntryAtPath(\n nestedRenameMap,\n occurrence.fieldPath\n );\n if (renameEntry) {\n renameEntry.children = new Map();\n }\n }\n }\n }\n\n if (nestedRenameMap.size > 0) {\n pruneContext.dictionaryKeyToFieldRenameMap.set(\n dictionaryKey,\n nestedRenameMap\n );\n }\n }\n\n if (partiallyMinifiedDictionariesCount > 0) {\n logger([\n `Partially minified`,\n colorizeNumber(partiallyMinifiedDictionariesCount),\n `dictionar${partiallyMinifiedDictionariesCount === 1 ? 'y' : 'ies'}`,\n `(preserved nested keys for opaque fields).`,\n ]);\n }\n};\n\n// ── Dictionary file writing ───────────────────────────────────────────────────\n\n/**\n * Names of the top-level content fields of a compiled dictionary, whatever\n * shape its `content` uses. Used to report which fields the purge removed.\n */\nconst readContentFieldNames = (\n content: CompiledDictionaryJson['content']\n): string[] => {\n // Shape A – fields live inside each locale object.\n if (isTranslationNode(content)) {\n const firstLocaleValue = Object.values(content.translation)[0];\n return isPlainRecord(firstLocaleValue) ? Object.keys(firstLocaleValue) : [];\n }\n\n // Shape B / dynamic – flat content record.\n if (isPlainRecord(content)) return Object.keys(content);\n\n return [];\n};\n\n/**\n * Running totals of the purge, reported once the whole pipeline is done.\n */\ntype PurgeStats = {\n /** Dictionary key → number of fields removed from it. */\n prunedFieldsCountPerDictionary: Map<string, number>;\n /**\n * Dictionary keys whose \"pruned fields\" line has already been printed. A\n * key spans several files (one static, one per locale), and they all remove\n * the same fields.\n */\n loggedPrunedDictionaryKeys: Set<string>;\n /**\n * Dictionary keys whose \"analysis is incomplete\" warning has already been\n * printed, deduplicated the same way.\n */\n loggedIncompleteAnalysisKeys: Set<string>;\n};\n\n/**\n * Reads a compiled dictionary JSON file, applies the purge and/or minify\n * transformations, and writes it back in-place when something changed.\n *\n * `dictionaryKind` selects the prune strategy and the minified output shape:\n * static dictionaries keep `{ key, content }`, dynamic per-locale\n * dictionaries additionally keep `locale`.\n */\nconst processDictionaryFile = (\n filePath: string,\n dictionaryKind: 'static' | 'dynamic',\n pruneContext: PruneContext,\n shouldPurge: boolean,\n shouldMinify: boolean,\n logger: PurgeLogger,\n stats: PurgeStats\n): void => {\n let parsedDict: CompiledDictionaryJson;\n try {\n parsedDict = JSON.parse(\n readFileSync(filePath, 'utf-8')\n ) as CompiledDictionaryJson;\n } catch {\n return; // Unreadable or invalid JSON – leave file unchanged.\n }\n\n const { key: dictionaryKey } = parsedDict;\n\n if (!dictionaryKey) {\n logger(\n [\n `Dictionary file`,\n formatPath(filePath),\n `is missing a \"key\" field. Skipping prune for this file.`,\n ],\n { level: 'warn' }\n );\n return;\n }\n\n if (pruneContext.dictionariesWithEdgeCases.has(dictionaryKey)) return;\n\n let modified = false;\n\n if (shouldPurge) {\n const fieldUsage =\n pruneContext.dictionaryKeyToFieldUsageMap.get(dictionaryKey);\n if (fieldUsage && fieldUsage !== 'all') {\n const pruneDictionaryContent =\n dictionaryKind === 'static'\n ? pruneStaticDictionaryContent\n : pruneDynamicDictionaryContent;\n const originalFieldNames = readContentFieldNames(parsedDict.content);\n const { prunedDictionary, wasRecognised } = pruneDictionaryContent(\n parsedDict,\n fieldUsage\n );\n if (!wasRecognised) {\n pruneContext.dictionariesWithEdgeCases.add(dictionaryKey);\n logger(\n [\n `Unrecognised content structure in dictionary`,\n colorizeKey(dictionaryKey),\n `(file:`,\n `${formatPath(filePath)}).`,\n `Skipping prune for this dictionary.`,\n ],\n { level: 'warn' }\n );\n return;\n }\n\n const removedFieldNames = originalFieldNames.filter(\n (fieldName) => !fieldUsage.has(fieldName)\n );\n\n if (removedFieldNames.length > 0) {\n stats.prunedFieldsCountPerDictionary.set(\n dictionaryKey,\n removedFieldNames.length\n );\n\n if (!stats.loggedPrunedDictionaryKeys.has(dictionaryKey)) {\n stats.loggedPrunedDictionaryKeys.add(dictionaryKey);\n logger(\n [\n `Pruned`,\n colorizeNumber(removedFieldNames.length),\n `unused field${removedFieldNames.length === 1 ? '' : 's'} from`,\n `${colorizeKey(dictionaryKey)}:`,\n removedFieldNames\n .map((fieldName) => colorize(fieldName, ANSIColors.GREY_LIGHT))\n .join(', '),\n ],\n { isVerbose: true }\n );\n }\n }\n\n parsedDict = prunedDictionary;\n modified = true;\n } else if (\n !fieldUsage &&\n pruneContext.hasUnparsableSourceFiles &&\n !stats.loggedIncompleteAnalysisKeys.has(dictionaryKey)\n ) {\n // An unparsable source file might be the one referencing this key, so its\n // usage set cannot be trusted to be empty.\n stats.loggedIncompleteAnalysisKeys.add(dictionaryKey);\n logger(\n [\n `Skipping prune for dictionary`,\n colorizeKey(dictionaryKey),\n `: analysis is incomplete due to earlier source-file parse failures.`,\n ],\n { level: 'warn' }\n );\n }\n }\n\n if (shouldMinify) {\n const fieldRenameMap =\n pruneContext.dictionaryKeyToFieldRenameMap.get(dictionaryKey);\n if (fieldRenameMap && fieldRenameMap.size > 0) {\n parsedDict = applyFieldRenameToDict(\n parsedDict as Record<string, unknown>,\n fieldRenameMap\n ) as CompiledDictionaryJson;\n modified = true;\n }\n }\n\n if (!modified) return;\n\n const outputDict = shouldMinify\n ? dictionaryKind === 'static'\n ? { key: parsedDict.key, content: parsedDict.content }\n : {\n key: parsedDict.key,\n content: parsedDict.content,\n locale: parsedDict.locale,\n }\n : parsedDict;\n\n try {\n writeFileSync(filePath, JSON.stringify(outputDict), 'utf-8');\n } catch {\n // Write failure – leave file unchanged.\n }\n};\n\nconst processAllDictionaryFiles = (\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n pruneContext: PruneContext,\n shouldPurge: boolean,\n shouldMinify: boolean,\n logger: PurgeLogger\n): void => {\n const stats: PurgeStats = {\n prunedFieldsCountPerDictionary: new Map(),\n loggedPrunedDictionaryKeys: new Set(),\n loggedIncompleteAnalysisKeys: new Set(),\n };\n\n if (existsSync(dictionariesDir)) {\n for (const entry of readdirSync(dictionariesDir)) {\n if (!entry.endsWith('.json')) continue;\n processDictionaryFile(\n join(dictionariesDir, entry),\n 'static',\n pruneContext,\n shouldPurge,\n shouldMinify,\n logger,\n stats\n );\n }\n }\n\n if (existsSync(dynamicDictionariesDir)) {\n for (const keyDir of readdirSync(dynamicDictionariesDir)) {\n const keyDirPath = join(dynamicDictionariesDir, keyDir);\n try {\n for (const localeFile of readdirSync(keyDirPath)) {\n if (!localeFile.endsWith('.json')) continue;\n processDictionaryFile(\n join(keyDirPath, localeFile),\n 'dynamic',\n pruneContext,\n shouldPurge,\n shouldMinify,\n logger,\n stats\n );\n }\n } catch {\n // Unreadable key directory – skip.\n }\n }\n }\n\n const totalPrunedFieldsCount = [\n ...stats.prunedFieldsCountPerDictionary.values(),\n ].reduce((total, count) => total + count, 0);\n const totalPrunedDictionariesCount =\n stats.prunedFieldsCountPerDictionary.size;\n\n if (totalPrunedFieldsCount > 0) {\n logger([\n `Pruned`,\n colorizeNumber(totalPrunedFieldsCount),\n `unused field${totalPrunedFieldsCount === 1 ? '' : 's'} across`,\n colorizeNumber(totalPrunedDictionariesCount),\n `dictionar${totalPrunedDictionariesCount === 1 ? 'y' : 'ies'}.`,\n ]);\n }\n};\n\n// ── Reporting helpers ─────────────────────────────────────────────────────────\n\n/**\n * Explains why the requested steps did nothing: the visual editor needs the\n * full dictionary content, so both purge and minify stand down when it is on.\n */\nconst logStepDisabledByEditor = (\n logger: PurgeLogger,\n purge: boolean,\n minify: boolean\n): void => {\n const explainDisabled = (stepLabel: string) =>\n logger([\n stepLabel,\n 'is',\n colorize('disabled', ANSIColors.GREY_DARK),\n 'because',\n colorize('editor.enabled', ANSIColors.BLUE),\n 'is',\n colorize('true', ANSIColors.GREY_DARK),\n colorize(\n '— the editor requires full dictionary content',\n ANSIColors.GREY\n ),\n ]);\n\n if (purge) explainDisabled('Dictionary purge');\n if (minify) explainDisabled('Dictionary minification');\n};\n\n/**\n * Reports the dictionaries whose consumption could not be tracked statically,\n * with the source files responsible — those keep their full content.\n */\nconst logUntrackedBindings = (\n logger: PurgeLogger,\n pruneContext: PruneContext\n): void => {\n for (const [\n dictionaryKey,\n sourceFilePaths,\n ] of pruneContext.dictionaryKeysWithUntrackedBindings) {\n logger(\n [\n `Dictionary`,\n colorizeKey(dictionaryKey),\n `cannot be purged or minified.`,\n `\\n Reason: the result of`,\n `${colorize(`useIntlayer(`, ANSIColors.GREY_LIGHT)}${colorizeKey(\n `'${dictionaryKey}'`\n )}${colorize(`)`, ANSIColors.GREY_LIGHT)}`,\n `is assigned to a plain variable in:`,\n ...sourceFilePaths.map(\n (filePath) => `\\n - ${formatPath(filePath)}`\n ),\n ],\n { level: 'warn' }\n );\n }\n};\n\n// ── Main initialisation ───────────────────────────────────────────────────────\n\n/**\n * Runs the full purge/minify pipeline for the given options, using a\n * module-level cache so the work happens at most once per process per\n * unique `baseDir`.\n *\n * Exported so bundler integrations that do not go through Babel can drive the\n * same pipeline. The Next.js integration is the main consumer: its SWC plugin\n * runs as a per-file Wasm transform with no filesystem access, so the analysis\n * and the dictionary rewrite happen here, in Node, and only the resulting\n * field-rename tables (see {@link serializeFieldRenameMap}) are forwarded to\n * the plugin.\n *\n * **This performs file I/O**: it reads every source file listed in\n * `componentFilesList` and overwrites the compiled dictionary JSON files\n * in-place. Call it at most once per build, after the dictionaries have been\n * built.\n */\nexport const runIntlayerPurgePipeline = (\n options: PurgePluginOptions\n): PruneContext => {\n const {\n baseDir,\n purge,\n minify,\n optimize,\n editorEnabled,\n dictionariesDir,\n dynamicDictionariesDir,\n componentFilesList,\n dictionaryKeyToImportModeMap,\n nestedDictionaryReferences,\n compatCallers,\n logConfig,\n } = options;\n\n const cachedContext = _pruneContextCache.get(baseDir);\n if (cachedContext) return cachedContext;\n\n const pruneContext = createPruneContext();\n _pruneContextCache.set(baseDir, pruneContext);\n\n const logger = getAppLogger(logConfig);\n\n const shouldPurge = purge && !editorEnabled;\n const shouldMinify = minify && !editorEnabled;\n\n if (editorEnabled && (purge || minify)) {\n logStepDisabledByEditor(logger, purge, minify);\n }\n\n if ((!shouldPurge && !shouldMinify) || optimize === false)\n return pruneContext;\n\n // Phase 1: Synchronously analyse all component source files.\n for (const sourceFilePath of componentFilesList) {\n if (!SOURCE_FILE_REGEX.test(sourceFilePath)) continue;\n analyzeSourceFileSync(sourceFilePath, pruneContext, compatCallers);\n }\n\n // Phase 1.5: Keep `nest()` targets resolvable — must run before the rename\n // maps are built so nest targets are excluded from field renaming.\n if (nestedDictionaryReferences) {\n preserveNestedDictionaryFields(pruneContext, nestedDictionaryReferences);\n }\n\n // Phase 1.6: Warn about the dictionaries the analysis could not follow.\n logUntrackedBindings(logger, pruneContext);\n\n // Phase 2: Build field-rename maps (minify only).\n if (shouldMinify) {\n buildRenameMapsSynchronously(\n dictionariesDir,\n dynamicDictionariesDir,\n dictionaryKeyToImportModeMap,\n pruneContext,\n logger\n );\n }\n\n // Phase 3: Write pruned / minified dictionary JSON files to disk.\n processAllDictionaryFiles(\n dictionariesDir,\n dynamicDictionariesDir,\n pruneContext,\n shouldPurge,\n shouldMinify,\n logger\n );\n\n return pruneContext;\n};\n\n// ── Babel plugin ──────────────────────────────────────────────────────────────\n\n/**\n * Babel plugin that analyses all project source files and rewrites compiled\n * dictionary JSON files in-place to remove unused content fields\n * (`build.purge`) and/or rename them to short alphabetic aliases\n * (`build.minify`).\n *\n * All option values must be pre-resolved via {@link getPurgePluginOptions}\n * before being passed here — the plugin does not load the intlayer\n * configuration itself.\n *\n * This plugin performs **file I/O as a side effect**: on the very first Babel\n * transform in a given Node.js process it synchronously scans the component\n * files listed in `options.componentFilesList`, builds field-usage data, and\n * writes the processed dictionaries to disk. Subsequent transforms are\n * no-ops.\n *\n * Source-code field renames (rewriting `content.title` → `content.a`) are\n * handled by the companion {@link intlayerMinifyBabelPlugin}.\n *\n * @example\n * ```js\n * // babel.config.js\n * const {\n * intlayerPurgeBabelPlugin,\n * intlayerMinifyBabelPlugin,\n * intlayerOptimizeBabelPlugin,\n * getPurgePluginOptions,\n * getMinifyPluginOptions,\n * getOptimizePluginOptions,\n * } = require(\"@intlayer/babel\");\n *\n * module.exports = {\n * presets: [\"next/babel\"],\n * plugins: [\n * [intlayerPurgeBabelPlugin, getPurgePluginOptions()],\n * [intlayerMinifyBabelPlugin, getMinifyPluginOptions()],\n * [intlayerOptimizeBabelPlugin, getOptimizePluginOptions()],\n * ],\n * };\n * ```\n *\n * @remarks\n * - Intended for **production builds** only. Dictionary JSON files are\n * overwritten in-place; running `intlayer build` afterwards restores the\n * originals.\n * - The plugin is a no-op when `optimize` is `false` or `editorEnabled` is\n * `true`.\n */\nexport const intlayerPurgeBabelPlugin = (_babel: {\n types: typeof BabelTypes;\n}): PluginObject => ({\n name: 'intlayer-purge',\n\n pre(this: PluginPass) {\n runIntlayerPurgePipeline(this.opts as PurgePluginOptions);\n },\n\n visitor: {\n // No AST transforms: all work is done as a side effect in pre().\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoJA,MAAM,qCAAqB,IAAI,IAA0B;;;;;;;;;AAUzD,MAAa,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F,4EAA+B,cAAc,0BAA0B;CAIzE,qBAAqB,QAAQ,YAAY;CAGzC,IAAI,cACF,6BACE,iBACA,wBACA,8BACA,cACA,MACF;CAIF,0BACE,iBACA,wBACA,cACA,aACA,cACA,MACF;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,MAAa,4BAA4B,YAEpB;CACnB,MAAM;CAEN,MAAsB;EACpB,yBAAyB,KAAK,IAA0B;CAC1D;CAEA,SAAS,CAET;AACF"}
|
|
@@ -11,6 +11,50 @@ const createPruneContext = () => ({
|
|
|
11
11
|
dictionariesSkippingFieldRename: /* @__PURE__ */ new Set(),
|
|
12
12
|
pendingFrameworkAnalysis: /* @__PURE__ */ new Map()
|
|
13
13
|
});
|
|
14
|
+
/**
|
|
15
|
+
* Records `nest()` references in a prune context so nest targets stay
|
|
16
|
+
* resolvable — and no larger than they need to be — after purge and minify.
|
|
17
|
+
*
|
|
18
|
+
* A nested node stores the ORIGINAL dot path of the field it reads
|
|
19
|
+
* (`nest('common', 'period')` → `'period'`) and `getNesting` resolves it at
|
|
20
|
+
* runtime against the compiled JSON. That drives three adjustments:
|
|
21
|
+
*
|
|
22
|
+
* - Nest targets never take part in field renaming, since the stored path
|
|
23
|
+
* would no longer match the renamed keys.
|
|
24
|
+
* - A target already consumed by a call site keeps its analysed fields plus
|
|
25
|
+
* the nested ones, so neither consumer loses content.
|
|
26
|
+
* - A target reached *only* through `nest()` is given a usage entry holding
|
|
27
|
+
* exactly the nested fields. Without one, the purge pass leaves the whole
|
|
28
|
+
* dictionary untouched; with one, it trims the dictionary down to what the
|
|
29
|
+
* nest references actually read. This matters most for `dynamic` / `fetch`
|
|
30
|
+
* dictionaries, whose full static snapshot would otherwise be pulled into
|
|
31
|
+
* the eager bundle just to satisfy a single nested field.
|
|
32
|
+
*
|
|
33
|
+
* Seeding is skipped when a source file failed to parse: that file could
|
|
34
|
+
* reference the dictionary in a way the analysis never saw, which is the same
|
|
35
|
+
* guard the purge pass applies to keys with no usage entry.
|
|
36
|
+
*
|
|
37
|
+
* @param pruneContext - Shared analysis state to update in place.
|
|
38
|
+
* @param nestedDictionaryReferences - Nest-target key → referenced top-level
|
|
39
|
+
* fields, as returned by `getNestedDictionaryReferences`.
|
|
40
|
+
*/
|
|
41
|
+
const preserveNestedDictionaryFields = (pruneContext, nestedDictionaryReferences) => {
|
|
42
|
+
for (const [dictionaryKey, nestedFields] of nestedDictionaryReferences.entries()) {
|
|
43
|
+
pruneContext.dictionariesSkippingFieldRename.add(dictionaryKey);
|
|
44
|
+
const currentFieldUsage = pruneContext.dictionaryKeyToFieldUsageMap.get(dictionaryKey);
|
|
45
|
+
if (nestedFields === "all") {
|
|
46
|
+
pruneContext.dictionaryKeyToFieldUsageMap.set(dictionaryKey, "all");
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (!currentFieldUsage) {
|
|
50
|
+
if (pruneContext.hasUnparsableSourceFiles) continue;
|
|
51
|
+
pruneContext.dictionaryKeyToFieldUsageMap.set(dictionaryKey, new Set(nestedFields));
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (currentFieldUsage === "all") continue;
|
|
55
|
+
for (const nestedField of nestedFields) currentFieldUsage.add(nestedField);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
14
58
|
/** Canonical intlayer caller names that trigger usage analysis. */
|
|
15
59
|
const INTLAYER_CALLER_NAMES = ["useIntlayer", "getIntlayer"];
|
|
16
60
|
/**
|
|
@@ -607,4 +651,5 @@ exports.DEFAULT_COMPAT_CALLERS = DEFAULT_COMPAT_CALLERS;
|
|
|
607
651
|
exports.INTLAYER_CALLER_NAMES = INTLAYER_CALLER_NAMES;
|
|
608
652
|
exports.createPruneContext = createPruneContext;
|
|
609
653
|
exports.makeUsageAnalyzerBabelPlugin = makeUsageAnalyzerBabelPlugin;
|
|
654
|
+
exports.preserveNestedDictionaryFields = preserveNestedDictionaryFields;
|
|
610
655
|
//# sourceMappingURL=babel-plugin-intlayer-usage-analyzer.cjs.map
|