|
| 1 | +/** |
| 2 | + * @migration-cleanup(sourceId-normalization-v2): Remove entire file once all lockfiles are migrated |
| 3 | + * |
| 4 | + * Source ID Normalization Migration (sourceId-normalization-v2) |
| 5 | + * |
| 6 | + * Migrates local data (config.json sources, source cache files, installation records) |
| 7 | + * from legacy source IDs (host-only lowercase) to v2 source IDs (full URL lowercase). |
| 8 | + * |
| 9 | + * Lockfiles are NOT rewritten here -- they are Git-committed and shared across teams. |
| 10 | + * Lockfile entries migrate organically when bundles are installed/updated. |
| 11 | + * Dual-read fallback in RepositoryActivationService and RegistryManager handles the gap. |
| 12 | + */ |
| 13 | + |
| 14 | +import * as fs from 'fs'; |
| 15 | +import * as path from 'path'; |
| 16 | +import { promisify } from 'util'; |
| 17 | +import { RegistryStorage } from '../storage/RegistryStorage'; |
| 18 | +import { MigrationRegistry } from '../services/MigrationRegistry'; |
| 19 | +import { |
| 20 | + generateHubSourceId, |
| 21 | + generateLegacyHubSourceId |
| 22 | +} from '../utils/sourceIdUtils'; |
| 23 | +import { Logger } from '../utils/logger'; |
| 24 | + |
| 25 | +const rename = promisify(fs.rename); |
| 26 | +const readFile = promisify(fs.readFile); |
| 27 | +const writeFile = promisify(fs.writeFile); |
| 28 | +const readdir = promisify(fs.readdir); |
| 29 | + |
| 30 | +export const MIGRATION_NAME = 'sourceId-normalization-v2'; |
| 31 | + |
| 32 | +/** |
| 33 | + * Run the source ID normalization migration. |
| 34 | + * Idempotent: uses MigrationRegistry to ensure it only runs once. |
| 35 | + */ |
| 36 | +export async function runSourceIdNormalizationMigration( |
| 37 | + storage: RegistryStorage, |
| 38 | + migrationRegistry: MigrationRegistry |
| 39 | +): Promise<void> { |
| 40 | + await migrationRegistry.runMigration(MIGRATION_NAME, async () => { |
| 41 | + const logger = Logger.getInstance(); |
| 42 | + const paths = storage.getPaths(); |
| 43 | + |
| 44 | + // Step 1: Migrate config.json sources |
| 45 | + const idMap = await migrateConfigSources(storage, logger); |
| 46 | + |
| 47 | + if (idMap.size === 0) { |
| 48 | + logger.info('No sources require ID migration'); |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + logger.info(`Migrating ${idMap.size} source ID(s): ${[...idMap.entries()].map(([o, n]) => `${o} -> ${n}`).join(', ')}`); |
| 53 | + |
| 54 | + // Step 2: Rename source cache files |
| 55 | + await migrateSourceCacheFiles(paths.sourcesCache, idMap, logger); |
| 56 | + |
| 57 | + // Step 3: Update installation records that reference old sourceIds |
| 58 | + await migrateInstallationRecords(paths.userInstalled, idMap, logger); |
| 59 | + await migrateInstallationRecords(paths.installed, idMap, logger); |
| 60 | + }); |
| 61 | +} |
| 62 | + |
| 63 | +/** |
| 64 | + * Migrate source IDs in config.json. |
| 65 | + * Returns a map of oldId -> newId for sources that were migrated. |
| 66 | + */ |
| 67 | +async function migrateConfigSources( |
| 68 | + storage: RegistryStorage, |
| 69 | + logger: Logger |
| 70 | +): Promise<Map<string, string>> { |
| 71 | + const idMap = new Map<string, string>(); |
| 72 | + const sources = await storage.getSources(); |
| 73 | + let changed = false; |
| 74 | + |
| 75 | + for (const source of sources) { |
| 76 | + // Only hub-generated IDs (format: {type}-{12hexchars}) need migration |
| 77 | + if (!isHubGeneratedId(source.id)) { |
| 78 | + continue; |
| 79 | + } |
| 80 | + |
| 81 | + // Compute what the new ID should be |
| 82 | + const newId = generateHubSourceId(source.type, source.url, { |
| 83 | + branch: source.config?.branch, |
| 84 | + collectionsPath: source.config?.collectionsPath |
| 85 | + }); |
| 86 | + |
| 87 | + // If the stored ID differs from the new format, it's a legacy ID |
| 88 | + if (source.id !== newId) { |
| 89 | + // Verify it's actually the legacy form (not some other mismatch) |
| 90 | + const legacyId = generateLegacyHubSourceId(source.type, source.url, { |
| 91 | + branch: source.config?.branch, |
| 92 | + collectionsPath: source.config?.collectionsPath |
| 93 | + }); |
| 94 | + |
| 95 | + if (legacyId && source.id === legacyId) { |
| 96 | + logger.info(`Migrating source '${source.name}': ${source.id} -> ${newId}`); |
| 97 | + idMap.set(source.id, newId); |
| 98 | + source.id = newId; |
| 99 | + changed = true; |
| 100 | + } |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + if (changed) { |
| 105 | + // Save the updated config through RegistryStorage |
| 106 | + const config = await storage.loadConfig(); |
| 107 | + config.sources = sources; |
| 108 | + await storage.saveConfig(config); |
| 109 | + } |
| 110 | + |
| 111 | + return idMap; |
| 112 | +} |
| 113 | + |
| 114 | +/** |
| 115 | + * Check if a source ID looks like a hub-generated ID (format: {type}-{12hexchars}) |
| 116 | + */ |
| 117 | +function isHubGeneratedId(id: string): boolean { |
| 118 | + return /^[a-z]+-[a-f0-9]{12}$/.test(id); |
| 119 | +} |
| 120 | + |
| 121 | +/** |
| 122 | + * Rename source cache files from old sanitized ID to new sanitized ID. |
| 123 | + */ |
| 124 | +async function migrateSourceCacheFiles( |
| 125 | + cacheDir: string, |
| 126 | + idMap: Map<string, string>, |
| 127 | + logger: Logger |
| 128 | +): Promise<void> { |
| 129 | + for (const [oldId, newId] of idMap) { |
| 130 | + const oldFile = path.join(cacheDir, `${sanitize(oldId)}.json`); |
| 131 | + const newFile = path.join(cacheDir, `${sanitize(newId)}.json`); |
| 132 | + |
| 133 | + try { |
| 134 | + if (fs.existsSync(oldFile) && !fs.existsSync(newFile)) { |
| 135 | + await rename(oldFile, newFile); |
| 136 | + logger.debug(`Renamed cache file: ${sanitize(oldId)}.json -> ${sanitize(newId)}.json`); |
| 137 | + } |
| 138 | + } catch (error) { |
| 139 | + logger.warn(`Failed to rename cache file for ${oldId}`, error as Error); |
| 140 | + } |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +/** |
| 145 | + * Update sourceId references in installation record JSON files. |
| 146 | + */ |
| 147 | +async function migrateInstallationRecords( |
| 148 | + installDir: string, |
| 149 | + idMap: Map<string, string>, |
| 150 | + logger: Logger |
| 151 | +): Promise<void> { |
| 152 | + let files: string[]; |
| 153 | + try { |
| 154 | + files = await readdir(installDir); |
| 155 | + } catch { |
| 156 | + return; // directory doesn't exist |
| 157 | + } |
| 158 | + |
| 159 | + for (const file of files) { |
| 160 | + if (!file.endsWith('.json')) { |
| 161 | + continue; |
| 162 | + } |
| 163 | + |
| 164 | + const filepath = path.join(installDir, file); |
| 165 | + try { |
| 166 | + const data = await readFile(filepath, 'utf-8'); |
| 167 | + const record = JSON.parse(data); |
| 168 | + |
| 169 | + if (record.sourceId && idMap.has(record.sourceId)) { |
| 170 | + record.sourceId = idMap.get(record.sourceId); |
| 171 | + await writeFile(filepath, JSON.stringify(record, null, 2), 'utf-8'); |
| 172 | + logger.debug(`Updated sourceId in installation record: ${file}`); |
| 173 | + } |
| 174 | + } catch (error) { |
| 175 | + logger.warn(`Failed to migrate installation record ${file}`, error as Error); |
| 176 | + } |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +/** |
| 181 | + * Sanitize an ID for filenames (mirrors RegistryStorage.sanitizeFilename logic). |
| 182 | + */ |
| 183 | +function sanitize(id: string): string { |
| 184 | + return id.replace(/[^A-Za-z0-9._-]/g, '_').substring(0, 200); |
| 185 | +} |
0 commit comments