@discord/metro-intl-transformer 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Discord, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,69 @@
1
+ const { isMessageDefinitionsFile, hashMessageKey } = require('@discord/intl-message-database');
2
+
3
+ /**
4
+ * Babel plugin for obfuscating and minifying intl message _usages_, like
5
+ * turning `intl.format(messages.SOME_LONG_MESSAGE_KEY_NAME)` into
6
+ * `intl.format(messages['f21c/3'])`. This transform gets applied to every
7
+ * file in the project, but only member expressions of imports from
8
+ * `.messages.js` files are considered and affected.
9
+ *
10
+ * @param {any} babel - The Babel core object.
11
+ * @returns {{visitor: import("babel__traverse").Visitor}} A visitor object for the Babel transform.
12
+ */
13
+ module.exports = function metroIntlTransformerPlugin(babel) {
14
+ /** @type {{types: import("@babel/types")}} */
15
+ const { types: t } = babel;
16
+
17
+ return {
18
+ visitor: {
19
+ ImportDeclaration(path, _state) {
20
+ const importSource = path.node.source.value;
21
+ // This transformer only handles usages of intl messages, so only
22
+ // imports of definitions files need to be handled.
23
+ if (!isMessageDefinitionsFile(importSource)) {
24
+ return;
25
+ }
26
+
27
+ const defaultImport = path.node.specifiers.find(
28
+ (specifier) => specifier.type === 'ImportDefaultSpecifier',
29
+ );
30
+ const bindingName = defaultImport?.local.name;
31
+ if (bindingName == null) {
32
+ return;
33
+ }
34
+
35
+ const binding = path.scope.bindings[bindingName];
36
+ for (const reference of binding.referencePaths) {
37
+ const parent = reference.parent;
38
+ // We only care about member expressions that use the `.` syntax or
39
+ // use string literals, since other syntaxes could be invalid.
40
+ if (
41
+ parent.type !== 'MemberExpression' ||
42
+ (parent.computed && parent.property.type !== 'StringLiteral')
43
+ ) {
44
+ continue;
45
+ }
46
+
47
+ // We just want the actual value of the member being accessed.
48
+ /** @type {string} */
49
+ const memberName = (() => {
50
+ switch (parent.property.type) {
51
+ case 'StringLiteral':
52
+ return parent.property.value;
53
+ case 'Identifier':
54
+ return parent.property.name;
55
+ default:
56
+ throw new Error(
57
+ '[INTL] Encountered a member expression with neither an identifier nor string literal member node',
58
+ );
59
+ }
60
+ })();
61
+
62
+ // Then hash it up and re-write the member with the hashed version.
63
+ parent.computed = true;
64
+ parent.property = t.stringLiteral(hashMessageKey(memberName));
65
+ }
66
+ },
67
+ },
68
+ };
69
+ };
package/index.js ADDED
@@ -0,0 +1,99 @@
1
+ const crypto = require('node:crypto');
2
+ const fs = require('node:fs/promises');
3
+ const path = require('node:path');
4
+ const {
5
+ isMessageDefinitionsFile,
6
+ isMessageTranslationsFile,
7
+ } = require('@discord/intl-message-database');
8
+
9
+ const { database } = require('./src/database');
10
+ const { MessageDefinitionsTransformer } = require('./src/transformer');
11
+ const {
12
+ ensureVirtualTranslationsModulesDirectory,
13
+ getVirtualTranslationsModulePath,
14
+ } = require('./src/virtual-modules');
15
+
16
+ /**
17
+ * @param {{
18
+ * filename: string,
19
+ * src: string,
20
+ * getPrelude: () => string
21
+ * getTranslationAssetExtension: () => string,
22
+ * createAssetImport: (importPath: string) => string,
23
+ * virtualModulesDir: string
24
+ * }} options
25
+ * @returns
26
+ */
27
+ async function transformToString({
28
+ filename,
29
+ src,
30
+ getPrelude,
31
+ getTranslationAssetExtension,
32
+ createAssetImport,
33
+ virtualModulesDir,
34
+ }) {
35
+ ensureVirtualTranslationsModulesDirectory(virtualModulesDir);
36
+
37
+ if (isMessageDefinitionsFile(filename)) {
38
+ database.processDefinitionsFileContent(filename, src);
39
+ const sourceFile = database.getSourceFile(filename);
40
+ if (sourceFile.type !== 'definition') {
41
+ throw new Error(
42
+ 'Expected an intl messages definition file, but found a translation file instead.',
43
+ );
44
+ }
45
+
46
+ // TODO: This should be built inside the native extension instead.
47
+ const locales = database.getKnownLocales();
48
+ /** @type {Record<string, string>} */
49
+ const localeMap = {};
50
+ for (const locale of locales) {
51
+ localeMap[locale] =
52
+ `${sourceFile.meta.translationsPath}/${locale}.${getTranslationAssetExtension()}`;
53
+ }
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;
83
+
84
+ const transformer = new MessageDefinitionsTransformer(
85
+ database.getSourceFileHashedKeys(filename),
86
+ localeMap,
87
+ createAssetImport,
88
+ getPrelude,
89
+ );
90
+
91
+ return transformer.getOutput();
92
+ } else if (isMessageTranslationsFile(filename)) {
93
+ const localeName = path.basename(filename).split('.')[0];
94
+ database.processTranslationFileContent(filename, localeName, src);
95
+ return database.precompileToBuffer(localeName);
96
+ }
97
+ }
98
+
99
+ module.exports = { transformToString };
package/package.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "@discord/metro-intl-transformer",
3
+ "version": "0.0.1",
4
+ "license": "MIT",
5
+ "description": "Metro/Babel transformer plugin for compiling, bundling, and minifying intl message definitions and usages using intl-message-database.",
6
+ "exports": {
7
+ ".": "./index.js",
8
+ "./babel-plugin": "./babel-plugin.js",
9
+ "./resolver": "./resolver.js",
10
+ "./.cache/*": "./.cache/*"
11
+ },
12
+ "dependencies": {
13
+ "@discord/intl-message-database": "0.0.1"
14
+ },
15
+ "devDependencies": {
16
+ "@babel/types": "^7.24.9",
17
+ "@types/babel__traverse": "7.20.6"
18
+ }
19
+ }
@@ -0,0 +1,9 @@
1
+ const {IntlMessagesDatabase} = require('@discord/intl-message-database');
2
+
3
+ /**
4
+ * A shared message database instance that's used and shared across all parts
5
+ * of the loader and plugin together.
6
+ */
7
+ const database = new IntlMessagesDatabase();
8
+
9
+ module.exports = {database};
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Common class for parsing and transforming the content of a messages
3
+ * definition file (e.g., "SomeFeature.messages.js") into a production-ready
4
+ * version, with string keys obfuscated, loading harnesses configured, and
5
+ * more.
6
+ *
7
+ * This transformation is intended to be used alongside the consumer
8
+ * transforms implemented as SWC and Babel plugins, which transform the
9
+ * callsites for messages into matching formats. Consider this input example:
10
+ *
11
+ * ```typescript
12
+ * // SomeModule.messages.js
13
+ * import {defineMessages} from '@discord/intl';
14
+ *
15
+ * export default defineMessages({
16
+ * THIS_IS_A_MESSAGE: 'it has some content with {values}',
17
+ * });
18
+ *
19
+ * // SomeConsumer.tsx
20
+ * import someModuleMessages from 'SomeModule.messages.js';
21
+ * i18n.format(someModuleMessages.THIS_IS_A_MESSAGE, {values: "i'm a value!"});
22
+ * ```
23
+ *
24
+ * This transformer will only handle `SomeModule.messages.js`, and will output
25
+ * something like:
26
+ *
27
+ * ```typescript
28
+ * const {i18n} = require('@discord/intl');
29
+ * const MESSAGE_KEYS = ["a9fn23"]
30
+ * const loader = createLoader(MESSAGE_KEYS, {"en-US": () => require('./messages/en-US.messages.jsona')});
31
+ * export default MESSAGE_KEYS.reduce((acc, k) => {acc[k] = loader.bindFor(k); return acc}, {});
32
+ * ```
33
+ *
34
+ * Notice how the message keys have been hashed into short keys, and the
35
+ * dynamic imports for each locale's data have been inserted automatically.
36
+ *
37
+ * The SWC and Babel transformers then take care of the second file,
38
+ * transforming the usage to use the hashed keys:
39
+ *
40
+ * ```typescript
41
+ * import someModuleMessages from 'SomeModule.messages.js';
42
+ * i18n.format(someModuleMessages["a9fn23"], {values: "i'm a value!"});
43
+ * ```
44
+ */
45
+ class MessageDefinitionsTransformer {
46
+ /**
47
+ * @param {string[]} messageKeys The list of hashed message keys that this file manages.
48
+ * @param {Record<string, string>} localeMap A map of locale names to paths used for importing translations.
49
+ * @param {() => string} getPrelude A function that returns a prelude to inject at the start of the transformed file.
50
+ * @param {(importPath: string) => string} createAssetImport A function to generate a require statement for the compiled asset file.
51
+ */
52
+ constructor(messageKeys, localeMap, createAssetImport, getPrelude) {
53
+ this.messageKeys = messageKeys;
54
+ this.localeMap = localeMap;
55
+ this.getPrelude = getPrelude;
56
+ this.createAssetImport = createAssetImport;
57
+ }
58
+
59
+ /**
60
+ * Returns a compiled string for an object that maps locale names to a
61
+ * dynamic require function for that locale, based on the supported locales
62
+ * that were determined for this file. The shape ends up as:
63
+ *
64
+ * ```typescript
65
+ * {
66
+ * "en-US": () => import("path/to/en-US.json"),
67
+ * }
68
+ * ```
69
+ *
70
+ * @returns {string}
71
+ */
72
+ getLocaleRequireMap() {
73
+ const localeProperties = [];
74
+ for (const [locale, importPath] of Object.entries(this.localeMap)) {
75
+ // leading `./`, which is necessary for the bundler to be able to
76
+ // NOTE: This doesn't use `path.join` because it will remove any
77
+ // resolve the import as a relative path.
78
+ // This also assumes that the author has specified `translationsPath`
79
+ // as a properly-resolvable path for the bundler, which we can't easily
80
+ // enforce, unfortunately.
81
+ localeProperties.push(
82
+ `"${locale}": () => ${this.createAssetImport(importPath)}.then((data) => ({default: data}))`,
83
+ );
84
+ }
85
+
86
+ return `{${localeProperties.join(',')}}`;
87
+ }
88
+
89
+ /**
90
+ * Returns the reduced, transformed output for this file. Currently not
91
+ * configurable, but could be told to include default messages or preserve
92
+ * information as necessary.
93
+ */
94
+ getOutput() {
95
+ const messageKeys = this.messageKeys;
96
+
97
+ const i18nImport = `const {createLoader} = require('@discord/intl');`;
98
+ const keysDefinition = `const _keys = ${JSON.stringify(messageKeys)};`;
99
+ const localeMapDefinition = `const _locales = ${this.getLocaleRequireMap()};`;
100
+ const loaderDefinition = 'const loader = createLoader(_keys, _locales);';
101
+ const messagesExport = 'export default loader.getBinds();';
102
+
103
+ return [
104
+ this.getPrelude(),
105
+ i18nImport,
106
+ keysDefinition,
107
+ localeMapDefinition,
108
+ loaderDefinition,
109
+ messagesExport,
110
+ ].join('\n');
111
+ }
112
+ }
113
+
114
+ module.exports = {
115
+ MessageDefinitionsTransformer,
116
+ };
@@ -0,0 +1,30 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+
4
+ /**
5
+ * Ensure the configured cache directory exists so that files can be read from and written to it.
6
+ * Call this once when Metro is first started to ensure that the folder exists and has been
7
+ * cleaned.
8
+ *
9
+ * @param {string} cacheDir
10
+ */
11
+ function ensureVirtualTranslationsModulesDirectory(cacheDir) {
12
+ fs.mkdirSync(cacheDir, { recursive: true });
13
+ }
14
+
15
+ /**
16
+ * Returns the absolute path to the virtual translations module that
17
+ * `moduleName` should resolve to.
18
+ * @param {string} cacheDir
19
+ * @param {string} moduleName
20
+ * @returns {string}
21
+ */
22
+ function getVirtualTranslationsModulePath(cacheDir, moduleName) {
23
+ const resolvedModuleName = moduleName.replace(/[\/\\]+/g, '+').replace(/[:\?<>"\*\|]/g, '!');
24
+ return path.resolve(cacheDir, resolvedModuleName);
25
+ }
26
+
27
+ module.exports = {
28
+ ensureVirtualTranslationsModulesDirectory,
29
+ getVirtualTranslationsModulePath,
30
+ };