obsidian-plugin-config 1.4.4 → 1.4.6

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.
@@ -1,731 +1,725 @@
1
1
  #!/usr/bin/env tsx
2
2
 
3
- import fs from "fs";
4
- import path from "path";
5
- import { execSync } from "child_process";
6
- import { fileURLToPath } from "url";
7
- import { isValidPath, gitExec } from "./utils.js";
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { execSync } from 'child_process';
6
+ import { fileURLToPath } from 'url';
7
+ import { isValidPath, gitExec } from './utils.js';
8
8
 
9
9
  export interface InjectionPlan {
10
- targetPath: string;
11
- isObsidianPlugin: boolean;
12
- hasPackageJson: boolean;
13
- hasManifest: boolean;
14
- hasScriptsFolder: boolean;
15
- currentDependencies: string[];
10
+ targetPath: string;
11
+ isObsidianPlugin: boolean;
12
+ hasPackageJson: boolean;
13
+ hasManifest: boolean;
14
+ hasScriptsFolder: boolean;
15
+ currentDependencies: string[];
16
16
  }
17
17
 
18
18
  /**
19
19
  * Analyze the target plugin directory
20
20
  */
21
21
  export async function analyzePlugin(pluginPath: string): Promise<InjectionPlan> {
22
- const packageJsonPath = path.join(pluginPath, "package.json");
23
- const manifestPath = path.join(pluginPath, "manifest.json");
24
- const scriptsPath = path.join(pluginPath, "scripts");
25
-
26
- const plan: InjectionPlan = {
27
- targetPath: pluginPath,
28
- isObsidianPlugin: false,
29
- hasPackageJson: await isValidPath(packageJsonPath),
30
- hasManifest: await isValidPath(manifestPath),
31
- hasScriptsFolder: await isValidPath(scriptsPath),
32
- currentDependencies: []
33
- };
34
-
35
- if (plan.hasManifest) {
36
- try {
37
- const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
38
- plan.isObsidianPlugin = !!(manifest.id && manifest.name && manifest.version);
39
- } catch {
40
- console.warn("Warning: Could not parse manifest.json");
41
- }
42
- }
43
-
44
- if (plan.hasPackageJson) {
45
- try {
46
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
47
- plan.currentDependencies = [
48
- ...Object.keys(packageJson.dependencies || {}),
49
- ...Object.keys(packageJson.devDependencies || {})
50
- ];
51
- } catch {
52
- console.warn("Warning: Could not parse package.json");
53
- }
54
- }
55
-
56
- return plan;
22
+ const packageJsonPath = path.join(pluginPath, 'package.json');
23
+ const manifestPath = path.join(pluginPath, 'manifest.json');
24
+ const scriptsPath = path.join(pluginPath, 'scripts');
25
+
26
+ const plan: InjectionPlan = {
27
+ targetPath: pluginPath,
28
+ isObsidianPlugin: false,
29
+ hasPackageJson: await isValidPath(packageJsonPath),
30
+ hasManifest: await isValidPath(manifestPath),
31
+ hasScriptsFolder: await isValidPath(scriptsPath),
32
+ currentDependencies: []
33
+ };
34
+
35
+ if (plan.hasManifest) {
36
+ try {
37
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
38
+ plan.isObsidianPlugin = !!(manifest.id && manifest.name && manifest.version);
39
+ } catch {
40
+ console.warn('Warning: Could not parse manifest.json');
41
+ }
42
+ }
43
+
44
+ if (plan.hasPackageJson) {
45
+ try {
46
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
47
+ plan.currentDependencies = [
48
+ ...Object.keys(packageJson.dependencies || {}),
49
+ ...Object.keys(packageJson.devDependencies || {})
50
+ ];
51
+ } catch {
52
+ console.warn('Warning: Could not parse package.json');
53
+ }
54
+ }
55
+
56
+ return plan;
57
57
  }
58
58
 
59
59
  /**
60
60
  * Find plugin-config root directory (handles NPM global installs)
61
61
  */
62
62
  export function findPluginConfigRoot(): string {
63
- const scriptDir = path.dirname(fileURLToPath(import.meta.url));
64
- const npmPackageRoot = path.resolve(scriptDir, "..");
65
- const npmPackageJson = path.join(npmPackageRoot, "package.json");
66
-
67
- if (fs.existsSync(npmPackageJson)) {
68
- try {
69
- const packageContent = JSON.parse(fs.readFileSync(npmPackageJson, "utf8"));
70
- if (packageContent.name === "obsidian-plugin-config") {
71
- return npmPackageRoot;
72
- }
73
- } catch {
74
- // Ignore parsing errors
75
- }
76
- }
77
-
78
- return process.cwd();
63
+ const scriptDir = path.dirname(fileURLToPath(import.meta.url));
64
+ const npmPackageRoot = path.resolve(scriptDir, '..');
65
+ const npmPackageJson = path.join(npmPackageRoot, 'package.json');
66
+
67
+ if (fs.existsSync(npmPackageJson)) {
68
+ try {
69
+ const packageContent = JSON.parse(fs.readFileSync(npmPackageJson, 'utf8'));
70
+ if (packageContent.name === 'obsidian-plugin-config') {
71
+ return npmPackageRoot;
72
+ }
73
+ } catch {
74
+ // Ignore parsing errors
75
+ }
76
+ }
77
+
78
+ return process.cwd();
79
79
  }
80
80
 
81
81
  /**
82
82
  * Copy file content from local plugin-config directory
83
83
  */
84
84
  export function copyFromLocal(filePath: string): string {
85
- const configRoot = findPluginConfigRoot();
86
- const sourcePath = path.join(configRoot, filePath);
87
-
88
- try {
89
- return fs.readFileSync(sourcePath, "utf8");
90
- } catch (error) {
91
- throw new Error(`Failed to copy ${filePath}: ${error}`);
92
- }
85
+ const configRoot = findPluginConfigRoot();
86
+ const sourcePath = path.join(configRoot, filePath);
87
+
88
+ try {
89
+ return fs.readFileSync(sourcePath, 'utf8');
90
+ } catch (error) {
91
+ throw new Error(`Failed to copy ${filePath}: ${error}`);
92
+ }
93
93
  }
94
94
 
95
95
  /**
96
96
  * Check if plugin-config repo is clean and commit if needed
97
97
  */
