@9of9solutions/replikator 1.0.11 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/main.js +218 -139
  2. package/package.json +35 -28
package/main.js CHANGED
@@ -1,61 +1,61 @@
1
1
  #!/usr/bin/env node
2
- import path from 'path';
3
- import fs from 'fs-extra';
4
- import chokidar from 'chokidar';
5
- import inquirer from 'inquirer';
2
+ import path from 'path';
3
+ import fs from 'fs-extra';
4
+ import chokidar from 'chokidar';
5
+ import inquirer from 'inquirer';
6
6
  import url from 'url';
7
7
  const projectRoot = process.cwd();
8
8
  const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
9
- const pkgPath = path.join(__dirname, 'package.json');
9
+ const pkgPath = path.join(__dirname, 'package.json');
10
10
 
11
11
  async function getVersion() {
12
- const pkg = await fs.readJson(pkgPath, 'utf8');
13
- return pkg.version;
12
+ const pkg = await fs.readJson(pkgPath, 'utf8');
13
+ return pkg.version;
14
14
  }
15
15
  //We save configuration in root package.json
16
16
  const PACKAGE_JSON_ROOT_PATH = path.resolve(projectRoot, 'package.json');
17
-
17
+ const SHARED_PATH = 'shared';
18
18
  /**
19
19
  * Recursively searches for folders that contain both
20
20
  * a `src` subfolder and a `package.json` file, starting from `root`.
21
21
  * Returns an array of objects: { name, src }.
22
22
  */
23
23
  async function findApplications(root) {
24
- const applications= [];
25
- async function recurse(dir) {
26
- for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
27
- if (!entry.isDirectory()) continue;
28
- if(entry.name == "node_modules") continue;
29
- const fullPath = path.join(dir, entry.name);
30
- const srcDir = path.join(fullPath, 'src');
31
- const pkgFile = path.join(fullPath, 'package.json');
32
- let hasSrcAndPkg = false;
33
- try {
34
- const [srcStat, pkgStat] = await Promise.all([
35
- fs.stat(srcDir),
36
- fs.stat(pkgFile)
37
- ]);
38
- hasSrcAndPkg = srcStat.isDirectory() && pkgStat.isFile();
39
- } catch {
40
- // either src or package.json doesn't exist, skip
41
- }
42
- if (hasSrcAndPkg) {
43
- // read package.json to get the "name" field
44
- let appName = entry.name;
45
- try {
46
- const pkg = JSON.parse(await fs.readFile(pkgFile, 'utf8'));
47
- if (pkg.name) appName = pkg.name;
48
- } catch {
49
- // if JSON parse fails, stick with folder name
24
+ const applications = [];
25
+ async function recurse(dir) {
26
+ for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
27
+ if (!entry.isDirectory()) continue;
28
+ if (entry.name == "node_modules") continue;
29
+ const fullPath = path.join(dir, entry.name);
30
+ const srcDir = path.join(fullPath, 'src');
31
+ const pkgFile = path.join(fullPath, 'package.json');
32
+ let hasSrcAndPkg = false;
33
+ try {
34
+ const [srcStat, pkgStat] = await Promise.all([
35
+ fs.stat(srcDir),
36
+ fs.stat(pkgFile)
37
+ ]);
38
+ hasSrcAndPkg = srcStat.isDirectory() && pkgStat.isFile();
39
+ } catch {
40
+ // either src or package.json doesn't exist, skip
41
+ }
42
+ if (hasSrcAndPkg) {
43
+ // read package.json to get the "name" field
44
+ let appName = entry.name;
45
+ try {
46
+ const pkg = JSON.parse(await fs.readFile(pkgFile, 'utf8'));
47
+ if (pkg.name) appName = pkg.name;
48
+ } catch {
49
+ // if JSON parse fails, stick with folder name
50
+ }
51
+ applications.push({ name: appName, src: srcDir, appPath: dir, fullPath: fullPath });
52
+ }
53
+ // dive deeper
54
+ await recurse(fullPath);
50
55
  }
51
- applications.push({ name: appName, src: srcDir });
52
- }
53
- // dive deeper
54
- await recurse(fullPath);
55
56
  }
56
- }
57
- await recurse(root);
58
- return applications;
57
+ await recurse(root);
58
+ return applications;
59
59
  }
