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

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 CHANGED
@@ -1,6 +1,6 @@
1
- {
2
- "trailingComma": "es5",
3
- "tabWidth": 2,
4
- "semi": true,
5
- "singleQuote": true
6
- }
1
+ {
2
+ "trailingComma": "es5",
3
+ "tabWidth": 2,
4
+ "semi": true,
5
+ "singleQuote": true
6
+ }
@@ -1,6 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getAssetDestRelativePath = void 0;
4
+ /*
5
+ cyrb53 (c) 2018 bryc (github.com/bryc)
6
+ License: Public domain. Attribution appreciated.
7
+ A fast and simple 53-bit string hash function with decent collision resistance.
8
+ Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
9
+ */
10
+ function cyrb53(str, seed = 0) {
11
+ let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
12
+ for (let i = 0, ch; i < str.length; i++) {
13
+ ch = str.charCodeAt(i);
14
+ h1 = Math.imul(h1 ^ ch, 2654435761);
15
+ h2 = Math.imul(h2 ^ ch, 1597334677);
16
+ }
17
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
18
+ h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
19
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
20
+ h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
21
+ return 4294967296 * (2097151 & h2) + (h1 >>> 0);
22
+ }
23
+ ;
4
24
  function getAssetDestRelativePath(asset) {
5
25
  const fileName = getResourceIdentifier(asset);
6
26
  return `${fileName}.${asset.type}`;
@@ -8,11 +28,9 @@ function getAssetDestRelativePath(asset) {
8
28
  exports.getAssetDestRelativePath = getAssetDestRelativePath;
9
29
  function getResourceIdentifier(asset) {
10
30
  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
31
+ const fullAssetPath = `${folderPath}/${asset.name}.${asset.type}`.toLowerCase();
32
+ const assetPathHash = cyrb53(fullAssetPath);
33
+ return assetPathHash.toString(16);
16
34
  }
17
35
  function getBasePath(asset) {
18
36
  let basePath = asset.httpServerLocation;
package/jest.config.js CHANGED
@@ -1,5 +1,5 @@
1
- /** @type {import('ts-jest').JestConfigWithTsJest} */
2
- module.exports = {
3
- preset: 'ts-jest',
4
- testEnvironment: 'node',
5
- };
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
2
+ module.exports = {
3
+ preset: 'ts-jest',
4
+ testEnvironment: 'node',
5
+ };
package/package.json CHANGED
@@ -1,47 +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
- }
1
+ {
2
+ "name": "@react-native-oh/react-native-harmony-cli",
3
+ "version": "0.0.16",
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
+ }
@@ -1,10 +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;
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;
@@ -1,25 +1,44 @@
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
- }
1
+ import type { AssetData } from 'metro';
2
+
3
+ export type Asset = AssetData;
4
+
5
+ /*
6
+ cyrb53 (c) 2018 bryc (github.com/bryc)
7
+ License: Public domain. Attribution appreciated.
8
+ A fast and simple 53-bit string hash function with decent collision resistance.
9
+ Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
10
+ */
11
+ function cyrb53(str: string, seed = 0) {
12
+ let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
13
+ for(let i = 0, ch; i < str.length; i++) {
14
+ ch = str.charCodeAt(i);
15
+ h1 = Math.imul(h1 ^ ch, 2654435761);
16
+ h2 = Math.imul(h2 ^ ch, 1597334677);
17
+ }
18
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
19
+ h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
20
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
21
+ h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
22
+ return 4294967296 * (2097151 & h2) + (h1 >>> 0);
23
+ };
24
+
25
+
26
+ export function getAssetDestRelativePath(asset: Asset): string {
27
+ const fileName = getResourceIdentifier(asset);
28
+ return `${fileName}.${asset.type}`;
29
+ }
30
+
31
+ function getResourceIdentifier(asset: Asset): string {
32
+ const folderPath = getBasePath(asset);
33
+ const fullAssetPath = `${folderPath}/${asset.name}.${asset.type}`.toLowerCase();
34
+ const assetPathHash = cyrb53(fullAssetPath);
35
+ return assetPathHash.toString(16);
36
+ }
37
+
38
+ function getBasePath(asset: Asset): string {
39
+ let basePath = asset.httpServerLocation;
40
+ if (basePath[0] === '/') {
41
+ basePath = basePath.substr(1);
42
+ }
43
+ return basePath;
44
+ }
@@ -1,202 +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
- }
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
+ }
@@ -1,3 +1,3 @@
1
- export * from './bundle-harmony';
2
- export * from './pack-harmony';
3
- export * from './unpack-harmony';
1
+ export * from './bundle-harmony';
2
+ export * from './pack-harmony';
3
+ export * from './unpack-harmony';
@@ -1,118 +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
- }
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
+ }
@@ -1,156 +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
- }
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
+ }
@@ -1 +1 @@
1
- export class ValidationError extends Error {}
1
+ export class ValidationError extends Error {}
package/src/core/index.ts CHANGED
@@ -1 +1 @@
1
- export * from './ValidationError';
1
+ export * from './ValidationError';
package/src/index.ts CHANGED
@@ -1,10 +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>;
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>;
@@ -1,6 +1,6 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "exclude": [
4
- "tests"
5
- ]
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "exclude": [
4
+ "tests"
5
+ ]
6
6
  }
package/tsconfig.json CHANGED
@@ -1,3 +1,3 @@
1
- {
2
- "extends": "@tsconfig/recommended/tsconfig.json",
1
+ {
2
+ "extends": "@tsconfig/recommended/tsconfig.json",
3
3
  }