98
98
  export async function ensurePluginConfigClean(): Promise<void> {
99
- const configRoot = findPluginConfigRoot();
100
- const gitDir = path.join(configRoot, ".git");
101
-
102
- // Skip git check if not a git repo
103
- // (e.g. NPM global install)
104
- if (!fs.existsSync(gitDir)) {
105
- console.log(
106
- `āœ… Plugin-config repo is clean` +
107
- ` (NPM install, no git check)`
108
- );
109
- return;
110
- }
111
-
112
- const originalCwd = process.cwd();
113
-
114
- try {
115
- process.chdir(configRoot);
116
- const gitStatus = execSync(
117
- "git status --porcelain",
118
- { encoding: "utf8" }
119
- ).trim();
120
-
121
- if (gitStatus) {
122
- console.log(
123
- `\nāš ļø Plugin-config has uncommitted changes:`
124
- );
125
- console.log(gitStatus);
126
- console.log(
127
- `\nšŸ”§ Auto-committing changes...`
128
- );
129
-
130
- const msg =
131
- "šŸ”§ Update plugin-config templates";
132
- gitExec("git add -A");
133
- gitExec(`git commit -m "${msg}"`);
134
-
135
- try {
136
- const branch = execSync(
137
- "git rev-parse --abbrev-ref HEAD",
138
- { encoding: "utf8" }
139
- ).trim();
140
- gitExec(`git push origin ${branch}`);
141
- console.log(
142
- `āœ… Changes committed and pushed`
143
- );
144
- } catch {
145
- try {
146
- const branch = execSync(
147
- "git rev-parse --abbrev-ref HEAD",
148
- { encoding: "utf8" }
149
- ).trim();
150
- gitExec(
151
- `git push --set-upstream origin ${branch}`
152
- );
153
- console.log(
154
- `āœ… New branch pushed with upstream`
155
- );
156
- } catch {
157
- console.log(
158
- `āš ļø Committed locally, push failed`
159
- );
160
- }
161
- }
162
- } else {
163
- console.log(`āœ… Plugin-config repo is clean`);
164
- }
165
- } finally {
166
- process.chdir(originalCwd);
167
- }
99
+ const configRoot = findPluginConfigRoot();
100
+ const gitDir = path.join(configRoot, '.git');
101
+
102
+ // Skip git check if not a git repo
103
+ // (e.g. NPM global install)
104
+ if (!fs.existsSync(gitDir)) {
105
+ console.log(`āœ… Plugin-config repo is clean` + ` (NPM install, no git check)`);
106
+ return;
107
+ }
108
+
109
+ const originalCwd = process.cwd();
110
+
111
+ try {
112
+ process.chdir(configRoot);
113
+ const gitStatus = execSync('git status --porcelain', { encoding: 'utf8' }).trim();
114
+
115
+ if (gitStatus) {
116
+ console.log(`\nāš ļø Plugin-config has uncommitted changes:`);
117
+ console.log(gitStatus);
118
+ console.log(`\nšŸ”§ Auto-committing changes...`);
119
+
120
+ const msg = 'šŸ”§ Update plugin-config templates';
121
+ gitExec('git add -A');
122
+ gitExec(`git commit -m "${msg}"`);
123
+
124
+ try {
125
+ const branch = execSync('git rev-parse --abbrev-ref HEAD', {
126
+ encoding: 'utf8'
127
+ }).trim();
128
+ gitExec(`git push origin ${branch}`);
129
+ console.log(`āœ… Changes committed and pushed`);
130
+ } catch {
131
+ try {
132
+ const branch = execSync('git rev-parse --abbrev-ref HEAD', {
133
+ encoding: 'utf8'
134
+ }).trim();
135
+ gitExec(`git push --set-upstream origin ${branch}`);
136
+ console.log(`āœ… New branch pushed with upstream`);
137
+ } catch {
138
+ console.log(`āš ļø Committed locally, push failed`);
139
+ }
140
+ }
141
+ } else {
142
+ console.log(`āœ… Plugin-config repo is clean`);
143
+ }
144
+ } finally {
145
+ process.chdir(originalCwd);
146
+ }
168
147
  }
169
148
 
170
149
  /**
171
150
  * Display injection plan and ask for confirmation
172
151
  */
173
152
  export async function showInjectionPlan(
174
- plan: InjectionPlan,
175
- autoConfirm: boolean = false,
176
- useSass: boolean = false
153
+ plan: InjectionPlan,
154
+ autoConfirm: boolean = false,
155
+ useSass: boolean = false
177
156
  ): Promise<boolean> {
178
- const { askConfirmation, createReadlineInterface } = await import("./utils.js");
179
- const rl = createReadlineInterface();
180
-
181
- console.log(`\nšŸŽÆ Injection Plan for: ${plan.targetPath}`);
182
- console.log(`šŸ“ Target: ${path.basename(plan.targetPath)}`);
183
- console.log(`šŸ“¦ Package.json: ${plan.hasPackageJson ? "āœ…" : "āŒ"}`);
184
- console.log(`šŸ“‹ Manifest.json: ${plan.hasManifest ? "āœ…" : "āŒ"}`);
185
- console.log(
186
- `šŸ“‚ Scripts folder: ${plan.hasScriptsFolder ? "āœ… (will be updated)" : "āŒ (will be created)"}`
187
- );
188
- console.log(`šŸ”Œ Obsidian plugin: ${plan.isObsidianPlugin ? "āœ…" : "āŒ"}`);
189
- console.log(
190
- `šŸŽØ SASS support: ${useSass ? "āœ… (esbuild-sass-plugin will be added)" : "āŒ"}`
191
- );
192
-
193
- if (!plan.isObsidianPlugin) {
194
- console.log(`\nāš ļø Warning: This doesn't appear to be a valid Obsidian plugin`);
195
- console.log(` Missing manifest.json or invalid structure`);
196
- }
197
-
198
- console.log(`\nšŸ“‹ Will inject:`);
199
- console.log(` āœ… Local scripts (utils.ts, esbuild.config.ts, acp.ts, etc.)`);
200
- console.log(` āœ… Updated package.json scripts`);
201
- console.log(` āœ… Required dependencies`);
202
- console.log(` šŸ” Analyze centralized imports (manual commenting may be needed)`);
203
-
204
- if (autoConfirm) {
205
- console.log(`\nāœ… Auto-confirming injection...`);
206
- rl.close();
207
- return true;
208
- }
209
-
210
- const result = await askConfirmation(`\nProceed with injection?`, rl);
211
- rl.close();
212
- return result;
157
+ const { askConfirmation, createReadlineInterface } = await import('./utils.js');
158
+ const rl = createReadlineInterface();
159
+
160
+ console.log(`\nšŸŽÆ Injection Plan for: ${plan.targetPath}`);
161
+ console.log(`šŸ“ Target: ${path.basename(plan.targetPath)}`);
162
+ console.log(`šŸ“¦ Package.json: ${plan.hasPackageJson ? 'āœ…' : 'āŒ'}`);
163
+ console.log(`šŸ“‹ Manifest.json: ${plan.hasManifest ? 'āœ…' : 'āŒ'}`);
164
+ console.log(
165
+ `šŸ“‚ Scripts folder: ${plan.hasScriptsFolder ? 'āœ… (will be updated)' : 'āŒ (will be created)'}`
166
+ );
167
+ console.log(`šŸ”Œ Obsidian plugin: ${plan.isObsidianPlugin ? 'āœ…' : 'āŒ'}`);
168
+ console.log(
169
+ `šŸŽØ SASS support: ${useSass ? 'āœ… (esbuild-sass-plugin will be added)' : 'āŒ'}`
170
+ );
171
+
172
+ if (!plan.isObsidianPlugin) {
173
+ console.log(`\nāš ļø Warning: This doesn't appear to be a valid Obsidian plugin`);
174
+ console.log(` Missing manifest.json or invalid structure`);
175
+ }
176
+
177
+ console.log(`\nšŸ“‹ Will inject:`);
178
+ console.log(` āœ… Local scripts (utils.ts, esbuild.config.ts, acp.ts, etc.)`);
179
+ console.log(` āœ… Updated package.json scripts`);
180
+ console.log(` āœ… Required dependencies`);
181
+ console.log(` šŸ” Analyze centralized imports (manual commenting may be needed)`);
182
+
183
+ if (autoConfirm) {
184
+ console.log(`\nāœ… Auto-confirming injection...`);
185
+ rl.close();
186
+ return true;
187
+ }
188
+
189
+ const result = await askConfirmation(`\nProceed with injection?`, rl);
190
+ rl.close();
191
+ return result;
213
192
  }