60
60
 
61
61
 
@@ -65,123 +65,202 @@ async function findApplications(root) {
65
65
  * Returns an object { src, targets, ignore } where src/targets are absolute paths.
66
66
  */
67
67
  async function loadConfigOrPrompt(prompt) {
68
- if (await fs.pathExists(PACKAGE_JSON_ROOT_PATH)) {
69
- if(!prompt) {
70
- const raw = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
71
- if(raw.replikator && raw.replikator.src && raw.replikator.targets && raw.replikator.ignore) {
72
- return {
73
- src: path.resolve(projectRoot, raw.replikator.src),
74
- targets: raw.replikator.targets.map(rel => path.resolve(projectRoot, rel)),
75
- ignore: raw.replikator.ignore
76
- };
68
+ if (await fs.pathExists(PACKAGE_JSON_ROOT_PATH)) {
69
+ if (!prompt) {
70
+ const raw = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
71
+ if (raw.replikator && raw.replikator.src && raw.replikator.targets && raw.replikator.ignore) {
72
+ return {
73
+ src: path.resolve(projectRoot, raw.replikator.src),
74
+ targets: raw.replikator.targets.map(rel => path.resolve(projectRoot, rel)),
75
+ ignore: raw.replikator.ignore
76
+ };
77
+ }
78
+ }
79
+ } else {
80
+ throw new Error(`Unable to find root package.json`);
77
81
  }
82
+
83
+ const applications = await findApplications(projectRoot);
84
+ const answers = await inquirer.prompt([
85
+ {
86
+ name: 'src',
87
+ type: 'input',
88
+ message: 'Path to the directory to replicate:',
89
+ default: 'packages/shared',
90
+ validate: i => fs.pathExistsSync(path.resolve(projectRoot, i)) || 'The folder does not exist'
91
+ },
92
+ {
93
+ name: 'targets',
94
+ type: 'checkbox',
95
+ message: 'Select the targeted applications:',
96
+ choices: applications.map(a => { return { name: a.name, value: { src: a.src, appPath: a.appPath, fullPath: a.fullPath } } }),
97
+ validate(ans) {
98
+ if (ans.length < 1) {
99
+ return 'You must choose at least one application.';
100
+ }
101
+ return true;
102
+ }
103
+ },
104
+ {
105
+ name: 'turbo',
106
+ type: 'list',
107
+ message: 'Would you like to configure for Turbo?',
108
+ choices: [{ name: 'Yes', value: true }, { name: 'No', value: false }],
109
+ default: true
110
+ }
111
+ ]);
112
+
113
+ const absSrc = path.resolve(projectRoot, answers.src);
114
+ const absTargets = await Promise.all(answers.targets.map(async t => path.join(t.src, SHARED_PATH)));
115
+ const relSrc = path.relative(projectRoot, absSrc);
116
+ const relTargets = absTargets.map(abs => path.relative(projectRoot, abs));
117
+
118
+ if (answers.turbo) {
119
+ const appPaths = new Set(answers.targets.map(t => t.appPath))
120
+ for (const appPath of appPaths) {
121
+ const replikatorPath = path.join(appPath, 'replikator')
122
+ const replikatorPackagePath = path.join(replikatorPath, 'package.json')
123
+ await fs.ensureDir(replikatorPath);
124
+ if (await fs.pathExists(replikatorPackagePath)) {
125
+ const replikatorPackageJson = await fs.readJson(replikatorPackagePath);
126
+ const config = { ...replikatorPackageJson, scripts: { dev: `cd ${path.relative(replikatorPath, projectRoot)} && rpk run` } };
127
+ fs.writeJson(replikatorPackagePath, config, { spaces: 2 });
128
+ } else {
129
+ const config = { name: 'replikator', scripts: { dev: `cd ${path.relative(replikatorPath, projectRoot)} && rpk run` } };
130
+ fs.writeJson(replikatorPackagePath, config, { spaces: 2 });
131
+ }
132
+ }
78
133
  }
79
- } else {
80
- throw new Error(`Unable to find root package.json`);
81
- }
82
-
83
- const applications = await findApplications(projectRoot);
84
- const answers = await inquirer.prompt([
85
- {
86
- name: 'src',
87
- type: 'input',
88
- message: 'Path to the directory to replicate:',
89
- default: 'packages/shared',
90
- validate: i => fs.pathExistsSync(path.resolve(projectRoot, i)) || 'The folder does not exist'
91
- },
92
- {
93
- name: 'targets',
94
- type: 'checkbox',
95
- message: 'Select the targeted applications:',
96
- choices: applications.map(a => { return {name: a.name, value: a.src}}),
97
- validate(ans) {
98
- if (ans.length < 1) {
99
- return 'You must choose at least one application.';
134
+
135
+ for (const app of answers.targets) {
136
+ const fullPath = app.fullPath
137
+ const tsconfigPath = path.join(fullPath, 'tsconfig.json')
138
+ if (await fs.pathExists(tsconfigPath)) {
139
+ const tsconfigJson = await fs.readJson(tsconfigPath);
140
+ const config = { ...tsconfigJson, compilerOptions: { ...tsconfigJson?.compilerOptions, paths: { ...tsconfigJson?.compilerOptions?.paths, "shared/*": [path.join(path.relative(fullPath, absSrc), '*')] } } };
141
+ fs.writeJson(tsconfigPath, config, { spaces: 2 });
142
+ } else {
143
+ const config = { compilerOptions: { paths: { "shared/*": [path.join(path.relative(fullPath, absSrc), '*')] } } };
144
+ fs.writeJson(tsconfigPath, config, { spaces: 2 });
145
+ }
146
+ const aliasLine = `'shared': path.resolve(__dirname, 'src/shared'),`;
147
+ const viteConfigPath = path.join(fullPath, 'vite.config.ts')
148
+ if (await fs.pathExists(viteConfigPath)) {
149
+ let code = await fs.readFile(viteConfigPath, 'utf-8');
150
+ if (!code.includes(aliasLine)) {
151
+ const aliasBlockRe = /(resolve\s*:\s*{[^}]*alias\s*:\s*{)([^}]*)(\})/m;
152
+ if (aliasBlockRe.test(code)) {
153
+ code = code.replace(aliasBlockRe, (_, start, inner, end) =>
154
+ `${start}${inner.trim()}\n ${aliasLine}\n ${end}`
155
+ );
156
+
157
+ } else if (/resolve\s*:\s*{/.test(code)) {
158
+ code = code.replace(
159
+ /resolve\s*:\s*{([^}]*)}/m,
160
+ (_, inner) => `resolve: {\n alias: {\n ${aliasLine}\n },\n ${inner.trim()}\n }`
161
+ );
162
+ } else {
163
+ code = code.replace(
164
+ /defineConfig\(\s*{([\s\S]*?)}\s*\)/m,
165
+ (_, inner) => `defineConfig({\n resolve: {\n alias: {\n ${aliasLine}\n }\n },\n${inner.trim()}\n})`
166
+ );
167
+ }
168
+ await fs.writeFile(viteConfigPath, code, 'utf-8');
169
+ }
170
+ } else {
171
+ await fs.ensureDir(path.dirname(viteConfigPath))
172
+ const tpl = `import { defineConfig } from 'vite';
173
+ import path from 'path';
174
+
175
+ export default defineConfig({
176
+ resolve: {
177
+ alias: {
178
+ ${aliasLine}
179
+ }
180
+ }
181
+ });
182
+ `;
183
+ await fs.writeFile(viteConfigPath, tpl, 'utf-8')
100
184
  }
101
- return true;
102
- }
103
185
  }
104
- ]);
105
-
106
- const absSrc = path.resolve(projectRoot, answers.src);
107
- const absTargets = await Promise.all(answers.targets.map(async t => path.join(t, 'shared')));
108
- const relSrc = path.relative(projectRoot, absSrc);
109
- const relTargets = absTargets.map(abs => path.relative(projectRoot, abs));
110
-
111
- const package_json = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
112
- const config = { ...package_json, replikator: { src: relSrc, targets: relTargets, ignore: []} };
113
- await fs.writeJson(PACKAGE_JSON_ROOT_PATH, config, { spaces: 2 });
114
- console.log(`Configuration saved in ${path.relative(projectRoot, PACKAGE_JSON_ROOT_PATH)}`);
115
-
116
- return { src: absSrc, targets: absTargets, ignore: [] };
186
+
187
+
188
+
189
+
190
+ const package_json = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
191
+ const config = { ...package_json, replikator: { src: relSrc, targets: relTargets, ignore: [] } };
192
+ await fs.writeJson(PACKAGE_JSON_ROOT_PATH, config, { spaces: 2 });
193
+ console.log(`Configuration saved in ${path.relative(projectRoot, PACKAGE_JSON_ROOT_PATH)}`);
194
+
195
+ return { src: absSrc, targets: absTargets, ignore: [] };
117
196
  }
118
197
 
119
198
  /**
120
199
  * Starts the initial copy and then sets up the watcher.
121
200
  */
122
201
  async function main() {
123
- let prompt = false;
124
- if(process.argv.length > 2) {
125
- switch (process.argv[2]) {
126
- case "init":
127
- prompt = true
128
- break;
129
- case "run":
130
- prompt = false
131
- break;
132
- case "clean":
133
- console.log('Cleaning...');
134
- console.log('\x1b[32mCleaning is complete.\x1b[0m');
202
+ let prompt = false;
203
+ if (process.argv.length > 2) {
204
+ switch (process.argv[2]) {
205
+ case "init":
206
+ prompt = true
207
+ break;
208
+ case "run":
209
+ prompt = false
210
+ break;
211
+ case "clean":
212
+ console.log('Cleaning...');
213
+ console.log('\x1b[32mCleaning is complete.\x1b[0m');
214
+ process.exit(0);
215
+ }
216
+ } else {
217
+ console.log(`RPK / Replikator CLI tool / version ${await getVersion()}`)
218
+ console.log("");
219
+ console.log("Usage: rpk [command]");
220
+ console.log("");
221
+ console.log("Commands:");
222
+ console.log(" init Command used to init replikator configuration.");
223
+ console.log(" run Command used to run replikator.");
135
224
  process.exit(0);
136
225
  }
137
- } else {
138
- console.log(`RPK / Replikator CLI tool / version ${await getVersion()}`)
139
- console.log("");
140
- console.log("Usage: rpk [command]");
141
- console.log("");
142
- console.log("Commands:");
143
- console.log(" init Command used to init replikator configuration.");
144
- console.log(" run Command used to run replikator.");
145
- process.exit(0);
146
- }
147
- const { src, targets, ignore } = await loadConfigOrPrompt(prompt);
148
-
149
- await Promise.all(
150
- targets.map(dest =>
151
- fs.ensureDir(dest).then(() =>
152
- fs.copy(src, dest, { overwrite: true })
153
- )
154
- )
155
- );
156
- console.log('Initial copy completed.');
157
-
158
- const watcher = chokidar.watch(src, { ignored: ignore, persistent: true });
159
- watcher
160
- .on('add', p => syncFile('add', p, src, targets))
161
- .on('change', p => syncFile('change', p, src, targets))
162
- .on('unlink', p => syncFile('unlink', p, src, targets))
163
- .on('error', e => console.error('Watcher error:', e));
226
+ const { src, targets, ignore } = await loadConfigOrPrompt(prompt);
227
+
228
+ await Promise.all(
229
+ targets.map(dest =>
230
+ fs.ensureDir(dest).then(() =>
231
+ fs.copy(src, dest, { overwrite: true })
232
+ )
233
+ )
234
+ );
235
+ console.log('Initial copy completed.');
236
+
237
+ const watcher = chokidar.watch(src, { ignored: ignore, persistent: true });
238
+ watcher
239
+ .on('add', p => syncFile('add', p, src, targets))
240
+ .on('change', p => syncFile('change', p, src, targets))
241
+ .on('unlink', p => syncFile('unlink', p, src, targets))
242
+ .on('error', e => console.error('Watcher error:', e));
164
243
  }
165
244
 
166
245
  /**
167
246
  * Syncs a file that was added/modified/deleted to all targets.
168
247
  */
169
248
  async function syncFile(event, filePath, srcDir, targets) {
170
- const rel = path.relative(srcDir, filePath);
171
- await Promise.all(targets.map(async destRoot => {
172
- const destPath = path.join(destRoot, rel);
173
- if (event === 'unlink') {
174
- await fs.remove(destPath);
175
- console.log(`Deleted: ${rel}`);
176
- } else {
177
- await fs.ensureDir(path.dirname(destPath));
178
- await fs.copy(filePath, destPath, { overwrite: true });
179
- console.log(`${event === 'add' ? 'Added' : 'Updated'}: ${rel}`);
180
- }
181
- }));
249
+ const rel = path.relative(srcDir, filePath);
250
+ await Promise.all(targets.map(async destRoot => {
251
+ const destPath = path.join(destRoot, rel);
252
+ if (event === 'unlink') {
253
+ await fs.remove(destPath);
254
+ console.log(`Deleted: ${rel}`);
255
+ } else {
256
+ await fs.ensureDir(path.dirname(destPath));
257
+ await fs.copy(filePath, destPath, { overwrite: true });
258
+ console.log(`${event === 'add' ? 'Added' : 'Updated'}: ${rel}`);
259
+ }
260
+ }));
182
261
  }
183
262
 
184
263
  main().catch(err => {
185
- console.error('Fatal error:', err);
186
- process.exit(1);
264
+ console.error('Fatal error:', err);
265
+ process.exit(1);
187
266
  });
package/package.json CHANGED
@@ -1,31 +1,38 @@
1
1
  {
2
- "name": "@9of9solutions/replikator",
3
- "version": "1.0.11",
4
- "type": "module",
5
- "main": "main.js",
6
- "bin": {
7
- "replikator": "main.js",
8
- "rpk": "main.js"
9
- },
10
- "scripts": {
11
- "replikator": "node main.js",
12
- "rpk": "node main.js"
13
- },
14
- "files": [
15
- "main.js"
2
+ "name": "@9of9solutions/replikator",
3
+ "version": "1.0.13",
4
+ "type": "module",
5
+ "main": "main.js",
6
+ "bin": {
7
+ "replikator": "main.js",
8
+ "rpk": "main.js"
9
+ },
10
+ "scripts": {
11
+ "replikator": "node main.js",
12
+ "rpk": "node main.js"
13
+ },
14
+ "files": [
15
+ "main.js"
16
+ ],
17
+ "keywords": [],
18
+ "author": "Germain LESPINGAL",
19
+ "license": "ISC",
20
+ "description": "",
21
+ "devDependencies": {
22
+ "chokidar": "^4.0.3",
23
+ "fs-extra": "^11.3.0"
24
+ },
25
+ "dependencies": {
26
+ "commander": "^13.1.0",
27
+ "degit": "^2.8.4",
28
+ "inquirer": "^8.2.6",
29
+ "winston": "^3.17.0"
30
+ },
31
+ "replikator": {
32
+ "src": "packages/shared",
33
+ "targets": [
34
+ "apps/app1/src/shared"
16
35
  ],
17
- "keywords": [],
18
- "author": "Germain LESPINGAL",
19
- "license": "ISC",
20
- "description": "",
21
- "devDependencies": {
22
- "chokidar": "^4.0.3",
23
- "fs-extra": "^11.3.0"
24
- },
25
- "dependencies": {
26
- "commander": "^13.1.0",
27
- "degit": "^2.8.4",
28
- "inquirer": "^8.2.6",
29
- "winston": "^3.17.0"
30
- }
36
+ "ignore": []
37
+ }
31
38
  }