@react-native-oh/react-native-harmony-cli 0.0.15

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/.prettierrc ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "trailingComma": "es5",
3
+ "tabWidth": 2,
4
+ "semi": true,
5
+ "singleQuote": true
6
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getAssetDestRelativePath = void 0;
4
+ function getAssetDestRelativePath(asset) {
5
+ const fileName = getResourceIdentifier(asset);
6
+ return `${fileName}.${asset.type}`;
7
+ }
8
+ exports.getAssetDestRelativePath = getAssetDestRelativePath;
9
+ function getResourceIdentifier(asset) {
10
+ const folderPath = getBasePath(asset);
11
+ return `${folderPath}/${asset.name}`
12
+ .toLowerCase()
13
+ .replace(/\//g, '_') // Encode folder structure in file name
14
+ .replace(/([^a-z0-9_])/g, '') // Remove illegal chars
15
+ .replace(/^assets_/, ''); // Remove "assets_" prefix
16
+ }
17
+ function getBasePath(asset) {
18
+ let basePath = asset.httpServerLocation;
19
+ if (basePath[0] === '/') {
20
+ basePath = basePath.substr(1);
21
+ }
22
+ return basePath;
23
+ }
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.commandBundleHarmony = void 0;
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const fs_extra_1 = __importDefault(require("fs-extra"));
18
+ const metro_1 = __importDefault(require("metro"));
19
+ const Server_1 = __importDefault(require("metro/src/Server"));
20
+ const path_1 = __importDefault(require("path"));
21
+ const assetResolver_1 = require("../assetResolver");
22
+ const ARK_RESOURCE_PATH = './harmony/entry/src/main/resources/rawfile';
23
+ const ASSETS_DEFAULT_DEST_PATH = './harmony/entry/src/main/resources/rawfile/assets';
24
+ exports.commandBundleHarmony = {
25
+ name: 'bundle-harmony',
26
+ description: 'Creates JS bundle, creates a special cpp header containing the JS code, copies assets directory to the project.',
27
+ options: [
28
+ {
29
+ name: '--dev [boolean]',
30
+ description: 'If false, warnings are disabled and the bundle is minified',
31
+ parse: (val) => val !== 'false',
32
+ default: true,
33
+ },
34
+ {
35
+ name: '--entry-file <path>',
36
+ description: 'Path to the root JS file, either absolute or relative to JS root',
37
+ default: 'index.js',
38
+ },
39
+ {
40
+ name: '--config <path>',
41
+ description: 'Path to the Metro configuration file',
42
+ },
43
+ {
44
+ name: '--bundle-output <path>',
45
+ description: 'File name where to store the resulting bundle, ex. /tmp/groups.bundle',
46
+ default: ARK_RESOURCE_PATH + '/bundle.harmony.js',
47
+ },
48
+ {
49
+ name: '--assets-dest <path>',
50
+ description: 'Directory name where to store assets referenced in the bundle',
51
+ default: ASSETS_DEFAULT_DEST_PATH,
52
+ },
53
+ {
54
+ name: '--sourcemap-output <path>',
55
+ description: 'File name where to store the resulting source map, ex. /tmp/groups.map',
56
+ },
57
+ {
58
+ name: '--minify [boolean]',
59
+ description: 'Allows overriding whether bundle is minified',
60
+ parse: (val) => val !== 'false',
61
+ },
62
+ ],
63
+ func: (argv, config, args) => __awaiter(void 0, void 0, void 0, function* () {
64
+ const buildOptions = {
65
+ entry: args.entryFile,
66
+ platform: 'harmony',
67
+ minify: args.minify !== undefined ? args.minify : !args.dev,
68
+ dev: args.dev,
69
+ sourceMap: args.sourcemapOutput,
70
+ sourceMapUrl: args.sourcemapOutput,
71
+ };
72
+ const metroConfig = yield loadMetroConfig(args.config);
73
+ const bundle = yield createBundle(metroConfig, buildOptions);
74
+ yield saveBundle(bundle, args.bundleOutput, args.sourcemapOutput);
75
+ const assets = yield retrieveAssetsData(metroConfig, buildOptions);
76
+ copyAssets(assets, args.assetsDest);
77
+ }),
78
+ };
79
+ function loadMetroConfig(configPath) {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ return configPath
82
+ ? yield metro_1.default.loadConfig({ config: configPath })
83
+ : yield metro_1.default.loadConfig();
84
+ });
85
+ }
86
+ function createBundle(metroConfig, buildOptions) {
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ // casting needed as Metro.runBuild returns Promise<{code: string, map: string}>
89
+ // despite being typed as Promise<void>
90
+ return (yield metro_1.default.runBuild(metroConfig, buildOptions));
91
+ });
92
+ }
93
+ function saveBundle(bundle, bundleOutput, sourceMapOutput) {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ yield fs_extra_1.default.ensureDir(path_1.default.dirname(bundleOutput));
96
+ fs_1.default.writeFileSync(bundleOutput, bundle.code);
97
+ console.log(`[CREATED] ${bundleOutput}`);
98
+ if (sourceMapOutput) {
99
+ fs_1.default.writeFileSync(sourceMapOutput, bundle.map);
100
+ console.log(`[CREATED] ${sourceMapOutput}`);
101
+ }
102
+ });
103
+ }
104
+ function retrieveAssetsData(metroConfig, buildOptions) {
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ const metroServer = new Server_1.default(metroConfig);
107
+ try {
108
+ return yield metroServer.getAssets(Object.assign(Object.assign(Object.assign({}, Server_1.default.DEFAULT_BUNDLE_OPTIONS), buildOptions), { entryFile: buildOptions.entry, bundleType: 'todo' }));
109
+ }
110
+ finally {
111
+ metroServer.end();
112
+ }
113
+ });
114
+ }
115
+ function copyAssets(assetsData, assetsDest) {
116
+ return __awaiter(this, void 0, void 0, function* () {
117
+ if (assetsDest == null) {
118
+ console.warn('Assets destination folder is not set, skipping...');
119
+ return;
120
+ }
121
+ yield fs_extra_1.default.ensureDir(assetsDest);
122
+ const fileDestBySrc = {};
123
+ for (const asset of assetsData) {
124
+ const idx = getHighestQualityFileIdx(asset);
125
+ fileDestBySrc[asset.files[idx]] = path_1.default.join(assetsDest, (0, assetResolver_1.getAssetDestRelativePath)(asset));
126
+ }
127
+ return copyFiles(fileDestBySrc);
128
+ });
129
+ }
130
+ function getHighestQualityFileIdx(assetData) {
131
+ let result = 0;
132
+ let maxScale = -1;
133
+ for (let idx = 0; idx < assetData.scales.length; idx++) {
134
+ const scale = assetData.scales[idx];
135
+ if (scale > maxScale) {
136
+ maxScale = scale;
137
+ result = idx;
138
+ }
139
+ }
140
+ return result;
141
+ }
142
+ function copyFiles(fileDestBySrc) {
143
+ const fileSources = Object.keys(fileDestBySrc);
144
+ if (fileSources.length === 0) {
145
+ return Promise.resolve();
146
+ }
147
+ console.info(`Copying ${fileSources.length} asset files`);
148
+ return new Promise((resolve, reject) => {
149
+ const copyNext = (error) => {
150
+ if (error) {
151
+ reject(error);
152
+ return;
153
+ }
154
+ if (fileSources.length === 0) {
155
+ console.info('Done copying assets');
156
+ resolve();
157
+ }
158
+ else {
159
+ // fileSources.length === 0 is checked in previous branch, so this is string
160
+ const src = fileSources.shift();
161
+ const dest = fileDestBySrc[src];
162
+ copyFile(src, dest, copyNext);
163
+ }
164
+ };
165
+ copyNext();
166
+ });
167
+ }
168
+ function copyFile(src, dest, onFinished) {
169
+ const destDir = path_1.default.dirname(dest);
170
+ fs_1.default.mkdir(destDir, { recursive: true }, (err) => {
171
+ if (err) {
172
+ onFinished(err);
173
+ return;
174
+ }
175
+ fs_1.default.createReadStream(src)
176
+ .pipe(fs_1.default.createWriteStream(dest))
177
+ .on('finish', onFinished);
178
+ });
179
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./bundle-harmony"), exports);
18
+ __exportStar(require("./pack-harmony"), exports);
19
+ __exportStar(require("./unpack-harmony"), exports);
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.commandPackHarmony = void 0;
16
+ const glob_1 = require("glob");
17
+ const path_1 = __importDefault(require("path"));
18
+ const tar_1 = __importDefault(require("tar"));
19
+ const fs_1 = __importDefault(require("fs"));
20
+ const core_1 = require("../core");
21
+ const ignore_1 = __importDefault(require("ignore"));
22
+ const json5_1 = __importDefault(require("json5"));
23
+ exports.commandPackHarmony = {
24
+ name: 'pack-harmony',
25
+ description: 'Pack native code. Used for package development.',
26
+ options: [
27
+ {
28
+ name: '--oh-module-path <string>',
29
+ description: 'Path to the OH module',
30
+ },
31
+ {
32
+ name: '--harmony-dir-path <string>',
33
+ description: 'Path to the harmony dir',
34
+ },
35
+ {
36
+ name: '--package-json-path <string>',
37
+ description: 'Path to the package.json',
38
+ },
39
+ ],
40
+ func: (argv, config, args) => __awaiter(void 0, void 0, void 0, function* () {
41
+ try {
42
+ yield pack(path_1.default.resolve(args.harmonyDirPath), path_1.default.resolve(args.ohModulePath), path_1.default.resolve(args.packageJsonPath));
43
+ }
44
+ catch (err) {
45
+ if (err instanceof core_1.ValidationError) {
46
+ console.error('[ERROR]', err.message);
47
+ process.exit(1);
48
+ }
49
+ else {
50
+ throw err;
51
+ }
52
+ }
53
+ }),
54
+ };
55
+ function pack(harmonyDirPath, ohModuleDirPath, packageJSONPath) {
56
+ return __awaiter(this, void 0, void 0, function* () {
57
+ syncVersions(packageJSONPath, path_1.default.join(ohModuleDirPath, 'oh-package.json5'));
58
+ yield createTGZFromDir(ohModuleDirPath, path_1.default.join(harmonyDirPath, `${path_1.default.parse(ohModuleDirPath).name}.tar.gz`));
59
+ yield createTGZFromDir(harmonyDirPath, path_1.default.join(path_1.default.dirname(harmonyDirPath), 'harmony.tar.gz'));
60
+ });
61
+ }
62
+ function syncVersions(packageJSONFilePath, ohPackageJSONFilePath) {
63
+ const packageJSONFileContent = JSON.parse(fs_1.default.readFileSync(packageJSONFilePath, { encoding: 'utf-8' }));
64
+ if (fs_1.default.existsSync(ohPackageJSONFilePath)) {
65
+ const ohPackageJSONFileContent = json5_1.default.parse(fs_1.default.readFileSync(ohPackageJSONFilePath, { encoding: 'utf-8' }));
66
+ ohPackageJSONFileContent['version'] = packageJSONFileContent['version'];
67
+ fs_1.default.writeFileSync(ohPackageJSONFilePath, json5_1.default.stringify(ohPackageJSONFileContent));
68
+ }
69
+ }
70
+ function createTGZFromDir(dirPath, outputFilePath) {
71
+ return __awaiter(this, void 0, void 0, function* () {
72
+ const ig = getIgnoreUtil(path_1.default.join(dirPath, '.tarignore'));
73
+ const filesToInclude = (0, glob_1.globSync)('**', {
74
+ cwd: dirPath,
75
+ nodir: true,
76
+ }).filter((path) => !ig.ignores(path));
77
+ yield createArchive(outputFilePath, dirPath, filesToInclude);
78
+ });
79
+ }
80
+ function getIgnoreUtil(tarignorePath) {
81
+ if (!fs_1.default.existsSync(tarignorePath)) {
82
+ return (0, ignore_1.default)();
83
+ }
84
+ return (0, ignore_1.default)().add(fs_1.default.readFileSync(tarignorePath).toString());
85
+ }
86
+ function createArchive(outputFilePath, packageDirPath, filesToInclude) {
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ if (filesToInclude.length === 0) {
89
+ throw new core_1.ValidationError('Nothing to pack');
90
+ }
91
+ yield tar_1.default.c({
92
+ gzip: true,
93
+ file: outputFilePath,
94
+ cwd: packageDirPath,
95
+ }, filesToInclude);
96
+ });
97
+ }
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.commandUnpackHarmony = void 0;
16
+ const path_1 = __importDefault(require("path"));
17
+ const fs_1 = __importDefault(require("fs"));
18
+ const zlib_1 = __importDefault(require("zlib"));
19
+ const tar_1 = __importDefault(require("tar"));
20
+ const json5_1 = __importDefault(require("json5"));
21
+ const core_1 = require("../core");
22
+ exports.commandUnpackHarmony = {
23
+ name: 'unpack-harmony',
24
+ description: 'Pack native code. Used for package development.',
25
+ options: [
26
+ {
27
+ name: '--node-modules-path <string>',
28
+ description: 'Path to node_modules directory',
29
+ default: './node_modules',
30
+ },
31
+ {
32
+ name: '--output-dir <string>',
33
+ description: 'Output directory to which OH modules should be unpacked to',
34
+ default: './harmony/react_native_modules',
35
+ },
36
+ ],
37
+ func: (argv, config, args) => __awaiter(void 0, void 0, void 0, function* () {
38
+ try {
39
+ yield unpack(path_1.default.resolve(args.nodeModulesPath), path_1.default.resolve(args.outputDir));
40
+ }
41
+ catch (err) {
42
+ if (err instanceof core_1.ValidationError) {
43
+ console.error('[ERROR]', err.message);
44
+ process.exit(1);
45
+ }
46
+ else {
47
+ throw err;
48
+ }
49
+ }
50
+ }),
51
+ };
52
+ function unpack(nodeModulesPath, outputDirPath) {
53
+ return __awaiter(this, void 0, void 0, function* () {
54
+ const nodeModuleNames = fs_1.default.readdirSync(nodeModulesPath);
55
+ for (const nodeModuleName of nodeModuleNames) {
56
+ const nodeModulePath = path_1.default.join(nodeModulesPath, nodeModuleName);
57
+ const nodePackageVersion = getNodePackageVersion(nodeModulePath);
58
+ const harmonyArchivePath = path_1.default.join(nodeModulePath, 'harmony.tar.gz');
59
+ const pkgHarmonyDirPath = path_1.default.join(nodeModulePath, 'harmony');
60
+ const ohModulesInfo = getOhModulesInfo(pkgHarmonyDirPath, outputDirPath);
61
+ if (nodePackageVersion &&
62
+ shouldUnpackHarmonyArchive(harmonyArchivePath, pkgHarmonyDirPath, outputDirPath, nodePackageVersion)) {
63
+ console.log(`[UNPACKING] ${nodeModuleName}/harmony.tar.gz`);
64
+ yield unpackTarGz(harmonyArchivePath, pkgHarmonyDirPath);
65
+ for (const ohModuleInfo of ohModulesInfo) {
66
+ console.log(`[UNPACKING] ${nodeModuleName}/harmony/${ohModuleInfo.archiveFileName}`);
67
+ yield unpackTarGz(ohModuleInfo.archivePath, ohModuleInfo.computedModulePath);
68
+ }
69
+ }
70
+ }
71
+ });
72
+ }
73
+ function shouldUnpackHarmonyArchive(harmonyArchivePath, pkgHarmonyDirPath, outputDirPath, nodePackageVersion) {
74
+ if (!fs_1.default.existsSync(harmonyArchivePath))
75
+ return false;
76
+ if (!fs_1.default.existsSync(pkgHarmonyDirPath))
77
+ return true;
78
+ const ohModulesInfo = getOhModulesInfo(pkgHarmonyDirPath, outputDirPath);
79
+ for (const ohModuleInfo of ohModulesInfo) {
80
+ if (!fs_1.default.existsSync(ohModuleInfo.computedModulePath) ||
81
+ getOhPackageVersion(ohModuleInfo.computedModulePath) !==
82
+ nodePackageVersion) {
83
+ return true;
84
+ }
85
+ }
86
+ return false;
87
+ }
88
+ function getNodePackageVersion(nodeModulePath) {
89
+ const packageJSONPath = path_1.default.join(nodeModulePath, 'package.json');
90
+ if (!fs_1.default.existsSync(packageJSONPath))
91
+ return null;
92
+ const content = fs_1.default.readFileSync(packageJSONPath, { encoding: 'utf-8' });
93
+ return JSON.parse(content)['version'];
94
+ }
95
+ function getOhPackageVersion(modulePath) {
96
+ const ohPackagePath = path_1.default.join(modulePath, 'oh-package.json5');
97
+ if (!fs_1.default.existsSync(ohPackagePath))
98
+ return null;
99
+ const content = fs_1.default.readFileSync(ohPackagePath, { encoding: 'utf-8' });
100
+ return json5_1.default.parse(content)['version'];
101
+ }
102
+ function getOhModulesInfo(pkgHarmonyDirPath, outputDirPath) {
103
+ const results = [];
104
+ if (!fs_1.default.existsSync(pkgHarmonyDirPath))
105
+ return [];
106
+ const names = fs_1.default.readdirSync(pkgHarmonyDirPath);
107
+ for (const name of names) {
108
+ if (name.endsWith('.tar.gz')) {
109
+ const archivePath = path_1.default.join(pkgHarmonyDirPath, name);
110
+ const computedModuleName = path_1.default
111
+ .parse(archivePath)
112
+ .name.split('.')[0];
113
+ const computedModulePath = path_1.default.join(outputDirPath, computedModuleName);
114
+ results.push({
115
+ archivePath,
116
+ archiveFileName: name,
117
+ computedModulePath,
118
+ computedModuleName,
119
+ });
120
+ }
121
+ }
122
+ return results;
123
+ }
124
+ function unpackTarGz(archivePath, outputDirPath) {
125
+ if (!fs_1.default.existsSync(outputDirPath)) {
126
+ fs_1.default.mkdirSync(outputDirPath, { recursive: true });
127
+ }
128
+ const readStream = fs_1.default.createReadStream(archivePath);
129
+ const writeStream = tar_1.default.extract({
130
+ cwd: outputDirPath,
131
+ });
132
+ readStream.pipe(zlib_1.default.createGunzip()).pipe(writeStream);
133
+ return new Promise((resolve, reject) => {
134
+ writeStream.on('finish', () => {
135
+ resolve(undefined);
136
+ });
137
+ writeStream.on('error', (err) => {
138
+ reject(err);
139
+ });
140
+ });
141
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ValidationError = void 0;
4
+ class ValidationError extends Error {
5
+ }
6
+ exports.ValidationError = ValidationError;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./ValidationError"), exports);
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.config = void 0;
4
+ const commands_1 = require("./commands");
5
+ exports.config = {
6
+ commands: [commands_1.commandBundleHarmony, commands_1.commandPackHarmony, commands_1.commandUnpackHarmony],
7
+ };
package/jest.config.js ADDED
@@ -0,0 +1,5 @@
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
2
+ module.exports = {
3
+ preset: 'ts-jest',
4
+ testEnvironment: 'node',
5
+ };
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@react-native-oh/react-native-harmony-cli",
3
+ "version": "0.0.15",
4
+ "description": "",
5
+ "publishConfig": {
6
+ "registry": "https://registry.npmjs.org/",
7
+ "access": "public"
8
+ },
9
+ "scripts": {
10
+ "build": "tsc --outDir dist -p tsconfig.build.json",
11
+ "prepack": "npm run build",
12
+ "verify": "tsc --noEmit && npm run test",
13
+ "test": "npm run build && jest",
14
+ "rn": "npm run build && react-native",
15
+ "prepublishOnly": "npm run verify"
16
+ },
17
+ "keywords": [],
18
+ "author": "",
19
+ "license": "ISC",
20
+ "peerDependencies": {
21
+ "metro": "*"
22
+ },
23
+ "main": "dist/index.js",
24
+ "devDependencies": {
25
+ "@react-native-community/cli-types": "^11.3.0",
26
+ "@types/fs-extra": "^11.0.1",
27
+ "@types/jest": "^29.5.1",
28
+ "@types/tar": "^6.1.5",
29
+ "@types/tmp": "^0.2.3",
30
+ "directory-tree": "^3.5.1",
31
+ "execa": "npm:@esm2cjs/execa@^6.1.1-cjs.1",
32
+ "jest": "^29.5.0",
33
+ "react-native": "^0.72.0",
34
+ "tmp": "^0.2.1",
35
+ "ts-jest": "^29.1.0",
36
+ "ts-node": "^10.9.1",
37
+ "typescript": "^5.0.4"
38
+ },
39
+ "dependencies": {
40
+ "@tsconfig/recommended": "^1.0.2",
41
+ "fs-extra": "^11.1.1",
42
+ "glob": "^10.2.6",
43
+ "ignore": "^5.2.4",
44
+ "json5": "^2.2.3",
45
+ "tar": "^6.1.15"
46
+ }
47
+ }
@@ -0,0 +1,10 @@
1
+ const { config: harmonyConfig } = require('./dist');
2
+
3
+ /**
4
+ * @type {import("@react-native-community/cli-types").Config}
5
+ */
6
+ const config = {
7
+ commands: harmonyConfig.commands,
8
+ };
9
+
10
+ module.exports = config;
@@ -0,0 +1,25 @@
1
+ import type { AssetData } from 'metro';
2
+
3
+ export type Asset = AssetData;
4
+
5
+ export function getAssetDestRelativePath(asset: Asset): string {
6
+ const fileName = getResourceIdentifier(asset);
7
+ return `${fileName}.${asset.type}`;
8
+ }
9
+
10
+ function getResourceIdentifier(asset: Asset): string {
11
+ const folderPath = getBasePath(asset);
12
+ return `${folderPath}/${asset.name}`
13
+ .toLowerCase()
14
+ .replace(/\//g, '_') // Encode folder structure in file name
15
+ .replace(/([^a-z0-9_])/g, '') // Remove illegal chars
16
+ .replace(/^assets_/, ''); // Remove "assets_" prefix
17
+ }
18
+
19
+ function getBasePath(asset: Asset): string {
20
+ let basePath = asset.httpServerLocation;
21
+ if (basePath[0] === '/') {
22
+ basePath = basePath.substr(1);
23
+ }
24
+ return basePath;
25
+ }
@@ -0,0 +1,202 @@
1
+ import { Command } from '@react-native-community/cli-types';
2
+ import fs from 'fs';
3
+ import fse from 'fs-extra';
4
+ import Metro from 'metro';
5
+ import { RunBuildOptions as BuildOptions } from 'metro';
6
+ import MetroServer from 'metro/src/Server';
7
+ import pathUtils from 'path';
8
+ import { getAssetDestRelativePath } from '../assetResolver';
9
+ import { ConfigT as MetroConfig } from 'metro-config';
10
+
11
+ const ARK_RESOURCE_PATH = './harmony/entry/src/main/resources/rawfile';
12
+ const ASSETS_DEFAULT_DEST_PATH = './harmony/entry/src/main/resources/rawfile/assets';
13
+
14
+ type AssetData = Metro.AssetData;
15
+ type Bundle = { code: string; map: string };
16
+ type Path = string;
17
+
18
+ export const commandBundleHarmony: Command = {
19
+ name: 'bundle-harmony',
20
+ description:
21
+ 'Creates JS bundle, creates a special cpp header containing the JS code, copies assets directory to the project.',
22
+ options: [
23
+ {
24
+ name: '--dev [boolean]',
25
+ description: 'If false, warnings are disabled and the bundle is minified',
26
+ parse: (val: string) => val !== 'false',
27
+ default: true,
28
+ },
29
+ {
30
+ name: '--entry-file <path>',
31
+ description:
32
+ 'Path to the root JS file, either absolute or relative to JS root',
33
+ default: 'index.js',
34
+ },
35
+ {
36
+ name: '--config <path>',
37
+ description: 'Path to the Metro configuration file',
38
+ },
39
+ {
40
+ name: '--bundle-output <path>',
41
+ description:
42
+ 'File name where to store the resulting bundle, ex. /tmp/groups.bundle',
43
+ default: ARK_RESOURCE_PATH + '/bundle.harmony.js',
44
+ },
45
+ {
46
+ name: '--assets-dest <path>',
47
+ description:
48
+ 'Directory name where to store assets referenced in the bundle',
49
+ default: ASSETS_DEFAULT_DEST_PATH,
50
+ },
51
+ {
52
+ name: '--sourcemap-output <path>',
53
+ description:
54
+ 'File name where to store the resulting source map, ex. /tmp/groups.map',
55
+ },
56
+ {
57
+ name: '--minify [boolean]',
58
+ description: 'Allows overriding whether bundle is minified',
59
+ parse: (val: string) => val !== 'false',
60
+ },
61
+ ],
62
+ func: async (argv, config, args: any) => {
63
+ const buildOptions: BuildOptions = {
64
+ entry: args.entryFile,
65
+ platform: 'harmony',
66
+ minify: args.minify !== undefined ? args.minify : !args.dev,
67
+ dev: args.dev,
68
+ sourceMap: args.sourcemapOutput,
69
+ sourceMapUrl: args.sourcemapOutput,
70
+ };
71
+ const metroConfig = await loadMetroConfig(args.config);
72
+ const bundle = await createBundle(metroConfig, buildOptions);
73
+ await saveBundle(bundle, args.bundleOutput, args.sourcemapOutput);
74
+ const assets = await retrieveAssetsData(metroConfig, buildOptions);
75
+ copyAssets(assets, args.assetsDest);
76
+ },
77
+ };
78
+
79
+ async function loadMetroConfig(
80
+ configPath: Path | undefined
81
+ ): Promise<MetroConfig> {
82
+ return configPath
83
+ ? await Metro.loadConfig({ config: configPath })
84
+ : await Metro.loadConfig();
85
+ }
86
+
87
+ async function createBundle(
88
+ metroConfig: MetroConfig,
89
+ buildOptions: BuildOptions
90
+ ): Promise<Bundle> {
91
+ // casting needed as Metro.runBuild returns Promise<{code: string, map: string}>
92
+ // despite being typed as Promise<void>
93
+ return (await Metro.runBuild(metroConfig, buildOptions)) as unknown as Bundle;
94
+ }
95
+
96
+ async function saveBundle(
97
+ bundle: Bundle,
98
+ bundleOutput: Path,
99
+ sourceMapOutput: Path | undefined
100
+ ) {
101
+ await fse.ensureDir(pathUtils.dirname(bundleOutput));
102
+ fs.writeFileSync(bundleOutput, bundle.code);
103
+ console.log(`[CREATED] ${bundleOutput}`);
104
+ if (sourceMapOutput) {
105
+ fs.writeFileSync(sourceMapOutput, bundle.map);
106
+ console.log(`[CREATED] ${sourceMapOutput}`);
107
+ }
108
+ }
109
+
110
+ async function retrieveAssetsData(
111
+ metroConfig: MetroConfig,
112
+ buildOptions: BuildOptions
113
+ ): Promise<readonly AssetData[]> {
114
+ const metroServer = new MetroServer(metroConfig);
115
+ try {
116
+ return await metroServer.getAssets({
117
+ ...MetroServer.DEFAULT_BUNDLE_OPTIONS,
118
+ ...buildOptions,
119
+ entryFile: buildOptions.entry,
120
+ bundleType: 'todo',
121
+ });
122
+ } finally {
123
+ metroServer.end();
124
+ }
125
+ }
126
+
127
+ async function copyAssets(
128
+ assetsData: readonly AssetData[],
129
+ assetsDest: Path
130
+ ): Promise<void> {
131
+ if (assetsDest == null) {
132
+ console.warn('Assets destination folder is not set, skipping...');
133
+ return;
134
+ }
135
+ await fse.ensureDir(assetsDest);
136
+ const fileDestBySrc: Record<Path, Path> = {};
137
+ for (const asset of assetsData) {
138
+ const idx = getHighestQualityFileIdx(asset);
139
+ fileDestBySrc[asset.files[idx]] = pathUtils.join(
140
+ assetsDest,
141
+ getAssetDestRelativePath(asset)
142
+ );
143
+ }
144
+ return copyFiles(fileDestBySrc);
145
+ }
146
+
147
+ function getHighestQualityFileIdx(assetData: AssetData): number {
148
+ let result = 0;
149
+ let maxScale = -1;
150
+ for (let idx = 0; idx < assetData.scales.length; idx++) {
151
+ const scale = assetData.scales[idx];
152
+ if (scale > maxScale) {
153
+ maxScale = scale;
154
+ result = idx;
155
+ }
156
+ }
157
+ return result;
158
+ }
159
+
160
+ function copyFiles(fileDestBySrc: Record<Path, Path>) {
161
+ const fileSources = Object.keys(fileDestBySrc);
162
+ if (fileSources.length === 0) {
163
+ return Promise.resolve();
164
+ }
165
+
166
+ console.info(`Copying ${fileSources.length} asset files`);
167
+ return new Promise<void>((resolve, reject) => {
168
+ const copyNext = (error?: Error) => {
169
+ if (error) {
170
+ reject(error);
171
+ return;
172
+ }
173
+ if (fileSources.length === 0) {
174
+ console.info('Done copying assets');
175
+ resolve();
176
+ } else {
177
+ // fileSources.length === 0 is checked in previous branch, so this is string
178
+ const src = fileSources.shift()!;
179
+ const dest = fileDestBySrc[src];
180
+ copyFile(src, dest, copyNext);
181
+ }
182
+ };
183
+ copyNext();
184
+ });
185
+ }
186
+
187
+ function copyFile(
188
+ src: string,
189
+ dest: string,
190
+ onFinished: (error: Error) => void
191
+ ): void {
192
+ const destDir = pathUtils.dirname(dest);
193
+ fs.mkdir(destDir, { recursive: true }, (err?) => {
194
+ if (err) {
195
+ onFinished(err);
196
+ return;
197
+ }
198
+ fs.createReadStream(src)
199
+ .pipe(fs.createWriteStream(dest))
200
+ .on('finish', onFinished);
201
+ });
202
+ }
@@ -0,0 +1,3 @@
1
+ export * from './bundle-harmony';
2
+ export * from './pack-harmony';
3
+ export * from './unpack-harmony';
@@ -0,0 +1,118 @@
1
+ import { Command } from '@react-native-community/cli-types';
2
+ import { globSync } from 'glob';
3
+ import pathUtils from 'path';
4
+ import tar from 'tar';
5
+ import fs from 'fs';
6
+ import { ValidationError } from '../core';
7
+ import ignore, { Ignore } from 'ignore';
8
+ import JSON5 from 'json5';
9
+
10
+ export const commandPackHarmony: Command = {
11
+ name: 'pack-harmony',
12
+ description: 'Pack native code. Used for package development.',
13
+ options: [
14
+ {
15
+ name: '--oh-module-path <string>',
16
+ description: 'Path to the OH module',
17
+ },
18
+ {
19
+ name: '--harmony-dir-path <string>',
20
+ description: 'Path to the harmony dir',
21
+ },
22
+ {
23
+ name: '--package-json-path <string>',
24
+ description: 'Path to the package.json',
25
+ },
26
+ ],
27
+ func: async (argv, config, args: any) => {
28
+ try {
29
+ await pack(
30
+ pathUtils.resolve(args.harmonyDirPath),
31
+ pathUtils.resolve(args.ohModulePath),
32
+ pathUtils.resolve(args.packageJsonPath)
33
+ );
34
+ } catch (err) {
35
+ if (err instanceof ValidationError) {
36
+ console.error('[ERROR]', err.message);
37
+ process.exit(1);
38
+ } else {
39
+ throw err;
40
+ }
41
+ }
42
+ },
43
+ };
44
+
45
+ async function pack(
46
+ harmonyDirPath: string,
47
+ ohModuleDirPath: string,
48
+ packageJSONPath: string
49
+ ) {
50
+ syncVersions(
51
+ packageJSONPath,
52
+ pathUtils.join(ohModuleDirPath, 'oh-package.json5')
53
+ );
54
+ await createTGZFromDir(
55
+ ohModuleDirPath,
56
+ pathUtils.join(
57
+ harmonyDirPath,
58
+ `${pathUtils.parse(ohModuleDirPath).name}.tar.gz`
59
+ )
60
+ );
61
+ await createTGZFromDir(
62
+ harmonyDirPath,
63
+ pathUtils.join(pathUtils.dirname(harmonyDirPath), 'harmony.tar.gz')
64
+ );
65
+ }
66
+
67
+ function syncVersions(
68
+ packageJSONFilePath: string,
69
+ ohPackageJSONFilePath: string
70
+ ) {
71
+ const packageJSONFileContent = JSON.parse(
72
+ fs.readFileSync(packageJSONFilePath, { encoding: 'utf-8' })
73
+ );
74
+ if (fs.existsSync(ohPackageJSONFilePath)) {
75
+ const ohPackageJSONFileContent = JSON5.parse(
76
+ fs.readFileSync(ohPackageJSONFilePath, { encoding: 'utf-8' })
77
+ );
78
+ ohPackageJSONFileContent['version'] = packageJSONFileContent['version'];
79
+ fs.writeFileSync(
80
+ ohPackageJSONFilePath,
81
+ JSON5.stringify(ohPackageJSONFileContent)
82
+ );
83
+ }
84
+ }
85
+
86
+ async function createTGZFromDir(dirPath: string, outputFilePath: string) {
87
+ const ig = getIgnoreUtil(pathUtils.join(dirPath, '.tarignore'));
88
+ const filesToInclude = globSync('**', {
89
+ cwd: dirPath,
90
+ nodir: true,
91
+ }).filter((path) => !ig.ignores(path));
92
+ await createArchive(outputFilePath, dirPath, filesToInclude);
93
+ }
94
+
95
+ function getIgnoreUtil(tarignorePath: string): Ignore {
96
+ if (!fs.existsSync(tarignorePath)) {
97
+ return ignore();
98
+ }
99
+ return ignore().add(fs.readFileSync(tarignorePath).toString());
100
+ }
101
+
102
+ async function createArchive(
103
+ outputFilePath: string,
104
+ packageDirPath: string,
105
+ filesToInclude: string[]
106
+ ) {
107
+ if (filesToInclude.length === 0) {
108
+ throw new ValidationError('Nothing to pack');
109
+ }
110
+ await tar.c(
111
+ {
112
+ gzip: true,
113
+ file: outputFilePath,
114
+ cwd: packageDirPath,
115
+ },
116
+ filesToInclude
117
+ );
118
+ }
@@ -0,0 +1,156 @@
1
+ import { Command } from '@react-native-community/cli-types';
2
+
3
+ import pathUtils from 'path';
4
+ import fs from 'fs';
5
+ import zlib from 'zlib';
6
+ import tar from 'tar';
7
+ import JSON5 from 'json5';
8
+ import { ValidationError } from '../core';
9
+
10
+ export const commandUnpackHarmony: Command = {
11
+ name: 'unpack-harmony',
12
+ description: 'Pack native code. Used for package development.',
13
+ options: [
14
+ {
15
+ name: '--node-modules-path <string>',
16
+ description: 'Path to node_modules directory',
17
+ default: './node_modules',
18
+ },
19
+ {
20
+ name: '--output-dir <string>',
21
+ description: 'Output directory to which OH modules should be unpacked to',
22
+ default: './harmony/react_native_modules',
23
+ },
24
+ ],
25
+ func: async (argv, config, args: any) => {
26
+ try {
27
+ await unpack(
28
+ pathUtils.resolve(args.nodeModulesPath),
29
+ pathUtils.resolve(args.outputDir)
30
+ );
31
+ } catch (err) {
32
+ if (err instanceof ValidationError) {
33
+ console.error('[ERROR]', err.message);
34
+ process.exit(1);
35
+ } else {
36
+ throw err;
37
+ }
38
+ }
39
+ },
40
+ };
41
+
42
+ async function unpack(nodeModulesPath: string, outputDirPath: string) {
43
+ const nodeModuleNames = fs.readdirSync(nodeModulesPath);
44
+ for (const nodeModuleName of nodeModuleNames) {
45
+ const nodeModulePath = pathUtils.join(nodeModulesPath, nodeModuleName);
46
+ const nodePackageVersion = getNodePackageVersion(nodeModulePath);
47
+ const harmonyArchivePath = pathUtils.join(nodeModulePath, 'harmony.tar.gz');
48
+ const pkgHarmonyDirPath = pathUtils.join(nodeModulePath, 'harmony');
49
+ const ohModulesInfo = getOhModulesInfo(pkgHarmonyDirPath, outputDirPath);
50
+ if (
51
+ nodePackageVersion &&
52
+ shouldUnpackHarmonyArchive(
53
+ harmonyArchivePath,
54
+ pkgHarmonyDirPath,
55
+ outputDirPath,
56
+ nodePackageVersion
57
+ )
58
+ ) {
59
+ console.log(`[UNPACKING] ${nodeModuleName}/harmony.tar.gz`);
60
+ await unpackTarGz(harmonyArchivePath, pkgHarmonyDirPath);
61
+ for (const ohModuleInfo of ohModulesInfo) {
62
+ console.log(
63
+ `[UNPACKING] ${nodeModuleName}/harmony/${ohModuleInfo.archiveFileName}`
64
+ );
65
+ await unpackTarGz(
66
+ ohModuleInfo.archivePath,
67
+ ohModuleInfo.computedModulePath
68
+ );
69
+ }
70
+ }
71
+ }
72
+ }
73
+
74
+ function shouldUnpackHarmonyArchive(
75
+ harmonyArchivePath: string,
76
+ pkgHarmonyDirPath: string,
77
+ outputDirPath: string,
78
+ nodePackageVersion: string
79
+ ) {
80
+ if (!fs.existsSync(harmonyArchivePath)) return false;
81
+ if (!fs.existsSync(pkgHarmonyDirPath)) return true;
82
+ const ohModulesInfo = getOhModulesInfo(pkgHarmonyDirPath, outputDirPath);
83
+ for (const ohModuleInfo of ohModulesInfo) {
84
+ if (
85
+ !fs.existsSync(ohModuleInfo.computedModulePath) ||
86
+ getOhPackageVersion(ohModuleInfo.computedModulePath) !==
87
+ nodePackageVersion
88
+ ) {
89
+ return true;
90
+ }
91
+ }
92
+ return false;
93
+ }
94
+
95
+ function getNodePackageVersion(nodeModulePath: string) {
96
+ const packageJSONPath = pathUtils.join(nodeModulePath, 'package.json');
97
+ if (!fs.existsSync(packageJSONPath)) return null;
98
+ const content = fs.readFileSync(packageJSONPath, { encoding: 'utf-8' });
99
+ return JSON.parse(content)['version'];
100
+ }
101
+
102
+ function getOhPackageVersion(modulePath: string) {
103
+ const ohPackagePath = pathUtils.join(modulePath, 'oh-package.json5');
104
+ if (!fs.existsSync(ohPackagePath)) return null;
105
+ const content = fs.readFileSync(ohPackagePath, { encoding: 'utf-8' });
106
+ return JSON5.parse(content)['version'];
107
+ }
108
+
109
+ function getOhModulesInfo(pkgHarmonyDirPath: string, outputDirPath: string) {
110
+ const results: {
111
+ archivePath: string;
112
+ archiveFileName: string;
113
+ computedModulePath: string;
114
+ computedModuleName: string;
115
+ }[] = [];
116
+ if (!fs.existsSync(pkgHarmonyDirPath)) return [];
117
+ const names = fs.readdirSync(pkgHarmonyDirPath);
118
+ for (const name of names) {
119
+ if (name.endsWith('.tar.gz')) {
120
+ const archivePath = pathUtils.join(pkgHarmonyDirPath, name);
121
+ const computedModuleName = pathUtils
122
+ .parse(archivePath)
123
+ .name.split('.')[0];
124
+ const computedModulePath = pathUtils.join(
125
+ outputDirPath,
126
+ computedModuleName
127
+ );
128
+ results.push({
129
+ archivePath,
130
+ archiveFileName: name,
131
+ computedModulePath,
132
+ computedModuleName,
133
+ });
134
+ }
135
+ }
136
+ return results;
137
+ }
138
+
139
+ function unpackTarGz(archivePath: string, outputDirPath: string) {
140
+ if (!fs.existsSync(outputDirPath)) {
141
+ fs.mkdirSync(outputDirPath, { recursive: true });
142
+ }
143
+ const readStream = fs.createReadStream(archivePath);
144
+ const writeStream = tar.extract({
145
+ cwd: outputDirPath,
146
+ });
147
+ readStream.pipe(zlib.createGunzip()).pipe(writeStream);
148
+ return new Promise((resolve, reject) => {
149
+ writeStream.on('finish', () => {
150
+ resolve(undefined);
151
+ });
152
+ writeStream.on('error', (err) => {
153
+ reject(err);
154
+ });
155
+ });
156
+ }
@@ -0,0 +1 @@
1
+ export class ValidationError extends Error {}
@@ -0,0 +1 @@
1
+ export * from './ValidationError';
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { Config } from '@react-native-community/cli-types';
2
+ import {
3
+ commandBundleHarmony,
4
+ commandPackHarmony,
5
+ commandUnpackHarmony,
6
+ } from './commands';
7
+
8
+ export const config = {
9
+ commands: [commandBundleHarmony, commandPackHarmony, commandUnpackHarmony],
10
+ } satisfies Partial<Config>;
@@ -0,0 +1,6 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "exclude": [
4
+ "tests"
5
+ ]
6
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "extends": "@tsconfig/recommended/tsconfig.json",
3
+ }