214
193
 
215
194
  /**
216
195
  * Clean old script files
217
196
  */
218
197
  export async function cleanOldScripts(scriptsPath: string): Promise<void> {
219
- const scriptNames = ["utils", "esbuild.config", "acp", "update-version", "release", "help"];
220
- const extensions = [".ts", ".mts", ".js", ".mjs"];
221
-
222
- for (const scriptName of scriptNames) {
223
- for (const ext of extensions) {
224
- const scriptFile = path.join(scriptsPath, `${scriptName}${ext}`);
225
- if (await isValidPath(scriptFile)) {
226
- fs.unlinkSync(scriptFile);
227
- console.log(`šŸ—‘ļø Removed existing ${scriptName}${ext} (will be replaced)`);
228
- }
229
- }
230
- }
231
-
232
- const obsoleteRootFiles = ["help-plugin.ts"];
233
- for (const fileName of obsoleteRootFiles) {
234
- const filePath = path.join(path.dirname(scriptsPath), fileName);
235
- if (await isValidPath(filePath)) {
236
- fs.unlinkSync(filePath);
237
- console.log(`šŸ—‘ļø Removed obsolete root file: ${fileName}`);
238
- }
239
- }
240
-
241
- const obsoleteFiles = ["start.mjs", "start.js"];
242
- for (const fileName of obsoleteFiles) {
243
- const filePath = path.join(scriptsPath, fileName);
244
- if (await isValidPath(filePath)) {
245
- fs.unlinkSync(filePath);
246
- console.log(`šŸ—‘ļø Removed obsolete file: ${fileName}`);
247
- }
248
- }
198
+ const scriptNames = [
199
+ 'utils',
200
+ 'esbuild.config',
201
+ 'acp',
202
+ 'update-version',
203
+ 'release',
204
+ 'help'
205
+ ];
206
+ const extensions = ['.ts', '.mts', '.js', '.mjs'];
207
+
208
+ for (const scriptName of scriptNames) {
209
+ for (const ext of extensions) {
210
+ const scriptFile = path.join(scriptsPath, `${scriptName}${ext}`);
211
+ if (await isValidPath(scriptFile)) {
212
+ fs.unlinkSync(scriptFile);
213
+ console.log(
214
+ `šŸ—‘ļø Removed existing ${scriptName}${ext} (will be replaced)`
215
+ );
216
+ }
217
+ }
218
+ }
219
+
220
+ const obsoleteRootFiles = ['help-plugin.ts'];
221
+ for (const fileName of obsoleteRootFiles) {
222
+ const filePath = path.join(path.dirname(scriptsPath), fileName);
223
+ if (await isValidPath(filePath)) {
224
+ fs.unlinkSync(filePath);
225
+ console.log(`šŸ—‘ļø Removed obsolete root file: ${fileName}`);
226
+ }
227
+ }
228
+
229
+ const obsoleteFiles = ['start.mjs', 'start.js'];
230
+ for (const fileName of obsoleteFiles) {
231
+ const filePath = path.join(scriptsPath, fileName);
232
+ if (await isValidPath(filePath)) {
233
+ fs.unlinkSync(filePath);
234
+ console.log(`šŸ—‘ļø Removed obsolete file: ${fileName}`);
235
+ }
236
+ }
249
237
  }
250
238
 
251
239
  /**
252
240
  * Clean old ESLint config files
253
241
  */
254
242
  export async function cleanOldLintFiles(targetPath: string): Promise<void> {
255
- const oldLintFiles = [".eslintrc", ".eslintrc.js", ".eslintrc.json", ".eslintignore"];
256
- const conflictingLintFiles = [
257
- "eslint.config.ts",
258
- "eslint.config.cjs",
259
- "eslint.config.js",
260
- "eslint.config.mjs"
261
- ];
262
-
263
- for (const fileName of oldLintFiles) {
264
- const filePath = path.join(targetPath, fileName);
265
- if (await isValidPath(filePath)) {
266
- fs.unlinkSync(filePath);
267
- console.log(`šŸ—‘ļø Removed old ESLint file: ${fileName} (replaced by eslint.config.ts)`);
268
- }
269
- }
270
-
271
- for (const fileName of conflictingLintFiles) {
272
- const filePath = path.join(targetPath, fileName);
273
- if (await isValidPath(filePath)) {
274
- fs.unlinkSync(filePath);
275
- console.log(
276
- `šŸ—‘ļø Removed existing ESLint file: ${fileName} (will be replaced by injection)`
277
- );
278
- }
279
- }
243
+ const oldLintFiles = ['.eslintrc', '.eslintrc.js', '.eslintrc.json', '.eslintignore'];
244
+ const conflictingLintFiles = [
245
+ 'eslint.config.ts',
246
+ 'eslint.config.cjs',
247
+ 'eslint.config.js',
248
+ 'eslint.config.mjs'
249
+ ];
250
+
251
+ for (const fileName of oldLintFiles) {
252
+ const filePath = path.join(targetPath, fileName);
253
+ if (await isValidPath(filePath)) {
254
+ fs.unlinkSync(filePath);
255
+ console.log(
256
+ `šŸ—‘ļø Removed old ESLint file: ${fileName} (replaced by eslint.config.ts)`
257
+ );
258
+ }
259
+ }
260
+
261
+ for (const fileName of conflictingLintFiles) {
262
+ const filePath = path.join(targetPath, fileName);
263
+ if (await isValidPath(filePath)) {
264
+ fs.unlinkSync(filePath);
265
+ console.log(
266
+ `šŸ—‘ļø Removed existing ESLint file: ${fileName} (will be replaced by injection)`
267
+ );
268
+ }
269
+ }
280
270
  }
