@discord/metro-intl-transformer 0.0.2-rc.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +3 -41
  2. package/package.json +8 -5
  3. package/watcher.js +88 -0
package/index.js CHANGED
@@ -1,5 +1,3 @@
1
- const crypto = require('node:crypto');
2
- const fs = require('node:fs/promises');
3
1
  const path = require('node:path');
4
2
  const {
5
3
  isMessageDefinitionsFile,
@@ -8,10 +6,6 @@ const {
8
6
 
9
7
  const { database } = require('./src/database');
10
8
  const { MessageDefinitionsTransformer } = require('./src/transformer');
11
- const {
12
- ensureVirtualTranslationsModulesDirectory,
13
- getVirtualTranslationsModulePath,
14
- } = require('./src/virtual-modules');
15
9
 
16
10
  /**
17
11
  * @param {{
@@ -20,7 +14,6 @@ const {
20
14
  * getPrelude: () => string
21
15
  * getTranslationAssetExtension: () => string,
22
16
  * createAssetImport: (importPath: string) => string,
23
- * virtualModulesDir: string
24
17
  * }} options
25
18
  * @returns
26
19
  */
@@ -30,10 +23,7 @@ async function transformToString({
30
23
  getPrelude,
31
24
  getTranslationAssetExtension,
32
25
  createAssetImport,
33
- virtualModulesDir,
34
26
  }) {
35
- ensureVirtualTranslationsModulesDirectory(virtualModulesDir);
36
-
37
27
  if (isMessageDefinitionsFile(filename)) {
38
28
  database.processDefinitionsFileContent(filename, src);
39
29
  const sourceFile = database.getSourceFile(filename);
@@ -43,7 +33,6 @@ async function transformToString({
43
33
  );
44
34
  }
45
35
 
46
- // TODO: This should be built inside the native extension instead.
47
36
  const locales = database.getKnownLocales();
48
37
  /** @type {Record<string, string>} */
49
38
  const localeMap = {};
@@ -51,35 +40,8 @@ async function transformToString({
51
40
  localeMap[locale] =
52
41
  `${sourceFile.meta.translationsPath}/${locale}.${getTranslationAssetExtension()}`;
53
42
  }
54
-
55
- // Metro's file map and worker model means that there's a disconnect
56
- // between a file getting written to the system and when Metro actually
57
- // becomes aware of it. This is _hideous_, but neither Watchman nor the
58
- // default FSEventsWatcher will have updated in time for the second part
59
- // of this transformation to be able to resolve the newly-created compiled
60
- // file. Waiting for a little bit (hopefully) gives it enough time to catch
61
- // the event and successfully compile the added dependency.
62
- //
63
- // Metro also hyper-caches everything that gets transformed, with no way to
64
- // access and invalidate entries from that cache just from a file name. This
65
- // fileHash gives a way to ensure that most changes to the source file will
66
- // guarantee a cache miss and pick up the newly-compiled asset. Because the
67
- // file is created on the fly inside of this transformer, if Metro decides
68
- // that the source file doesn't need to be transformed again (i.e., make a
69
- // change, save, then undo the change), the compiled file won't get
70
- // reverted. Versioning through the fileHash means that when the cached
71
- // transform is loaded, it will point _back_ to the version of the compiled
72
- // file with the matching content.
73
- const fileHash = crypto.createHash('md5').update(src).digest('hex');
74
- const virtualModulePath = getVirtualTranslationsModulePath(
75
- virtualModulesDir,
76
- `${filename}.compiled.${fileHash}.${getTranslationAssetExtension()}`,
77
- );
78
- await fs.writeFile(virtualModulePath, database.precompileToBuffer('en-US'));
79
- await new Promise((resolve) => {
80
- setTimeout(resolve, 400);
81
- });
82
- localeMap['en-US'] = virtualModulePath;
43
+ const fileBasename = filename.substring(0, filename.lastIndexOf('.messages.js'));
44
+ localeMap['en-US'] = path.dirname(fileBasename + '.compiled.messages.jsona');
83
45
 
84
46
  const transformer = new MessageDefinitionsTransformer(
85
47
  database.getSourceFileHashedKeys(filename),
@@ -92,7 +54,7 @@ async function transformToString({
92
54
  } else if (isMessageTranslationsFile(filename)) {
93
55
  const localeName = path.basename(filename).split('.')[0];
94
56
  database.processTranslationFileContent(filename, localeName, src);
95
- return database.precompileToBuffer(localeName);
57
+ return database.precompileToBuffer(filename, localeName);
96
58
  }
97
59
  }
98
60
 
package/package.json CHANGED
@@ -1,19 +1,22 @@
1
1
  {
2
2
  "name": "@discord/metro-intl-transformer",
3
- "version": "0.0.2-rc.1",
3
+ "version": "0.0.3",
4
4
  "license": "MIT",
5
5
  "description": "Metro/Babel transformer plugin for compiling, bundling, and minifying intl message definitions and usages using intl-message-database.",
6
6
  "exports": {
7
7
  ".": "./index.js",
8
8
  "./babel-plugin": "./babel-plugin.js",
9
- "./resolver": "./resolver.js",
10
- "./.cache/*": "./.cache/*"
9
+ "./watcher": "./watcher.js"
11
10
  },
12
11
  "dependencies": {
13
- "@discord/intl-message-database": "0.0.2-rc.1"
12
+ "chokidar": "^3.6.0",
13
+ "debug": "^4.3.6",
14
+ "fast-glob": "^3.3.2",
15
+ "@discord/intl-message-database": "0.0.3"
14
16
  },
15
17
  "devDependencies": {
16
18
  "@babel/types": "^7.24.9",
17
- "@types/babel__traverse": "7.20.6"
19
+ "@types/babel__traverse": "7.20.6",
20
+ "@types/debug": "^4.1.12"
18
21
  }
19
22
  }
package/watcher.js ADDED
@@ -0,0 +1,88 @@
1
+ const path = require('node:path');
2
+
3
+ const chokidar = require('chokidar');
4
+ const fg = require('fast-glob');
5
+ const debug = require('debug')('intl:metro-intl-transformer:watcher');
6
+
7
+ const { database } = require('./src/database');
8
+ const {
9
+ IntlCompiledMessageFormat,
10
+ isMessageDefinitionsFile,
11
+ } = require('@discord/intl-message-database');
12
+
13
+ const IGNORE_PATTERNS = [
14
+ // Ignore our own compiled message files, even though they shouldn't have a matching extension.
15
+ '*.compiled.messages.*',
16
+ // Also ignore a bunch of default folders that just make globs/watches take forever.
17
+ '**/node_modules/**',
18
+ '**/target/**',
19
+ '**/native/**',
20
+ '**/dist/**',
21
+ '**/build/**',
22
+ '**/cache/**',
23
+ '**/.cache/**',
24
+ '**/__pycache__/**',
25
+ ];
26
+ const MESSAGE_DEFINITION_FILE_PATTERNS = ['*.messages.js'];
27
+ const DEFAULT_LOCALE = 'en-US';
28
+
29
+ /**
30
+ * @param {string} filePath
31
+ */
32
+ function processFile(filePath) {
33
+ if (!isMessageDefinitionsFile(filePath)) {
34
+ return;
35
+ }
36
+ debug(`Processing file: ${filePath}`);
37
+ try {
38
+ // Convert the file name from `.messages.js` to `.compiled.messages.jsona` for output.
39
+ const fileBasename = filePath.substring(0, filePath.lastIndexOf('.messages.js'));
40
+ const outputPath = path.resolve(
41
+ path.dirname(filePath),
42
+ `${fileBasename}.compiled.messages.jsona`,
43
+ );
44
+
45
+ database.processDefinitionsFile(filePath);
46
+ database.precompile(filePath, 'en-US', outputPath, IntlCompiledMessageFormat.Json);
47
+ } catch (e) {
48
+ debug('[INTL Error] Failed to compile messages');
49
+ console.error(e);
50
+ }
51
+ }
52
+
53
+ /**
54
+ * @param {string[]} watchedFolders
55
+ * @param {{
56
+ * watch?: boolean
57
+ * }} options
58
+ */
59
+ async function compileIntlMessageFiles(watchedFolders, { watch = true } = {}) {
60
+ const globs = watchedFolders.flatMap((folder) => path.join(folder, '**/*.messages.js'));
61
+
62
+ // Perform one initial scan and compilation to ensure all files exist before Metro might try to
63
+ // resolve them.
64
+ debug('Scanning for initial messages files');
65
+ for await (const filePath of fg.stream(globs, {
66
+ ignore: IGNORE_PATTERNS,
67
+ absolute: true,
68
+ onlyFiles: true,
69
+ followSymbolicLinks: false,
70
+ })) {
71
+ processFile(filePath.toString());
72
+ }
73
+ debug('Initial message scan completed.');
74
+
75
+ if (watch) {
76
+ debug(`Setting up file watching for configured paths:\n- ${globs.join('\n- ')}`);
77
+ chokidar
78
+ .watch(globs, { ignored: IGNORE_PATTERNS, ignoreInitial: true })
79
+ .on('all', (event, filePath) => {
80
+ debug(`Got event ${event} for ${filePath}`);
81
+ processFile(filePath);
82
+ });
83
+ } else {
84
+ debug('Not watching files because `watch` option was false');
85
+ }
86
+ }
87
+
88
+ module.exports = { compileIntlMessageFiles };