@scheduler-systems/gal-run 0.0.197

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.
@@ -0,0 +1,237 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * GAL CLI Preuninstall Script
4
+ *
5
+ * Automatically cleans up GAL-installed files when the CLI is uninstalled via pnpm.
6
+ * This script runs as a package lifecycle hook before package removal.
7
+ *
8
+ * What it cleans:
9
+ * 1. Hook files → ~/.claude/hooks/gal-*.js
10
+ * 2. Status line script → ~/.claude/status_lines/gal-sync-status.py
11
+ * 3. Rules file → ~/.claude/rules/gal-cli.md
12
+ * 4. Hook entries in ~/.claude/settings.json (preserves file and other hooks)
13
+ * 5. GAL config directory → ~/.gal/ (auth tokens, sync state, telemetry queue)
14
+ *
15
+ * Cleanup scope:
16
+ * - User-level files only (not project-level .gal directories)
17
+ * - GAL-specific entries only (preserves user's other Claude configs)
18
+ * - Silent fail strategy (won't prevent uninstall on errors)
19
+ *
20
+ * When it runs:
21
+ * - Automatically during `pnpm rm -g @scheduler-systems/gal-run`
22
+ * - Before package files are removed from node_modules
23
+ * - Can be manually triggered via `pnpm run preuninstall` in the CLI package directory
24
+ *
25
+ * Prerequisites:
26
+ * - Node.js 18+ (CommonJS module)
27
+ * - Runs with user's file system permissions
28
+ *
29
+ * Related files:
30
+ * - apps/cli/scripts/postinstall.cjs - Installation script
31
+ * - apps/cli/package.json - package lifecycle hooks configuration
32
+ */
33
+
34
+ const fs = require('fs');
35
+ const path = require('path');
36
+ const os = require('os');
37
+
38
+ // =============================================================================
39
+ // Cleanup Functions - settings.json
40
+ // =============================================================================
41
+
42
+ /**
43
+ * Remove GAL hook entries from settings.json without deleting the file.
44
+ *
45
+ * This function surgically removes only GAL-specific hook entries while
46
+ * preserving the user's other hooks and settings. It handles:
47
+ * - Filtering GAL hooks from UserPromptSubmit array
48
+ * - Filtering GAL hooks from SessionStart array (v2.x)
49
+ * - Removing empty hook arrays after filtering
50
+ * - Preserving the settings.json file structure
51
+ *
52
+ * @param {string} settingsPath - Full path to ~/.claude/settings.json
53
+ * @returns {boolean} True if any GAL entries were removed, false otherwise
54
+ */
55
+ function removeGalHookEntries(settingsPath) {
56
+ try {
57
+ if (!fs.existsSync(settingsPath)) {
58
+ return false;
59
+ }
60
+
61
+ const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
62
+
63
+ if (!settings.hooks?.UserPromptSubmit) {
64
+ return false;
65
+ }
66
+
67
+ // Filter out GAL hooks while preserving user's other hooks
68
+ const originalLength = settings.hooks.UserPromptSubmit.length;
69
+ settings.hooks.UserPromptSubmit = settings.hooks.UserPromptSubmit.filter((entry) => {
70
+ if (!entry.hooks) return true;
71
+ // Keep entry only if it has non-GAL hooks
72
+ entry.hooks = entry.hooks.filter((hook) =>
73
+ !hook.command?.includes('gal-') && !hook.command?.includes('/gal/')
74
+ );
75
+ return entry.hooks.length > 0;
76
+ });
77
+
78
+ // Remove empty hooks array
79
+ if (settings.hooks.UserPromptSubmit.length === 0) {
80
+ delete settings.hooks.UserPromptSubmit;
81
+ }
82
+
83
+ // Remove empty hooks object
84
+ if (Object.keys(settings.hooks).length === 0) {
85
+ delete settings.hooks;
86
+ }
87
+
88
+ if (settings.hooks?.UserPromptSubmit?.length !== originalLength) {
89
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
90
+ return true;
91
+ }
92
+
93
+ return false;
94
+ } catch {
95
+ // Silent fail - don't prevent uninstall if settings.json is corrupted
96
+ return false;
97
+ }
98
+ }
99
+
100
+ // =============================================================================
101
+ // Cleanup Functions - User-Level Files
102
+ // =============================================================================
103
+
104
+ /**
105
+ * Clean up GAL-installed files from user's home directory.
106
+ *
107
+ * Removes:
108
+ * - Hook files: ~/.claude/hooks/gal-*.js
109
+ * - Status line script: ~/.claude/status_lines/gal-sync-status.py
110
+ * - Rules file: ~/.claude/rules/gal-cli.md
111
+ * - Hook entries from settings.json
112
+ *
113
+ * Uses silent fail strategy - logs removed files but doesn't throw errors.
114
+ * This ensures uninstall proceeds even if individual files are missing or
115
+ * have permission issues.
116
+ *
117
+ * @returns {string[]} Array of paths to files that were successfully removed
118
+ */
119
+ function cleanupUserLevel() {
120
+ const claudeDir = path.join(os.homedir(), '.claude');
121
+ const hooksDir = path.join(claudeDir, 'hooks');
122
+ const settingsPath = path.join(claudeDir, 'settings.json');
123
+
124
+ let removed = [];
125
+
126
+ // Remove GAL hook files
127
+ if (fs.existsSync(hooksDir)) {
128
+ try {
129
+ const files = fs.readdirSync(hooksDir);
130
+ for (const file of files) {
131
+ if (file.startsWith('gal-')) {
132
+ const hookPath = path.join(hooksDir, file);
133
+ try {
134
+ fs.unlinkSync(hookPath);
135
+ removed.push(hookPath);
136
+ } catch (err) {
137
+ // Silent fail
138
+ }
139
+ }
140
+ }
141
+ } catch (err) {
142
+ // Silent fail
143
+ }
144
+ }
145
+
146
+ // Remove GAL hook entries from settings.json
147
+ if (removeGalHookEntries(settingsPath)) {
148
+ removed.push(`${settingsPath} (GAL hooks removed)`);
149
+ }
150
+
151
+ return removed;
152
+ }
153
+
154
+ // =============================================================================
155
+ // Cleanup Functions - GAL Config Directory
156
+ // =============================================================================
157
+
158
+ /**
159
+ * Clean up GAL config directory from user's home directory.
160
+ *
161
+ * Removes entire ~/.gal directory, including:
162
+ * - config.json (auth token, default org)
163
+ * - telemetry-pending-events.json (queued telemetry events)
164
+ * - Any other GAL-specific cache or state files
165
+ *
166
+ * Note: Does NOT remove project-level .gal directories (those belong to repos)
167
+ *
168
+ * Uses silent fail strategy to ensure uninstall proceeds even if directory
169
+ * is missing or has permission issues.
170
+ *
171
+ * @returns {string[]} Array containing the removed directory path, or empty array
172
+ */
173
+ function cleanupGalConfig() {
174
+ const galConfigDir = path.join(os.homedir(), '.gal');
175
+
176
+ if (fs.existsSync(galConfigDir)) {
177
+ try {
178
+ fs.rmSync(galConfigDir, { recursive: true, force: true });
179
+ return [galConfigDir];
180
+ } catch (err) {
181
+ // Silent fail
182
+ return [];
183
+ }
184
+ }
185
+
186
+ return [];
187
+ }
188
+
189
+ // =============================================================================
190
+ // Main Cleanup Orchestration
191
+ // =============================================================================
192
+
193
+ /**
194
+ * Main cleanup orchestration function.
195
+ *
196
+ * Coordinates all cleanup operations and provides user feedback.
197
+ * Runs both user-level and config directory cleanups, then reports results.
198
+ *
199
+ * @returns {void}
200
+ */
201
+ function cleanup() {
202
+ console.log('\n═══════════════════════════════════════════════════');
203
+ console.log(' GAL CLI Uninstall Cleanup');
204
+ console.log('═══════════════════════════════════════════════════\n');
205
+
206
+ const userLevelFiles = cleanupUserLevel();
207
+ const galConfigFiles = cleanupGalConfig();
208
+ const allRemoved = [...userLevelFiles, ...galConfigFiles];
209
+
210
+ if (allRemoved.length > 0) {
211
+ console.log('✓ Cleaned up GAL files:');
212
+ for (const file of allRemoved) {
213
+ console.log(` - ${file}`);
214
+ }
215
+ } else {
216
+ console.log('No GAL files found to clean up.');
217
+ }
218
+
219
+ console.log('\n═══════════════════════════════════════════════════');
220
+ console.log(' GAL CLI has been uninstalled');
221
+ console.log('═══════════════════════════════════════════════════\n');
222
+ console.log('To reinstall: pnpm add -g @scheduler-systems/gal-run\n');
223
+ }
224
+
225
+ // =============================================================================
226
+ // Entry Point
227
+ // =============================================================================
228
+
229
+ // Run cleanup with silent fail strategy
230
+ // Even if cleanup fails, we don't prevent npm uninstall from proceeding
231
+ try {
232
+ cleanup();
233
+ } catch (error) {
234
+ // Log error but allow uninstall to continue
235
+ console.error('GAL cleanup encountered an error, but uninstall will proceed.');
236
+ // Note: We don't process.exit(1) here - uninstall should always succeed
237
+ }