281
271
 
282
272
  /**
283
273
  * Inject scripts and config files
284
274
  */
285
275
  export async function injectScripts(targetPath: string): Promise<void> {
286
- const scriptsPath = path.join(targetPath, "scripts");
287
-
288
- if (!await isValidPath(scriptsPath)) {
289
- fs.mkdirSync(scriptsPath, { recursive: true });
290
- console.log(`šŸ“ Created scripts directory`);
291
- }
292
-
293
- await cleanOldScripts(scriptsPath);
294
- await cleanOldLintFiles(targetPath);
295
-
296
- const scriptFiles = [
297
- "templates/scripts/utils.ts",
298
- "templates/scripts/esbuild.config.ts",
299
- "templates/scripts/acp.ts",
300
- "templates/scripts/update-version.ts",
301
- "templates/scripts/release.ts",
302
- "templates/scripts/help.ts"
303
- ];
304
-
305
- // Files that need value-preserving merge instead
306
- // of full overwrite (user fills in their paths)
307
- const mergeEnvFile = new Set([".env"]);
308
-
309
- // Files with .template suffix (NPM excludes dotfiles)
310
- // Map: { source: targetName }
311
- const configFileMap: Record<string, string> = {
312
- "templates/tsconfig.json": "tsconfig.json",
313
- "templates/gitignore.template": ".gitignore",
314
- "templates/eslint.config.mts": "eslint.config.mts",
315
- "templates/.editorconfig": ".editorconfig",
316
- "templates/.prettierrc": ".prettierrc",
317
- "templates/npmrc.template": ".npmrc",
318
- "templates/env.template": ".env",
319
- };
320
-
321
- const configVscodeMap: Record<string, string> = {
322
- "templates/.vscode/settings.json":
323
- ".vscode/settings.json",
324
- "templates/.vscode/tasks.json":
325
- ".vscode/tasks.json",
326
- };
327
-
328
- const workflowFiles = [
329
- "templates/.github/workflows/release.yml",
330
- "templates/.github/workflows/release-body.md"
331
- ];
332
-
333
- console.log(`\nšŸ“„ Copying scripts from local files...`);
334
-
335
- for (const scriptFile of scriptFiles) {
336
- try {
337
- const content = copyFromLocal(scriptFile);
338
- const fileName = path.basename(scriptFile);
339
- const targetFile = path.join(scriptsPath, fileName);
340
- fs.writeFileSync(targetFile, content, "utf8");
341
- console.log(` āœ… ${fileName}`);
342
- } catch (error) {
343
- console.error(
344
- ` āŒ Failed to inject ${scriptFile}: ${error}`
345
- );
346
- }
347
- }
348
-
349
- console.log(`\nšŸ“„ Copying config files...`);
350
-
351
- // Copy root config files
352
- for (const [src, destName] of Object.entries(
353
- configFileMap
354
- )) {
355
- try {
356
- const targetFile = path.join(targetPath, destName);
357
- const templateContent = copyFromLocal(src);
358
-
359
- // For .env: merge existing values into the template
360
- if (
361
- mergeEnvFile.has(destName) &&
362
- fs.existsSync(targetFile)
363
- ) {
364
- const existing = fs.readFileSync(
365
- targetFile, "utf8"
366
- );
367
- // Parse existing key=value pairs
368
- const existingVals: Record<string, string> = {};
369
- for (const line of existing.split(/\r?\n/)) {
370
- const m = line.match(/^([^#=]+)=(.*)$/);
371
- if (m) existingVals[m[1].trim()] = m[2].trim();
372
- }
373
- // Re-write template, substituting existing values
374
- const merged = templateContent
375
- .split(/\r?\n/)
376
- .map((line) => {
377
- const m = line.match(/^([^#=]+)=(.*)$/);
378
- if (m) {
379
- const key = m[1].trim();
380
- const val = existingVals[key] ?? m[2].trim();
381
- return `${key}=${val}`;
382
- }
383
- return line;
384
- })
385
- .join("\n");
386
- fs.writeFileSync(targetFile, merged, "utf8");
387
- console.log(` āœ… ${destName} (values preserved)`);
388
- continue;
389
- }
390
-
391
- fs.writeFileSync(targetFile, templateContent, "utf8");
392
- console.log(` āœ… ${destName}`);
393
- } catch (error) {
394
- console.error(
395
- ` āŒ Failed to inject ${destName}: ${error}`
396
- );
397
- }
398
-
399
- }
400
-
401
- // Copy .vscode config files
402
- for (const [src, destName] of Object.entries(
403
- configVscodeMap
404
- )) {
405
- try {
406
- const content = copyFromLocal(src);
407
- const targetFile = path.join(
408
- targetPath, destName
409
- );
410
- const targetDir = path.dirname(targetFile);
411
- if (!await isValidPath(targetDir)) {
412
- fs.mkdirSync(targetDir, { recursive: true });
413
- }
414
- fs.writeFileSync(targetFile, content, "utf8");
415
- console.log(` āœ… ${destName}`);
416
- } catch (error) {
417
- console.error(
418
- ` āŒ Failed to inject ${destName}: ${error}`
419
- );
420
- }
421
- }
422
-
423
- console.log(`\nšŸ“„ Copying GitHub workflows from local files...`);
424
-
425
- for (const workflowFile of workflowFiles) {
426
- try {
427
- const content = copyFromLocal(workflowFile);
428
- const relativePath = workflowFile.replace("templates/", "");
429
- const targetFile = path.join(targetPath, relativePath);
430
- const targetDir = path.dirname(targetFile);
431
-
432
- if (!await isValidPath(targetDir)) {
433
- fs.mkdirSync(targetDir, { recursive: true });
434
- }
435
-
436
- fs.writeFileSync(targetFile, content, "utf8");
437
- console.log(` āœ… ${relativePath}`);
438
- } catch (error) {
439
- console.error(` āŒ Failed to inject ${workflowFile}: ${error}`);
440
- }
441
- }
276
+ const scriptsPath = path.join(targetPath, 'scripts');
277
+
278
+ if (!(await isValidPath(scriptsPath))) {
279
+ fs.mkdirSync(scriptsPath, { recursive: true });
280
+ console.log(`šŸ“ Created scripts directory`);
281
+ }
282
+
283
+ await cleanOldScripts(scriptsPath);
284
+ await cleanOldLintFiles(targetPath);
285
+
286
+ const scriptFiles = [
287
+ 'templates/scripts/utils.ts',
288
+ 'templates/scripts/esbuild.config.ts',
289
+ 'templates/scripts/acp.ts',
290
+ 'templates/scripts/update-version.ts',
291
+ 'templates/scripts/release.ts',
292
+ 'templates/scripts/help.ts'
293
+ ];
294
+
295
+ // Files that need value-preserving merge instead
296
+ // of full overwrite (user fills in their paths)
297
+ const mergeEnvFile = new Set(['.env']);
298
+
299
+ // Files with .template suffix (NPM excludes dotfiles)
300
+ // Map: { source: targetName }
301
+ const configFileMap: Record<string, string> = {
302
+ 'templates/tsconfig.json': 'tsconfig.json',
303
+ 'templates/gitignore.template': '.gitignore',
304
+ 'templates/eslint.config.mts': 'eslint.config.mts',
305
+ 'templates/.editorconfig': '.editorconfig',
306
+ 'templates/.prettierrc': '.prettierrc',
307
+ 'templates/npmrc.template': '.npmrc',
308
+ 'templates/env.template': '.env'
309
+ };
310
+
311
+ const configVscodeMap: Record<string, string> = {
312
+ 'templates/.vscode/settings.json': '.vscode/settings.json',
313
+ 'templates/.vscode/tasks.json': '.vscode/tasks.json'
314
+ };
315
+
316
+ const workflowFiles = [
317
+ 'templates/.github/workflows/release.yml',
318
+ 'templates/.github/workflows/release-body.md'
319
+ ];
320
+
321
+ console.log(`\nšŸ“„ Copying scripts from local files...`);
322
+
323
+ for (const scriptFile of scriptFiles) {
324
+ try {
325
+ const content = copyFromLocal(scriptFile);
326
+ const fileName = path.basename(scriptFile);
327
+ const targetFile = path.join(scriptsPath, fileName);
328
+ fs.writeFileSync(targetFile, content, 'utf8');
329
+ console.log(` āœ… ${fileName}`);
330
+ } catch (error) {
331
+ console.error(` āŒ Failed to inject ${scriptFile}: ${error}`);
332
+ }
333
+ }
334
+
335
+ console.log(`\nšŸ“„ Copying config files...`);
336
+
337
+ // Copy root config files
338
+ for (const [src, destName] of Object.entries(configFileMap)) {
339
+ try {
340
+ const targetFile = path.join(targetPath, destName);
341
+ const templateContent = copyFromLocal(src);
342
+
343
+ // For .env: merge existing values into the template
344
+ if (mergeEnvFile.has(destName) && fs.existsSync(targetFile)) {
345
+ const existing = fs.readFileSync(targetFile, 'utf8');
346
+ // Parse existing key=value pairs
347
+ const existingVals: Record<string, string> = {};
348
+ for (const line of existing.split(/\r?\n/)) {
349
+ const m = line.match(/^([^#=]+)=(.*)$/);
350
+ if (m) existingVals[m[1].trim()] = m[2].trim();
351
+ }
352
+ // Re-write template, substituting existing values
353
+ const merged = templateContent
354
+ .split(/\r?\n/)
355
+ .map((line) => {
356
+ const m = line.match(/^([^#=]+)=(.*)$/);
357
+ if (m) {
358
+ const key = m[1].trim();
359
+ const val = existingVals[key] ?? m[2].trim();
360
+ return `${key}=${val}`;
361
+ }
362
+ return line;
363
+ })
364
+ .join('\n');
365
+ fs.writeFileSync(targetFile, merged, 'utf8');
366
+ console.log(` āœ… ${destName} (values preserved)`);
367
+ continue;
368
+ }
369
+
370
+ fs.writeFileSync(targetFile, templateContent, 'utf8');
371
+ console.log(` āœ… ${destName}`);
372
+ } catch (error) {
373
+ console.error(` āŒ Failed to inject ${destName}: ${error}`);
374
+ }
375
+ }
376
+
377
+ // Copy .vscode config files
378
+ for (const [src, destName] of Object.entries(configVscodeMap)) {
379
+ try {
380
+ const content = copyFromLocal(src);
381
+ const targetFile = path.join(targetPath, destName);
382
+ const targetDir = path.dirname(targetFile);
383
+ if (!(await isValidPath(targetDir))) {
384
+ fs.mkdirSync(targetDir, { recursive: true });
385
+ }
386
+ fs.writeFileSync(targetFile, content, 'utf8');
387
+ console.log(` āœ… ${destName}`);
388
+ } catch (error) {
389
+ console.error(` āŒ Failed to inject ${destName}: ${error}`);
390
+ }
391
+ }
392
+
393
+ console.log(`\nšŸ“„ Copying GitHub workflows from local files...`);
394
+
395
+ for (const workflowFile of workflowFiles) {
396
+ try {
397
+ const content = copyFromLocal(workflowFile);
398
+ const relativePath = workflowFile.replace('templates/', '');
399
+ const targetFile = path.join(targetPath, relativePath);
400
+ const targetDir = path.dirname(targetFile);
401
+
402
+ if (!(await isValidPath(targetDir))) {
403
+ fs.mkdirSync(targetDir, { recursive: true });
404
+ }
405
+
406
+ fs.writeFileSync(targetFile, content, 'utf8');
407
+ console.log(` āœ… ${relativePath}`);
408
+ } catch (error) {
409
+ console.error(` āŒ Failed to inject ${workflowFile}: ${error}`);
410
+ }
411
+ }
442
412
  }
443
413
 
444
414
  /**
445
415
  * Update package.json with autonomous configuration
446
416
  */
447
417
  export async function updatePackageJson(
448
- targetPath: string,
449
- useSass: boolean = false
418
+ targetPath: string,
419
+ useSass: boolean = false
450
420
  ): Promise<void> {
451
- const packageJsonPath = path.join(targetPath, "package.json");
452
-
453
- if (!await isValidPath(packageJsonPath)) {
454
- console.log(`āŒ No package.json found, skipping package.json update`);
455
- return;
456
- }
457
-
458
- try {
459
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
460
-
461
- const configRoot = findPluginConfigRoot();
462
- const templatePkg = JSON.parse(
463
- fs.readFileSync(path.join(configRoot, "templates/package.json"), "utf8")
464
- );
465
-
466
- if (useSass) {
467
- const sassPkg = JSON.parse(
468
- fs.readFileSync(path.join(configRoot, "templates/package-sass.json"), "utf8")
469
- );
470
- Object.assign(templatePkg.devDependencies, sassPkg.devDependencies);
471
- }
472
-
473
- const obsoleteScripts = ["version"];
474
- for (const script of obsoleteScripts) {
475
- if (packageJson.scripts?.[script]) {
476
- console.log(` 🧹 Removing obsolete script: "${script}"`);
477
- delete packageJson.scripts[script];
478
- }
479
- }
480
-
481
- packageJson.scripts = {
482
- ...packageJson.scripts,
483
- ...templatePkg.scripts
484
- };
485
-
486
- if (!packageJson.devDependencies) packageJson.devDependencies = {};
487
-
488
- const requiredDeps: Record<string, string> = templatePkg.devDependencies;
489
-
490
- let addedDeps = 0;
491
- let updatedDeps = 0;
492
- for (const [dep, version] of Object.entries(requiredDeps)) {
493
- if (!packageJson.devDependencies[dep]) {
494
- packageJson.devDependencies[dep] = version as string;
495
- addedDeps++;
496
- } else if (packageJson.devDependencies[dep] !== version) {
497
- packageJson.devDependencies[dep] = version as string;
498
- updatedDeps++;
499
- }
500
- }
501
-
502
- if (!packageJson.engines) packageJson.engines = {};
503
- packageJson.engines.npm = templatePkg.engines.npm;
504
- packageJson.engines.yarn = templatePkg.engines.yarn;
505
- packageJson.type = templatePkg.type;
506
-
507
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), "utf8");
508
- console.log(` āœ… Updated package.json (${addedDeps} new, ${updatedDeps} updated dependencies)`);
509
- } catch (error) {
510
- console.error(` āŒ Failed to update package.json: ${error}`);
511
- }
421
+ const packageJsonPath = path.join(targetPath, 'package.json');
422
+
423
+ if (!(await isValidPath(packageJsonPath))) {
424
+ console.log(`āŒ No package.json found, skipping package.json update`);
425
+ return;
426
+ }
427
+
428
+ try {
429
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
430
+
431
+ const configRoot = findPluginConfigRoot();
432
+ const templatePkg = JSON.parse(
433
+ fs.readFileSync(path.join(configRoot, 'templates/package.json'), 'utf8')
434
+ );
435
+
436
+ if (useSass) {
437
+ const sassPkg = JSON.parse(
438
+ fs.readFileSync(
439
+ path.join(configRoot, 'templates/package-sass.json'),
440
+ 'utf8'
441
+ )
442
+ );
443
+ Object.assign(templatePkg.devDependencies, sassPkg.devDependencies);
444
+ }
445
+
446
+ const obsoleteScripts = ['version'];
447
+ for (const script of obsoleteScripts) {
448
+ if (packageJson.scripts?.[script]) {
449
+ console.log(` 🧹 Removing obsolete script: "${script}"`);
450
+ delete packageJson.scripts[script];
451
+ }
452
+ }
453
+
454
+ packageJson.scripts = {
455
+ ...packageJson.scripts,
456
+ ...templatePkg.scripts
457
+ };
458
+
459
+ if (!packageJson.devDependencies) packageJson.devDependencies = {};
460
+
461
+ const requiredDeps: Record<string, string> = templatePkg.devDependencies;
462
+
463
+ let addedDeps = 0;
464
+ let updatedDeps = 0;
465
+ for (const [dep, version] of Object.entries(requiredDeps)) {
466
+ if (!packageJson.devDependencies[dep]) {
467
+ packageJson.devDependencies[dep] = version as string;
468
+ addedDeps++;
469
+ } else if (packageJson.devDependencies[dep] !== version) {
470
+ packageJson.devDependencies[dep] = version as string;
471
+ updatedDeps++;
472
+ }
473
+ }
474
+
475
+ if (!packageJson.engines) packageJson.engines = {};
476
+ packageJson.engines.npm = templatePkg.engines.npm;
477
+ packageJson.engines.yarn = templatePkg.engines.yarn;
478
+ packageJson.type = templatePkg.type;
479
+
480
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf8');
481
+ console.log(
482
+ ` āœ… Updated package.json (${addedDeps} new, ${updatedDeps} updated dependencies)`
483
+ );
484
+ } catch (error) {
485
+ console.error(` āŒ Failed to update package.json: ${error}`);
486
+ }
512
487
  }
513
488
 
514
489
  /**
515
490
  * Analyze centralized imports in source files (without modifying)
516
491
  */
517
492
  export async function analyzeCentralizedImports(targetPath: string): Promise<void> {
518
- const srcPath = path.join(targetPath, "src");
519
-
520
- if (!await isValidPath(srcPath)) {
521
- console.log(` ā„¹ļø No src directory found`);
522
- return;
523
- }
524
-
525
- console.log(`\nšŸ” Analyzing centralized imports...`);
526
-
527
- try {
528
- const findTsFiles = (dir: string): string[] => {
529
- const files: string[] = [];
530
- for (const item of fs.readdirSync(dir)) {
531
- const fullPath = path.join(dir, item);
532
- if (fs.statSync(fullPath).isDirectory()) {
533
- files.push(...findTsFiles(fullPath));
534
- } else if (item.endsWith(".ts") || item.endsWith(".tsx")) {
535
- files.push(fullPath);
536
- }
537
- }
538
- return files;
539
- };
540
-
541
- const tsFiles = findTsFiles(srcPath);
542
- let filesWithImports = 0;
543
-
544
- for (const filePath of tsFiles) {
545
- try {
546
- const content = fs.readFileSync(filePath, "utf8");
547
- const importRegex = /import\s+.*from\s+["']obsidian-plugin-config[^"']*["']/g;
548
- if (importRegex.test(content)) {
549
- filesWithImports++;
550
- console.log(` āš ļø ${path.relative(targetPath, filePath)} - contains centralized imports`);
551
- }
552
- } catch (error) {
553
- console.warn(` āš ļø Could not analyze ${path.relative(targetPath, filePath)}: ${error}`);
554
- }
555
- }
556
-
557
- if (filesWithImports === 0) {
558
- console.log(` āœ… No centralized imports found`);
559
- } else {
560
- console.log(` āš ļø Found ${filesWithImports} files with centralized imports`);
561
- console.log(` šŸ’” You may need to manually comment these imports for the plugin to work`);
562
- }
563
- } catch (error) {
564
- console.error(` āŒ Failed to analyze imports: ${error}`);
565
- }
493
+ const srcPath = path.join(targetPath, 'src');
494
+
495
+ if (!(await isValidPath(srcPath))) {
496
+ console.log(` ā„¹ļø No src directory found`);
497
+ return;
498
+ }
499
+
500
+ console.log(`\nšŸ” Analyzing centralized imports...`);
501
+
502
+ try {
503
+ const findTsFiles = (dir: string): string[] => {
504
+ const files: string[] = [];
505
+ for (const item of fs.readdirSync(dir)) {
506
+ const fullPath = path.join(dir, item);
507
+ if (fs.statSync(fullPath).isDirectory()) {
508
+ files.push(...findTsFiles(fullPath));
509
+ } else if (item.endsWith('.ts') || item.endsWith('.tsx')) {
510
+ files.push(fullPath);
511
+ }
512
+ }
513
+ return files;
514
+ };
515
+
516
+ const tsFiles = findTsFiles(srcPath);
517
+ let filesWithImports = 0;
518
+
519
+ for (const filePath of tsFiles) {
520
+ try {
521
+ const content = fs.readFileSync(filePath, 'utf8');
522
+ const importRegex =
523
+ /import\s+.*from\s+["']obsidian-plugin-config[^"']*["']/g;
524
+ if (importRegex.test(content)) {
525
+ filesWithImports++;
526
+ console.log(
527
+ ` āš ļø ${path.relative(targetPath, filePath)} - contains centralized imports`
528
+ );
529
+ }
530
+ } catch (error) {
531
+ console.warn(
532
+ ` āš ļø Could not analyze ${path.relative(targetPath, filePath)}: ${error}`
533
+ );
534
+ }
535
+ }
536
+
537
+ if (filesWithImports === 0) {
538
+ console.log(` āœ… No centralized imports found`);
539
+ } else {
540
+ console.log(
541
+ ` āš ļø Found ${filesWithImports} files with centralized imports`
542
+ );
543
+ console.log(
544
+ ` šŸ’” You may need to manually comment these imports for the plugin to work`
545
+ );
546
+ }
547
+ } catch (error) {
548
+ console.error(` āŒ Failed to analyze imports: ${error}`);
549
+ }
566
550
  }
567
551
 
568
552
  /**
569
553
  * Create required directories
570
554
  */
571
555
  export async function createRequiredDirectories(targetPath: string): Promise<void> {
572
- const directories = [path.join(targetPath, ".github", "workflows")];
573
-
574
- for (const dir of directories) {
575
- if (!await isValidPath(dir)) {
576
- fs.mkdirSync(dir, { recursive: true });
577
- console.log(` šŸ“ Created ${path.relative(targetPath, dir)}`);
578
- }
579
- }
556
+ const directories = [path.join(targetPath, '.github', 'workflows')];
557
+
558
+ for (const dir of directories) {
559
+ if (!(await isValidPath(dir))) {
560
+ fs.mkdirSync(dir, { recursive: true });
561
+ console.log(` šŸ“ Created ${path.relative(targetPath, dir)}`);
562
+ }
563
+ }
580
564
  }
581
565
 
582
566
  /**
583
567
  * Create injection info file
584
568
  */
585
569
  export async function createInjectionInfo(targetPath: string): Promise<void> {
586
- const configRoot = findPluginConfigRoot();
587
- const configPackageJsonPath = path.join(configRoot, "package.json");
588
-
589
- let injectorVersion = "unknown";
590
- try {
591
- const configPackageJson = JSON.parse(fs.readFileSync(configPackageJsonPath, "utf8"));
592
- injectorVersion = configPackageJson.version || "unknown";
593
- } catch {
594
- console.warn("Warning: Could not read injector version");
595
- }
596
-
597
- const injectionInfo = {
598
- injectorVersion,
599
- injectionDate: new Date().toISOString(),
600
- injectorName: "obsidian-plugin-config"
601
- };
602
-
603
- const infoPath = path.join(targetPath, ".injection-info.json");
604
- fs.writeFileSync(infoPath, JSON.stringify(injectionInfo, null, 2));
605
- console.log(` āœ… Created injection info file (.injection-info.json)`);
570
+ const configRoot = findPluginConfigRoot();
571
+ const configPackageJsonPath = path.join(configRoot, 'package.json');
572
+
573
+ let injectorVersion = 'unknown';
574
+ try {
575
+ const configPackageJson = JSON.parse(
576
+ fs.readFileSync(configPackageJsonPath, 'utf8')
577
+ );
578
+ injectorVersion = configPackageJson.version || 'unknown';
579
+ } catch {
580
+ console.warn('Warning: Could not read injector version');
581
+ }
582
+
583
+ const injectionInfo = {
584
+ injectorVersion,
585
+ injectionDate: new Date().toISOString(),
586
+ injectorName: 'obsidian-plugin-config'
587
+ };
588
+
589
+ const infoPath = path.join(targetPath, '.injection-info.json');
590
+ fs.writeFileSync(infoPath, JSON.stringify(injectionInfo, null, 2));
591
+ console.log(` āœ… Created injection info file (.injection-info.json)`);
606
592
  }
607
593
 
608
594
  /**
609
595
  * Read injection info from target plugin
610
596
  */
611
597
  export function readInjectionInfo(targetPath: string): Record<string, string> | null {
612
- const infoPath = path.join(targetPath, ".injection-info.json");
598
+ const infoPath = path.join(targetPath, '.injection-info.json');
613
599
 
614
- if (!fs.existsSync(infoPath)) return null;
600
+ if (!fs.existsSync(infoPath)) return null;
615
601
 
616
- try {
617
- return JSON.parse(fs.readFileSync(infoPath, "utf8"));
618
- } catch {
619
- console.warn("Warning: Could not parse .injection-info.json");
620
- return null;
621
- }
602
+ try {
603
+ return JSON.parse(fs.readFileSync(infoPath, 'utf8'));
604
+ } catch {
605
+ console.warn('Warning: Could not parse .injection-info.json');
606
+ return null;
607
+ }
622
608
  }
623
609
 
624
610
  /**
625
611
  * Clean NPM artifacts if package-lock.json is found
626
612
  */
627
613
  export async function cleanNpmArtifactsIfNeeded(targetPath: string): Promise<void> {
628
- const packageLockPath = path.join(targetPath, "package-lock.json");
629
-
630
- if (fs.existsSync(packageLockPath)) {
631
- console.log(`\n🧹 NPM installation detected, cleaning artifacts...`);
632
-
633
- try {
634
- fs.unlinkSync(packageLockPath);
635
- console.log(` šŸ—‘ļø Removed package-lock.json`);
636
-
637
- const nodeModulesPath = path.join(targetPath, "node_modules");
638
- if (fs.existsSync(nodeModulesPath)) {
639
- fs.rmSync(nodeModulesPath, { recursive: true, force: true });
640
- console.log(` šŸ—‘ļø Removed node_modules (will be reinstalled with Yarn)`);
641
- }
642
-
643
- console.log(` āœ… NPM artifacts cleaned to avoid Yarn conflicts`);
644
- } catch (error) {
645
- console.error(` āŒ Failed to clean NPM artifacts: ${error}`);
646
- console.log(` šŸ’” You may need to manually remove package-lock.json and node_modules`);
647
- }
648
- }
614
+ const packageLockPath = path.join(targetPath, 'package-lock.json');
615
+
616
+ if (fs.existsSync(packageLockPath)) {
617
+ console.log(`\n🧹 NPM installation detected, cleaning artifacts...`);
618
+
619
+ try {
620
+ fs.unlinkSync(packageLockPath);
621
+ console.log(` šŸ—‘ļø Removed package-lock.json`);
622
+
623
+ const nodeModulesPath = path.join(targetPath, 'node_modules');
624
+ if (fs.existsSync(nodeModulesPath)) {
625
+ fs.rmSync(nodeModulesPath, { recursive: true, force: true });
626
+ console.log(
627
+ ` šŸ—‘ļø Removed node_modules (will be reinstalled with Yarn)`
628
+ );
629
+ }
630
+
631
+ console.log(` āœ… NPM artifacts cleaned to avoid Yarn conflicts`);
632
+ } catch (error) {
633
+ console.error(` āŒ Failed to clean NPM artifacts: ${error}`);
634
+ console.log(
635
+ ` šŸ’” You may need to manually remove package-lock.json and node_modules`
636
+ );
637
+ }
638
+ }
649
639
  }
650
640
 
651
641
  /**
652
642
  * Check if tsx is installed locally and install it if needed
653
643
  */
654
644
  export async function ensureTsxInstalled(targetPath: string): Promise<void> {
655
- console.log(`\nšŸ” Checking tsx installation...`);
656
-
657
- const packageJsonPath = path.join(targetPath, "package.json");
658
-
659
- try {
660
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
661
- const devDependencies = packageJson.devDependencies || {};
662
- const dependencies = packageJson.dependencies || {};
663
-
664
- if (devDependencies.tsx || dependencies.tsx) {
665
- console.log(` āœ… tsx is already installed`);
666
- return;
667
- }
668
-
669
- console.log(` āš ļø tsx not found, installing as dev dependency...`);
670
- execSync("yarn add -D tsx", { cwd: targetPath, stdio: "inherit" });
671
- console.log(` āœ… tsx installed successfully`);
672
- } catch (error) {
673
- console.error(` āŒ Failed to install tsx: ${error}`);
674
- console.log(` šŸ’” You may need to install tsx manually: yarn add -D tsx`);
675
- throw new Error("tsx installation failed");
676
- }
645
+ console.log(`\nšŸ” Checking tsx installation...`);
646
+
647
+ const packageJsonPath = path.join(targetPath, 'package.json');
648
+
649
+ try {
650
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
651
+ const devDependencies = packageJson.devDependencies || {};
652
+ const dependencies = packageJson.dependencies || {};
653
+
654
+ if (devDependencies.tsx || dependencies.tsx) {
655
+ console.log(` āœ… tsx is already installed`);
656
+ return;
657
+ }
658
+
659
+ console.log(` āš ļø tsx not found, installing as dev dependency...`);
660
+ execSync('yarn add -D tsx', { cwd: targetPath, stdio: 'inherit' });
661
+ console.log(` āœ… tsx installed successfully`);
662
+ } catch (error) {
663
+ console.error(` āŒ Failed to install tsx: ${error}`);
664
+ console.log(` šŸ’” You may need to install tsx manually: yarn add -D tsx`);
665
+ throw new Error('tsx installation failed');
666
+ }
677
667
  }
678
668
 
679
669
  /**
680
670
  * Run yarn install in target directory
681
671
  */
682
672
  export async function runYarnInstall(targetPath: string): Promise<void> {
683
- console.log(`\nšŸ“¦ Installing dependencies...`);
684
-
685
- try {
686
- execSync("yarn install", { cwd: targetPath, stdio: "inherit" });
687
- console.log(` āœ… Dependencies installed successfully`);
688
- } catch (error) {
689
- console.error(` āŒ Failed to install dependencies: ${error}`);
690
- console.log(` šŸ’” You may need to run 'yarn install' manually in the target directory`);
691
- }
673
+ console.log(`\nšŸ“¦ Installing dependencies...`);
674
+
675
+ try {
676
+ execSync('yarn install', { cwd: targetPath, stdio: 'inherit' });
677
+ console.log(` āœ… Dependencies installed successfully`);
678
+ } catch (error) {
679
+ console.error(` āŒ Failed to install dependencies: ${error}`);
680
+ console.log(
681
+ ` šŸ’” You may need to run 'yarn install' manually in the target directory`
682
+ );
683
+ }
692
684
  }
693
685
 
694
686
  /**
695
687
  * Main injection orchestration function
696
688
  */
697
689
  export async function performInjection(
698
- targetPath: string,
699
- useSass: boolean = false
690
+ targetPath: string,
691
+ useSass: boolean = false
700
692
  ): Promise<void> {
701
- console.log(`\nšŸš€ Starting injection process...`);
702
-
703
- try {
704
- await cleanNpmArtifactsIfNeeded(targetPath);
705
- await ensureTsxInstalled(targetPath);
706
- await injectScripts(targetPath);
707
-
708
- console.log(`\nšŸ“¦ Updating package.json...`);
709
- await updatePackageJson(targetPath, useSass);
710
-
711
- await analyzeCentralizedImports(targetPath);
712
-
713
- console.log(`\nšŸ“ Creating required directories...`);
714
- await createRequiredDirectories(targetPath);
715
-
716
- await runYarnInstall(targetPath);
717
-
718
- console.log(`\nšŸ“ Creating injection info...`);
719
- await createInjectionInfo(targetPath);
720
-
721
- console.log(`\nāœ… Injection completed successfully!`);
722
- console.log(`\nšŸ“‹ Next steps:`);
723
- console.log(` 1. cd ${targetPath}`);
724
- console.log(` 2. yarn build # Test the build`);
725
- console.log(` 3. yarn start # Test development mode`);
726
- console.log(` 4. yarn acp # Commit changes (or yarn bacp for build+commit)`);
727
- } catch (error) {
728
- console.error(`\nāŒ Injection failed: ${error}`);
729
- throw error;
730
- }
693
+ console.log(`\nšŸš€ Starting injection process...`);
694
+
695
+ try {
696
+ await cleanNpmArtifactsIfNeeded(targetPath);
697
+ await ensureTsxInstalled(targetPath);
698
+ await injectScripts(targetPath);
699
+
700
+ console.log(`\nšŸ“¦ Updating package.json...`);
701
+ await updatePackageJson(targetPath, useSass);
702
+
703
+ await analyzeCentralizedImports(targetPath);
704
+
705
+ console.log(`\nšŸ“ Creating required directories...`);
706
+ await createRequiredDirectories(targetPath);
707
+
708
+ await runYarnInstall(targetPath);
709
+
710
+ console.log(`\nšŸ“ Creating injection info...`);
711
+ await createInjectionInfo(targetPath);
712
+
713
+ console.log(`\nāœ… Injection completed successfully!`);
714
+ console.log(`\nšŸ“‹ Next steps:`);
715
+ console.log(` 1. cd ${targetPath}`);
716
+ console.log(` 2. yarn build # Test the build`);
717
+ console.log(` 3. yarn start # Test development mode`);
718
+ console.log(
719
+ ` 4. yarn acp # Commit changes (or yarn bacp for build+commit)`
720
+ );
721
+ } catch (error) {
722
+ console.error(`\nāŒ Injection failed: ${error}`);
723
+ throw error;
724
+ }
731
725
  }